GithubHelp home page GithubHelp logo

r-toolbox's Introduction

OLD version of the R-toolbox (based on the OSP Suite 8 and below). New version of the R-Toolbox (OSP 9 and above) can be found in the OSPSuite-R repository

About the Toolbox

The R Toolbox is a collection of R functions which allows the processing of models developed in PK-Sim® or MoBi® from within R. A variety of functions is offered to manipulate models, to simulate models, and to handle simulation results. The functions are designed very similar to the functions that are provided with the MoBi® Toolbox for Matlab®. Details are available in the build-in help of R upon loading the R package.

Installing the R Toolbox

The R Toolbox is provided to the user as a zip file. This zip file can be found under "C:\Program Files\Open Systems Pharmacology\MoBi Toolbox for R X.Y\MoBiToolboxForR__X.Y.Z_.zip" . The standard package install via zip files is used. On Windows, install.packages can install a binary package from a local zip file by setting argument repos to NULL. Rgui.exe has a menu Packages with a GUI interface to install.packages that may be used.

The R Toolbox is only available for the 64bit R (versions 3.5 or later).

Getting Started

  • Install nuget and add nuget.exe to your path
  • Install ruby version 2.2 or higher
  • clone the repository with recursive option
git clone <url.git> --recursive
  • restore nuget packages manually
nuget restore packages.config -PackagesDirectory packages
  • create the package and setup
rake create_setup[7.4.0]

Code Status

Build status

Code of conduct

Everyone interacting in the Open Systems Pharmacology community (codebases, issue trackers, chat rooms, mailing lists etc...) is expected to follow the Open Systems Pharmacology code of conduct.

Contribution

We encourage contribution to the Open Systems Pharmacology community. Before getting started please read the contribution guidelines. If you are contributing code, please be familiar with the coding standards.

License

R-Toolbox is released under the GPLv2 License.

r-toolbox's People

Contributors

candidethunder avatar msevestre avatar onwhenrdy avatar pavelbal avatar yuri05 avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

r-toolbox's Issues

Round brackets () in path names should be escaped authomatically

Path names which contain brackets, e.g., "Param (a)", must be specified as "Param \(a\)" by the user. This is inconvenient, and should be performed in the background.

Suggestion is to add

searchValue <- gsub('(', '\\(', searchValue, fixed = TRUE)
searchValue <- gsub(')', '\\)', searchValue, fixed = TRUE)

after this line

searchValue <- gsub('&', '\\&', searchValue, fixed = TRUE)

Add "skip" property to initializeIfFormula in initiParameter/initSpeciesInitialValue

During initialization of parameters/species, the onces defined by the formula can be handeled differently. For this, the functions "initParameter" and "initSpeciesInitialValue" have an argument "initializeIfFormula" with three possible states:

"never": If the parameter is a formula, initSimulation() will produce an error
"always": If the parameter is a formula, initSimulation() will silently succeed
"withWarning": The parameter will be initialized, but a warning will be displayed.

What I miss is another option:
"skip": the parameter will be not initialized, but initSimulation() will still succeed.

Possible use case - I have two version of a model with a certain parameter "X". In one model, "X" is a constant, in another it is a formula. In R-code, I only want to initialize "X" if it is constant. WIth having the "skip" option, I coud use the same code for the both models.

processSimulation(): include TryCatch error-handling

In Matlab, return value of processSimulation() was boolean to flag if simulation was successful, but it would always continue, no matter what.

Now in R, return value is taken up by DCI_Info, and failed simulations are handled with errors.
I am building my own tryCatch() routine around processSimulation, but maybe we should integrate sth. in processSimulation (maybe optional so it can be set via the function inputs like "stopOnErrors" or "continueWithWarning"...) so it can be used easily.

Thoughts?

Typo in documentation of initParameter

The documentation states:

initializeIfFormula | Should the parameter be initialized if it contains a formula? ("never", "allways", "withWarning")

It must be "always" and not "allways".

initSpeciesInitialValue(): if the same path_id is initialized once again with different initializeIfFormula-Property, the old one is still used

If a certain parameter, defined by a formula, is initialized with the flag "initializeIfFormula = "never"", initialization fails (as expected):

