# FSK2R: an interface between FSK-ML and R

#### Alberto Garre, Miguel de Alba-Aparicio, Pablo S. Fernandez, Matthias Filter

#### 2020-05-11

## The FSK2R package

The FSK2R package provides an interface between the R programming language and the FSK-ML standard. It enables to import already existing models compliant with the FSK-ML standard into R. It also includes functions for the creation of a model with the FSK-ML format based on an already existing R model (an R script). The models can be queried and editted in R. This includes running the simulations included in the model, as well as defining new ones. Finally, the models can be exported as an .fskx file, compliant with the FSK-ML standard.

This document first makes a brief description of the FSK-ML standard. Then, it describes the main features of the FSK2R package using several examples. These are:

- Import of existing FSK-ML compliant models into R.
- Creating of FSK-ML compliant files based on already existing R models.
- Running the simulations included in an FSK file, as well as editting the existing ones and adding new ones.
- Exporting the FSK model (potentially created or editted in R) as a file compliant with FSK-ML.
- Checking the compliance of an FSK file with the FSK-ML standard.

The package can easily be installed from CRAN with the following line of code:

    # install.packages("FSK2R")

Once installed, it can be loaded with:

    library(FSK2R)

## The FSK-ML (Food Safety Markup Language) standard

Food safety risk assessments, control of food production processes as well as the development of new food products are nowadays supported by application of mathematical modelling and data analysis techniques. This creates an increasing demand for resources facilitating the efficient, transparent and quality proven exchange of relevant information, e.g. analytical data, mathematical models, simulation setting as well as simulated data. For example, new parameterized microbial models are frequently made publicly available only in written mode via scientific publications. However, in order to apply these models to a given practical decision support question (e.g. on the growth/no-growth of a microorganism in a specific food matrix under given processing conditions) the interested end-user would have to re-implement the model based on information provided in a publication. Here it would be more efficient if those who create parameterized models could provide their model additionally as a file complying with a standardized file format that is also capable of transferring all relevant meta data. Such a file could e.g. be provided as a supplement to the publication and could be read-in by the end user’s software tools (thus overcoming an error-prone re-implementation process).

A first standardized file format has been proposed in the “Predictive Modelling in Food Markup Language (PMF-ML) Software Developer Guide”. This document describes in detail how experimental data and mathematical models from the domain of predictive microbial modelling (and beyond) can be saved and encoded in a software independent manner. With the Food Safety Knowledge Markup Language (FSK-ML) we now extend the PMF-ML format to enable the exchange of knowledge / information that is embedded in specific script-based programming languages (e.g. “R”, Matlab, Python). I.e. the FSK-ML guidance document primarily aims at harmonizing the exchange of food safety knowledge (e.g. predictive models) including the associated meta data where this knowledge is only available in a software dependent format. The FSK-ML format therefore relaxes and adapts certain specifications of the PMF-ML format while at the same time maintaining the highest possible synergies between both formats. This will also help to make sure that food safety models encoded in a software independent manner (using PMF-ML) can easily be interpreted by FSK-ML import and export software functions in the future.

## Importing an FSK file

The FSK2R packages includes the function import_fsk() for importing a model file compatible with the FSK-ML standard into R. This function has two arguments:

- `file_path`: the path to the FSK file.
- `check`: whether some automatic checks are made (`FALSE` by default).

