Use R to save table into csv - openmpp/openmpp.github.io GitHub Wiki
It is a convenient to use GNU R to prepare model parameters and analyze output values. There are two different R APIs which we can use for openM++ models:
- openMpp package: simple and convenient specially for desktop users, upstream and downstream analysis;
-
oms
JSON web-service API: preferable choice to run models on computational clusters and in cloud.
There is also an excelent R package created by Matthew T. Warkentin available at: mattwarkentin.github.io/openmpp.
Below is an example how to use oms
JSON web-service to read output table values from multiple model runs and save it into CSV file.
In that example we are reading RiskPaths
model output table T04_FertilityRatesByAgeGroup
values
from 3 model runs: "New 123,000 cases", "New 456,000 cases", "New 789,000 cases"
and saving it into T04_FertilityRatesByAgeGroup.csv
.
#
# Read table values from multiple model runs and save it as TableName.csv
#
# If any of library below is not installed then do:
# install.packages("jsonlite")
# install.packages("httr")
#
library("jsonlite")
library("httr")
# Include openM++ helper functions from your $HOME directory
#
source("~/omsCommon.R")
#
# Model digest of RiskPaths version 3.0.0.0: "d90e1e9a49a06d972ecf1d50e684c62b"
# We MUST use model digest if there are multiple versions of the model published.
# We can use model name if only single version of the model is published.
#
md <- "d90e1e9a49a06d972ecf1d50e684c62b"
# oms web-service URL from file: ~/oms_url.txt
#
apiUrl <- getOmsApiUrl()
# model runs can be identified by digest, by run stamp or by run name
# run digest is unique and it preferable way to identify model run
# run names are user friendly may not be unique
#
runNames <- c(
"New 123,000 cases",
"New 456,000 cases",
"New 789,000 cases"
)
# combine all run results and write it into T04_FertilityRatesByAgeGroup.csv
#
tableName <- "T04_FertilityRatesByAgeGroup"
allCct <- NULL
nRuns <- length(runNames)
for (k in 1:nRuns)
{
cct <- read.csv(paste0(
apiUrl, "model/", md, "/run/", URLencode(runNames[k], reserved = TRUE), "/table/", tableName, "/expr/csv"
))
cct$RunName <- runNames[k]
allCct <- rbind(allCct, cct)
}
write.csv(allCct, paste0(tableName, ".csv"), row.names = FALSE)