changeset 102:ce996e90f5a7 draft

Uploaded
author greg
date Tue, 05 Dec 2017 10:32:04 -0500
parents 691b677d8f83
children 4d9e40d8af0f
files insect_phenology_model.R
diffstat 1 files changed, 232 insertions(+), 252 deletions(-) [+]
line wrap: on
line diff
--- a/insect_phenology_model.R	Mon Dec 04 13:34:28 2017 -0500
+++ b/insect_phenology_model.R	Tue Dec 05 10:32:04 2017 -0500
@@ -3,14 +3,14 @@
 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 degree-days 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("-a", "--adult_mortality"), action="store", dest="adult_mortality", type="integer", help="Adjustment rate for adult mortality"),
+    make_option(c("-b", "--adult_accumulation"), action="store", dest="adult_accumulation", type="integer", help="Adjustment of degree-days accumulation (old nymph->adult)"),
+    make_option(c("-c", "--egg_mortality"), action="store", dest="egg_mortality", 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 degree-days accumulation (young nymph->old nymph)"),
+    make_option(c("-j", "--nymph_mortality"), action="store", dest="nymph_mortality", type="integer", help="Adjustment rate for nymph mortality"),
+    make_option(c("-k", "--old_nymph_accumulation"), action="store", dest="old_nymph_accumulation", type="integer", help="Adjustment of degree-days 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"),
@@ -18,7 +18,7 @@
     make_option(c("-s", "--replications"), action="store", dest="replications", type="integer", help="Number of replications"),
     make_option(c("-t", "--std_error_plot"), action="store", dest="std_error_plot", help="Plot Standard error"),
     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 degree-days accumulation (egg->young nymph)"),
+    make_option(c("-y", "--young_nymph_accumulation"), action="store", dest="young_nymph_accumulation", type="integer", help="Adjustment of degree-days accumulation (egg->young nymph)"),
     make_option(c("-x", "--insect"), action="store", dest="insect", help="Insect name")
 )
 
@@ -26,23 +26,6 @@
 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,28 +40,51 @@
         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
     degree_days <- 0
-    if (dxp < threshold) {
+    if (curr_max_temp < threshold) {
         degree_days <- 0
     }
     else {
@@ -98,12 +104,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
                 }
@@ -113,7 +119,7 @@
             }
             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 +129,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
                 }
@@ -134,64 +140,87 @@
         }
         degree_days <- sum(dh) / 24
     }
-    return(c(dmean, degree_days))
-}
-
-dev.egg = function(temperature) {
-    dev.rate= -0.9843 * temperature + 33.438
-    return(dev.rate)
+    return(c(curr_mean_temp, degree_days))
 }
 
-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("topleft", c("Egg", "Nymph", "Adult"), lty=c(1, 1, 1), col=c(4, 2, 1), cex=3)
+    } else if (chart_type == "pop_size_by_generation") {
+        title <- paste(insect, ": Total pop. by generation :", location, ": Lat:", latitude, ":", start_date, "-", end_date, sep=" ")
+        legend("topleft", c("P", "F1", "F2"), lty=c(1, 1, 1), col=c(1, 2, 4), cex=3)
+    } 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("topleft", c("P", "F1", "F2"), lty=c(1, 1, 1), col=c(1, 2, 4), cex=3)
     }
-    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)
+    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)
@@ -202,16 +231,16 @@
 cat("Number of days: ", opt$num_days, "\n")
 
 # Initialize matrices.
-S0.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
-S1.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
-S2.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
-S3.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
-S4.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
-S5.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
+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)
 newborn.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)
 adult.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
-pop.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)
 P.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)
 F2.replications <- matrix(rep(0, opt$num_days*opt$replications), ncol=opt$replications)
@@ -219,7 +248,7 @@
 F1_adults.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)
 
-# Loop through replications.
+# Process replications.
 for (N.replications in 1:opt$replications) {
     # During each replication start with 1000 individuals.
     # TODO: user definable as well?
@@ -235,12 +264,12 @@
     overwintering_adult.population <- rep(0, opt$num_days)
     first_generation.population <- rep(0, opt$num_days)
     second_generation.population <- rep(0, opt$num_days)
-    S0 <- rep(0, opt$num_days)
-    S1 <- rep(0, opt$num_days)
-    S2 <- rep(0, opt$num_days)
-    S3 <- rep(0, opt$num_days)
-    S4 <- rep(0, opt$num_days)
-    S5 <- 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)
     P.adult <- rep(0, opt$num_days)
     F1.adult <- rep(0, opt$num_days)
     F2.adult <- rep(0, opt$num_days)