The FSK2R package includes an example FSK file to use as teaching material. Additional files can be downloaded, for instance, in the RAKIP model repository (https://foodrisklabs.bfr.bund.de/rakip-model-repository-web-services/). The location of the example file can be retrieved with the following code.

    path_example <- system.file("extdata", "ToyModelv4.fskx", package = "FSK2R")
    print(path_example)

    ## [1] "C:/Users/alberto/AppData/Local/Temp/RtmpKeiY4U/Rinst182cfb32897/FSK2R/extdata/ToyModelv4.fskx"

In this vignette, we will use that example file to demonstrate the features included in FSK2R. To import the file into R, we just have to call `import_fsk()` with the path to the file as only argument.

    my_fsk <- import_fsk(path_example)

The function creates a list of class `FSK2R`.

    class(my_fsk)

    ## [1] "FSK2R" "list"

The package includes a function to test whether an object is an instance of `FSK2R`:

    is.FSK2R(my_fsk)

    ## [1] TRUE

The list of class `FSK2R` has several entries, each one corresponding to one file in the original FSK file.

    names(my_fsk)

    ##  [1] "manifest"       "metadata"       "model_metadata" "model"
    ##  [5] "packages"       "readme"         "simulation"     "R_model"
    ##  [9] "visualization"  "other_files"

The entry `manifest` is a `data.frame` which lists the location of all the files within the FSK file:

    my_fsk$manifest

    ## # A tibble: 15 x 4
    ##    format                            location             filename      filetype
    ##    <chr>                             <chr>                <chr>         <chr>
    ##  1 http://identifiers.org/combine.s~ .                    .             ""
    ##  2 https://www.iana.org/assignments~ ./Dose_matrix.csv    Dose_matrix.~ csv
    ##  3 http://purl.org/NET/mediatypes/a~ ./gridExtra_2.3.zip  gridExtra_2.~ zip
    ##  4 https://www.iana.org/assignments~ ./packages.json      packages.json json
    ##  5 http://purl.org/NET/mediatypes/t~ ./README.txt         README.txt    txt
    ##  6 http://purl.org/NET/mediatypes/a~ ./simulations/defau~ defaultSimul~ R
    ##  7 http://identifiers.org/combine.s~ ".\\metadata.rdf"    metadata.rdf  rdf
    ##  8 http://identifiers.org/combine.s~ ./manifest.xml       manifest.xml  xml
    ##  9 http://purl.org/NET/mediatypes/a~ ./model.sbml         model.sbml    sbml
    ## 10 http://purl.org/NET/mediatypes/a~ ./ggplot2_3.1.0.zip  ggplot2_3.1.~ zip
    ## 11 http://purl.org/NET/mediatypes/a~ ./visualization.r    visualizatio~ r
    ## 12 http://identifiers.org/combine.s~ ./sim.sedml          sim.sedml     sedml
    ## 13 http://purl.org/NET/mediatypes/a~ ./workspace.r        workspace.r   r
    ## 14 http://purl.org/NET/mediatypes/a~ ./model.r            model.r       r
    ## 15 https://www.iana.org/assignments~ ./metaData.json      metaData.json json

The entry `metadata` is a nested list including all the meta-information of the model. For further information about this item, go to the section Visualizing and editting the metadata of an FSK2R object of this manual.

The entry `model_metadata` includes the information that was defined in the metadata.rdf file of the FSK container. It is saved as a nested list.

The entry `model` includes all the information originally included in the model.sbml file. This includes (among others) the model parameters. It is a nested list:

    my_fsk$model

    ## $sbml
    ## $sbml$model
    ## $sbml$model$listOfParameters
    ## $sbml$model$listOfParameters$parameter
    ## $sbml$model$listOfParameters$parameter$annotation
    ## $sbml$model$listOfParameters$parameter$annotation$parameter
    ## list()
    ## attr(,"value")
    ## [1] "as.matrix(read.table(file =\"Dose_matrix.csv\",sep=\",\", header = TRUE, row.names=1))"
    ##
    ##
    ## attr(,"name")
    ## [1] "Dose_matrix"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "Dose_matrix"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## list()
    ## attr(,"name")
    ## [1] "nInf"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "nInf"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## list()
    ## attr(,"name")
    ## [1] "nIll"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "nIll"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## list()
    ## attr(,"name")
    ## [1] "meanPos"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "meanPos"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## list()
    ## attr(,"name")
    ## [1] "prev18"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "prev18"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## list()
    ## attr(,"name")
    ## [1] "prev100"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "prev100"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## list()
    ## attr(,"name")
    ## [1] "prev1000"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "prev1000"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## $sbml$model$listOfParameters$parameter$annotation
    ## $sbml$model$listOfParameters$parameter$annotation$parameter
    ## list()
    ## attr(,"value")
    ## [1] "0.04"
    ##
    ##
    ## attr(,"name")
    ## [1] "alpha"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "alpha"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## $sbml$model$listOfParameters$parameter$annotation
    ## $sbml$model$listOfParameters$parameter$annotation$parameter
    ## list()
    ## attr(,"value")
    ## [1] "0.055"
    ##
    ##
    ## attr(,"name")
    ## [1] "beta"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "beta"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## $sbml$model$listOfParameters$parameter$annotation
    ## $sbml$model$listOfParameters$parameter$annotation$parameter
    ## list()
    ## attr(,"value")
    ## [1] "0.00255"
    ##
    ##
    ## attr(,"name")
    ## [1] "eta"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "eta"
    ##
    ## $sbml$model$listOfParameters$parameter
    ## $sbml$model$listOfParameters$parameter$annotation
    ## $sbml$model$listOfParameters$parameter$annotation$parameter
    ## list()
    ## attr(,"value")
    ## [1] "0.086"
    ##
    ##
    ## attr(,"name")
    ## [1] "r"
    ## attr(,"constant")
    ## [1] "false"
    ## attr(,"id")
    ## [1] "r"
    ##
    ##
    ## attr(,"id")
    ## [1] "model"
    ##
    ## attr(,"level")
    ## [1] "3"
    ## attr(,"version")
    ## [1] "1"
    ## attr(,"xmlns")
    ## [1] "http://www.sbml.org/sbml/level3/version1/core"
    ## attr(,"xmlns:fsk")
    ## [1] "https://foodrisklabs.bfr.bund.de/wp-content/uploads/2017/01/FSK-ML_guidance_document_021216.pdf"

The entry `packages` is a `list` with all the R packages required by the model.

    my_fsk$packages

    ## $Language
    ## [1] "R 3"
    ##
    ## $PackageList
    ## $PackageList[[1]]
    ## $PackageList[[1]]$Package
    ## [1] "ggplot2"
    ##
    ## $PackageList[[1]]$Version
    ## [1] "3.1.0"
    ##
    ##
    ## $PackageList[[2]]
    ## $PackageList[[2]]$Package
    ## [1] "gridExtra"
    ##
    ## $PackageList[[2]]$Version
    ## [1] "2.3"
    ##
    ##
    ## $PackageList[[3]]
    ## $PackageList[[3]]$Package
    ## [1] "ggplot2"
    ##
    ## $PackageList[[3]]$Version
    ## [1] "3.1.0"
    ##
    ##
    ## $PackageList[[4]]
    ## $PackageList[[4]]$Package
    ## [1] "gridExtra"
    ##
    ## $PackageList[[4]]$Version
    ## [1] "2.3"

The entry `readme` includes the text defined in the README file:

    my_fsk$readme

    ## [1] "## FSK-Lab\nThis model is made available in the FSK-ML format, i.e. as .fskx file. To execute the model or to perform model-based predictions it is recommended to use the software FSK-Lab. FSK-Lab is an open-source extension of the open-source data analytics platform KNIME. To install FSK-Lab follow the installation instructions available at: https://foodrisklabs.bfr.bund.de/fsk-lab_de/. Once FSK-Lab is installed a new KNIME workflow should be created and the \"FSKX Reader\" node should be dragged into it. This \"FSKX Reader\" node can be configured to read in the given \".fskx\" file. To perform a model-based prediction connect the out-port of the \"FSKX Reader\" node with the \"FSK Simulation Configurator JS\" node to adjust if necessary input parameters and store this into a user defined simulation setting, After that connect the output port with the input of a FSK Runner node that perform the simulation and look at the results at the node's outport.\n## FSK-Lab"

The entry `simulation` is a nested list with the data defning the simulations. For more details on this item, go to section Running and editting simulations in the FSK file.

The entry `R_model` includes the code of the R model.

    cat(my_fsk$R_model)

    ## #########################################################################################
    ## # Code
    ## # Quantitative risk assessment of norovirus transmission in food establishments:
    ## # evaluating the impact of intervention strategies and food employee behavior on
    ## # the risk associated with norovirus in foods
    ## # Risk Analysis
    ## # January 2017
    ## #########################################################################################
    ##
    ## library(ggplot2)
    ## library(gridExtra)
    ##
    ##
    ## #Generation our Dose_matrix.csv file
    ## #save.image("I:/Norovirus at Retail Risk Assessment model/Original_nLoop1/workspace_Original_NoV_QRA.RData")
    ## #load("I:/Norovirus at Retail Risk Assessment model/Original_nLoop1/workspace_Original_NoV_QRA.RData")
    ## #dim(Dose_matrix)
    ## #write.csv(Dose_matrix, file = "Dose_matrix.csv")
    ##
    ## print("---> Starting simulation defined in the FSK-ML file...")
    ##
    ## ##################################
    ## ###### Does respone function #####
    ## ##################################
    ##
    ## DoseResponse <- function(Dose, model="Teunis"){
    ##   # See Teunis et al, 2008 model
    ##   Dose <- as.vector(Dose)
    ##
    ##
    ##   RiskInf <- 1-exp(lgamma(alpha+beta) + lgamma(beta+Dose)- lgamma(beta)- lgamma(alpha+beta+Dose))
    ##   PIllGivenInf <- 1 - (1 + Dose * eta)^(-r)
    ##   RiskIll <- RiskInf * PIllGivenInf
    ##   return(c(sum(RiskInf),sum(RiskIll)))
    ## }
    ##
    ##
    ## resFin <- NULL
    ##
    ## for(Scenario in 4){
    ##
    ##   #cat(Scenario,"\n")
    ##   #whereChains <- paste(PathToResults,Scenario,sep="")
    ##   #files <- list.files(whereChains)
    ##
    ##   #length(files)
    ##
    ##   res <- matrix(NA,nc=8,nrow=1000)
    ##   for(i in 1:1000){# cat(i)
    ##     #if((i %% 100) == 0) cat("*")
    ##     #load(paste(whereChains,files[i],sep="/"))
    ##     nCases <- apply(Dose_matrix,2,DoseResponse)
    ##     res[i,] <- c(mean=mean(Dose_matrix),prev=mean(Dose_matrix>0),meanPos=mean(Dose_matrix[Dose_matrix>0]),
    ##                  prev18 = mean(Dose_matrix>18), prev100=mean(Dose_matrix>100),prev1000=mean(Dose_matrix>1000),
    ##                  nInf=mean(nCases[1,]),    nIll=mean(nCases[2,]))
    ##
    ##   }
    ##   # cat("\n")
    ##   resFin <- rbind(resFin,c(apply(res,2,mean,na.rm=TRUE)))
    ##   # print()
    ##         #,
    ##                                  #as.vector(apply(res[,7:8],2,quantile,probs=c(.025,.5,.95,.975),na.rm=TRUE)))))
    ##   }
    ##
    ##
    ##
    ## colnames(resFin) <- c("Dose_matrix","prev","meanPos","prev18","prev100","prev1000","nInf","nIll")
    ## #,
    ##                       #"q025nInf","q050nInf","q950nInf","q975nInf",
    ##                       #"q025nIll","q050nIll","q950nIll","q975nIll")
    ##
    ## resFin
    ## res_df<-t(round(as.data.frame(resFin),2))

Finally, `visualization` contains the code of the visualization script:

    cat(my_fsk$visualization)

    ## qplot(1:10, 1:10, geom = "blank") + theme_bw() + theme(line = element_blank(), text = element_blank()) +
    ##   # Then I add my table :
    ##   annotation_custom(grob = tableGrob(res_df))
    ##

## Creating an FSK model based on an existing R file

The functions in the FSK2R package can be used to create a model compliant with the FSK-ML standard based on an already existing R script. This can be accomplished using the `create_fsk()` function. It has five arguments:

- `r_model`: the path to the R script where the model is defined.
- `r_visualization`: the path to the visualization script (optional).
- `readme`: A character describing the contents of the README file (optional).
- `other_files`: the path to other files that may be required by the model (optional).
- `pckg_frame`: a `data.frame` describing the dependencies. It must have two columns: `Package` (the package name) and `Version` the package version (optional).

The FSK2R includes an example model file and an example visualization file that can be used for learning purposes. The path of the model file can be found with:

    model_path <- system.file("extdata", "model.r", package = "FSK2R")
    print(model_path)

    ## [1] "C:/Users/alberto/AppData/Local/Temp/RtmpKeiY4U/Rinst182cfb32897/FSK2R/extdata/model.r"

And the one of the visualization file:

    visualization_path <- system.file("extdata", "visualization.r", package = "FSK2R")
    print(visualization_path)

    ## [1] "C:/Users/alberto/AppData/Local/Temp/RtmpKeiY4U/Rinst182cfb32897/FSK2R/extdata/visualization.r"

We can create a new FSK object by passing both paths to the `create_fsk()` function. The remaining arguments will be left to their default values and the information will be filled in later.

    FSK_from_R <- create_fsk(model_path, visualization_path)

The variable `FSK_from_R` now contains an instance of class `FSK2R`.

    class(FSK_from_R)

    ## [1] "FSK2R" "list"

It has the common structure of this object, compatible with the FSK-ML format.

    names(FSK_from_R)

    ## [1] "manifest"       "metadata"       "model_metadata" "model"
    ## [5] "packages"       "readme"         "simulation"     "R_model"
    ## [9] "visualization"

The function generates the typical `model_metadata`

    FSK_from_R$model_metadata

    ## $Description
    ## $Description$conformsTo
    ## [1] "2.0"
    ##
    ## $Description$.attrs
    ## about
    ##   "."
    ## attr(,"namespaces")
    ## http://www.w3.org/1999/02/22-rdf-syntax-ns#
    ##                                       "rdf"
    ##
    ##
    ## $Description
    ## $Description$type
    ## [1] "visualizationScript"
    ##
    ## $Description$.attrs
    ##              about
    ## "/visualization.r"
    ## attr(,"namespaces")
    ## http://www.w3.org/1999/02/22-rdf-syntax-ns#
    ##                                       "rdf"
    ##
    ##
    ## $Description
    ## $Description$type
    ## [1] "workspace"
    ##
    ## $Description$.attrs
    ##          about
    ## "/workspace.r"
    ## attr(,"namespaces")
    ## http://www.w3.org/1999/02/22-rdf-syntax-ns#
    ##                                       "rdf"
    ##
    ##
    ## $Description
    ## $Description$type
    ## [1] "modelScript"
    ##
    ## $Description$.attrs
    ##      about
    ## "/model.r"
    ## attr(,"namespaces")
    ## http://www.w3.org/1999/02/22-rdf-syntax-ns#
    ##                                       "rdf"
    ##
    ##
    ## $Description
    ## $Description$type
    ## [1] "readme"
    ##
    ## $Description$.attrs
    ##         about
    ## "/README.txt"
    ## attr(,"namespaces")
    ## http://www.w3.org/1999/02/22-rdf-syntax-ns#
    ##                                       "rdf"

## Running and editting simulations in the FSK file

The FSK2R package is able to run the simulations defined in an FSK-ML model, as long as they are written in the R programming language. The model

    is_fsk_with_r(FSK_from_R)

    ## [1] TRUE

The number of models included in `FSK_from_R` can be checked with the `n_simuls_fsk()` function included in FSK2R:

    n_simuls_fsk(FSK_from_R)

    ## [1] 1

In this case, the FSK model includes a single simulation. It can be run with the function `run_simulation()`. This function takes three arguments:

- `fsk_object`: an instance of FSK2R.
- `index`: an identifier for the simulation.
- `run_visualization`: whether to run the visualizatino script (FALSE by default).

Because `my_fsk` only has one simulation, we will set `index = 1`. When the function is called without specifying that the visualization script shall be run, the simulation is run silently (besides any `print` or `cat` defined in model.R):

    run_simulation(FSK_from_R, 1)

In order to run the simulation, `run_visualization` must be set to TRUE.

    run_simulation(FSK_from_R, 1, TRUE)

The FSK2R package can be used to define new simulations for the model using the function `set_new_simulation()`. It has three arguments:

- `fsk_object`: an instance of FSK2R.
- `simulation_id`: an identificator for the new simulation.
- `parameters`: a list describing what parameters to change.

Because of the scoping rules of R, the function does not change the `fsk_object` in place. Instead, it returns a copy of the FSK2R list with the additional information about the simulations added.

    new_model <- set_new_simulation(my_fsk, "new",
                                    list(r = 0.09,
                                         Dose_matrix = "as.matrix(read.table(file =\"Dose_matrix.csv\",sep=\",\", header = TRUE, row.names=1))",
                                         alpha = 0.05,
                                         beta = 0.045,
                                         eta = 0.003
                                         )
                                    )

We can now check that `new_model` has one new simulation than the original model:

    n_simuls_fsk(new_model)

    ## [1] 2

The new simulation can be run using the `run_simulation` function as shown above. The package also has the function `run_all_simulations` to run every simulation included in the model.

## Setters and getters

The FSK2R package includes several functions to query and edit the contents of a FSK-ML compliant model. This section describes them, except for those used for the metadata, which as presented in the following section.

The object `FSK_from_R` that we defined before did not have a readme. It can be defined with the function `set_readme()` included in FSK2R. This function takes two arguments:

- `fsk_object` an instance of FSK2R.
- `readme_text` A character string with the README text.

Note that this function does not directly update `fsk_object`. Instead, it returns a copy with the updated information.

    readme_text <- "This is an FSK-ML compliant model generated based on an existing R script"
    FSK_from_R <- set_readme(FSK_from_R, readme_text)

Then, the FSK2R package includes several functions to query the contents of an instance of `FSK2R`. For instance, we can retrieve the README content we just defined with `get_readme()`:

    get_readme(FSK_from_R)

    ## [1] "This is an FSK-ML compliant model generated based on an existing R script"

Furthermore, the data used for the simulations can also be retrieved with `get_simulations()`:

    # get_simulations(my_fsk)

## Visualizing and editting the metadata of an FSK2R object

The FSK2R package implements several getters specific for summarizing the metadata of an `FSK2R` object. All of them take an object of class `FSK2R` as argument and return a nested list with the relevant information.

The function `get_general_info()` summarizes the general metainformation of the model:

    get_general_info(my_fsk)

    ## $name
    ## [1] "Toy Model for Testing Purposes"
    ##
    ## $source
    ## [1] "UNPUBLISHED STUDIES (EXPERIMENTS-OBSERVATIONS): Studies and surveys"
    ##
    ## $identifier
    ## [1] "Toy_Model_Generic_03"
    ##
    ## $creationDate
    ## [1] "2018-04-19T22:00:00"
    ##
    ## $rights
    ## [1] "Creative Commons Attribution-NonCommercial 4.0"
    ##
    ## $language
    ## [1] "English"
    ##
    ## $software
    ## [1] "R"
    ##
    ## $creators
    ## # A tibble: 2 x 11
    ##   eClass title familyName givenName email telephone streetAddress country city
    ##   <chr>  <chr> <chr>      <chr>     <chr> <chr>     <chr>         <chr>   <chr>
    ## 1 http:~ Dr.   Romanov    Natalia   blac~ 030 12345 Nahmitzer Da~ Russia~ Berl~
    ## 2 http:~ Mr.   Parker     Peter     pete~ 03301 13~ Am Kleinen W~ United~ Pots~
    ## # ... with 2 more variables: region <chr>, organization <chr>
    ##
    ## $reference
    ## # A tibble: 3 x 11
    ##   eClass isReferenceDesc~ publicationType publicationDate doi   authorList
    ##   <chr>  <chr>            <chr>           <chr>           <chr> <chr>
    ## 1 http:~ TRUE             Pamphlet        2019-03-05T13:~ 10.5~ Jack Baue~
    ## 2 http:~ TRUE             <NA>            2019-03-05T13:~ 10.1~ James Bon~
    ## 3 http:~ TRUE             Dictionary      2019-03-05T13:~ 10.1~ Jack Ryan~
    ## # ... with 5 more variables: publicationTitle <chr>, publicationAbstract <chr>,
    ## #   publicationStatus <chr>, publicationWebsite <chr>, comment <chr>

The function `get_scope()` returns the scope of the model:

    get_scope(my_fsk)

    ## $product
    ## # A tibble: 3 x 12
    ##   eClass productName productDescript~ productUnit productionMethod packaging
    ##   <chr>  <chr>       <chr>            <chr>       <chr>            <chr>
    ## 1 http:~ Lettuce     fresh german le~ g           Organic product~ Packed
    ## 2 http:~ Tomatoes    not so fresh     g           Genetically mod~ Cardboar~
    ## 3 http:~ Meat, prep~ pretty much any~ g           Farmed Domestic~ Vacuum p~
    ## # ... with 6 more variables: productTreatment <chr>, originCountry <chr>,
    ## #   originArea <chr>, fisheriesArea <chr>, productionDate <chr>,
    ## #   expiryDate <chr>
    ##
    ## $hazard
    ## # A tibble: 3 x 14
    ##   eClass hazardType hazardName hazardDescripti~ hazardUnit adverseEffect
    ##   <chr>  <chr>      <chr>      <chr>            <chr>      <chr>
    ## 1 http:~ Organic c~ norovirus~ novovirus is de~ CFU        morbitity
    ## 2 http:~ Microorga~ Salmonell~ we dont know ho~ Fill       mortality
    ## 3 http:~ Food addi~ Monoammon~ tastes great bu~ fg/mL      obesity
    ## # ... with 8 more variables: sourceOfContamination <chr>,
    ## #   maximumResidueLimit <chr>, noObservedAdverseAffectLevel <chr>,
    ## #   lowestObservedAdverseAffectLevel <chr>,
    ## #   acceptableOperatorExposureLevel <chr>, acuteReferenceDose <chr>,
    ## #   acceptableDailyIntake <chr>, benchmarkDose <chr>

The function `get_background()` returns the background information of the model:

    get_background(my_fsk)

    ## $studyTitle
    ## [1] "Assessment of integrity of metadata in FKS Lab and associated services"
    ##
    ## $studyDescription
    ## [1] "This Study will show, wether the FSK Lab will correctly read and run a generic and fully annotated model"

The function `get_modelmath()` returns the metainformation of the model parameters:

    get_modelmath(my_fsk)

    ## $parameter
    ## # A tibble: 11 x 16
    ##    eClass parameterID parameterClassi~ parameterName parameterDescri~
    ##    <chr>  <chr>       <chr>            <chr>         <chr>
    ##  1 http:~ Dose_matrix Input            Dose_matrix   matrix with GEC~
    ##  2 http:~ nInf        Output           nInf          number of infec~
    ##  3 http:~ nIll        Output           nIll          number of ill i~
    ##  4 http:~ meanPos     Output           meanPos       mean number of ~
    ##  5 http:~ prev18      Output           prev18        proportion of s~
    ##  6 http:~ prev100     Output           prev100       proportion of s~
    ##  7 http:~ prev1000    Output           prev1000      proportion of s~
    ##  8 http:~ alpha       Input            alpha         Alpha parameter~
    ##  9 http:~ beta        Input            beta          Beta parameter ~
    ## 10 http:~ eta         Input            eta           Eta parameter i~
    ## 11 http:~ r           Input            r             R parameter in ~
    ## # ... with 11 more variables: parameterUnit <chr>, parameterUnitCategory <chr>,
    ## #   parameterDataType <chr>, parameterSource <chr>, parameterSubject <chr>,
    ## #   parameterDistribution <chr>, parameterValue <chr>,
    ## #   parameterVariabilitySubject <chr>, parameterValueMin <chr>,
    ## #   parameterValueMax <chr>, parameterError <chr>

The package also includes functions for updating the metadata based on the template available online: https://docs.google.com/spreadsheets/d/12ujuQn49Gp2F-zMbCAgsu9wYfLjooeR2c2Ec1zkLkl0/edit#gid=766274181.

For ease of use, the package includes the function `download_metadata_schema()` to download the latest version of the Metadata Template (at the moment of the package update to CRAN). This function takes as only argument the path where to save the template as a text file. Note that this function may request the user to authenticate with his/her gmail account name and password. This information is handled by the googlesheets package and is not, under any circumnstance, accesible to the FSK2R package.

    # download_metadata_schema("my_template.xlsx")

The FSK2R package includes functions to update the metainformation in an instance of `FSK2R` with the data defined in a Metadata Template (either in Excel or GoogleSheets format). The function `read_fsk_metadata()` is used for templates created in GoogleSheets and the function `read_fsk_metadata_excel()` for those created in Excel and saved locally. Both functions takes three arguments:

- `fsk_object`: The instance of `FSK2R` to update.
- `title` (only `read_fsk_metadata()`): Title of the GoogleSheet where the metadata is stored.
- `path` (only `read_fsk_metadata_excel()`): Path where the Metadata Template is saved.
- `type_of_model`: Type of model.

Note that the function `read_fsk_metadata()` may request the user to authenticate with his/her gmail account name and password. This information is handled by the googlesheets package and is not, under any circumnstance, accesible to the FSK2R package.

For training purposes, the FSK2R package includes an example Metadata Template in excel format. The path where it is saved can be accessed with the following command.

    template_path <- system.file("extdata", "example_template.xlsx", package = "FSK2R")
    print(template_path)

    ## [1] "C:/Users/alberto/AppData/Local/Temp/RtmpKeiY4U/Rinst182cfb32897/FSK2R/extdata/example_template.xlsx"

We will use the data in the template to populate the metadata of the FSK-ML compliant file that we generated from an R script.

    FSK_from_R <- read_fsk_metadata_excel(FSK_from_R, template_path)

    ## New names:
    ## * `` -> ...2
    ## * `` -> ...3

    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"
    ## Joining, by = "my_name"

## Exporting the FSK file

Finally, the package includes the function `export_fsk()` for exporting the instance of `FSK2R` as a file compliant with the FSK-ML format. This function takes two arguments:

- `fsk_object`: the instance of `FSK2R` to export.
- `out_path`: the path where to save the file.
- `check`: whether some checks on the file are performed (TRUE by default).

As a demonstration, we will export the object `my_fsk` as an FSK-ML compliant file called out.fskx.

    export_fsk(my_fsk, out_path=file.path(tempdir(), "out.fskx"))

    ## Warning in file.copy(fsk_object$other_files, out_path): problema al copiar
    ## C:\Users\alberto\AppData\Local\Temp\RtmpExQzYA\.\gridExtra_2.3.zip a C:
    ## \Users\alberto\AppData\Local\Temp\RtmpExQzYA\\FSK_3061\gridExtra_2.3.zip: No
    ## such file or directory

    ## Warning in file.copy(fsk_object$other_files, out_path): problema al copiar
    ## C:\Users\alberto\AppData\Local\Temp\RtmpExQzYA\.\ggplot2_3.1.0.zip a C:
    ## \Users\alberto\AppData\Local\Temp\RtmpExQzYA\\FSK_3061\ggplot2_3.1.0.zip: No
    ## such file or directory

This file can be imported back into R using the `import_fsk()` function, as usual.

    imported_model <- import_fsk(file.path(tempdir(), "out.fskx"))