changeset 6:fe3f86012394 draft

Uploaded
author greg
date Wed, 06 Dec 2017 10:07:21 -0500
parents 1878a03f9c9f
children ad26f07a7dd8
files insect_phenology_model.R insect_phenology_model.xml test-data/output.pdf
diffstat 3 files changed, 446 insertions(+), 441 deletions(-) [+]
line wrap: on
line diff
--- a/insect_phenology_model.R	Wed Nov 22 13:22:49 2017 -0500
+++ b/insect_phenology_model.R	Wed Dec 06 10:07:21 2017 -0500
@@ -3,46 +3,30 @@
 suppressPackageStartupMessages(library("optparse"))
 
 option_list <- list(
-    make_option(c("-a", "--adult_mort"), action="store", dest="adult_mort", type="integer", help="Adjustment rate for adult mortality"),
-    make_option(c("-b", "--adult_accum"), action="store", dest="adult_accum", type="integer", help="Adjustment of DD accumulation (old nymph->adult)"),
-    make_option(c("-c", "--egg_mort"), action="store", dest="egg_mort", type="integer", help="Adjustment rate for egg mortality"),
-    make_option(c("-e", "--location"), action="store", dest="location", help="Selected location"),
-    make_option(c("-f", "--min_clutch_size"), action="store", dest="min_clutch_size", type="integer", help="Adjustment of minimum clutch size"),
-    make_option(c("-i", "--max_clutch_size"), action="store", dest="max_clutch_size", type="integer", help="Adjustment of maximum clutch size"),
-    make_option(c("-j", "--nymph_mort"), action="store", dest="nymph_mort", type="integer", help="Adjustment rate for nymph mortality"),
-    make_option(c("-k", "--old_nymph_accum"), action="store", dest="old_nymph_accum", type="integer", help="Adjustment of DD accumulation (young nymph->old nymph)"),
-    make_option(c("-n", "--num_days"), action="store", dest="num_days", type="integer", help="Total number of days in the temperature dataset"),
-    make_option(c("-o", "--output"), action="store", dest="output", help="Output dataset"),
-    make_option(c("-p", "--oviposition"), action="store", dest="oviposition", type="integer", help="Adjustment for oviposition rate"),
-    make_option(c("-q", "--photoperiod"), action="store", dest="photoperiod", type="double", help="Critical photoperiod for diapause induction/termination"),
-    make_option(c("-s", "--replications"), action="store", dest="replications", type="integer", help="Number of replications"),
-    make_option(c("-t", "--se_plot"), action="store", dest="se_plot", help="Plot SE"),
-    make_option(c("-v", "--input"), action="store", dest="input", help="Temperature data for selected location"),
-    make_option(c("-y", "--young_nymph_accum"), action="store", dest="young_nymph_accum", type="integer", help="Adjustment of DD accumulation (egg->young nymph)"),
-    make_option(c("-x", "--insect"), action="store", dest="insect", help="Insect name")
+    make_option(c("--adult_mortality"), action="store", dest="adult_mortality", type="integer", help="Adjustment rate for adult mortality"),
+    make_option(c("--adult_accumulation"), action="store", dest="adult_accumulation", type="integer", help="Adjustment of degree-days accumulation (old nymph->adult)"),
+    make_option(c("--egg_mortality"), action="store", dest="egg_mortality", type="integer", help="Adjustment rate for egg mortality"),
+    make_option(c("--input"), action="store", dest="input", help="Temperature data for selected location"),
+    make_option(c("--insect"), action="store", dest="insect", help="Insect name"),
+    make_option(c("--insects_per_replication"), action="store", dest="insects_per_replication", type="integer", help="Number of insects with which to start each replication"),
+    make_option(c("--location"), action="store", dest="location", help="Selected location"),
+    make_option(c("--min_clutch_size"), action="store", dest="min_clutch_size", type="integer", help="Adjustment of minimum clutch size"),
+    make_option(c("--max_clutch_size"), action="store", dest="max_clutch_size", type="integer", help="Adjustment of maximum clutch size"),
+    make_option(c("--nymph_mortality"), action="store", dest="nymph_mortality", type="integer", help="Adjustment rate for nymph mortality"),
+    make_option(c("--old_nymph_accumulation"), action="store", dest="old_nymph_accumulation", type="integer", help="Adjustment of degree-days accumulation (young nymph->old nymph)"),
+    make_option(c("--num_days"), action="store", dest="num_days", type="integer", help="Total number of days in the temperature dataset"),
+    make_option(c("--output"), action="store", dest="output", help="Output dataset"),
+    make_option(c("--oviposition"), action="store", dest="oviposition", type="integer", help="Adjustment for oviposition rate"),
+    make_option(c("--photoperiod"), action="store", dest="photoperiod", type="double", help="Critical photoperiod for diapause induction/termination"),
+    make_option(c("--replications"), action="store", dest="replications", type="integer", help="Number of replications"),
+    make_option(c("--std_error_plot"), action="store", dest="std_error_plot", help="Plot Standard error"),
+    make_option(c("--young_nymph_accumulation"), action="store", dest="young_nymph_accumulation", type="integer", help="Adjustment of degree-days accumulation (egg->young nymph)")
 )
 
 parser <- OptionParser(usage="%prog [options] file", option_list=option_list)
 args <- parse_args(parser, positional_arguments=TRUE)
 opt <- args$options
 
-parse_input_data = function(input_file, num_rows) {
-    # Read in the input temperature datafile into a data frame.
-    temperature_data_frame <- read.csv(file=input_file, header=T, strip.white=TRUE, sep=",")
-    num_columns <- dim(temperature_data_frame)[2]
-    if (num_columns == 6) {
-        # The input data has the following 6 columns:
-        # LATITUDE, LONGITUDE, DATE, DOY, TMIN, TMAX
-        # Set the column names for access when adding daylight length..
-        colnames(temperature_data_frame) <- c("LATITUDE","LONGITUDE", "DATE", "DOY", "TMIN", "TMAX")
-        # Add a column containing the daylight length for each day.
-        temperature_data_frame <- add_daylight_length(temperature_data_frame, num_columns, num_rows)
-        # Reset the column names with the additional column for later access.
-        colnames(temperature_data_frame) <- c("LATITUDE","LONGITUDE", "DATE", "DOY", "TMIN", "TMAX", "DAYLEN")
-    }
-    return(temperature_data_frame)
-}
-
 add_daylight_length = function(temperature_data_frame, num_columns, num_rows) {
     # Return a vector of daylight length (photoperido profile) for
     # the number of days specified in the input temperature data
@@ -57,29 +41,52 @@
         theta <- 0.2163108 + 2 * atan(0.9671396 * tan(0.00860 * (doy - 186)))
         phi <- asin(0.39795 * cos(theta))
         # Compute the length of daylight for the day of the year.
-        daylight_length_vector[i] <- 24 - (24 / pi * acos((sin(p * pi / 180) + sin(latitude * pi / 180) * sin(phi)) / (cos(latitude * pi / 180) * cos(phi))))
+        darkness_length <- 24 / pi * acos((sin(p * pi / 180) + sin(latitude * pi / 180) * sin(phi)) / (cos(latitude * pi / 180) * cos(phi)))
+        daylight_length_vector[i] <- 24 - darkness_length
     }
     # Append daylight_length_vector as a new column to temperature_data_frame.
     temperature_data_frame[, num_columns+1] <- daylight_length_vector
     return(temperature_data_frame)
 }
 
