# Read model output from files
# ------------------------------------------------------------------------------
# Create data frames to hold information
n_variances = length(variances)
# First, the columns that don't change across species:
variance  = rep(-3, n_variances) # variance of shock (perturbation)
rep_id    = rep(NA, n_variances) # NA in this case
pr_ext    = rep(-3, n_variances) # proportion of replicates with extinction
# Generalists
spec_gen = rep(1, n_variances) # '1' denotes generalist
# NOTE: here I put the variance values in the second column. This is nonstandard wrt the
# output format, BUT makethatgraph() assumes that the parameter sweep is in the second
# column. so that's where it's going.
# Plant 1
spp_id   = rep(41, n_variances)
f1_extprobs = data.frame(spec_gen, variance, rep_id, spp_id, pr_ext)
# Pollinator 1
spp_id   = rep(91, n_variances)
b1_extprobs = data.frame(spec_gen, variance, rep_id, spp_id, pr_ext)
# Specialists
spec_gen = rep(0, n_variances) # '0' denotes specialist
# Plant 2
spp_id   = rep(42, n_variances)
f2_extprobs = data.frame(spec_gen, variance, rep_id, spp_id, pr_ext)
# Pollinator 2
spp_id   = rep(92, n_variances)
b2_extprobs = data.frame(spec_gen, variance, rep_id, spp_id, pr_ext)
# Define data frame for ext_configs (used in McNemar calculations)
# Lists the outcome for each species, by replicate
# first column is variance; the following four hold e/p information for f1, f2, b1, b2
variance  = rep(-3, n_variances * replicates) # variance of shock (perturbation)
f1        = rep(-3, n_variances * replicates) # F1 extinction/persistence outcome
f2        = rep(-3, n_variances * replicates) # F2 extinction/persistence outcome
b1        = rep(-3, n_variances * replicates) # B1 extinction/persistence outcome
b2        = rep(-3, n_variances * replicates) # B2 extinction/persistence outcome
ext_configs = cbind(variance, f1, f2, b1, b2)
# Now loop through the files
for(v in variances) {
v_index  = which(variances == v)-1 # for indexing ext_configs
print(v_index)
var_file = paste("4spp_mshock_s", v, ".csv", sep = "")
print(var_file)
output  = read.csv(var_file, header = FALSE) # model output
# define some vectors to hold population sizes across all replicates
f1_pops = rep(-3, replicates)
f2_pops = rep(-3, replicates)
b1_pops = rep(-3, replicates)
b2_pops = rep(-3, replicates)
# populate the ext_probs data frames with data from file
last_pops = output[tmax_rows,] # only the last population sizes from each replicate
# Remove output to free up memory
rm(output)
for(r in 1:replicates){ # go replicate by replicate through last_pops
lastpop_rep = last_pops[last_pops[,3]==r,] # last population sizes in replicate r
#print(lastpop_rep)
f1_pops[r]  = lastpop_rep[1,5]
f2_pops[r]  = lastpop_rep[2,5]
b1_pops[r]  = lastpop_rep[3,5]
b2_pops[r]  = lastpop_rep[4,5]
# populate ext_configs with extinction/persistence information for this replicate
# assume (as in MATLAB code) that extinction threshold is 1. TRUE ==> extinct
the_row = v_index*replicates + r
ext_configs[the_row, 1] = v
ext_configs[the_row, 2] = f1_pops[r] < 1
ext_configs[the_row, 3] = f2_pops[r] < 1
ext_configs[the_row, 4] = b1_pops[r] < 1
ext_configs[the_row, 5] = b2_pops[r] < 1
} # end loop through var_file
# Remove last_pops to free up memory
rm(last_pops)
# get proportion of replicates where each population is is extinct
f1_extprob_v = 1 - sum(f1_pops > 0.001) / replicates
f2_extprob_v = 1 - sum(f2_pops > 0.001) / replicates
b1_extprob_v = 1 - sum(b1_pops > 0.001) / replicates
b2_extprob_v = 1 - sum(b2_pops > 0.001) / replicates
# now populate the extprobs data frames across the variance sweep
the_row = which(variances==v) # row is the same as position of v in variances
f1_extprobs$variance[the_row] = v
f1_extprobs$rep_id[the_row]   = t_max
f1_extprobs$pr_ext[the_row]   = f1_extprob_v
f2_extprobs$variance[the_row] = v
f2_extprobs$rep_id[the_row]   = t_max
f2_extprobs$pr_ext[the_row]   = f2_extprob_v
b1_extprobs$variance[the_row] = v
b1_extprobs$rep_id[the_row]   = t_max
b1_extprobs$pr_ext[the_row]   = b1_extprob_v
b2_extprobs$variance[the_row] = v
b2_extprobs$rep_id[the_row]   = t_max
b2_extprobs$pr_ext[the_row]   = b2_extprob_v
} # end file read loop
# Return to original working directory
setwd(wd)
ext_configs = data.frame(ext_configs) # convert to data frame
# ------------------------------------------------------------------------------
# McNemar Calculations
# ------------------------------------------------------------------------------
# ---- COMPARISONS over ALL EXTINCTIONS -----------------------------------
# Create a 3D matrix to hold the contingency tables. each slice corresponds
# to the contingency table of the data at one level of input variance, e.g.
#
#             SPEC_EXT    SPEC_PERS
#            _____________________________
#   GEN_EXT  |____(a)______|____(b)______|
#   GEN_PERS |____(c)______|____(d)______|   % with counts stored in each cell.
#
# BUT there will be four of these: one for each comparison:
#    1. Specialist vs. Generalist- Plants
#    2. Specialist vs. Generalist- Pollinators
#    3. Plant vs. Pollinator- Specialist
#    4. Plant vs. Pollinator- Generalist
# I'm going to build these in the form of a data frame, with the following columns:
#   1. variance
#   2. cell (a)
#   3. cell (b)
#   4. cell (c)
#   5. cell (d)
# contingency tables for the different comparisons
variance = variances
# specialist vs. generalist
gs_ext = rep(0, n_variances)
gs_extpers = rep(0, n_variances)
gs_persext = rep(0, n_variances)
gs_pers    = rep(0, n_variances)
svg_f = data.frame(cbind(variance, gs_ext, gs_extpers, gs_persext, gs_pers)) # specialist vs. generalist, plants
svg_b = data.frame(cbind(variance, gs_ext, gs_extpers, gs_persext, gs_pers)) # specialist vs. generalist, pollinators
# plant vs. pollinator
fb_ext = rep(0, n_variances)
fb_extpers = rep(0, n_variances)
fb_persext = rep(0, n_variances)
fb_pers    = rep(0, n_variances)
fvb_s = data.frame(cbind(variance, fb_ext, fb_extpers, fb_persext, fb_pers)) # plant vs. pollinator, specialists
fvb_g = data.frame(cbind(variance, fb_ext, fb_extpers, fb_persext, fb_pers)) # plant vs. pollinator, generalists
# --- now populate the tables -----
for (v in variances) {
v_index  = which(variances == v)
# pull the subset of rows in ext_configs with 1st column == v
table_rows = ext_configs[ext_configs$variance==v,]
if (nrow(table_rows) != replicates) {
print(paste("MISMATCH BETWEEN TABLE_ROWS AND REPLICATES AT VARIANCE", v))
break
}
for (n in 1:nrow(table_rows)) {
# Figure out which cell describes the current row
# increment the count in that cell
current_row = table_rows[n,]
f1 = current_row[2]
f2 = current_row[3]
b1 = current_row[4]
b2 = current_row[5]
# Specialists vs. Generalists: Plants
svg_f[v_index, 1] = v # record the variance
if(f1 == 1 && f2 == 1) { # both extinct
svg_f[v_index, 2] = svg_f[v_index, 2] + 1
}
else if(f1 == 1 && f2 == 0) { # extinct generalist
svg_f[v_index, 3] = svg_f[v_index, 3] + 1
}
else if(f1==0 && f2 == 1) { # extinct specialist
svg_f[v_index, 4] = svg_f[v_index, 4] + 1
}
else if(f1 == 0 && f2 == 0) { # both persist
svg_f[v_index, 5] = svg_f[v_index, 5] + 1
}
else {
print("YOU DID SOMETHING WRONG THERE")
print("svg_f")
}
# Specialists vs. Generalists: Pollinators
svg_b[v_index, 1] = v # record the variance
if(b1 == 1 && b2 == 1) { # both extinct
svg_b[v_index, 2] = svg_b[v_index, 2] + 1
}
else if(b1 == 1 && b2 == 0) { # extinct generalist
svg_b[v_index, 3] = svg_b[v_index, 3] + 1
}
else if(b1==0 && b2 == 1) { # extinct specialist
svg_b[v_index, 4] = svg_b[v_index, 4] + 1
}
else if(b1 == 0 && b2 == 0) { # both persist
svg_b[v_index, 5] = svg_b[v_index, 5] + 1
}
else {
print("YOU DID SOMETHING WRONG THERE")
print("svg_b")
}
# Plants vs. Pollinators: Specialists
fvb_s[v_index, 1] = v # record the variance
if(f2 == 1 && b2 == 1) { # both extinct
fvb_s[v_index, 2] = fvb_s[v_index, 2] + 1
}
else if(f2 == 1 && b2 == 0) { # extinct generalist
fvb_s[v_index, 3] = fvb_s[v_index, 3] + 1
}
else if(f2 ==0 && b2 == 1) { # extinct specialist
fvb_s[v_index, 4] = fvb_s[v_index, 4] + 1
}
else if(f2 == 0 && b2 == 0) { # both persist
fvb_s[v_index, 5] = fvb_s[v_index, 5] + 1
}
else {
print("YOU DID SOMETHING WRONG THERE")
print("fvb_s")
}
# Plants vs. Pollinators: Generalists
fvb_g[v_index, 1] = v # record the variance
if(f1 == 1 && b1 == 1) { # both extinct
fvb_g[v_index, 2] = fvb_g[v_index, 2] + 1
}
else if(f1 == 1 && b1 == 0) { # extinct generalist
fvb_g[v_index, 3] = fvb_g[v_index, 3] + 1
}
else if(f1 ==0 && b1 == 1) { # extinct specialist
fvb_g[v_index, 4] = fvb_g[v_index, 4] + 1
}
else if(f1 == 0 && b1 == 0) { # both persist
fvb_g[v_index, 5] = fvb_g[v_index, 5] + 1
}
else {
print("YOU DID SOMETHING WRONG THERE")
print("fvb_g")
}
} # end of counting
} # finished populating contingency tables
# --- McNemar Calculations ------------------------------------------------
# looks like very low sums on the off-diagonal (1000 replicates).
# For the 10000-replicate data set, some variances have low off-diagonal
# counts; others have very high counts (in the thousands).
# ---- Asymptotic Version ----
# This is the usual McNemar test statistic, recommended where b+c > 25
# (where b, c are the off-diagonal/dissimilarity values)
# Anyway, here's the calculation:
#
# X^2 = (b-c)^2 / (b + c)        where that X is a CHI, obviously!
#
# reject the null hypothesis (b==c) when X^2 > 3.84 FOR SINGLE COMPARISONS
# Create vectors to hold the results for each set of contingency tables.
x_svg_f = rep(-3,n_variances)
x_svg_b = rep(-3,n_variances)
x_fvb_s = rep(-3,n_variances)
x_fvb_g = rep(-3,n_variances)
x_bvb_p = rep(-3,n_variances)
for(v in variances) {
v_index  = which(variances == v)
# I'm going to spell out the letters denoting the contingency table cells:
# aye, bee, cee dee: because. c is a function in R and I'm not feeling creative RN
# specialist vs. generalist: plants
bee = svg_f$gs_extpers[v_index]
cee = svg_f$gs_persext[v_index]
x_svg_f[v_index] = (bee-cee)^2 / (bee + cee)
# specialist vs. generalist: pollinators
bee = svg_b$gs_extpers[v_index]
cee = svg_b$gs_persext[v_index]
x_svg_b[v_index] = (bee-cee)^2 / (bee + cee)
# plant vs. pollinator: specialists
bee = fvb_s$fb_extpers[v_index]
cee = fvb_s$fb_persext[v_index]
x_fvb_s[v_index] = (bee-cee)^2 / (bee + cee)
# plant vs. pollinator: generalists
bee = fvb_g$fb_extpers[v_index]
cee = fvb_g$fb_persext[v_index]
x_fvb_g[v_index] = (bee-cee)^2 / (bee + cee)
} # done calculating X^2 values
# In the first few rows, there's a divide by zero error, because bee==0 and
# cee==0. BUT we can obviously tell in this case that there's no distinguishable
# difference here.
#
# So, for parctical purposes, set the NaN values to -1 since it's below the threshold
# but it doesn't claim to be a true zero
x_svg_f[which(is.nan(x_svg_f))] = -1
x_svg_b[which(is.nan(x_svg_b))] = -1
x_fvb_s[which(is.nan(x_fvb_s))] = -1
x_fvb_g[which(is.nan(x_fvb_g))] = -1
# ------------------------------------------------------------------------
# BONFERONNI-HOLM ADJUSTMENT
# applied to the McNemar p-values (FOR EXACT VERSION OF TEST, SEE BELOW).
# ------------------------------------------------------------------------
# TESTING THESE FOUR NULL HYPOTHESES:
# For a given level of input variance:
# 1. Extinction risk is the same between specialist and generalist plants.
#   (svg_f)
# 2. Extinction risk is the same between specialist and generalist
#    pollinators. (svg_b)
# 3. Extinction risk is the same between specialist plants and specialist
#    pollinators. (fvb_s)
# 4. Extinction risk is the same between generalist plants and generalist
#    pollinators. (fvb_g)
#
# Note that these are only four of the six possible null hypotheses. The
# other two involve comparisons between species that have no categories in
# common (plant generalist vs. pollinator specialist and vice versa). Since
# those don't generalize, I'm not interested in them.
n_hypotheses = 4
# Create matrix to hold hypothesis indices for each level of variance, and
# their corresponding p-values.
hp_rows = n_variances*n_hypotheses
# create data frame to hold variance, hypothesis ID, p-value over all variances
variance = rep(-3, hp_rows)
hyp_id   = rep(-3, hp_rows)
p        = rep(-3, hp_rows)
hp = data.frame(cbind(variance, hyp_id, p))
# Now populate hypotheses with McNemar p-values.
# NOTE that this requires converting the chi square test statistic into a
# p-value (using pchisq(X^2, df=1, lower.tail = FALSE), which is- by my understanding-
# the equivalent to MATLAB's chi2cdf(X^2, 1, 'upper')).
curr_row = 0 # keep track of which row in hp to access
# not the most elegant but im sleepy
for(v in variances) {
v_index  = which(variances == v)
# first hypothesis: svg_f
curr_row = curr_row + 1
hp$variance[curr_row] = v
hp$hyp_id[curr_row]   = 1
hp$p[curr_row]        = pchisq(x_svg_f[v_index],df=1, lower.tail = FALSE)
# second hypothesis: svg_b
curr_row = curr_row + 1
hp$variance[curr_row] = v
hp$hyp_id[curr_row]   = 2
hp$p[curr_row]        = pchisq(x_svg_b[v_index],df=1, lower.tail = FALSE)
# third hypothesis: fvb_s
curr_row = curr_row + 1
hp$variance[curr_row] = v
hp$hyp_id[curr_row]   = 3
hp$p[curr_row]        = pchisq(x_fvb_s[v_index],df=1, lower.tail = FALSE)
# fourth hypothesis: fvb_g
curr_row = curr_row + 1
hp$variance[curr_row] = v
hp$hyp_id[curr_row]   = 4
hp$p[curr_row]        = pchisq(x_fvb_g[v_index],df=1, lower.tail = FALSE)
} # done calculating McNemar p-values
# NOW THE CORRECTION
# Create matrix to hold the output of the correction
# Same dimensions as before but the final column is now 0/1 (where 1
# indicates rejection of the null)
variance = hp$variance      # reuse first two columns from hp
hyp_id   = hp$hyp_id
rej      = rep(-3, hp_rows)
h_sig = data.frame(cbind(variance, hyp_id, rej))
# compare the p-values against these numbers:
a = 0.05 # significance level alpha
k = 1:n_hypotheses
comp_values = a/(n_hypotheses + 1 - k)
# DO THE CORRECTION
# In the third column, assign 1 = significant (TRUE; reject null hypothesis)
#                             0 = not significant (FALSE; do not reject)
curr_row = 0 # keep track of which row in hp to access
# not the most elegant but im sleepy
for(v in variances) {
v_index = which(variances == v)-1
# subset all hypotheses for this variance in hp
hp_v = data.frame(hp[hp$variance==v,])
# sort by ascending p-value
p_index = order(hp_v$p)
hp_v = hp_v[p_index,]
# compare against comp_values
reject = hp_v$p <= comp_values
# align the reject vector with the hypotheses and input variance
for (h in 1:n_hypotheses) {
h_sig$rej[v_index*n_hypotheses + p_index[h]] = reject[h]
}
} # finished correction. h_sig now contains 1/0 for significance levels
makethatgraph_points = function(n_lines, data, ax_lims=NULL, color = "black", point_styles=NULL, new_plot = TRUE){
# makethatgraph makes THAT graph!
#  i.e. it plots extinction risk over a parameter sweep (e.g. increasing
#  mortality) for one or more sets of simulation replicates. That could be
# replicates with different levels of variance or whatever.
#
# THIS IS PORTED FROM A MATLAB FUNCTION OF THE SAME NAME (April 2015 version)
# modifications:
#     1. I'm ignoring color because this is for BW publication
#     2. Got rid of extra parameter for confidence intervals. This version
#        of the function will respond to the number of columns.
#     3. added new_plot parameter in order to use this function to add
#        new curves to existing plots
#     4. changed color_matrix to a single-color parameter
#     5. This version plots the data in points instead of lines. Got rid
#        of the line style parameter
#
#
#   INPUT
#   n_lines        number of lines to plot
#   data           data matrix (see below for format)
#   ax_lims        axis limits [xmin xmax ymin ymax]            (optional)
#   color_matrix   specify color for all lines plotted
#                  in this call                                 (optional)
#   new_plot       create a new plot? TRUE/FALSE                (optional)
#
#   data MATRIX
#   The 'data' matrix is assumed to have 5 columns, where the 2nd contains
#   parameter sweep values and the 5th contains extinction/persistence (1/0)
#   data. If there are 7 columns, they last two define the confidence interval.
# --- CHECK INPUTS -------------------------------------------------------
# color matrix- NOT SUPPORTED RIGHT NOW
#     eventually: figure out how to generate a color gradient.
#     color wheel with n_lines levels?
# confidence intervals- NOT SUPPORTED RIGHT NOW
#    eventually: plot them if columns 6 and 7 exist
# Line Styles
# If no user input, line_styles and point_styles are NULL.
# LINES:  Use lty in order (codes are cyclical in R)
# POINTS: Only override a NULL user input if n_lines > 6
#         since there are only 6 line styles--> need a point to
#         differentiate between trajectories
#         (IMPLEMENTATION NOT FINISHED)
#         I think this is left over from MATLAB
# ---- SET UP THE FIGURE -----------------------------------------------------
#windows() # this is for the windows version ONLY
# use quartz() for Apple
# with Linux X11() but really you're just SOL.
# set up axis limits
x_lims = c(min(data[,2]), max(data[,2]))
y_lims = c(0,1.1)
# chunk indices (1 chunk = 1 line on graph)
chunk_size = dim(data)[1]/n_lines; # SHOULD divide evenly
begin_chunk = 1
end_chunk = chunk_size
# get data for plotting first set of points
data_chunk = data[begin_chunk:end_chunk,]
horiz = data_chunk[,2] # parameter sweep values
vert  = data_chunk[,5] # extinction probability
# plot the first set of data
if(new_plot == TRUE) {
plot(horiz, vert, type="p", pch = 20, col = color, xlim=x_lims, ylim=y_lims, xlab = "", ylab = "")
}
else {
points(horiz, vert, pch = 20, col = color)
}
if(n_lines > 1) {
# plot the rest using points()
for(li in 2:n_lines) {
# update data chunk
begin_chunk = begin_chunk + chunk_size
end_chunk = end_chunk + chunk_size
data_chunk = data[begin_chunk:end_chunk,]
horiz = data_chunk[,2]
vert  = data_chunk[,5]
# plot the data
points(horiz, vert, pch = 1, col = color)
} # end plotting loop
} # end conditional
} # end function makethatgraph_points
# plants (HYPOTHESIS 1)
makethatgraph_points(2, rbind(f1_extprobs, f2_extprobs))
title(main="Plants", xlab="sigma squared epsilon", ylab = "proportion of replicates with extinction")
points(variances[which(h_sig[h_sig$hyp_id==1,]$rej > 0)], h_sig[h_sig$hyp_id==1,]$rej[which(h_sig[h_sig$hyp_id==1,]$rej > 0)] + 0.05, pch = '*', cex = 2)
variances[which(h_sig[h_sig$hyp_id==1,]$rej > 0)]
dim(f1_extprobs)
f1_extprobs
f2_extprobs
f1p = 0.6380
f2p = 0.7884
f1p - f2p
f2p/f1p
(f2p-f1p)/f1p
(.79-.64)/.64
# 21 December 2018
# This script calls makethatgraph() to generate the mu & variance sweep graphs
# shown in Figure 3 of the main text.
# Get current working directory path + save for later
wd = getwd()
source("makethatgraph.r")
# Set the working directory to the data directory
setwd("../../model_outputs/mu_sweep")
# --- 2-Species Sweep ---------------------------------------------------------
# Figure 3
# Read 2-species mu & variance sweep output
fb_pops = read.csv("2spp_mshock.csv", header = FALSE)
# Population outputs
# columns:
#  1. variance
#  2. mu
#  3. replicate ID
#  4. species ID (4=plant, 9=pollinator)
#  5. populaion size at end of replicate
# go back to original working directory
setwd(wd)
# order by species
fb_pops = fb_pops[order(fb_pops[,4]),]
# calculate extinction probabilities (proportion of replicates with extinction)
reps = 10000 # 2spp_mshock_s7007000.csv reports 10000 replicates of each parameter
# combination in the mu-variance sweep
rep_sets = nrow(fb_pops)/reps # number of sets of replicates
ext_threshold = 0.001 # as in main text
# data frame to hold extinction probabilities
fb_probs = data.frame(var=rep(-3,rep_sets), mu=rep(-3, rep_sets), reps=reps,
spp_id=rep(-3, rep_sets), pr_est=rep(-3,rep_sets))
for(r in 1:rep_sets){
first = (r-1)*10000 + 1 # first row in replicate set
last  = r*10000         # last row in replicate set
# get number of plant extinctions in the replicate set
n_ext = length(which(fb_pops[first:last,5] < ext_threshold))
pr_ext = n_ext / reps
# write it into some kind of data structure
var = fb_pops[first,1]
mu  = fb_pops[first,2]
spp = fb_pops[first,4]
fb_probs[r,] = c(var, mu, reps, spp, pr_ext)
} # end extinction probability calculation loop
# Separate out by species
# color coded: f=4, b=9
f_probs = fb_probs[fb_probs$spp_id==4,]
b_probs = fb_probs[fb_probs$spp_id==9,]
# How many variance values are represented?
length_varsweep = length(unique(f_probs$var))
# Make the graph!
# Only need to make one graph because mutualism is obligate
makethatgraph(length_varsweep,f_probs)
# In the figure, I only use variances 0, 0.05, 0.5, 5
fprobs_short    = f_probs[f_probs$var %in% c(0,0.05,0.5,5),]
length_varsweep = 4
makethatgraph(length_varsweep,fprobs_short)
setwd("../../model_outputs/mu_sweep")
list.files()