> initStruct = list()
> initStruct = initSpeciesInitialValue(initStruct = initStruct, path_id = "*|Organism|RHS_Param_formulaInit", initializeIfFormula = "never"); DCI_inf = initSimulation(testXML, ParamList = initStruct)
Error in initParameterStruct(ParamList, TableArray[[id]], id, DCI_Info) : 
  The SpeciesInitialValue is defined as Formula:  If you want to inititalize this species initial value do not use option 'never' for the function initParameter testSim|Organism|RHS_Param_formulaInit 5+6

If I try to initialize the parameter again, but with "initializeIfFormula = "always"" without clearing initStruct, the new value is not applied:

initStruct = initSpeciesInitialValue(initStruct = initStruct, path_id = "*|Organism|RHS_Param_formulaInit", initializeIfFormula = "always"); DCI_inf = initSimulation(testXML, ParamList = initStruct)
Error in initParameterStruct(ParamList, TableArray[[id]], id, DCI_Info) : 
  The SpeciesInitialValue is defined as Formula:  If you want to inititalize this species initial value do not use option 'never' for the function initParameter testSim|Organism|RHS_Param_formulaInit 5+6

This is against my expectations, as I am expecting the last initialization being the valid one. I propose to change the behavior.

initSpeciesInitialValue(initializeIfFormula = "never") does not initialize a species even if it is no forumula

Parameter a is not defined by a formula

#Try to initialize with "never"
initStruct <- list()
initStruct <- initSpeciesInitialValue(initStruct, "*|Organism|a" , initializeIfFormula = "never")
DCI_Info_opt <- initSimulation(xmlSF_opt, ParamList = initStruct)

length(DCI_Info_opt$InputTab$VariableSpecies$Path)
# Returns 0, indicating that not species initial values are variable

getSpeciesInitialValue(path_id ="*|Organism|a", list(Type = "readonly", Property = "IsFormula", Index = idx), DCI_Info=DCI_Info_opt)$Value
# Returns 0, indicating that "*|Organism|a" is not a formula

#Try to initialize with "withWarning"
initStruct <- list()
initStruct <- initSpeciesInitialValue(initStruct, "*|Organism|a" , initializeIfFormula = "withWarning")
DCI_Info_opt <- initSimulation(xmlSF_opt, ParamList = initStruct)

length(DCI_Info_opt$InputTab$VariableSpecies$Path)
# Returns 1, indicating that one species initial values is variable

Run R Unit tests on CI

Apparently there are Unit tests in R!! Woot woot. But...we are not running them before creating the package which is not so great.

An awesome feature would be to be able to run those tests via command line from the CI Server.
Right now we are performing quite a bunch of stuff to package the code into an R package etc..
Especially we have to install

  • R
  • R Tools.

Is there a way to run those unit tests ? A simple command line would be enough.

The appveyor script could be updated to run all tests upon commit and would fail if one or more test is failing.

Anyone?

R toolbox: setSimulationTime fails if number of time interval is changed

setSimulationTime can be used to set one or several simulation time intervals. If the simulation contains e.g. 2 intervals, and that is overwritten to 1 interval, processSimulation fails.

See attached example code.
tests.zip

simModelXML <- "./models/black american girl.xml"
dci_info <- initSimulation(XML=simModelXML, whichInitParam="none")
length (dci_info$InputTab$TimeSchema$StartTime) #2 -> two different time intervals

processSim

ulation(DCI_Info=dci_info) # works!

dci_info <- setSimulationTime(c(1:60, timepoints=(0:7)*60), DCI_Info=dci_info) # two different time intervals
processSimulation(DCI_Info=dci_info) # works!

dci_info <- setSimulationTime(c(1:60), DCI_Info=dci_info) # one time interval
processSimulation(DCI_Info=dci_info) # not working!

# Error in processSimulation(DCI_Info = dci_info) : 
#   Unknown interval distribution type passed: 


runit.getParameter.R -> test.CheckParameterInSimulationNoneVariables not clear what it should do

I cannot really understand what the above mentioned test should check for.

