require(data.table) cropIntensitySummary = function (luDt, cropType) { yDt = luDt[cropland > 0, list( irrig = get(paste0(cropType, '_IQ')), fert = get(paste0(cropType, '_FQ')), otherint = get(paste0(cropType, '_OI')), thisCropFact = get(paste0(cropType, '_A')), allCropFact = cropland/area, area = get(paste0(cropType, '_A'))*cropland, yield = get(paste0(cropType, '_Y'))) ] # yDt[thisCropFact>0.05 & allCropFact > 0.03, list(cropType = cropType, yield=sum(area * yield)/sum(area), yDt[thisCropFact>0, list(cropType = cropType, yield=sum(area * yield)/sum(area), irrig=sum(area * irrig)/sum(area), fert=sum(area * fert)/sum(area), otherint=sum(area * otherint)/sum(area), area = sum(area)) ] } summariseLandUseOutput = function(simDir, writeFile=TRUE) { years = list.files(simDir, pattern="[0-9]+") cropSumDt = NULL for (year in years) { fileName = file.path(simDir, year, 'LandUse.txt') if (file.exists(fileName)) { print (paste("Processing", year, "from", fileName)) luDt = data.table(read.table(fileName, header=TRUE)) for (cropType in c('maize', 'rice', 'wheat', 'energycrops', 'oilcrops', 'pulses', 'starchyRoots')) { cropSummary = cropIntensitySummary(luDt, cropType) if (nrow(cropSummary) >0) cropSumDt = rbind(cropSumDt, cbind(cropSummary, year=year)) } } else { print(paste("Can't find file, so skipping:", fileName)) } } resDt = rbind(cropSumDt, cropSumDt[cropType != 'energycrops', list(cropType='avgExcEC', yield=sum(yield*area)/sum(area), irrig=sum(irrig*area)/sum(area), fert=sum(fert*area)/sum(area), otherint=sum(otherint*area)/sum(area), area=sum(area)), by=year]) resDt = rbind(resDt, cropSumDt[, list(cropType='avgIncEC', yield=sum(yield*area)/sum(area), irrig=sum(irrig*area)/sum(area), fert=sum(fert*area)/sum(area), otherint=sum(otherint*area)/sum(area), area=sum(area)), by=year]) if (writeFile) write.table(resDt, file.path(simDir, "LandUseSummary.csv"), sep=",", row.names=FALSE, quote=FALSE) resDt } baseOutputDir="/exports/csce/eddie/geos/groups/LURG/models/PLUM/output" # "~/Downloads" ensemble = commandArgs(trailingOnly = TRUE)[1] ensDir=file.path(baseOutputDir, ensemble) if (dir.exists(ensDir)) { print(paste(ensDir, "exists. Processing")) summariseLandUseOutput(simDir = ensDir) } else { print(paste(ensDir, "does not exist. Stopping")) }