Overview

Custom code allows user to set up the minimum additional required configurations to run the digital twin simulations (combinations), while additionally providing an environment where to extend custom functionality and pre-set report visualization configurations.

Code layout

Next code shows the schema/layout of how custom code look like.

Note

Within next code, ... , indicates code sections that might be available in the real custom code but have been excluded as they might differ depending on Simulation Parameters, Output/Constant/Simulated variables setup.

#region ExtendedVariables
// State variables
...
// Constant variables
...
// Simulated variables
...
#endregion

#region UserCustomVariables   
// Custom variables can be declared here.
#endregion

public override void Initialize()
{
  #region CustomCodeIni
  // Custom code here.
  #endregion

  #region MandatoryCodeSimulatedEquations
  // Not currently in use
  #endregion

  #region MandatoryCodeIni
  this.XAxis.SimMin = TOBESET; // Start value
  this.XAxis.SimRes = ...;	   // Step (Resolution)
  this.XAxis.SimMax = TOBESET; // End value


  // Initial volume (if any; set '1.0d' if not)
  ...
  #endregion
} 

public override void EvaluateStep()
{
  #region CustomCodeEval
  // Custom code can be declared here.
  #endregion

  #region MandatoryCodeEval
  // Simulated variables (ti) - Values.
  ...
  // Output variables (ti) - Added mass (if any; set '0.0d' if none).
  ...
  // Output variables (ti) - Added volume (if any; set '0.0d' if none).
  ...
  // Output variables (ti) - Sampled volume (if any; set '0.0d' if none).
  ...
  #endregion
}

Warning