@@ -265,79 +294,79 @@
         # All individuals.
         for (i in 1:num_insects) {
             # Find individual record.
-            vector.ind <- vector.matrix[i,]
+            vector.individual <- vector.matrix[i,]
             # First of all, still alive?
             # Adjustment for late season mortality rate.
             if (latitude < 40.0) {
-                post.mort <- 1
+                post.mortality <- 1
                 day.kill <- 300
             }
             else {
-                post.mort <- 2
+                post.mortality <- 2
                 day.kill <- 250
             }
-            if (vector.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 (vector.ind[2] == 1 | vector.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 (vector.ind[2] == 3 | vector.ind[2] == 4 | vector.ind[2] == 5) {
+            else if (vector.individual[2] == 3 | vector.individual[2] == 4 | vector.individual[2] == 5) {
                 # For 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?)
             u.d <- runif(1)
-            if (u.d < death.prob) {
+            if (u.d < death.probability) {
                 death.vector <- c(death.vector, i)
             }
             else {
                 # Aggregrate index of dead bug.
                 # Event 1 end of diapause.
-                if (vector.ind[1] == 0 && vector.ind[2] == 3) {
+                if (vector.individual[1] == 0 && vector.individual[2] == 3) {
                     # Overwintering adult (previttelogenic).
-                    if (photoperiod > opt$photoperiod && vector.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.
-                        vector.ind <- c(0, 4, 0, 0, 0)
-                        vector.matrix[i,] <- vector.ind
+                        vector.individual <- c(0, 4, 0, 0, 0)
+                        vector.matrix[i,] <- vector.individual
                     }
                     else {
                         # Add to degree_days.
-                        vector.ind[3] <- vector.ind[3] + degree_days.temp
+                        vector.individual[3] <- vector.individual[3] + degree_days.temp
                         # Add 1 day in current stage.
-                        vector.ind[4] <- vector.ind[4] + 1
-                        vector.matrix[i,] <- vector.ind
+                        vector.individual[4] <- vector.individual[4] + 1
+                        vector.matrix[i,] <- vector.individual
                     }
                 }
-                if (vector.ind[1] != 0 && vector.ind[2] == 3) {
+                if (vector.individual[1] != 0 && vector.individual[2] == 3) {
                     # Not overwintering adult (previttelogenic).
-                    current.gen <- vector.ind[1]
-                    if (vector.ind[3] > 68) {
+                    current.gen <- vector.individual[1]
+                    if (vector.individual[3] > 68) {
                         # Add 68C to become fully reproductively matured.
                         # Transfer to vittelogenic.
-                        vector.ind <- c(current.gen, 4, 0, 0, 0)
-                        vector.matrix[i,] <- vector.ind
+                        vector.individual <- c(current.gen, 4, 0, 0, 0)
+                        vector.matrix[i,] <- vector.individual
                     }
                     else {
                         # Add to degree_days.
-                        vector.ind[3] <- vector.ind[3] + degree_days.temp
+                        vector.individual[3] <- vector.individual[3] + degree_days.temp
                         # Add 1 day in current stage.
-                        vector.ind[4] <- vector.ind[4] + 1
-                        vector.matrix[i,] <- vector.ind
+                        vector.individual[4] <- vector.individual[4] + 1
+                        vector.matrix[i,] <- vector.individual
                     }
                 }
                 # Event 2 oviposition -- where population dynamics comes from.
-                if (vector.ind[2] == 4 && vector.ind[1] == 0 && mean.temp > 10) {
+                if (vector.individual[2] == 4 && vector.individual[1] == 0 && mean.temp > 10) {
                     # Vittelogenic stage, overwintering generation.
-                    if (vector.ind[4] == 0) {
+                    if (vector.individual[4] == 0) {
                         # Just turned in vittelogenic stage.
                         num_insects.birth = round(runif(1, 2 + opt$min_clutch_size, 8 + opt$max_clutch_size))
                     }
@@ -350,16 +379,16 @@
                         }
                     }
                     # Add to degree_days.
-                    vector.ind[3] <- vector.ind[3] + degree_days.temp
+                    vector.individual[3] <- vector.individual[3] + degree_days.temp
                     # Add 1 day in current stage.
-                    vector.ind[4] <- vector.ind[4] + 1
-                    vector.matrix[i,] <- vector.ind
+                    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 <- vector.ind[1] + 1
+                        new.gen <- vector.individual[1] + 1
                         # Egg profile.
-                        new.ind <- c(new.gen, 0, 0, 0, 0)
-                        new.vector <- rep(new.ind, num_insects.birth)
+                        new.individual <- c(new.gen, 0, 0, 0, 0)
+                        new.vector <- rep(new.individual, num_insects.birth)
                         # Update batch of egg profile.
                         new.vector <- t(matrix(new.vector, nrow=5))
                         # Group with total eggs laid in that day.
@@ -367,11 +396,11 @@
                     }
                 }
                 # Event 2 oviposition -- for generation 1.
-                if (vector.ind[2] == 4 && vector.ind[1] == 1 && mean.temp > 12.5 && doy < 222) {
+                if (vector.individual[2] == 4 && vector.individual[1] == 1 && mean.temp > 12.5 && doy < 222) {
                     # Vittelogenic stage, 1st generation
-                    if (vector.ind[4] == 0) {
+                    if (vector.individual[4] == 0) {
                         # Just turned in vittelogenic stage.
-                        num_insects.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.
@@ -382,16 +411,16 @@
                         }
                     }
                     # Add to degree_days.
-                    vector.ind[3] <- vector.ind[3] + degree_days.temp
+                    vector.individual[3] <- vector.individual[3] + degree_days.temp
                     # Add 1 day in current stage.
-                    vector.ind[4] <- vector.ind[4] + 1
-                    vector.matrix[i,] <- vector.ind
+                    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 <- vector.ind[1] + 1
+                        new.gen <- vector.individual[1] + 1
                         # Egg profile.
-                        new.ind <- c(new.gen, 0, 0, 0, 0)
-                        new.vector <- rep(new.ind, num_insects.birth)
+                        new.individual <- c(new.gen, 0, 0, 0, 0)
+                        new.vector <- rep(new.individual, num_insects.birth)
                         # Update batch of egg profile.
                         new.vector <- t(matrix(new.vector, nrow=5))
                         # Group with total eggs laid in that day.
@@ -399,78 +428,78 @@
                     }
                 }
                 # Event 3 development (with diapause determination).
-                # Event 3.1 egg development to young nymph (vector.ind[2]=0 -> egg).
-                if (vector.ind[2] == 0) {
+                # Event 3.1 egg development to young nymph (vector.individual[2]=0 -> egg).
+                if (vector.individual[2] == 0) {
                     # Egg stage.
                     # Add to degree_days.
-                    vector.ind[3] <- vector.ind[3] + degree_days.temp
-                    if (vector.ind[3] >= (68 + opt$young_nymph_accum)) {
+                    vector.individual[3] <- vector.individual[3] + degree_days.temp
+                    if (vector.individual[3] >= (68+opt$young_nymph_accumulation)) {
                         # From egg to young nymph, degree-days requirement met.
-                        current.gen <- vector.ind[1]
+                        current.gen <- vector.individual[1]
                         # Transfer to young nymph stage.
-                        vector.ind <- c(current.gen, 1, 0, 0, 0)
+                        vector.individual <- c(current.gen, 1, 0, 0, 0)
                     }
                     else {
                         # Add 1 day in current stage.
-                        vector.ind[4] <- vector.ind[4] + 1
+                        vector.individual[4] <- vector.individual[4] + 1
                     }
-                    vector.matrix[i,] <- vector.ind
+                    vector.matrix[i,] <- vector.individual
                 }
-                # Event 3.2 young nymph to old nymph (vector.ind[2]=1 -> young nymph: determines diapause).
-                if (vector.ind[2] == 1) {
+                # Event 3.2 young nymph to old nymph (vector.individual[2]=1 -> young nymph: determines diapause).
+                if (vector.individual[2] == 1) {
                     # Young nymph stage.
                     # Add to degree_days.
-                    vector.ind[3] <- vector.ind[3] + degree_days.temp
-                    if (vector.ind[3] >= (250 + opt$old_nymph_accum)) {
+                    vector.individual[3] <- vector.individual[3] + degree_days.temp
+                    if (vector.individual[3] >= (250+opt$old_nymph_accumulation)) {
                         # From young to old nymph, degree_days requirement met.
-                        current.gen <- vector.ind[1]
+                        current.gen <- vector.individual[1]
                         # Transfer to old nym stage.
-                        vector.ind <- c(current.gen, 2, 0, 0, 0)
+                        vector.individual <- c(current.gen, 2, 0, 0, 0)
                         if (photoperiod < opt$photoperiod && doy > 180) {
-                            vector.ind[5] <- 1
+                            vector.individual[5] <- 1
                         } # Prepare for diapausing.
                     }
                     else {
                         # Add 1 day in current stage.
-                        vector.ind[4] <- vector.ind[4] + 1
+                        vector.individual[4] <- vector.individual[4] + 1
                     }
-                    vector.matrix[i,] <- vector.ind
+                    vector.matrix[i,] <- vector.individual
                 }
                 # Event 3.3 old nymph to adult: previttelogenic or diapausing?
-                if (vector.ind[2] == 2) {
+                if (vector.individual[2] == 2) {
                     # Old nymph stage.
                     # Add to degree_days.
-                    vector.ind[3] <- vector.ind[3] + degree_days.temp
-                    if (vector.ind[3] >= (200 + opt$adult_accum)) {
+                    vector.individual[3] <- vector.individual[3] + degree_days.temp
+                    if (vector.individual[3] >= (200+opt$adult_accumulation)) {
                         # From old to adult, degree_days requirement met.
-                        current.gen <- vector.ind[1]
-                        if (vector.ind[5] == 0) {
+                        current.gen <- vector.individual[1]
+                        if (vector.individual[5] == 0) {
                             # Non-diapausing adult -- previttelogenic.
-                            vector.ind <- c(current.gen, 3, 0, 0, 0)
+                            vector.individual <- c(current.gen, 3, 0, 0, 0)
                         }
                         else {
                             # Diapausing.
-                            vector.ind <- c(current.gen, 5, 0, 0, 1)
+                            vector.individual <- c(current.gen, 5, 0, 0, 1)
                         }
                     }
                     else {
                         # Add 1 day in current stage.
-                        vector.ind[4] <- vector.ind[4] + 1
+                        vector.individual[4] <- vector.individual[4] + 1
                     }
-                    vector.matrix[i,] <- vector.ind
+                    vector.matrix[i,] <- vector.individual
                 }
                 # Event 4 growing of diapausing adult (unimportant, but still necessary).
-                if (vector.ind[2] == 5) {
-                    vector.ind[3] <- vector.ind[3] + degree_days.temp
-                    vector.ind[4] <- vector.ind[4] + 1
-                    vector.matrix[i,] <- vector.ind
+                if (vector.individual[2] == 5) {
+                    vector.individual[3] <- vector.individual[3] + degree_days.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 the number of deaths.
         num_insects.death <- length(death.vector)
         if (num_insects.death > 0) {
-      # Remove record of dead.
+            # Remove record of dead.
             vector.matrix <- vector.matrix[-death.vector, ]
         }
         # Find the number of births.
@@ -481,52 +510,53 @@
 
         # Aggregate results by day.
         total.population <- c(total.population, num_insects)
-
         # All adults population size.
-        num_insects.adult <- sum(vector.matrix[,2] == 3) + sum(vector.matrix[,2] == 4) + sum(vector.matrix[,2] == 5)
-
+        num_insects.adult <- sum(vector.matrix[,2]==3)+sum(vector.matrix[,2]==4)+sum(vector.matrix[,2]==5)
         # Overwintering adult population size.
-        overwintering_adult.population[row] <- sum(vector.matrix[,1] == 0)
+        overwintering_adult.population[row] <- sum(vector.matrix[,1]==0)
         # First generation population size.
-        first_generation.population[row] <- sum(vector.matrix[,1] == 1)
+        first_generation.population[row] <- sum(vector.matrix[,1]==1)
         # Second generation population size.
-        second_generation.population[row] <- sum(vector.matrix[,1] == 2)
-
+        second_generation.population[row] <- sum(vector.matrix[,1]==2)
         # Egg population size.
-        S0[row] <- sum(vector.matrix[,2]==0)
+        Eggs[row] <- sum(vector.matrix[,2]==0)
         # Young nymph population size.
-        S1[row] <- sum(vector.matrix[,2]==1)
+        YoungNymphs[row] <- sum(vector.matrix[,2]==1)
         # Old nymph population size.
-        S2[row] <- sum(vector.matrix[,2]==2)
+        OldNymphs[row] <- sum(vector.matrix[,2]==2)
         # Previtellogenic population size.
-        S3[row] <- sum(vector.matrix[,2]==3)
+        Previtellogenic[row] <- sum(vector.matrix[,2]==3)
         # Vitellogenic population size.
-        S4[row] <- sum(vector.matrix[,2]==4)
+        Vitellogenic[row] <- sum(vector.matrix[,2]==4)
         # Diapausing population size.
-        S5[row] <- sum(vector.matrix[,2]==5)
-
+        Diapausing[row] <- sum(vector.matrix[,2]==5)
+        # 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))
-
+        # Newborn population size.
         N.newborn[row] <- num_insects.newborn
+        # Dead population size.
         N.death[row] <- num_insects.death
+        # Adult population size.
         N.adult[row] <- num_insects.adult
-    }   # end of days specified in the input temperature data
+    }   # End of days specified in the input temperature data.
 
     degree_days.cum <- cumsum(degree_days.day)
 
-    # Collect all the outputs.
-    S0.replications[,N.replications] <- S0
-    S1.replications[,N.replications] <- S1
-    S2.replications[,N.replications] <- S2
-    S3.replications[,N.replications] <- S3
-    S4.replications[,N.replications] <- S4
-    S5.replications[,N.replications] <- S5
+    # 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
     death.replications[,N.replications] <- N.death
     adult.replications[,N.replications] <- N.adult
-    pop.replications[,N.replications] <- total.population
+    population.replications[,N.replications] <- total.population
     P.replications[,N.replications] <- overwintering_adult.population
     F1.replications[,N.replications] <- first_generation.population
     F2.replications[,N.replications] <- second_generation.population
@@ -536,11 +566,11 @@
 }
 
 # Mean value for adults.
-adults <- apply((S3.replications + S4.replications + S5.replications), 1, mean)
+adults <- apply((Previtellogenic.replications+Vitellogenic.replications+Diapausing.replications), 1, mean)
 # Mean value for nymphs.
-nymphs <- apply((S1.replications + S2.replications), 1, mean)
+nymphs <- apply((YoungNymphs.replications+OldNymphs.replications), 1, mean)
 # Mean value for eggs.
-eggs <- apply(S0.replications, 1, mean)
+eggs <- apply(Eggs.replications, 1, mean)
 # Mean value for P.
 P <- apply(P.replications, 1, mean)
 # Mean value for F1.
@@ -553,13 +583,12 @@
 F1_adults <- apply(F1_adults.replications, 1, mean)
 # Mean value for F2 adults.
 F2_adults <- apply(F2_adults.replications, 1, mean)
-
 # Standard error for adults.
-adults.std_error <- apply((S3.replications + S4.replications + S5.replications), 1, sd) / sqrt(opt$replications)
+adults.std_error <- apply((Previtellogenic.replications+Vitellogenic.replications+Diapausing.replications), 1, sd) / sqrt(opt$replications)
 # Standard error for nymphs.
-nymphs.std_error <- apply((S1.replications + S2.replications) / sqrt(opt$replications), 1, sd)
+nymphs.std_error <- apply((YoungNymphs.replications+OldNymphs.replications) / sqrt(opt$replications), 1, sd)
 # Standard error for eggs.
-eggs.std_error <- apply(S0.replications, 1, sd) / sqrt(opt$replications)
+eggs.std_error <- apply(Eggs.replications, 1, sd) / sqrt(opt$replications)
 # Standard error value for P.
 P.std_error <- apply(P.replications, 1, sd) / sqrt(opt$replications)
 # Standard error for F1.
@@ -573,11 +602,10 @@
 # Standard error for F2 adult.
 F2_adults.std_error <- apply(F2_adults.replications, 1, sd) / sqrt(opt$replications)
 
-dev.new(width=20, height=30)
+dev.new(width=20, height=40)
 
 # Start PDF device driver to save charts to output.
-pdf(file=opt$output, width=20, height=30, bg="white")
-
+pdf(file=opt$output, width=20, height=40, bg="white")
 par(mar=c(5, 6, 4, 4), mfrow=c(3, 1))
 
 # Data analysis and visualization plots
@@ -587,69 +615,21 @@
 end_date <- temperature_data_frame$DATE[opt$num_days]
 
 # 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, adults, main=title, type="l", ylim=c(0, max(eggs + eggs.std_error, nymphs + nymphs.std_error, adults + adults.std_error)), axes=F, lwd=2, xlab="", ylab="", cex=3, cex.lab=3, cex.axis=3, cex.main=3)
-# Young and old nymphs.
-lines(day.all, nymphs, lwd=2, lty=1, col=2)
-# Eggs
-lines(day.all, eggs, 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)
-legend("topleft", c("Egg", "Nymph", "Adult"), lty=c(1, 1, 1), col=c(4, 2, 1), cex=3)
-if (opt$std_error_plot == 1) {
-    # Add Standard error lines to plot
-    # Standard error for adults
-    lines (day.all, adults+adults.std_error, lty=2)
-    lines (day.all, adults-adults.std_error, lty=2)
-    # Standard error for nymphs
-    lines (day.all, nymphs+nymphs.std_error, col=2, lty=2)
-    lines (day.all, nymphs-nymphs.std_error, col=2, lty=2)
-    # Standard error for eggs
-    lines (day.all, eggs+eggs.std_error, col=4, lty=2)
-    lines (day.all, eggs-eggs.std_error, col=4, lty=2)
-}
+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.all, maxval,
+             opt$std_error_plot, adults, nymphs, eggs, adults.std_error, nymphs.std_error, eggs.std_error)
 
 # 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, P, main=title, type="l", ylim=c(0, max(F2)), axes=F, lwd=2, xlab="", ylab="", cex=3, cex.lab=3, cex.axis=3, cex.main=3)
-lines(day.all, F1, lwd = 2, lty = 1, col=2)
-lines(day.all, F2, 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)
-legend("topleft", c("P", "F1", "F2"), lty=c(1, 1, 1), col=c(1, 2, 4), cex=3)
-if (opt$std_error_plot == 1) {
-    # Add Standard error lines to plot
-    # Standard error for adults
-    lines (day.all, P+P.std_error, lty=2)
-    lines (day.all, P-P.std_error, lty=2)
-    # Standard error for nymphs
-    lines (day.all, F1+F1.std_error, col=2, lty=2)
-    lines (day.all, F1-F1.std_error, col=2, lty=2)
-    # Standard error for eggs
-    lines (day.all, F2+F2.std_error, col=4, lty=2)
-    lines (day.all, F2-F2.std_error, col=4, lty=2)
-}
+maxval <- max(F2)
+render_chart("pop_size_by_generation", opt$insect, opt$location, latitude, start_date, end_date, days.all, maxval,
+             opt$std_error_plot, P, F1, F2, P.std_error, F1.std_error, F2.std_error)
+
 
 # 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, P_adults, ylim=c(0, max(F2_adults) + 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, F1_adults, lwd = 2, lty = 1, col=2)
-lines(day.all, F2_adults, 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)
-legend("topleft", c("P", "F1", "F2"), lty=c(1, 1, 1), col=c(1, 2, 4), cex=3)
-if (opt$std_error_plot == 1) {
-    # Add Standard error lines to plot
-    # Standard error for adults
-    lines (day.all, P_adults+P_adults.std_error, lty=2)
-    lines (day.all, P_adults-P_adults.std_error, lty=2)
-    # Standard error for nymphs
-    lines (day.all, F1_adults+F1_adults.std_error, col=2, lty=2)
-    lines (day.all, F1_adults-F1_adults.std_error, col=2, lty=2)
-    # Standard error for eggs
-    lines (day.all, F2_adults+F2_adults.std_error, col=4, lty=2)
-    lines (day.all, F2_adults-F2_adults.std_error, col=4, lty=2)
-}
+maxval <- max(F2_adults) + 100
+render_chart("adult_pop_size_by_generation", opt$insect, opt$location, latitude, start_date, end_date, days.all, maxval,
+             opt$std_error_plot, P_adults, F1_adults, F2_adults, P_adults.std_error, F1_adults.std_error, F2_adults2.std_error)
+
 
 # Turn off device driver to flush output.
 dev.off()