My first expectation whas that it checks whether certain parameters (of the type "current) can be accessed even when no parameters were initialized.

  dci_info <- standard_dci_info
  options <- list(Type="current")
  parameter <- getParameter(path_id=113, DCI_Info = dci_info, options=options)

  checkEquals(names(parameter), c("Value","Index"))
  checkEquals(dci_info$InputTab$AllParameters$Value[parameter$Index], parameter$Value)

According to the XML of the model, the parameter with path_id=113 is "black american girl|Organism|Muscle|Plasma|my Compound|concentration". When getting this parameter with its numerical ID (how performed in the test), everything works fine:

> parameter <- getParameter(path_id=113, DCI_Info = dci_info, options=options)
> parameter
$Value
[1] 0

$Index
[1] 2986

When trying to do the same with the path string (which is not performed in the tests, but should be!), the parameter cannot be found:

> parameter <- getParameter(path_id="black american girl|Organism|Muscle|Plasma|my Compound|concentration", DCI_Info = dci_info, options=options)
> parameter
$Value
numeric(0)

$Index
[1] 0

Problem is,

  checkEquals(names(parameter), c("Value","Index"))
  checkEquals(dci_info$InputTab$AllParameters$Value[parameter$Index], parameter$Value)

still evaluate to TRUE, as dci_info$InputTab$AllParameters$Value[0] also returns numeric(0)! I.e., the test is always sucessfull.

So is there a bug in the test function, or am I getting the purpose of this test all wrong?

loading error

Hi,
I have installed the MoBi R toolbox and it successfully unpacked but when I try to load the library, I get this error:

Error: package ‘MoBiToolboxForR’ is not installed for 'arch = x64'

getParameter() stops when the given parameter is not found

The behavior of getParameter() (and also of getTableParameter()) is that it stops when the provided parameter is not found, interrupting the code. This is OK and should be managed by try-catch construct when the user searches for a parameter.

First problem:The try-catch hint should be placed to the documentation of the method - does R documentation has an extra block for the exceptions/errors the method can produce?

Second problem: No user probably knows of this behavior, because getParameter() ALWAYS returned something, even if the parameter is not in the simulation (or not for the specific type). In that case, the output was

$Value
numeric(0)

$Index
[1] 0

and everything happily proceeded with this output. Now that this is fixed and getParameter() behaves like it was supposed to behave (stopping when the parameter is not found), the users would be surprised to see their code "broken".

Third problem: Searching for all parameters, e.g., by getParameter("*", list(Type="variable"), DCI_Info = myDCI) can also cause errors. Instead, the method getParameterStatus should be used.

So this "new - old" behavior should be mentioned in the next release notes.

OR: whe change the behavior of getParameter/getTableParameter/getSpeciesInitialValue in that way that it ALWAYS will return a list with the columns "value" and "Index". If the given parameter is not found, the lenght of this list would be zero. Additionally, a warning message is to be displayed.

Submit R-Toolbox to CRAN

I recently gave a workshop on the R-Toolbox and was asked why the toolbox is not released on CRAN. What do you think, would it be an option?

Having the package on CRAN could help to increase the acceptance of the toolbox. In theory, the users could exchange their models as XML and use them in R, without having the need to install the whole OSP suite.

New function request: Scaling between species

It should be possible to scale an existing model to the physiology of another species from within the toolbox. E.g., if a human to a mouse model.

The problem is described here: #378. In short, the structures differ between species, so simply applying the parameter sets of a respective species leads to faulty models.

We should agree on a strategy here. The desired behavior is that of the "Scale"-function in PK-Sim. Support from the PK-Sim core team would be of great help, as they know best what the differences are.

getParameter() fails when parameter is accessed via path name and no variables were initialized.

Problem:

When trying the get a parameter via path name from a simulation with no initialized parameters, a zero-index is returned.


standard_dci_info <- initSimulation(XML=simModelXML, whichInitParam="none")
getParameter(path_id="black american girl|Organism|Age", DCI_Info = dci_info, options=options)

$Value
numeric(0)

$Index
[1] 0

Accessing the same parameter via numerical id works:

getParameter(path_id=48, DCI_Info = dci_info, options=options)

$Value
[1] 0

$Index
[1] 35

Confusion about parameters, species, and their types in the DCI

QC_R.zip

I am really confused about the concept of what is a parameter, what is a species, and what types they may have.

Consider the attached test model created in MoBi. It is a simple model with one compartment "Organism" and two molecules. No reactions or processes are defined.

There are three parameters of the compartment "Organism":

  1. "constantParam" with a constant value "0".
  2. "RHS_Param_constantInit", a state variable with a constant initial value "0"
  3. "RHS_Param_formulaInit", a state variable with the initial value defined by the formula "5+6".

There are two molecules:

  1. "myMolecule_constant" with the constant start value "0"
  2. "myMolecule_formula" with the start value defined by the formula "0".

The exported XML is also attached.

Now, loading this simulation in R.

library(MoBiToolboxForR, quietly=TRUE)

testXML = ".\\QC_R\\testSim.xml"
DCI_Info_test <- initSimulation(testXML, whichInitParam = "none")

Question 1: DCI_Info_test has the lists "InputTab" and "ReferenceTab". What do they mean?

The lists in the "InputTab":

  1. AllParameters:
> DCI_Info_test[["InputTab"]][["AllParameters"]][["Path"]]
 [1] "testSim|Organism|Volume"                            "testSim|Organism|constantParam"                    
 [3] "testSim|Organism|myMolecule_constant"               "testSim|Organism|myMolecule_constant|Concentration"
 [5] "testSim|Organism|myMolecule_formula"                "testSim|Organism|myMolecule_formula|Concentration" 
 [7] "AbsTol"                                             "RelTol"                                            
 [9] "H0"                                                 "HMin"                                              
[11] "HMax"                                               "MxStep"                                            
[13] "UseJacobian"                                       
attr(,"Name")
[1] "Path"
attr(,"Description")
[1] ""

Question 2: Why are the values of "testSim|Organism|myMolecule_constant" and "testSim|Organism|myMolecule_formula" included in the "AllParameters" list? They are species and not parameters, right? Even if the "species" were optimized to "Parameters" because they are constant (no transport processes, no reactions), it is veeeery confusion for the user, because I would expect to find my molecules under "species".

  1. AllSpecies:

> DCI_Info_test[["InputTab"]][["AllSpecies"]][["Path"]]
[1] "testSim|Organism|RHS_Param_constantInit" "testSim|Organism|RHS_Param_formulaInit" 
attr(,"Name")
[1] "Path"
attr(,"Description")
[1] ""

This time, species turned into parameters! OK, I got the concept of "state variables" being actually species and not parameters, but only because I asked @Yuri05 once.

And while the concept that a state variable is not a parameter but a species can be accepted (but not without proper documentation!!!), the other way around is a no-go, because the user cannot know, when a species (e.g., a modeled molecule) will turn into parameter!

Question 3: What do the types "VARIABLE", "READONLY", "CURRENT", "REFERENCE", mean?

Question 4: If a species (or a parameter) is initialized, it will appear in the list DCI_Info_test$InputTab$VariableSpecies, but still be also listed in DCI_Info_test$InputTab$AllSpecies. What happens, if any value is changed in VariableSpecies, but not in AllSpecies, or the other way around?

setSimulationTime should simply foward time points to SimModel instead of creating intervals

see discussion here
#10

and code here

In my eyes, the current implementation is overly complicated. The method setSimulationTime should simply forward the given time points array "AS IS" to SimModel as discrete time values array are supported.

The caller of the method would be responsible to define the interval as needed and the R code would do nothing more than forward the array by setting the expected properties into DCI_info

I do not see the need of supporting interval in R. The definition of a sequence is trivial in R via the seq method e.g. seq(0,12,2)

@Yuri05 @StephanSchaller @PavelBal
Thoughts ?

runit.saveSimulationToXML fails

test.CheckXMLAllVariables: FAILURE !! (check number 1) Error in checkEquals(dci_info[idx], savedDCI[idx]) : Component “InputTab”: Component “AllParameters”: Component “Value”: Mean absolute difference: Inf Component “InputTab”: Component “AllParameters”: Component “ParameterType”: 2629 string mismatches Component “InputTab”: Component “AllParameters”: Component “Formula”: 2629 string mismatches Component “InputTab”: Component “VariableParameters”: Component “Value”: Mean absolute difference: Inf Component “InputTab”: Component “VariableParameters”: Component “ParameterType”: 2629 string mismatches Component “InputTab”: Component “VariableParameters”: Component “Formula”: 2629 string mismatches Component “InputTab”: Component “AllSpecies”: Component “IsFormula”: Mean relative difference: 1 Component “InputTab”: Component “AllSpecies”: Component “Formula”: 205 string mismatches Component “InputTab”: Component “VariableSpecies”: Component “IsFormula”: Mean relative difference: 1 Component “InputTab”: Component “VariableSpecies”: Component “Formula”: 205 string mismatches Component “ReferenceTab”: Component “AllParameters”: Component “Value”: Mean absolute difference: Inf Component “ReferenceTab”: Component “AllParameters”: Component “ParameterType”: 2629 string mismatches Component “ReferenceTab”: Component “AllParameters”: Component “Formula”: 2629 string mismatches Component “ReferenceTab”: Component “VariableParameters”: Component “Value”: Mean absolute difference: Inf Component “ReferenceTab”: Component “VariableParameters”: Component “ParameterType”: 2629 string mismatches Component “ReferenceTab”: Component “VariableParameters”: Component “Formula”: 2629 string mismatches Component “ReferenceTab”: Component “AllSpecies”: Component “IsFormula”: Mean relative difference: 1 Component “ReferenceTab”: Component “AllSpecies”: Component “Formula”: 205 string mismatches Component “ReferenceTab”: Component “VariableSpecies”: Component “IsFormula”: Mean relative difference: 1 Component “ReferenceTab”: Component “VariableSpecies”: Component “Formula”: 205 string mismatches

@PavelBal

Remove check for manual escaping of the path in findTableIndex.R in future releases

Escaping of special characters like "(" and ")" in parameters paths is managed by the R code. This was not always the case, so users may have used manual escaping like "\(". The code checks for such escapings and gives a warning:

for (symbol in c("\\(", "\\)", "\\[", "\\]")){
if (grepl(symbol, path_id, fixed = TRUE)){
warning(paste(path_id, ": Escaping of the characters '(', ')', '[', and '[' in path names should not be done manually!"), immediate. = TRUE )
break
}
}

In future releases, this check should be removed.

Error when two simulations are initilized consequentially without being run in between

DCI1 <- initSimulation(xml1,initStruct)
DCI2 <- initSimulation(xml2,initStruct)
# run the original simulations
DCI1 <- processSimulation(DCI_Info = DCI1)
DCI2 <- processSimulation(DCI_Info = DCI2)

results in

 Error in updateSimulationInputs(DCI_Info) : 
  Component handle 258639328 is invalid! 

, while


DCI1 <- initSimulation(xml1,initStruct)
DCI1 <- processSimulation(DCI_Info = DCI1)

DCI2 <- initSimulation(xml2,initStruct)
DCI2 <- processSimulation(DCI_Info = DCI2)

works.

new function request: setScaleDivisorsAfterSim()

As name says, I would like to write a function, that calculates and then sets the scale divisors as you can do within MoBi after you have run a simulation.
For this, I have a few questions, as my first tries failed (DCI_Info got corrupted and simulation failed), maybe someone (@msevestre, @Yuri05 ?) can help:

  1. How is the divisor calculated in MoBi. From looking at the values it may be the geometric mean? Correct?
  2. Now, I have to know, where to write the value in the DCI_Info: from looking at the DCI_Info, there are a number of places:
    a. DCI_Info$InputTab$AllSpecies$ScaleFactor
    b. DCI_Info$InputTab$VariableSpecies$ScaleFactor
    c. DCI_Info$ReferenceTab$AllSpecies$ScaleFactor
    d. DCI_Info$ReferenceTab$VariableSpecies$ScaleFactor

Do I have to write them anywhere else? and...
3. are there any exceptions to the rule..i.e. do you skip any special species when setting the divisor (maybe Lumen, or EndosomalClearance)

Any help appreciated,
thanks, Stephan

Create x64 bit package of the R-Toolbox

We have started the move to 64 bit, at least for the very core components. SimModel is now available in 64 bit and the next step would be to start moving the toolboxes to see if any issues arise

Update DCI

Once DCI was moved to VS2017, update used components

Changing scale factors as distinct function

Setting scale factors of species should be performed by calling a method (to be created) setScaleFactor(scaleFactor, path_id). The method can be called after initSimulation without the need of setting the respective species variable.

At the same time, I propose to remove the ability to change scale factors via setSpeciesInitialValue(scaleFactor, options = list(Property = "ScaleFactor", Index = idx), DCI_Info=DCI_Info_opt) to avoid redundance. This will not destroy any previous code since setting scale factors never worked as expected.

The respective unit test must be adapted as well.

Please assign to me.

OSPSuite.Schema.xsd missing from package.

Hi MoBiToolboxForR developer

I would like to know where I can find the MoBiToolboxForR.zip file in Open Systems Pharmacology Suite v7.2.2 installation folder?

Thanks

runit.setParameter fails

test.SetParameterEffectOnFormular: FAILURE !! (check number 1) Error in checkTrue(getParameter("*|Effective molecular weight", DCI_Info = dci_info)$Value < : Test not TRUE

@PavelBal

Problems with parenthesis in paths

When extracting my simulation results an error is raised that the path of my output would not exist, however, the path is exactly the one from the corresponding XML file:

Error in getSimulationResult(path_id = outputs[k], DCI_Info = dci_info) : Result with path_id 5mg/kg Male - all|Organism|Liver|Compound1|Tissue (Liver) does not exist!

Observer in XML file
<Observer id="15625" entityId="bQMi_zFotESwJqmYAm36Yw" name="Tissue (Liver)" path="5mg/kg Male - all|Organism|Liver|Compound1|Tissue (Liver)" unit="µmol/l" persistable="1" formulaId="16917" />

This problem only occurs for paths that contain a parenthesis, so far. As soon as I modify the corresponding path in the XML file to:
<Observer id="15625" entityId="bQMi_zFotESwJqmYAm36Yw" name="Tissue (Liver)" path="5mg/kg Male - all|Organism|Liver|Compound1|Tissue Liver" unit="µmol/l" persistable="1" formulaId="16917" />
everything works well.

Could you, please, check what is the problem... especially as the observer I used is a predefined one in MoBi.

getSpeciesInitialValue() returns a wrong value for "IsFormula"

A system with 2 species - a and b.

a' = a*k; a(0) = b
b' = 0; b(0) = 1e-6.

#Initialize and run simulations as exported from MoBi
xml_1 = "./InitializeIfFormula_test.xml";

DCI_Info_1 = initSimulation(xml_1, whichInitParam = "none");

#First, initialize all species.
allSpecies = getSpeciesInitialValue(path_id ="*", list(Type = "readonly"), DCI_Info = DCI_Info_1);
initStruct <- list()
for (idx in allSpecies$Index){
  isFormula = getSpeciesInitialValue(path_id ="*", list(Type = "readonly", Property = "IsFormula", Index = idx), DCI_Info=DCI_Info_1)$Value;

#isFormula = 0 for a!!!

  if (!isFormula){
    path_id = getSpeciesInitialValue(path_id ="*", list(Type = "readonly", Property = "Path", Index = idx), DCI_Info=DCI_Info_1)$Value;
    initStruct <- initSpeciesInitialValue(initStruct, path_id, initializeIfFormula = "withWarning")
  }
}

print("init last sim")
DCI_Info_1 <- initSimulation(xml_1, ParamList = initStruct)
Warning message:
In initParameterStruct(ParamList, TableArray[[id]], id, DCI_Info) :
  The SpeciesInitialValue is defined as Formula:  however it is initialized InitializeIfFormula_test|Organism|a b

InitializeIfFormula_test.zip

RDCI does not update scaling factors, results erroneous

Originating from #43 It seems that RDCI ignores/messes up the scale factors if they are changed after initSimulation().

Two simulations exported from MoBi which are identical except for the scaling factors - "xml_one" with all scaling factors == 1, and xml_nonOne with scaling factors calculated in MoBi.

  1. Initialize xml_one, set all species initial values to variable, and simulate:
#Initialize a simulation with scale factors == 1.
xml_one <- "D:\\Work\\QSP_Diabetes_Platform\\Toolbox\\QC_R\\GIMHum_TestScaleFactors_1.xml"
DCI_Info_one <- initSimulation(xml_one, whichInitParam = "none")
allSpecies = getSpeciesInitialValue(path_id ="*", list(Type = "readonly"), DCI_Info = DCI_Info_one);
initStruct <- list()
for (idx in allSpecies$Index){
  path_id = getSpeciesInitialValue(path_id ="*", list(Type = "readonly", Property = "Path", Index = idx), DCI_Info=DCI_Info_one)$Value;
  initStruct <- initSpeciesInitialValue(initStruct, path_id, initializeIfFormula = "always")
}
DCI_Info_one = initSimulation(xml_one, ParamList = initStruct);
#Process sim one
DCI_Info_one <- processSimulation(DCI_Info = DCI_Info_one)
  1. Initialize "xml_nonOne" and set all species initial values to variable:
#Initialize a simulation with scale factors != 1.
xml_nonOne <- "D:\\Work\\QSP_Diabetes_Platform\\Toolbox\\QC_R\\GIMHum_TestScaleFactors.xml"
DCI_Info_nonOne <- initSimulation(xml_nonOne, whichInitParam = "none")
allSpecies = getSpeciesInitialValue(path_id ="*", list(Type = "readonly"), DCI_Info = DCI_Info_nonOne);
initStruct <- list()
for (idx in allSpecies$Index){
  path_id = getSpeciesInitialValue(path_id ="*", list(Type = "readonly", Property = "Path", Index = idx), DCI_Info=DCI_Info_nonOne)$Value;
  initStruct <- initSpeciesInitialValue(initStruct, path_id, initializeIfFormula = "always")
}
DCI_Info_nonOne = initSimulation(xml_nonOne, ParamList = initStruct);
  1. Set all scaling factors to 1 (I am doing it in all DCI table to compare the DCIs):
#Set all scale factors to 1
for (idx in 1 : length(DCI_Info_nonOne$InputTab$AllSpecies$ScaleFactor)){
  DCI_Info_nonOne$InputTab$AllSpecies$ScaleFactor[idx] = 1;
}
for (idx in 1 : length(DCI_Info_nonOne$InputTab$VariableSpecies$ScaleFactor)){
  DCI_Info_nonOne$InputTab$VariableSpecies$ScaleFactor[idx] = 1;
}
#
for (idx in 1 : length(DCI_Info_nonOne$ReferenceTab$AllSpecies$ScaleFactor)){
  DCI_Info_nonOne$ReferenceTab$AllSpecies$ScaleFactor[idx] = 1;
}
for (idx in 1 : length(DCI_Info_nonOne$ReferenceTab$VariableSpecies$ScaleFactor)){
  DCI_Info_nonOne$ReferenceTab$VariableSpecies$ScaleFactor[idx] = 1;
}

Input and reference tables are now identical between xml_one and xml_nonOne:

> all.equal(DCI_Info_one$InputTab, DCI_Info_nonOne$InputTab)
[1] TRUE
> all.equal(DCI_Info_one$ReferenceTab, DCI_Info_nonOne$ReferenceTab)
[1] TRUE
  1. Simulate xml_nonOne:

DCI_Info_nonOne <- processSimulation(DCI_Info = DCI_Info_nonOne)

Scaling factors in the InputTab$AllSpecies are reset!

> all.equal(DCI_Info_one$InputTab, DCI_Info_nonOne$InputTab)
[1] "Component “AllSpecies”: Component “ScaleFactor”: Mean relative difference: 2.259764"
> all.equal(DCI_Info_one$ReferenceTab, DCI_Info_nonOne$ReferenceTab)
[1] TRUE

This happens here

h <- .Call("RDCI_ProcessData", as.integer(DCI_Info$Handle), as.integer(1))
if (h == 0)
{
stop(.Call("RDCI_GetLastError"))
}
# Get updated input tables
TableArray <- .Call("RDCI_GetInputTables", as.integer(DCI_Info$Handle), as.integer(1))
DCI_Info$InputTab <- TableArray

As pointed out in #43 , the results are completely different, too!

Return a warning when the parameter cannot be found in getParameter();

Problem:

getParameter(path_id="nonExistent", DCI_Info = dci_info)

returns

$Value
numeric(0)

$Index
[1] 0

Though the output is valid, it is not the anticipated one.

Solution:

Print a warning message and set parameter = NULL or something else (to be discussed). Also include the check for is.null(parameter) in dependent methods.

Update Simmodel

Once Simmodel etc. was moved to VS2017, update used components

Error in initSimulation(XML = simModelXML, whichInitParam = "none") : Unknown Error

I have installed the latest version of R-toolbox 7.1 under R v3.3.3 environment.

I constantly met the same same error, when I tried to test my installation using R-Toolbox/tests/01_microtest.R script

After loading the model file, the initSimulation command gave the following error message:

standard_dci_info <- initSimulation(XML=simModelXML, whichInitParam="none")
Error in initSimulation(XML = simModelXML, whichInitParam = "none") :
Unknown Error
in SimModelComp_XMLHelper::XMLStringFromFile

Rename "MoBi Toolbox" to "OSP Toolbox"?

I think it makes more sense to call the toolboxes (valid for the Matlab toolbox, too) "OSP Toolbox" or "OSPM Toolbox" (for "OSP model) than "MoBi Toolbox". The current name may be misleading.

"IsFormula" is stored in the DCI_Info not correctly

Consider my example from #46 .

The described model is loaded into R and no parameters are initialized:

library(MoBiToolboxForR, quietly=TRUE)

testXML = ".\\QC_R\\testSim.xml"
DCI_Info_test <- initSimulation(testXML, whichInitParam = "none")

Now I want to initialized all species that are NOT formulas. For this, I first get all the species (which turn out to be parameters, and I am getting no species at all, but this is another story described in #46 ...), and iterate through the list while getting the property "IsFormula". If the species in not a formula, I initialize its initial value:

allSpecies = getSpeciesInitialValue(path_id ="*", list(Type = "readonly"), DCI_Info = DCI_Info_test);
initStruct <- list()
for (idx in allSpecies$Index){
  isFormula = getSpeciesInitialValue(path_id ="*", list(Type = "readonly", Property = "IsFormula", Index = idx), DCI_Info=DCI_Info_test)$Value;
  if (!isFormula){
    path_id = getSpeciesInitialValue(path_id ="*", list(Type = "readonly", Property = "Path", Index = idx), DCI_Info=DCI_Info_test)$Value;
    initStruct <- initSpeciesInitialValue(initStruct, path_id, initializeIfFormula = "never")
  }
}

Init struct now consists of two parameters (state variables), one of which was defined by a formula:

initStruct[["InitialValues"]][["Path_ID"]]
        [,1]                                     
        "testSim|Organism|RHS_Param_constantInit"
path_id "testSim|Organism|RHS_Param_formulaInit" 

Now we could think that the formula of "RHS_Param_formulaInit" was optimized to a constant, because it was just "5+6", and everything is fine. Well, it is not, because trying to initialized the model with this init struct leads to an error!

> DCI_Info_test <- initSimulation(testXML, ParamList = initStruct)
Error in initParameterStruct(ParamList, TableArray[[id]], id, DCI_Info) : 
  The SpeciesInitialValue is defined as Formula:  If you want to inititalize this species initial value do not use option 'never' for the function initParameter testSim|Organism|RHS_Param_formulaInit 5+6

Looking at DCI_Info, nether the parameters nor the Species lists have their "isFormula" set to 1 for any of the species/parameters!

> DCI_Info_test[["InputTab"]][["AllParameters"]][["Formula"]]
 [1] "" "" "" "" "" "" "" "" "" "" "" "" ""
attr(,"Name")
[1] "Formula"
attr(,"Description")
[1] ""

> DCI_Info_test[["InputTab"]][["AllSpecies"]][["IsFormula"]]
[1] 0 0
attr(,"MinValue")
[1] 0
attr(,"MaxValue")
[1] 0
attr(,"DefaultValue")
[1] 0
attr(,"Name")
[1] "IsFormula"
attr(,"Description")
[1] ""

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.