###################################################################################################################
# This R script computes subplot and plot tree basal area and wood area index 
# Author: Logan Berner, OSU
# Date: Nov 4th, 2015
###################################################################################################################
rm(list=ls())
require(lattice)
require(dplyr)
setwd('')

treeC <- read.csv('stem_survey/tree_C_npp_sap.csv', header=T)
plot.dims <- read.csv('plot_details/plot_dimensions.csv', header=T)

strata <- c('WJ','PP','GF')
plots <- 1:5
subplots <- 1:4


#--------------------------------------------------------------------------
# calculate wood area index for each subplot based on basal area
#--------------------------------------------------------------------------
treeC$ba.cm2 <- 3.14159*(treeC$dbh.cm/2)^2
stem.ba <- aggregate(ba.cm2~size.class+species+subplot+plot+strata, treeC, sum)
stem.ba$ba.m2 <- stem.ba$ba.cm2/10^4

subplot.sizeclass.ba.m2ha <- as.data.frame(matrix(NA, nrow=0, ncol=6))
colnames(subplot.sizeclass.ba.m2ha) <- c('size.class','species','subplot','plot','strata','ba.m2ha')
subplot.sizeclass.ba.m2ha$strata <- factor(subplot.sizeclass.ba.m2ha$strata, levels=c('WJ','PP','GF'))

for (i in strata){
  for (j in plots){
    dims <- subset(plot.dims, strata == i & plot == j)
    ba.subplot <- subset(stem.ba, strata == i & plot == j)
    sapling.ba <- subset(ba.subplot, size.class=='sapling')
    mature.ba <- subset(ba.subplot, size.class=='mature')
    sapling.ba$ba.m2ha <-sapling.ba$ba.m2/dims$sapling.plot.area.m2*10^4
    mature.ba$ba.m2ha <-mature.ba$ba.m2/dims$stem.plot.area.m2*10^4
    subplot.sizeclass.ba.m2ha <- rbind(subplot.sizeclass.ba.m2ha, sapling.ba, mature.ba)
  }
}
plot.sp.ba.m2ha <- subplot.sizeclass.ba.m2ha %>% group_by(strata,plot,species) %>% summarise_each(funs(sum), +ba.m2ha)
plot.sp.ba.m2ha <- plot.sp.ba.m2ha %>% mutate(total.ba=sum(ba.m2ha)) %>% mutate(ba.pcnt=round(ba.m2ha/total.ba*100))

write.table(plot.sp.ba.m2ha, 'plot_summaries/plot_sp_basal_area.csv', sep=',', row.names=F, col.names=T)
