###################################################################################################################
# This R script injests laboratory measurements of projected leaf area, estimates hemi-surface area, then derives
# specific leaf area (cm2 hsa / gC).
# Author: Logan Berner, OSU
# Date: Nov 4th, 2015
###################################################################################################################

rm(list=ls())
require(lattice)

setwd("")
leaf <- read.csv('data/leaf_traits/leaf_data.csv', header=T)
leaf.conversions <- read.csv('data/leaf_traits/leaf_surface_area_conversions.csv', header=T)

species <- unique(leaf$species)

leaf$strata <- factor(leaf$strata)
leaf$plot <- factor(leaf$plot)
leaf$subplot <- factor(leaf$subplot)
head(leaf)
dim(leaf)
fivenum(leaf$leaf.dry.wt.g)
#------------------------------------------------------------------------
# calculate half-surface area from projected surface area
#------------------------------------------------------------------------
leaf$hsa.cm2 <- rep(NA, nrow(leaf))
for (i in species){
  sp.index <- which(leaf$species%in%i)
  sp.dat <- leaf[sp.index,]
  sp.conv <- subset(leaf.conversions, species==i)
  leaf$hsa.cm2[sp.index] <- sp.dat$psa.cm2*sp.conv$psa.to.hsa
}

#------------------------------------------------------------------------
# leaf C and N
leaf$leaf.N.mg.g <- (leaf$N.pcnt/100)*1000
leaf$leaf.C.g.g <- leaf$C.pcnt
leaf$leaf.C.wt.g <- leaf$leaf.dry.wt.g*leaf$C.pcnt/100
leaf$leaf.N.wt.g <- leaf$leaf.dry.wt.g*leaf$N.pcnt/100
leaf$C.N.wt.ratio <- with(leaf, leaf.C.wt.g/leaf.N.wt.g)
leaf$C.N.molar.ratio <- with(leaf, (leaf.C.wt.g/12.011)/(leaf.N.wt.g/14.007)) # calculate C:N on a per mol basis

# sla 
leaf$sla.cm2.gC <- leaf$hsa.cm2/leaf$leaf.C.wt.g 

# remove cols with NAs
leaf <- leaf[-which(is.na(leaf$sla.cm2.gC)),]

write.csv(leaf, 'data/leaf_traits/leaf_processed.csv')
write.csv(subset(leaf, aci.sample=='Yes'), 'data/leaf_traits/leaf_aci_processed.csv')