It is strictly forbidden to delete/edit/rename code layout regions (lines containing #region ... and #endregion) and main methods (Initialize and EvaluateStep) declarations. Within regions, code can be edited when permitted (see regions table).

Code Execution

../../../../../../_images/executionSchematic.svg

When starting a digital twin simulation (Sim button clicked), ExtendedVariables and UserCustomVariables regions will be initialized.

Warning

This is the only time that ExtendedVariables and UserCustomVariables regions are initialize! Its variables instances will be shared along all possible simulation (combinations from constant variables).

If a digital twin (see referenced example) has a total of 9 possible combinations, equivalent number of simulations (9) will be carried out. For each of all possible combinations,

  • Initialize method will be executed once (first to execute).

  • EvaluateStep method will be called as many times as available SimSteps (see X-Axis).

Methods

Note

This section (Methods) is described in high level to avoid redundancy. Extensive detail is given for each one at the Regions section.

Initialize

public override void Initialize()
{
  #region CustomCodeIni
  ...
  #endregion

  #region MandatoryCodeSimulatedEquations
  ...
  #endregion

  #region MandatoryCodeIni
  this.XAxis.SimMin = TOBESET; // Start value
  this.XAxis.SimRes = TOBESET; // Step (Resolution)
  this.XAxis.SimMax = TOBESET; // End value	

  // Initial volume (if any; set '1.0d' if not)
  ...
  #endregion
}

Its function is to set simulation (specific combination),

EvaluateStep

public override void EvaluateStep()
{
  #region CustomCodeEval
  ...
  #endregion

  #region MandatoryCodeEval
  // Output variables (ti) - Added mass (if any; set '0.0d' if none).
  ...
  // Output variables (ti) - Added volume (if any; set '0.0d' if none).
  ...
  // Output variables (ti) - Sampled volume (if any; set '0.0d' if none).
  ...
  #endregion
}

Its function is to set simulation step,

Tip

When simulating a time series or a simulation where SimSteps != 1, you might be interested in in knowing current X-Axis value.

Because X-Axis is an extended variable, you can use its properties such as (but not limited),

Regions

Custom code has 7 regions as briefed in next table,

Name

Scope

Handling

Global

Initialize

EvaluateStep

Digital Twin

User

Shared

ExtendedVariables

UserCustomVariables

CustomCodeIni

MandatoryCodeSimulatedEquations

MandatoryCodeIni

CustomCodeEval

MandatoryCodeEval

Scope implies where region is located and its variables (if any) accessibility,

  • Global, it is scoped to the whole instance. Variables are accessible from within Initialize and EvaluateStep methods.

  • Initialize, it is scoped to the Initialize method and variables can only be accessed from within that method.

  • EvaluateStep, it is scoped to the EvaluateStep method and variables can only be accessed from within that method.

Handling implies who sets/edits the code regions,

  • Digital Twin. Regions are managed by the digital twin itself.

    Important

    It is forbidden to write/edit code from those regions manually.

  • User. Digital twin does not automatically write/edit code from within those regions. User can provide (if needed) custom code to perform additional calculations (e.g, for simulated variables).

  • Shared. Digital twin does automatically write/edit code from within those regions and user might have to manually compliment part of the code when required.

    Note

    When automatic generated code requires user attention/completion, it is indicated with a place holder TOBESET.

Warning

All regions handled by the Digital Twin or Shared mode, will be indirectly affected when using some of the custom code buttons. Check that section to understand the risks!

ExtendedVariables

Provides the declaration of all digital twin auto-generated Extended Variables.

Note

Even though discouraged, user can create its own custom Extended Variables.

UserCustomVariables

User can use this region the declare its own custom C# code such as for example (but not limited), custom Extended Variables, Structs, Classes, Enums, Lists, Arrays, Variables…

Warning

Do not use C# static modifier keyword anywhere!

Warning

Do not use any other C# access modifier rather than private keyword anywhere!

Note

When declaring a variable, method, class… unless otherwise stated, access modifiers are already by default private.

Example

private double varA = 4.7;

is equivalent to

double varA = 4.7;

Warning

When declaring custom variables within the Global scope (e.g., inside UserCustomVariables) those variables values will be shared along all combinations simulations.

Make sure to always override/re-initialize its values from within the Initialize method CustomCodeIni region to make sure a value from a previous simulation combination is not being accidentally re-used.

Example

...
#region UserCustomVariables   
// Custom variables can be declared here.
double myVariableA;
...
#endregion
...
public override void Initialize()
{
  #region CustomCodeIni
  // Custom code here.
  this.myVariableA = 5.1;
  ...
  #endregion
  ...

}

CustomCodeIni

Similar to UserCustomVariables this region allows user to create its own custom C# code to (but not limited),

MandatoryCodeSimulatedEquations

Note

This region is only functional when Use Symbolic Expressions is set to True otherwise region will be set as follows. If True, user must not edit this region and keep it empty as shown.

#region MandatoryCodeSimulatedEquations
// Not currently in use
#endregion

Warning

Due to it’s setup complexity, it is recommended to not use Symbolic Expressions.

Default value for previous simulation parameter is False in all new toolbox releases. Therefore this section on how to set symbolic expressions for simulated variables is not provided (as is not needed). If still need to set it up, feel free to contact us for more guided support.

MandatoryCodeIni

Required X-Axis and MassBalance (Initial Volume) auto-generated provided setup by the digital twin must be manually complimented (when needed) by the user.

X-Axis

Digital twin can simulate both,

  • Observations

  • Time series

This behavior is set on the Simulation Parameters panel by setting Time Series to either True (Time Series) or False (Single observation).

When False, digital twin automatically will handle setup, providing following code,

this.XAxis.SimMin = 1.0d; // Start value
this.XAxis.SimRes = 1.0d; // Step (Resolution)
this.XAxis.SimMax = 1.0d; // End value

Parameters SimMin, SimRes, SimMax allow the calculation of the total number of time points SimSteps within the current simulation (combination) time series,

\[\begin{gather*} SimSteps = \frac{SimMax - SimMin }{SimRes} \end{gather*}\]

Therefore, when all parameters are set to 1.0 the calculation yields to SimSteps = 1. This tells the digital twin that time series contains only 1 time point; virtually behaving as a single observation simulation.

On the other hand, when value is set to True, digital twin will still provide the X-Axis configuration layout but in Shared mode, requiring user to provide the TOBESET values.

this.XAxis.SimMin = TOBESET; // Start value
this.XAxis.SimRes = TOBESET; // Step (Resolution)
this.XAxis.SimMax = TOBESET; // End value

Note

When the digital twin has been created from an existing Hybrid model, if model was of type time series, digital twin will automatically set by default this.XAxis.SimRes to the same value provided on hybrid model identification setup Integrative dt.

When provided, this is just a default value automatically pre-set for user to simulate within the same conditions as hybrid model was trained on. In any case, user can override this value to whatever is intended.

If False or when SimSteps = 1, EvaluateStep will only be called once per simulation/combination.

Note

When False, if clicking buttons Reset Code or Update mandatory variables, custom code SimMin, SimRes, SimMax will automatically be set to 1.0. If True, previous values will need to be provided according your design/resolution space; a TOBESET placeholder will be set by default.

MassBalance (Initial Volume)

Note

This section only applies for digital twin created from an Hybrid Model.

This section, uses the MassBalance helper. Check out the SetInitialVolume method for more detailed information.

CustomCodeEval

Similar to UserCustomVariables or CustomCodeIni this region allows user to create its own custom C# code to (but not limited),

  • Declare local variables on the scope of EvaluateStep method.

  • Re-assign/re-initialize possible custom global variables declared on UserCustomVariables (see section for more details).

  • Custom code to calculate values that might be required by other regions on the EvaluateStep method (e.g., Simulation variables .Value, Mass balances .SetAddedMass(...), .SetAddedVolume(...), .SetSampledVolume(...))

MandatoryCodeEval

Tip

Remember that CustomCodeEval region can be used (recommended) to declare local variables on the scope of EvaluateStep method that can be directly used on sections current MandatoryCodeEval region.

Note

Current region sections, contains the (ti) on the headers. This indicates that provided value will be used only on the current simulation step.

If simulation is not a time series, only one step will be performed and (ti) can be considered as the single observation itself.

Simulated variables (ti) - Values

Digital Twin will list automatically all extended variables of type simulated variables.

User must mandatory provide a value foreach simulated variables. To do so, replace TOBESET placeholder by variables simulated value at that step (or ti).

#region MandatoryCodeEval
// Simulated variables (ti) - Values.
this.MySimulatedVar1.Value = TOBESET;
...
#endregion

Output variables (ti) - Added mass

Note

This section only applies for digital twin created from an Hybrid Model.

This section, uses the MassBalance helper. Check out the SetAddedMass method for more detailed information.

Output variables (ti) - Added volume

Note

This section only applies for digital twin created from an Hybrid Model.

This section, uses the MassBalance helper. Check out the SetAddedVolume method for more detailed information.

Output variables (ti) - Sampled volume

Note

This section only applies for digital twin created from an Hybrid Model.

This section, uses the MassBalance helper. Check out the SetSampledVolume method for more detailed information.

Buttons

The are 3 buttons available to facilitate custom code creation/update/validation,

Reset Code

When clicked, the whole custom code will be deleted and set to default template; replacing all Simulation Parameters setup and Output/Constant/Simulated variables adequately.

Warning

This action is irreversible! All previous code from the whole custom code editor window will be replaced. If you wan to keep it, consider copying the previous code somewhere else before performing this action.

Update mandatory variables

Similar to Reset Code, when clicked, specific code regions will be replaced/edited, rest will still be available on editor.

Warning

This action is irreversible! All previous code from affected regions will be replaced/edited. If you wan to keep it, consider copying the previous code (all/specific affected regions) somewhere else before performing this action.

Validate Code

When clicked, it will try to compile provided custom code. If compilation is,

  • Successful, a Compile succeeded. Code updated. message will be displayed.

    Note

    A successful compilation of custom code, does not mean that will work properly during runtime; it indicates that all code is correct and can be compiled internally by the Toolbox. Runtime exceptions on that code can still occur once simulation/optimization is started. If thats the case, runtime errors will be shown on the logger window from the digital twin.

  • Unsuccessful, a list of errors to fix with its code lines will be listed.

    Tip

    Check out custom code Typical Errors.

Available Assemblies

Within the C# custom code, following assemblies are imported and therefore available,

  • System.dll

  • System.Collections.dll

  • System.Data.dll

  • System.Xml.dll

  • System.Core.dll

  • MathNet.Symbolics.dll

  • MathNet.Numerics.dll

  • MathNet.Numerics.FSharp.dll

  • System.Numerics.dll

  • Microsoft.Scripting.dll

  • Microsoft.Scripting.Metadata.dll

  • Microsoft.CSharp.dll

  • Microsoft.AspNetCore.WebUtilities.dll

  • Newtonsoft.Json.dll

  • System.Net.Http.dll

  • System.Runtime.Serialization.dll

  • System.Diagnostics.Process.dll

  • System.Runtime.dll

Note

If you require more assemblies to be imported/available send us an email explaining which ones will be required and why and we will consider adding them.