+dev.egg = function(temperature) {
+    dev.rate = -0.9843 * temperature + 33.438
+    return(dev.rate)
+}
+
+dev.emerg = function(temperature) {
+    emerg.rate <- -0.5332 * temperature + 24.147
+    return(emerg.rate)
+}
+
+dev.old = function(temperature) {
+    n34 <- -0.6119 * temperature + 17.602
+    n45 <- -0.4408 * temperature + 19.036
+    dev.rate = mean(n34 + n45)
+    return(dev.rate)
+}
+
+dev.young = function(temperature) {
+    n12 <- -0.3728 * temperature + 14.68
+    n23 <- -0.6119 * temperature + 25.249
+    dev.rate = mean(n12 + n23)
+    return(dev.rate)
+}
+
 get_temperature_at_hour = function(latitude, temperature_data_frame, row, num_days) {
     # Base development threshold for Brown Marmolated Stink Bug
     # insect phenology model.
-    # TODO: Pass insect on the command line to accomodate more
-    # the just the Brown Marmolated Stink Bub.
     threshold <- 14.17
     # Minimum temperature for current row.
-    dnp <- temperature_data_frame$TMIN[row]
+    curr_min_temp <- temperature_data_frame$TMIN[row]
     # Maximum temperature for current row.
-    dxp <- temperature_data_frame$TMAX[row]
+    curr_max_temp <- temperature_data_frame$TMAX[row]
     # Mean temperature for current row.
-    dmean <- 0.5 * (dnp + dxp)
+    curr_mean_temp <- 0.5 * (curr_min_temp + curr_max_temp)
     # Initialize degree day accumulation
-    dd <- 0
-    if (dxp < threshold) {
-        dd <- 0
+    averages <- 0
+    if (curr_max_temp < threshold) {
+        averages <- 0
     }
     else {
         # Initialize hourly temperature.
@@ -98,12 +105,12 @@
         risetime <- 12 - y / 2
         # Sunset time.
         settime <- 12 + y / 2
-        ts <- (dxp - dnp) * sin(pi * (settime - 5) / (y + 2 * a)) + dnp
+        ts <- (curr_max_temp - curr_min_temp) * sin(pi * (settime - 5) / (y + 2 * a)) + curr_min_temp
         for (i in 1:24) {
             if (i > risetime && i < settime) {
                 # Number of hours after Tmin until sunset.
                 m <- i - 5
-                T[i] = (dxp - dnp) * sin(pi * m / (y + 2 * a)) + dnp
+                T[i] = (curr_max_temp - curr_min_temp) * sin(pi * m / (y + 2 * a)) + curr_min_temp
                 if (T[i] < 8.4) {
                     dh[i] <- 0
                 }
@@ -111,9 +118,9 @@
                     dh[i] <- T[i] - 8.4
                 }
             }
-            else if (i > settime) { 
+            else if (i > settime) {
                 n <- i - settime
-                T[i] = dnp + (ts - dnp) * exp( - b * n / z)
+                T[i] = curr_min_temp + (ts - curr_min_temp) * exp( - b * n / z)
                 if (T[i] < 8.4) {
                     dh[i] <- 0
                 }
@@ -123,7 +130,7 @@
             }
             else {
                 n <- i + 24 - settime
-                T[i]=dnp + (ts - dnp) * exp( - b * n / z)
+                T[i] = curr_min_temp + (ts - curr_min_temp) * exp( - b * n / z)
                 if (T[i] < 8.4) {
                     dh[i] <- 0
                 }
@@ -132,99 +139,153 @@
                 }
             }
         }
-        dd <- sum(dh) / 24
+        averages <- sum(dh) / 24
     }
-    return(c(dmean, dd))
-}
-
-dev.egg = function(temperature) {
-    dev.rate= -0.9843 * temperature + 33.438
-    return(dev.rate)
+    return(c(curr_mean_temp, averages))
 }
 
-dev.young = function(temperature) {
-    n12 <- -0.3728 * temperature + 14.68
-    n23 <- -0.6119 * temperature + 25.249
-    dev.rate = mean(n12 + n23)
-    return(dev.rate)
-}
-
-dev.old = function(temperature) {
-    n34 <- -0.6119 * temperature + 17.602
-    n45 <- -0.4408 * temperature + 19.036
-    dev.rate = mean(n34 + n45)
-    return(dev.rate)
-}
-
-dev.emerg = function(temperature) {
-    emerg.rate <- -0.5332 * temperature + 24.147
-    return(emerg.rate)
+mortality.adult = function(temperature) {
+    if (temperature < 12.7) {
+        mortality.probability = 0.002
+    }
+    else {
+        mortality.probability = temperature * 0.0005 + 0.02
+    }
+    return(mortality.probability)
 }
 
 mortality.egg = function(temperature) {
     if (temperature < 12.7) {
-        mort.prob = 0.8
+        mortality.probability = 0.8
     }
     else {
-        mort.prob = 0.8 - temperature / 40.0
-        if (mort.prob < 0) {
-            mort.prob = 0.01
+        mortality.probability = 0.8 - temperature / 40.0
+        if (mortality.probability < 0) {
+            mortality.probability = 0.01
         }
     }
-    return(mort.prob)
+    return(mortality.probability)
 }
 
 mortality.nymph = function(temperature) {
     if (temperature < 12.7) {
-        mort.prob = 0.03
+        mortality.probability = 0.03
     }
     else {
-        mort.prob = temperature * 0.0008 + 0.03
+        mortality.probability = temperature * 0.0008 + 0.03
     }
-    return(mort.prob)
+    return(mortality.probability)
+}
+
+parse_input_data = function(input_file, num_rows) {
+    # Read in the input temperature datafile into a data frame.
+    temperature_data_frame <- read.csv(file=input_file, header=T, strip.white=TRUE, sep=",")
+    num_columns <- dim(temperature_data_frame)[2]
+    if (num_columns == 6) {
+        # The input data has the following 6 columns:
+        # LATITUDE, LONGITUDE, DATE, DOY, TMIN, TMAX
+        # Set the column names for access when adding daylight length..
+        colnames(temperature_data_frame) <- c("LATITUDE","LONGITUDE", "DATE", "DOY", "TMIN", "TMAX")
+        # Add a column containing the daylight length for each day.
+        temperature_data_frame <- add_daylight_length(temperature_data_frame, num_columns, num_rows)
+        # Reset the column names with the additional column for later access.
+        colnames(temperature_data_frame) <- c("LATITUDE","LONGITUDE", "DATE", "DOY", "TMIN", "TMAX", "DAYLEN")
+    }
+    return(temperature_data_frame)
 }
 
-mortality.adult = function(temperature) {
-    if (temperature < 12.7) {
-        mort.prob = 0.002
+render_chart = function(chart_type, insect, location, latitude, start_date, end_date, days, maxval, plot_std_error,
+                        group1, group2, group3, group1_std_error, group2_std_error, group3_std_error) {
+    if (chart_type == "pop_size_by_life_stage") {
+        title <- paste(insect, ": Total pop. by life stage :", location, ": Lat:", latitude, ":", start_date, "-", end_date, sep=" ")
+        legend_text <- c("Egg", "Nymph", "Adult")
+        columns <- c(4, 2, 1)
+    } else if (chart_type == "pop_size_by_generation") {
+        title <- paste(insect, ": Total pop. by generation :", location, ": Lat:", latitude, ":", start_date, "-", end_date, sep=" ")
+        legend_text <- c("P", "F1", "F2")
+        columns <- c(1, 2, 4)
+    } else if (chart_type == "adult_pop_size_by_generation") {
+        title <- paste(insect, ": Adult pop. by generation :", location, ": Lat:", latitude, ":", start_date, "-", end_date, sep=" ")
+        legend_text <- c("P", "F1", "F2")
+        columns <- c(1, 2, 4)
     }
-    else {
-        mort.prob = temperature * 0.0005 + 0.02
+    plot(days, group1, main=title, type="l", ylim=c(0, maxval), axes=F, lwd=2, xlab="", ylab="", cex=3, cex.lab=3, cex.axis=3, cex.main=3)
+    legend("topleft", legend_text, lty=c(1, 1, 1), col=columns, cex=3)
+    lines(days, group2, lwd=2, lty=1, col=2)
+    lines(days, group3, lwd=2, lty=1, col=4)
+    axis(1, at=c(1:12) * 30 - 15, cex.axis=3, labels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
+    axis(2, cex.axis=3)
+    if (plot_std_error==1) {
+        # Standard error for group1.
+        lines(days, group1+group1_std_error, lty=2)
+        lines (days, group1-group1_std_error, lty=2)
+        # Standard error for group2.
+        lines(days, group2+group2_std_error, col=2, lty=2)
+        lines(days, group2-group2_std_error, col=2, lty=2)
+        # Standard error for group3.
+        lines(days, group3+group3_std_error, col=4, lty=2)
+        lines(days, group3-group3_std_error, col=4, lty=2)
     }
-    return(mort.prob)
 }
 
 temperature_data_frame <- parse_input_data(opt$input, opt$num_days)
-# All latitude values are the same,
-# so get the value from the first row.
+# All latitude values are the same, so get the value from the first row.
 latitude <- temperature_data_frame$LATITUDE[1]
 
-cat("Number of days: ", opt$num_days, "\n")
+# Initialize matrices.
+Eggs.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+YoungNymphs.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+OldNymphs.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+Previtellogenic.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+Vitellogenic.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+Diapausing.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
 
-# Initialize matrix for results from all replications.
-S0.rep <- S1.rep <- S2.rep <- S3.rep <- S4.rep <- S5.rep <- matrix(rep(0, opt$num_days * opt$replications), ncol = opt$replications)
-newborn.rep <- death.rep <- adult.rep <- pop.rep <- g0.rep <- g1.rep <- g2.rep <- g0a.rep <- g1a.rep <- g2a.rep <- matrix(rep(0, opt$num_days * opt$replications), ncol=opt$replications)
+newborn.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+adult.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+death.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+
+P.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+P_adults.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+F1.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+F1_adults.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+F2.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+F2_adults.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+
+population.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
 
-# Loop through replications.
-for (N.rep in 1:opt$replications) {
-    # During each replication start with 1000 individuals.
-    # TODO: user definable as well?
-    n <- 1000
-    # Generation, Stage, DD, T, Diapause.
-    vec.ini <- c(0, 3, 0, 0, 0)
-    # Overwintering, previttelogenic, DD=0, T=0, no-diapause.
-    vec.mat <- rep(vec.ini, n)
+# Process replications.
+for (N.replications in 1:opt$replications) {
+    # Start with the user-defined number of insects per replication.
+    num_insects <- opt$insects_per_replication
+    # Generation, Stage, degree-days, T, Diapause.
+    vector.ini <- c(0, 3, 0, 0, 0)
+    # Overwintering, previttelogenic, degree-days=0, T=0, no-diapause.
+    vector.matrix <- rep(vector.ini, num_insects)
     # Complete matrix for the population.
-    vec.mat <- base::t(matrix(vec.mat, nrow=5))
+    vector.matrix <- base::t(matrix(vector.matrix, nrow=5))
     # Time series of population size.
-    tot.pop <- NULL
-    gen0.pop <- rep(0, opt$num_days)
-    gen1.pop <- rep(0, opt$num_days)
-    gen2.pop <- rep(0, opt$num_days)
-    S0 <- S1 <- S2 <- S3 <- S4 <- S5 <- rep(0, opt$num_days)
-    g0.adult <- g1.adult <- g2.adult <- rep(0, opt$num_days)
-    N.newborn <- N.death <- N.adult <- rep(0, opt$num_days)
-    dd.day <- rep(0, opt$num_days)
+    Eggs <- rep(0, opt$num_days)
+    YoungNymphs <- rep(0, opt$num_days)
+    OldNymphs <- rep(0, opt$num_days)
+    Previtellogenic <- rep(0, opt$num_days)
+    Vitellogenic <- rep(0, opt$num_days)
+    Diapausing <- rep(0, opt$num_days)
+
+    N.newborn <- rep(0, opt$num_days)
+    N.adult <- rep(0, opt$num_days)
+    N.death <- rep(0, opt$num_days)
+
+    overwintering_adult.population <- rep(0, opt$num_days)
+    first_generation.population <- rep(0, opt$num_days)
+    second_generation.population <- rep(0, opt$num_days)
+
+    P.adult <- rep(0, opt$num_days)
+    F1.adult <- rep(0, opt$num_days)
+    F2.adult <- rep(0, opt$num_days)
+
+    total.population <- NULL
+
+    averages.day <- rep(0, opt$num_days)
     # All the days included in the input temperature dataset.
     for (row in 1:opt$num_days) {
         # Get the integer day of the year for the current row.
@@ -233,415 +294,357 @@
         photoperiod <- temperature_data_frame$DAYLEN[row]
         temp.profile <- get_temperature_at_hour(latitude, temperature_data_frame, row, opt$num_days)
         mean.temp <- temp.profile[1]
-        dd.temp <- temp.profile[2]
-        dd.day[row] <- dd.temp
+        averages.temp <- temp.profile[2]
+        averages.day[row] <- averages.temp
         # Trash bin for death.
-        death.vec <- NULL
+        death.vector <- NULL
         # Newborn.
-        birth.vec <- NULL
+        birth.vector <- NULL
         # All individuals.
-        for (i in 1:n) {
-            # Find individual record.
-            vec.ind <- vec.mat[i,]
-            # First of all, still alive?
-            # Adjustment for late season mortality rate.
+        for (i in 1:num_insects) {
+            # Individual record.
+            vector.individual <- vector.matrix[i,]
+            # Adjustment for late season mortality rate (still alive?).
             if (latitude < 40.0) {
-                post.mort <- 1
+                post.mortality <- 1
                 day.kill <- 300
             }
             else {
-                post.mort <- 2
+                post.mortality <- 2
                 day.kill <- 250
             }
-            if (vec.ind[2] == 0) {
+            if (vector.individual[2] == 0) {
                 # Egg.
-                death.prob = opt$egg_mort * mortality.egg(mean.temp)
+                death.probability = opt$egg_mortality * mortality.egg(mean.temp)
             }
-            else if (vec.ind[2] == 1 | vec.ind[2] == 2) {
-                death.prob = opt$nymph_mort * mortality.nymph(mean.temp)
+            else if (vector.individual[2] == 1 | vector.individual[2] == 2) {
+                death.probability = opt$nymph_mortality * mortality.nymph(mean.temp)
             }
-            else if (vec.ind[2] == 3 | vec.ind[2] == 4 | vec.ind[2] == 5) {
-                # For adult.
+            else if (vector.individual[2] == 3 | vector.individual[2] == 4 | vector.individual[2] == 5) {
+                # Adult.
                 if (doy < day.kill) {
-                    death.prob = opt$adult_mort * mortality.adult(mean.temp)
+                    death.probability = opt$adult_mortality * mortality.adult(mean.temp)
                 }
                 else {
                     # Increase adult mortality after fall equinox.
-                    death.prob = opt$adult_mort * post.mort * mortality.adult(mean.temp)
+                    death.probability = opt$adult_mortality * post.mortality * mortality.adult(mean.temp)
                 }
             }
-            # (or dependent on temperature and life stage?)
+            # Dependent on temperature and life stage?
             u.d <- runif(1)
-            if (u.d < death.prob) {
-                death.vec <- c(death.vec, i)
-            } 
+            if (u.d < death.probability) {
+                death.vector <- c(death.vector, i)
+            }
             else {
-                # Aggregrate index of dead bug.
-                # Event 1 end of diapause.
-                if (vec.ind[1] == 0 && vec.ind[2] == 3) {
+                # End of diapause.
+                if (vector.individual[1] == 0 && vector.individual[2] == 3) {
                     # Overwintering adult (previttelogenic).
-                    if (photoperiod > opt$photoperiod && vec.ind[3] > 68 && doy < 180) {
+                    if (photoperiod > opt$photoperiod && vector.individual[3] > 68 && doy < 180) {
                         # Add 68C to become fully reproductively matured.
                         # Transfer to vittelogenic.
-                        vec.ind <- c(0, 4, 0, 0, 0)
-                        vec.mat[i,] <- vec.ind
+                        vector.individual <- c(0, 4, 0, 0, 0)
+                        vector.matrix[i,] <- vector.individual
                     }
                     else {
-                        # Add to dd.
-                        vec.ind[3] <- vec.ind[3] + dd.temp
+                        # Add to # Add average temperature for current day.
+                        vector.individual[3] <- vector.individual[3] + averages.temp
                         # Add 1 day in current stage.
-                        vec.ind[4] <- vec.ind[4] + 1
-                        vec.mat[i,] <- vec.ind
+                        vector.individual[4] <- vector.individual[4] + 1
+                        vector.matrix[i,] <- vector.individual
                     }
                 }
-                if (vec.ind[1] != 0 && vec.ind[2] == 3) {
+                if (vector.individual[1] != 0 && vector.individual[2] == 3) {
                     # Not overwintering adult (previttelogenic).
-                    current.gen <- vec.ind[1]
-                    if (vec.ind[3] > 68) {
+                    current.gen <- vector.individual[1]
+                    if (vector.individual[3] > 68) {
                         # Add 68C to become fully reproductively matured.
                         # Transfer to vittelogenic.
-                        vec.ind <- c(current.gen, 4, 0, 0, 0)
-                        vec.mat[i,] <- vec.ind
+                        vector.individual <- c(current.gen, 4, 0, 0, 0)
+                        vector.matrix[i,] <- vector.individual
                     }
                     else {
-                        # Add to dd.
-                        vec.ind[3] <- vec.ind[3] + dd.temp
+                        # Add average temperature for current day.
+                        vector.individual[3] <- vector.individual[3] + averages.temp
                         # Add 1 day in current stage.
-                        vec.ind[4] <- vec.ind[4] + 1
-                        vec.mat[i,] <- vec.ind
+                        vector.individual[4] <- vector.individual[4] + 1
+                        vector.matrix[i,] <- vector.individual
                     }
                 }
-                # Event 2 oviposition -- where population dynamics comes from.
-                if (vec.ind[2] == 4 && vec.ind[1] == 0 && mean.temp > 10) {
+                # Oviposition -- where population dynamics comes from.
+                if (vector.individual[2] == 4 && vector.individual[1] == 0 && mean.temp > 10) {
                     # Vittelogenic stage, overwintering generation.
-                    if (vec.ind[4] == 0) {
+                    if (vector.individual[4] == 0) {
                         # Just turned in vittelogenic stage.
-                        n.birth=round(runif(1, 2 + opt$min_clutch_size, 8 + opt$max_clutch_size))
+                        num_insects.birth = round(runif(1, 2 + opt$min_clutch_size, 8 + opt$max_clutch_size))
                     }
                     else {
                         # Daily probability of birth.
                         p.birth = opt$oviposition * 0.01
                         u1 <- runif(1)
                         if (u1 < p.birth) {
-                            n.birth=round(runif(1, 2, 8))
+                            num_insects.birth = round(runif(1, 2, 8))
                         }
                     }
-                    # Add to dd.
-                    vec.ind[3] <- vec.ind[3] + dd.temp
+                    # Add average temperature for current day.
+                    vector.individual[3] <- vector.individual[3] + averages.temp
                     # Add 1 day in current stage.
-                    vec.ind[4] <- vec.ind[4] + 1
-                    vec.mat[i,] <- vec.ind
-                    if (n.birth > 0) {
+                    vector.individual[4] <- vector.individual[4] + 1
+                    vector.matrix[i,] <- vector.individual
+                    if (num_insects.birth > 0) {
                         # Add new birth -- might be in different generations.
-                        new.gen <- vec.ind[1] + 1
+                        new.gen <- vector.individual[1] + 1
                         # Egg profile.
-                        new.ind <- c(new.gen, 0, 0, 0, 0)
-                        new.vec <- rep(new.ind, n.birth)
+                        new.individual <- c(new.gen, 0, 0, 0, 0)
+                        new.vector <- rep(new.individual, num_insects.birth)
                         # Update batch of egg profile.
-                        new.vec <- t(matrix(new.vec, nrow=5))
+                        new.vector <- t(matrix(new.vector, nrow=5))
                         # Group with total eggs laid in that day.
-                        birth.vec <- rbind(birth.vec, new.vec)
+                        birth.vector <- rbind(birth.vector, new.vector)
                     }
                 }
-                # Event 2 oviposition -- for generation 1.
-                if (vec.ind[2] == 4 && vec.ind[1] == 1 && mean.temp > 12.5 && doy < 222) {
+                # Oviposition -- for generation 1.
+                if (vector.individual[2] == 4 && vector.individual[1] == 1 && mean.temp > 12.5 && doy < 222) {
                     # Vittelogenic stage, 1st generation
-                    if (vec.ind[4] == 0) {
+                    if (vector.individual[4] == 0) {
                         # Just turned in vittelogenic stage.
-                        n.birth=round(runif(1, 2 + opt$min_clutch_size, 8 + opt$max_clutch_size))
+                        num_insects.birth = round(runif(1, 2+opt$min_clutch_size, 8+opt$max_clutch_size))
                     }
                     else {
                         # Daily probability of birth.
                         p.birth = opt$oviposition * 0.01
                         u1 <- runif(1)
                         if (u1 < p.birth) {
-                            n.birth = round(runif(1, 2, 8))
+                            num_insects.birth = round(runif(1, 2, 8))
                         }
                     }
-                    # Add to dd.
-                    vec.ind[3] <- vec.ind[3] + dd.temp
+                    # Add average temperature for current day.
+                    vector.individual[3] <- vector.individual[3] + averages.temp
                     # Add 1 day in current stage.
-                    vec.ind[4] <- vec.ind[4] + 1
-                    vec.mat[i,] <- vec.ind
-                    if (n.birth > 0) {
+                    vector.individual[4] <- vector.individual[4] + 1
+                    vector.matrix[i,] <- vector.individual
+                    if (num_insects.birth > 0) {
                         # Add new birth -- might be in different generations.
-                        new.gen <- vec.ind[1] + 1
+                        new.gen <- vector.individual[1] + 1
                         # Egg profile.
-                        new.ind <- c(new.gen, 0, 0, 0, 0)
-                        new.vec <- rep(new.ind, n.birth)
+                        new.individual <- c(new.gen, 0, 0, 0, 0)
+                        new.vector <- rep(new.individual, num_insects.birth)
                         # Update batch of egg profile.
-                        new.vec <- t(matrix(new.vec, nrow=5))
+                        new.vector <- t(matrix(new.vector, nrow=5))
                         # Group with total eggs laid in that day.
-                        birth.vec <- rbind(birth.vec, new.vec)
+                        birth.vector <- rbind(birth.vector, new.vector)
                     }
                 }
-                # Event 3 development (with diapause determination).
-                # Event 3.1 egg development to young nymph (vec.ind[2]=0 -> egg).
-                if (vec.ind[2] == 0) {
-                    # Egg stage.
-                    # Add to dd.
-                    vec.ind[3] <- vec.ind[3] + dd.temp
-                    if (vec.ind[3] >= (68 + opt$young_nymph_accum)) {
-                        # From egg to young nymph, DD requirement met.
-                        current.gen <- vec.ind[1]
+                # Egg to young nymph.
+                if (vector.individual[2] == 0) {
+                    # Add average temperature for current day.
+                    vector.individual[3] <- vector.individual[3] + averages.temp
+                    if (vector.individual[3] >= (68+opt$young_nymph_accumulation)) {
+                        # From egg to young nymph, degree-days requirement met.
+                        current.gen <- vector.individual[1]
                         # Transfer to young nymph stage.
-                        vec.ind <- c(current.gen, 1, 0, 0, 0)
+                        vector.individual <- c(current.gen, 1, 0, 0, 0)
                     }
                     else {
                         # Add 1 day in current stage.
-                        vec.ind[4] <- vec.ind[4] + 1
+                        vector.individual[4] <- vector.individual[4] + 1
                     }
-                    vec.mat[i,] <- vec.ind
+                    vector.matrix[i,] <- vector.individual
                 }
-                # Event 3.2 young nymph to old nymph (vec.ind[2]=1 -> young nymph: determines diapause).
-                if (vec.ind[2] == 1) {
-                    # young nymph stage.
-                    # add to dd.
-                    vec.ind[3] <- vec.ind[3] + dd.temp
-                    if (vec.ind[3] >= (250 + opt$old_nymph_accum)) {
-                        # From young to old nymph, dd requirement met.
-                        current.gen <- vec.ind[1]
+                # Young nymph to old nymph.
+                if (vector.individual[2] == 1) {
+                    # Add average temperature for current day.
+                    vector.individual[3] <- vector.individual[3] + averages.temp
+                    if (vector.individual[3] >= (250+opt$old_nymph_accumulation)) {
+                        # From young to old nymph, degree_days requirement met.
+                        current.gen <- vector.individual[1]
                         # Transfer to old nym stage.
-                        vec.ind <- c(current.gen, 2, 0, 0, 0)
+                        vector.individual <- c(current.gen, 2, 0, 0, 0)
                         if (photoperiod < opt$photoperiod && doy > 180) {
-                            vec.ind[5] <- 1
+                            vector.individual[5] <- 1
                         } # Prepare for diapausing.
                     }
                     else {
                         # Add 1 day in current stage.
-                        vec.ind[4] <- vec.ind[4] + 1
+                        vector.individual[4] <- vector.individual[4] + 1
                     }
-                    vec.mat[i,] <- vec.ind
-                }  
-                # Event 3.3 old nymph to adult: previttelogenic or diapausing?
-                if (vec.ind[2] == 2) {
-                    # Old nymph stage.
-                    # add to dd.
-                    vec.ind[3] <- vec.ind[3] + dd.temp
-                    if (vec.ind[3] >= (200 + opt$adult_accum)) {
-                        # From old to adult, dd requirement met.
-                        current.gen <- vec.ind[1]
-                        if (vec.ind[5] == 0) {
-                            # Non-diapausing adult -- previttelogenic.
-                            vec.ind <- c(current.gen, 3, 0, 0, 0)
+                    vector.matrix[i,] <- vector.individual
+                }
+                # Old nymph to adult: previttelogenic or diapausing?
+                if (vector.individual[2] == 2) {
+                    # Add average temperature for current day.
+                    vector.individual[3] <- vector.individual[3] + averages.temp
+                    if (vector.individual[3] >= (200+opt$adult_accumulation)) {
+                        # From old to adult, degree_days requirement met.
+                        current.gen <- vector.individual[1]
+                        if (vector.individual[5] == 0) {
+                            # Previttelogenic.
+                            vector.individual <- c(current.gen, 3, 0, 0, 0)
                         }
                         else {
                             # Diapausing.
-                            vec.ind <- c(current.gen, 5, 0, 0, 1)
+                            vector.individual <- c(current.gen, 5, 0, 0, 1)
                         }
                     }
                     else {
                         # Add 1 day in current stage.
-                        vec.ind[4] <- vec.ind[4] + 1
+                        vector.individual[4] <- vector.individual[4] + 1
                     }
-                    vec.mat[i,] <- vec.ind
+                    vector.matrix[i,] <- vector.individual
                 }
-                # Event 4 growing of diapausing adult (unimportant, but still necessary).
-                if (vec.ind[2] == 5) {
-                    vec.ind[3] <- vec.ind[3] + dd.temp
-                    vec.ind[4] <- vec.ind[4] + 1
-                    vec.mat[i,] <- vec.ind
+                # Growing of diapausing adult (unimportant, but still necessary).
+                if (vector.individual[2] == 5) {
+                    vector.individual[3] <- vector.individual[3] + averages.temp
+                    vector.individual[4] <- vector.individual[4] + 1
+                    vector.matrix[i,] <- vector.individual
                 }
             } # Else if it is still alive.
         } # End of the individual bug loop.
-        # Find how many died.
-        n.death <- length(death.vec)
-        if (n.death > 0) {
-            vec.mat <- vec.mat[-death.vec, ]
+
+        # Number of deaths.
+        num_insects.death <- length(death.vector)
+        if (num_insects.death > 0) {
+            # Remove record of dead.
+            vector.matrix <- vector.matrix[-death.vector, ]
         }
-        # Remove record of dead.
-        # Find how many new born.
-        n.newborn <- length(birth.vec[,1])
-        vec.mat <- rbind(vec.mat, birth.vec)
+        # Number of births.
+        num_insects.newborn <- length(birth.vector[,1])
+        vector.matrix <- rbind(vector.matrix, birth.vector)
         # Update population size for the next day.
-        n <- n - n.death + n.newborn 
+        num_insects <- num_insects - num_insects.death + num_insects.newborn
 
         # Aggregate results by day.
-        tot.pop <- c(tot.pop, n) 
-        # Egg.
-        s0 <- sum(vec.mat[,2] == 0)
-        # Young nymph.
-        s1 <- sum(vec.mat[,2] == 1)
-        # Old nymph.
-        s2 <- sum(vec.mat[,2] == 2)
-        # Previtellogenic.
-        s3 <- sum(vec.mat[,2] == 3)
-        # Vitellogenic.
-        s4 <- sum(vec.mat[,2] == 4)
-        # Diapausing.
-        s5 <- sum(vec.mat[,2] == 5)
-        # Overwintering adult.
-        gen0 <- sum(vec.mat[,1] == 0)
-        # First generation.
-        gen1 <- sum(vec.mat[,1] == 1)
-        # Second generation.
-        gen2 <- sum(vec.mat[,1] == 2)
-        # Sum of all adults.
-        n.adult <- sum(vec.mat[,2] == 3) + sum(vec.mat[,2] == 4) + sum(vec.mat[,2] == 5)
+        # Egg population size.
+        Eggs[row] <- sum(vector.matrix[,2]==0)
+        # Young nymph population size.
+        YoungNymphs[row] <- sum(vector.matrix[,2]==1)
+        # Old nymph population size.
+        OldNymphs[row] <- sum(vector.matrix[,2]==2)
+        # Previtellogenic population size.
+        Previtellogenic[row] <- sum(vector.matrix[,2]==3)
+        # Vitellogenic population size.
+        Vitellogenic[row] <- sum(vector.matrix[,2]==4)
+        # Diapausing population size.
+        Diapausing[row] <- sum(vector.matrix[,2]==5)
 
-        # Generation 0 pop size.
-        gen0.pop[row] <- gen0
-        gen1.pop[row] <- gen1
-        gen2.pop[row] <- gen2
+        # Newborn population size.
+        N.newborn[row] <- num_insects.newborn
+        # Adult population size.
+        N.adult[row] <- sum(vector.matrix[,2]==3) + sum(vector.matrix[,2]==4) + sum(vector.matrix[,2]==5)
+        # Dead population size.
+        N.death[row] <- num_insects.death
+
+        total.population <- c(total.population, num_insects)
+
+        # Overwintering adult population size.
+        overwintering_adult.population[row] <- sum(vector.matrix[,1]==0)
+        # First generation population size.
+        first_generation.population[row] <- sum(vector.matrix[,1]==1)
+        # Second generation population size.
+        second_generation.population[row] <- sum(vector.matrix[,1]==2)
 
-        S0[row] <- s0
-        S1[row] <- s1
-        S2[row] <- s2
-        S3[row] <- s3
-        S4[row] <- s4
-        S5[row] <- s5
+        # P adult population size.
+        P.adult[row] <- sum(vector.matrix[,1]==0)
+        # F1 adult population size.
+        F1.adult[row] <- sum((vector.matrix[,1]==1 & vector.matrix[,2]==3) | (vector.matrix[,1]==1 & vector.matrix[,2]==4) | (vector.matrix[,1]==1 & vector.matrix[,2]==5))
+        # F2 adult population size
+        F2.adult[row] <- sum((vector.matrix[,1]==2 & vector.matrix[,2]==3) | (vector.matrix[,1]==2 & vector.matrix[,2]==4) | (vector.matrix[,1]==2 & vector.matrix[,2]==5))
+    }   # End of days specified in the input temperature data.
 
-        g0.adult[row] <- sum(vec.mat[,1] == 0)
-        g1.adult[row] <- sum((vec.mat[,1] == 1 & vec.mat[,2] == 3) | (vec.mat[,1] == 1 & vec.mat[,2] == 4) | (vec.mat[,1] == 1 & vec.mat[,2] == 5))
-        g2.adult[row] <- sum((vec.mat[,1]== 2 & vec.mat[,2] == 3) | (vec.mat[,1] == 2 & vec.mat[,2] == 4) | (vec.mat[,1] == 2 & vec.mat[,2] == 5))
-
-        N.newborn[row] <- n.newborn
-        N.death[row] <- n.death
-        N.adult[row] <- n.adult
-    }   # end of days specified in the input temperature data
-
-    dd.cum <- cumsum(dd.day)
+    averages.cum <- cumsum(averages.day)
 
-    # Collect all the outputs.
-    S0.rep[,N.rep] <- S0
-    S1.rep[,N.rep] <- S1
-    S2.rep[,N.rep] <- S2
-    S3.rep[,N.rep] <- S3
-    S4.rep[,N.rep] <- S4
-    S5.rep[,N.rep] <- S5
-    newborn.rep[,N.rep] <- N.newborn
-    death.rep[,N.rep] <- N.death
-    adult.rep[,N.rep] <- N.adult
-    pop.rep[,N.rep] <- tot.pop
-    g0.rep[,N.rep] <- gen0.pop
-    g1.rep[,N.rep] <- gen1.pop
-    g2.rep[,N.rep] <- gen2.pop
-    g0a.rep[,N.rep] <- g0.adult
-    g1a.rep[,N.rep] <- g1.adult
-    g2a.rep[,N.rep] <- g2.adult
+    # Define the output values.
+    Eggs.replications[,N.replications] <- Eggs
+    YoungNymphs.replications[,N.replications] <- YoungNymphs
+    OldNymphs.replications[,N.replications] <- OldNymphs
+    Previtellogenic.replications[,N.replications] <- Previtellogenic
+    Vitellogenic.replications[,N.replications] <- Vitellogenic
+    Diapausing.replications[,N.replications] <- Diapausing
+
+    newborn.replications[,N.replications] <- N.newborn
+    adult.replications[,N.replications] <- N.adult
+    death.replications[,N.replications] <- N.death
+
+    P.replications[,N.replications] <- overwintering_adult.population
+    P_adults.replications[,N.replications] <- P.adult
+    F1.replications[,N.replications] <- first_generation.population
+    F1_adults.replications[,N.replications] <- F1.adult
+    F2.replications[,N.replications] <- second_generation.population
+    F2_adults.replications[,N.replications] <- F2.adult
+
+    population.replications[,N.replications] <- total.population
 }
 
-# Data analysis and visualization can currently
-# plot only within a single calendar year.
-# TODO: enhance this to accomodate multiple calendar years.
-start_date <- temperature_data_frame$DATE[1]
-end_date <- temperature_data_frame$DATE[opt$num_days]
+# Mean value for eggs.
+eggs <- apply(Eggs.replications, 1, mean)
+# Standard error for eggs.
+eggs.std_error <- apply(Eggs.replications, 1, sd) / sqrt(opt$replications)
+
+# Mean value for nymphs.
+nymphs <- apply((YoungNymphs.replications+OldNymphs.replications), 1, mean)
+# Standard error for nymphs.
+nymphs.std_error <- apply((YoungNymphs.replications+OldNymphs.replications) / sqrt(opt$replications), 1, sd)
 
-n.yr <- 1
-day.all <- c(1:opt$num_days * n.yr)
+# Mean value for adults.
+adults <- apply((Previtellogenic.replications+Vitellogenic.replications+Diapausing.replications), 1, mean)
+# Standard error for adults.
+adults.std_error <- apply((Previtellogenic.replications+Vitellogenic.replications+Diapausing.replications), 1, sd) / sqrt(opt$replications)
+
+# Mean value for P.
+P <- apply(P.replications, 1, mean)
+# Standard error for P.
+P.std_error <- apply(P.replications, 1, sd) / sqrt(opt$replications)
 
-# mean value for adults
-sa <- apply((S3.rep + S4.rep + S5.rep), 1, mean)
-# mean value for nymphs
-sn <- apply((S1.rep + S2.rep), 1,mean)
-# mean value for eggs
-se <- apply(S0.rep, 1, mean)
-# mean value for P
-g0 <- apply(g0.rep, 1, mean)
-# mean value for F1
-g1 <- apply(g1.rep, 1, mean)
-# mean value for F2
-g2 <- apply(g2.rep, 1, mean)
-# mean value for P adult
-g0a <- apply(g0a.rep, 1, mean)
-# mean value for F1 adult
-g1a <- apply(g1a.rep, 1, mean)
-# mean value for F2 adult
-g2a <- apply(g2a.rep, 1, mean)
+# Mean value for P adults.
+P_adults <- apply(P_adults.replications, 1, mean)
+# Standard error for P_adult.
+P_adults.std_error <- apply(P_adults.replications, 1, sd) / sqrt(opt$replications)
+
+# Mean value for F1.
+F1 <- apply(F1.replications, 1, mean)
+# Standard error for F1.
+F1.std_error <- apply(F1.replications, 1, sd) / sqrt(opt$replications)
 
-# SE for adults
-sa.se <- apply((S3.rep + S4.rep + S5.rep), 1, sd) / sqrt(opt$replications)
-# SE for nymphs
-sn.se <- apply((S1.rep + S2.rep) / sqrt(opt$replications), 1, sd)
-# SE for eggs
-se.se <- apply(S0.rep, 1, sd) / sqrt(opt$replications)
-# SE value for P
-g0.se <- apply(g0.rep, 1, sd) / sqrt(opt$replications)
-# SE for F1
-g1.se <- apply(g1.rep, 1, sd) / sqrt(opt$replications)
-# SE for F2
-g2.se <- apply(g2.rep, 1, sd) / sqrt(opt$replications)
-# SE for P adult
-g0a.se <- apply(g0a.rep, 1, sd) / sqrt(opt$replications)
-# SE for F1 adult
-g1a.se <- apply(g1a.rep, 1, sd) / sqrt(opt$replications)
-# SE for F2 adult
-g2a.se <- apply(g2a.rep, 1, sd) / sqrt(opt$replications)
+# Mean value for F1 adults.
+F1_adults <- apply(F1_adults.replications, 1, mean)
+# Standard error for F1 adult.
+F1_adults.std_error <- apply(F1_adults.replications, 1, sd) / sqrt(opt$replications)
+
+# Mean value for F2.
+F2 <- apply(F2.replications, 1, mean)
+# Standard error for F2.
+F2.std_error <- apply(F2.replications, 1, sd) / sqrt(opt$replications)
+
+# Mean value for F2 adults.
+F2_adults <- apply(F2_adults.replications, 1, mean)
+# Standard error for F2 adult.
+F2_adults.std_error <- apply(F2_adults.replications, 1, sd) / sqrt(opt$replications)
+
+# Display the total number of days in the Galaxy history item blurb.
+cat("Number of days: ", opt$num_days, "\n")
 
 dev.new(width=20, height=30)
 
 # Start PDF device driver to save charts to output.
 pdf(file=opt$output, width=20, height=30, bg="white")
-
-par(mar = c(5, 6, 4, 4), mfrow=c(3, 1))
+par(mar=c(5, 6, 4, 4), mfrow=c(3, 1))
 
-# Subfigure 1: population size by life stage
-title <- paste(opt$insect, ": Total pop. by life stage :", opt$location, ": Lat:", latitude, ":", start_date, "-", end_date, sep=" ")
-plot(day.all, sa, main=title, type="l", ylim=c(0, max(se + se.se, sn + sn.se, sa + sa.se)), axes=F, lwd=2, xlab="", ylab="", cex=3, cex.lab=3, cex.axis=3, cex.main=3)
-# Young and old nymphs.
-lines(day.all, sn, lwd=2, lty=1, col=2)
-# Eggs
-lines(day.all, se, lwd=2, lty=1, col=4)
-axis(1, at=c(1:12) * 30 - 15, cex.axis=3, labels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
-axis(2, cex.axis=3)
-leg.text <- c("Egg", "Nymph", "Adult")
-legend("topleft", leg.text, lty=c(1, 1, 1), col=c(4, 2, 1), cex=3)
-if (opt$se_plot == 1) {
-    # Add SE lines to plot
-    # SE for adults
-    lines (day.all, sa + sa.se, lty=2)
-    lines (day.all, sa - sa.se, lty=2) 
-    # SE for nymphs
-    lines (day.all, sn + sn.se, col=2, lty=2)
-    lines (day.all, sn - sn.se, col=2, lty=2)
-    # SE for eggs
-    lines (day.all, se + se.se, col=4, lty=2)
-    lines (day.all, se - se.se, col=4, lty=2)
-}
+# Data analysis and visualization plots only within a single calendar year.
+days <- c(1:opt$num_days)
+start_date <- temperature_data_frame$DATE[1]
+end_date <- temperature_data_frame$DATE[opt$num_days]
 
-# Subfigure 2: population size by generation
-title <- paste(opt$insect, ": Total pop. by generation :", opt$location, ": Lat:", latitude, ":", start_date, "-", end_date, sep=" ")
-plot(day.all, g0, main=title, type="l", ylim=c(0, max(g2)), axes=F, lwd=2, xlab="", ylab="", cex=3, cex.lab=3, cex.axis=3, cex.main=3)
-lines(day.all, g1, lwd = 2, lty = 1, col=2)
-lines(day.all, g2, lwd = 2, lty = 1, col=4)
-axis(1, at=c(1:12) * 30 - 15, cex.axis=3, labels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
-axis(2, cex.axis=3)
-leg.text <- c("P", "F1", "F2")
-legend("topleft", leg.text, lty=c(1, 1, 1), col=c(1, 2, 4), cex=3)
-if (opt$se_plot == 1) {
-    # Add SE lines to plot
-    # SE for adults
-    lines (day.all, g0+g0.se, lty=2)
-    lines (day.all, g0-g0.se, lty=2) 
-    # SE for nymphs
-    lines (day.all, g1+g1.se, col=2, lty=2)
-    lines (day.all, g1-g1.se, col=2, lty=2)
-    # SE for eggs
-    lines (day.all, g2+g2.se, col=4, lty=2)
-    lines (day.all, g2-g2.se, col=4, lty=2)
-}
-
-# Subfigure 3: adult population size by generation
-title <- paste(opt$insect, ": Adult pop. by generation :", opt$location, ": Lat:", latitude, ":", start_date, "-", end_date, sep=" ")
-plot(day.all, g0a, ylim=c(0, max(g2a) + 100), main=title, type="l", axes=F, lwd=2, xlab="", ylab="", cex=3, cex.lab=3, cex.axis=3, cex.main=3)
-lines(day.all, g1a, lwd = 2, lty = 1, col=2)
-lines(day.all, g2a, lwd = 2, lty = 1, col=4)
-axis(1, at=c(1:12) * 30 - 15, cex.axis=3, labels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
-axis(2, cex.axis=3)
-leg.text <- c("P", "F1", "F2")
-legend("topleft", leg.text, lty=c(1, 1, 1), col=c(1, 2, 4), cex=3)
-if (opt$se_plot == 1) {
-    # Add SE lines to plot
-    # SE for adults
-    lines (day.all, g0a+g0a.se, lty=2)
-    lines (day.all, g0a-g0a.se, lty=2) 
-    # SE for nymphs
-    lines (day.all, g1a+g1a.se, col=2, lty=2)
-    lines (day.all, g1a-g1a.se, col=2, lty=2)
-    # SE for eggs
-    lines (day.all, g2a+g2a.se, col=4, lty=2)
-    lines (day.all, g2a-g2a.se, col=4, lty=2)
-}
+# Subfigure 1: population size by life stage.
+maxval <- max(eggs+eggs.std_error, nymphs+nymphs.std_error, adults+adults.std_error)
+render_chart("pop_size_by_life_stage", opt$insect, opt$location, latitude, start_date, end_date, days, maxval,
+             opt$std_error_plot, adults, nymphs, eggs, adults.std_error, nymphs.std_error, eggs.std_error)
+# Subfigure 2: population size by generation.
+maxval <- max(F2)
+render_chart("pop_size_by_generation", opt$insect, opt$location, latitude, start_date, end_date, days, maxval,
+             opt$std_error_plot, P, F1, F2, P.std_error, F1.std_error, F2.std_error)
+# Subfigure 3: adult population size by generation.
+maxval <- max(F2_adults) + 100
+render_chart("adult_pop_size_by_generation", opt$insect, opt$location, latitude, start_date, end_date, days, maxval,
+             opt$std_error_plot, P_adults, F1_adults, F2_adults, P_adults.std_error, F1_adults.std_error, F2_adults.std_error)
 
 # Turn off device driver to flush output.
 dev.off()
--- a/insect_phenology_model.xml	Wed Nov 22 13:22:49 2017 -0500
+++ b/insect_phenology_model.xml	Wed Dec 06 10:07:21 2017 -0500
@@ -5,23 +5,24 @@
     </requirements>
     <command detect_errors="exit_code"><![CDATA[
 Rscript '$__tool_directory__/insect_phenology_model.R'
--a $adult_mort
--b $adult_accum
--c $egg_mort
--e '$location'
--f $max_clutch_size
--i $min_clutch_size
--j $nymph_mort
--k $old_nymph_accum
--n $input.metadata.data_lines
--o '$output'
--p $oviposition
--q $photoperiod
--s $replications
--t $se_plot
--v '$input'
--y $young_nymph_accum
--x '$insect']]></command>
+--adult_mortality $adult_mortality
+--adult_accumulation $adult_accumulation
+--egg_mortality $egg_mortality
+--input '$input'
+--insect '$insect'
+--insects_per_replication $insects_per_replication
+--location '$location'
+--max_clutch_size $max_clutch_size
+--min_clutch_size $min_clutch_size
+--nymph_mortality $nymph_mortality
+--num_days $input.metadata.data_lines
+--old_nymph_accumulation $old_nymph_accumulation
+--output '$output'
+--oviposition $oviposition
+--photoperiod $photoperiod
+--replications $replications
+--std_error_plot $std_error_plot
+--young_nymph_accumulation $young_nymph_accumulation]]></command>
     <inputs>
         <param name="input" type="data" format="csv" label="Temperature data" />
         <param name="location" type="text" value="" optional="false" label="Location" />
@@ -29,17 +30,18 @@
             <option value="Brown Marmolated Stink Bug" selected="True">Brown Marmolated Stink Bug</option>
         </param>
         <param name="replications" type="integer" value="10" min="1" label="Number of replications" />
+        <param name="insects_per_replication" type="integer" value="1000" min="1" label="Number of insects with which to start each replication" />
         <param name="photoperiod" type="float" value="13.5" min="0" label="Critical photoperiod for diapause induction/termination" />
-        <param name="egg_mort" type="integer" value="1" min="0" label="Adjustment rate for egg mortality" />
-        <param name="nymph_mort" type="integer" value="1" min="0" label="Adjustment rate for nymph mortality" />
-        <param name="adult_mort" type="integer" value="1" min="0" label="Adjustment rate for adult mortality" />
+        <param name="egg_mortality" type="integer" value="1" min="0" label="Adjustment rate for egg mortality" />
+        <param name="nymph_mortality" type="integer" value="1" min="0" label="Adjustment rate for nymph mortality" />
+        <param name="adult_mortality" type="integer" value="1" min="0" label="Adjustment rate for adult mortality" />
         <param name="oviposition" type="integer" value="1" min="0" label="Adjustment oviposition rate" />
         <param name="min_clutch_size" type="integer" value="0" min="0" label="Adjustment of minimum clutch size" />
         <param name="max_clutch_size" type="integer" value="0" min="0" label="Adjustment of maximum clutch size" />
-        <param name="young_nymph_accum" type="integer" value="0" min="0" label="Adjustment of DD accumulation (egg->young nymph)" />
-        <param name="old_nymph_accum" type="integer" value="0" min="0" label="Adjustment of DD accumulation (young nymph->old nymph)" />
-        <param name="adult_accum" type="integer" value="0" min="0" label="Adjustment of DD accumulation (old nymph->adult)" />
-        <param name="se_plot" type="select" label="Plot SE?">
+        <param name="young_nymph_accumulation" type="integer" value="0" min="0" label="Adjustment of degree-days accumulation (egg->young nymph)" />
+        <param name="old_nymph_accumulation" type="integer" value="0" min="0" label="Adjustment of degree-days accumulation (young nymph->old nymph)" />
+        <param name="adult_accumulation" type="integer" value="0" min="0" label="Adjustment of degree-days accumulation (old nymph->adult)" />
+        <param name="std_error_plot" type="select" label="Plot standard error?">
             <option value="1" selected="True">Yes</option>
             <option value="0">No</option>
         </param>
@@ -57,7 +59,7 @@
     </tests>
     <help>
 **What it does**
- 
+
 Provides an agent-based stochastic model expressing stage-specific phenology and population dynamics for an insect species across geographic regions.
 
 -----
@@ -66,7 +68,9 @@
 
  * **Location** - the location associated with the selected temperature data.
  * **Temperature data** - select the dataset from your history containing the temperature data.
+ * **Select insect** - currently only the Brown Marmolated Stink Bug can be analyzed.
  * **Number of replications** - number of replications.
+ * **Number of insects with which to start each replication** - the analysis for each replication will start with this number of insects.
  * **Critical photoperiod for diapause induction/termination** - critical photoperiod for diapause induction/termination.
  * **Adjustment rate for egg mortality** - adjustment rate for egg mortality.
  * **Adjustment rate for nymph mortality** - adjustment rate for nymph mortality.
@@ -74,11 +78,11 @@
  * **Adjustment oviposition rate** - adjustment oviposition rate.
  * **Adjustment of minimum clutch size** - adjustment of minimum clutch size.
  * **Adjustment of maximum clutch size** - adjustment of maximum clutch size
- * **Adjustment of DD accumulation (egg->young nymph)** - adjustment of DD accumulation (egg->young nymph).
- * **Adjustment of DD accumulation (young nymph->old nymph)** - adjustment of DD accumulation (young nymph->old nymph).
- * **Adjustment of DD accumulation (old nymph->adult)** - adjustment of DD accumulation (old nymph->adult).
- * **Plot SE** - add SE lines to plot for eggs, nymphs and adults.
- 
+ * **Adjustment of degree-days accumulation (egg->young nymph)** - adjustment of degree-days accumulation (egg->young nymph).
+ * **Adjustment of degree-days accumulation (young nymph->old nymph)** - adjustment of degree-days accumulation (young nymph->old nymph).
+ * **Adjustment of degree-days accumulation (old nymph->adult)** - adjustment of degree-days accumulation (old nymph->adult).
+ * **Plot standard error** - add standard error lines to plot.
+
     </help>
     <citations>
         <citation type="doi">10.3389/fphys.2016.00165</citation>
--- a/test-data/output.pdf	Wed Nov 22 13:22:49 2017 -0500
+++ b/test-data/output.pdf	Wed Dec 06 10:07:21 2017 -0500
@@ -1,19 +1,16 @@
+%PDF
 1 0 obj
 <<
+/CreationDate
+/ModDate
 /Title (R Graphics Output)
+/Producer
 /Creator (R)
->>
-endobj
-2 0 obj
 << /Type /Catalog /Pages 3 0 R >>
 endobj
 7 0 obj
 << /Type /Page /Parent 3 0 R /Contents 8 0 R /Resources 4 0 R >>
 endobj
-8 0 obj
-<<
->>
-stream
 3 0 obj
 << /Type /Pages /Kids [ 7 0 R ] /Count 1 /MediaBox [0 0 1440 2160] >>
 endobj
@@ -52,3 +49,4 @@
 trailer
 << /Size 12 /Info 1 0 R /Root 2 0 R >>
 startxref
+%%EOF