Skip to content

Scripting in MIKE OPERATIONS

Introduction

This HOWTO document in the MIKE OPERATIONS HOWTO series focuses on how to write a script.

The HOWTO assumes that the reader is familiar with programming against the MIKE OPERATIONS business layers. If this is not the case, the reader should read and understand reference documents /1/ and /2/.

Script environment

Scripts are essentially pieces of code that can implement some functions. The scripting language in the MIKE OPERATIONS platform is IronPython which is the Microsoft .NET framework implementation of the python scripting language. The Script Manager in the platform offers interface and functionality for users to write their own scripts utilising the API of the platform to create their customized applications.

Scripts in the Script Manager can be arranged in groups or by storage and are shown in the user interface as folders. The user is able view these two explorer structures by selecting “View by Group” or “View by Storage” in the Script Manager explorer as depicted in Figure 1.

Figure 1: “View by” menu

What is a Storage?

Storage is a physical collection of script functions. It is similar to a file. The user needs to create a new storage before writing a script. This will be discussed in more detail in the “Walk-Through: Get the values of a time series” section of this document. Script functions with common functionalities in a storage can be called by other functions in the same storage. Figure 2 illustrates the storage explorer in the script manager.

Figure 2: Storage explorer

Note the following:

There is no folder in the storage explorer. The item in this explorer is a script storage. The user can delete, rename or edit a storage by right-clicking on it and selecting corresponding menu item.

What is a Script Entity?

A script entity in the script manager is a script function in a storage, with specific comments. The script manager saves script functions with formatted comments in the database. To comply with the coding standard, the user should add comments in the definition of the function. This will allow the script manager to interpret the function parameters correctly. The following listing illustrates the format of the comments.

Listing 1 Formatted comments of a Script

Note the following:

  1. The author of the script.

  2. The function description of the script.

  3. Parameter description of the script - describes the names, types and meanings of the parameters. If these parameters are defined before execution, the user will be prompted to set correct values for these input parameters.

  4. Return value of the script - describes the type and meaning of the return value.

The script entity can be viewed in group explorer. Figure 3 shows the group explorer of script manager.

Figure 3: Group explorer

Note the following:

  1. The folder corresponds to the script group entity.

  2. The item corresponds to the script entity.

Folders in the group explorer can be created, deleted, renamed or moved like any normal folder. Scripts under a folder may originate from different storages and a storage may contain more than one script.

What is a Function?

The function is a script function without formatted comments as described for the script entity above. The function will be stored in the script storage but will not be treated as a script entity in the script manager. The function however, can call and be called by a script entity.

Using the business API in the MIKE OPERATIONS framework

The following sections will describe how to use the business API in the MIKE OPERATIONS framework to write a script in detail.

Walk-Through: Get the values of a time series

This section describes how to retrieve the values of a time series using the script.

Step 1 – Create a new script storage

In order to write a script, a new script storage to store customised script functions must be created. This process to create a new storage is as follows:

  • Select the storage view.

  • Right-click on the root (the “Database” node) in the storage explorer. The script manager’s context menu is shown in Figure 4.

Figure 4: “Add storage” menu

  • Click “Add storage” menu to create a new storage.

  • Right-click on the newly create storage. Context menu is shown in Figure 5 below.

Figure 5: Menu strip for storage

  • Click “Rename” to rename the storage, then, for example, set the name to “GetTimeseriesValues.”

Step 2 – Edit the script storage

After adding a new storage or clicking the “Edit storage” menu as depicted in Figure 5, the following editor (Figure 6) will be shown as a data view in the MIKE OPERATIONS platform. The tools in the editor will be discussed later in the “Hints and best practices” section of this document.

Figure 6: Script editor

Step 3 – Write the script function

The following listing shows how to retrieve values from a time series.

Listing 2 Script to get values of a time series

Note the following:

  1. Define a script function named “GetTimeSeriesValue” with one input parameter which is the path of a time series.

  2. Add comments in the script. Actually, you do not need to add these comments manually. There are tools and menus in the editor to insert the “Script without arguments” and “Script with arguments” which will insert the comments in a newly created script function. You just need to update them. The “Hints and best practices” section in this document will describe in detail how to simplify the editing of a script.

  3. Get the time series manager module: The app object represents the built-in IApplication interface which is available for scripts. The method to access the module in a script function is the same as in standard dotnet programming language. Please refer to document /2/ in the Reference documents table.

  4. Use the Fetch(string path) method to retrieve the TimeSeriesList from the database.

  5. Use FetchAll() method to get all value pairs of the time series.

  6. Loop over the data list and print the date times and values.

Walk-Through: Create a new time series

This section describes how to create a new time series, set its data values and save it to the database using script. As described in the “Walk-Through: Get the values of a time series” section, you first need to create a new storage which can be named “CreateTimeSeries” and then open the script editor to write the script functions.

The following listing demonstrates the script function to create a new time series and save it to the database.

Listing 3 Script to create a new time series

Note the following:

  1. Add reference to the mscorlib assembly.

  2. Add reference to the DHI.Solutions.Generic assembly.

  3. Import the DateTime class from System namespace which is defined in the mscorlib assembly.

  4. Import the DataSeriesAxisType, DataSeriesValueType and IDataSeries classes from the DHI.Solutions.Generic module.

  5. Define a script function named “CreateTimeSeries” with one input parameter which is the path of the new time series.

  6. Get the time series module.

  7. Create a new time series using the CreateNew(string path) method.

  8. Create a list of IDataSeriesValuePair.

  9. Set the above newly created data to the new time series.

  10. Set the properties of the newly created time series.

  11. Save the newly created time series to the database via Add(IDataSeries entity) method in the TimeSeriesList class.

Walk-Through: Update an existing time series

This section describes how to update an existing time series and save the changes to the database using script. The first and second steps here are the same as the first and second steps in the “Walk-Through: Get the values of a time series” section. The newly created storage can be named “UpdateTimeSeries”.

The following listing shows how to update a time series using scripts.

Listing 4 Script to update an existing time series

Note the following:

  1. Define a script function named “UpdateTimeSeries” with one input parameter which is the path of an existing time series.

  2. Get the time series module.

  3. Get the time series from the database using Fetch(string path) method of the TimeSeriesList class.

  4. Get all of the data of the above time series from database.

  5. Change the value of the first value pair if the count of data list is greater than zero.

  6. Use Update(IDataSeriesValuePair dataSeriesValuePair) to update the above change of data to the database.

  7. Set a new value to the ValueType of the existing time series.

  8. Save the above type change to the database via Update(IDataSeries entity) method of the TimeSeriesList class.

Walk-Through: Export a time series using the TimeseriesExportTool

This section describes how to export a time series using the TimeseriesExportTool defined in the time series manager via script.

The first and second steps here are same as the first and second steps in the “Walk-Through: Get the values of a time series” part. The name of the newly created storage can be “ExportTS”.

The following listing demonstrates the definition of the script function used by the TimeseriesExportTool to export a time series.

Listing 5 Script to export a time series

Note the following:

  1. Add reference to the DHI.Solutions.TimeseriesManager.Tools.TimeseriesExportTool assembly.

  2. Import all the class or variable definitions in the above assembly.

  3. Define a script function named “ExportTS” with one input parameter which is the path of a time series.

  4. Get the time series module.

  5. Get the time series from the database using Fetch(string path) method.

  6. Create a TimeseriesExportTool by using CreateNew(string toolName) method of the Tools class.

  7. Add the fetched time series to the input items of the export tool.

  8. Set the ExportFormat property of the export tool. It defines the format of the exported file. Use dfs0 as an example.

  9. Set the ExportDirectory property of the export tool. It defines the directory of the exported file.

  10. Execute the export tool. A dfs0 file will be created in the specified export directory.

Walk-through: Execute a scenario

This section describes how to execute a scenario via script. You will also need to create a new storage and open the storage editor first as described in the “Walk-Through: Get the values of a time series” Section. The new storage can be named “ExecuteScenario”.

After following the above steps, write the script as in the following listing, to implement the function of executing a scenario.

Listing 6 Script to execute a scenario

Note the following:

  1. Define a script function named “ExecuteScenario” with one input parameter which is the path of an existing scenario.

  2. Get the module of scenario manager.

  3. Get the scenario from the database using the Fetch(string path) method.

  4. Define a simulation variable.

  5. Execute the scenario via the RunScenario(IScenario scenario, bool runModelGUI, bool approveSimulation, ref ISimulation simulation) method defined in the scenario module class.

Walk-through: Get a simulation of an executed scenario

This section describes how to get a simulation of an executed scenario via script. The first and second steps are the same as the first and second steps in the “Walk-Through: Get the values of a time series” section. The new storage can be named “GetSimulation.”

The following listing shows the script function to get the latest simulation of a scenario.

Listing 7 Script to get the latest simulation of an executed scenario

Note the following:

  1. Define a script named “GetSimulation” with one input parameter which is the path of an executed scenario.

  2. Get the scenario manager module.

  3. Get all simulations of a scenario specified by the input scenario path from the database by the FetchChildren(string groupPath) method of the SimulationList class.

  4. Define a simulation variable.

  5. Get the run time list of the above child simulations.

  6. Get the latest simulation of the specified scenario by calling find function defined in the same storage.

  7. Return the result simulation.

  8. Define a function named “find” in the same storage. This function will be used to retrieve an item from a collection, matching it up according to a search criteria. As the function does not have the formatted comments, it will not be treated as a script entity in the script manager.

Walk-through: Get attributes from a feature class

This section describes how to retrieve attributes from a feature class using script. Firstly you would need to create a new storage and open the storage editor which has been introduced in the “Walk-Through: Get the values of a time series” section. The storage can be named as “GetFeatureAttributes”. After that, write the script functions in the editor to get a feature class’ attributes, similar to those shown in the following listing. Take the “Countries” feature class as an example.

Listing 8 Script to get the name attribute of “Countries” feature class

Note the following:

  1. Add reference to the DHI.Solutions.GISManager.Interfaces assembly.

  2. Import all classes and variables defined in the above assembly.

  3. Define a script function named “GetFeatureAttributes” which has no input parameters.

  4. Get the module of GIS manager.

  5. Get the “Countries” feature class from the database using the Fetch(string path) method.

  6. Get the attribute list of the above feature class.

  7. Get the name attribute from the attribute list by calling the find function defined in the same storage.

  8. Get all features of the “Countries” feature class from the database via the FetchAll() method of the IFeatureClass class.

  9. Get the list of name values by using this [IFeatureClassAttribute attribute] property of the IFeature class.

  10. Return the result value list of name attribute.

  11. Define a function named “find” to return the item, matching it up according to search criteria. If nothing is found, it will return “None”. It is not a script entity as it does not have formatted comments.

Walk-through: Get and set a cell value in a spread sheet

This section describes how to get or set a cell’s value in a spread sheet using script. The first and second steps here are the same as the first and second steps in the “Walk-Through: Get the values of a time series” section. The name of the newly created storage can be “GetSetCellValue”.

After adding the storage and opening the editor, write the script code, as indicated in the following listing, to the editor to get a cell value from a specified spread sheet or to set a cell value in a specified spread sheet.

Listing 9 Script to get/set a cell value

Note the following:

  1. Define a script function named “GetCellValue” with three parameters. These parameters are: the path of the spreadsheet, the name of a specific sheet in the spreadsheet and the cell address in the sheet.

  2. Get the module of spreadsheet manager.

  3. Open the spreadsheet using the OpenSpreadsheet(string path) method in the spreadsheet manager module.

  4. Get the cell value using the GetCellValue(ISpreadsheet document, string sheetName, string reference) method in the module.

  5. Close the spreadsheet using CloseSpreadsheet(ISpreadsheet document) method in the module.

  6. Return the cell value.

  7. Define a script function named “SetCellValue” with four parameters being, the path of a spreadsheet, the worksheet name in the spreadsheet, the cell address in the worksheet and the new input cell value. This function is defined in the same storage as the “GetCellValue” function.

  8. Set the cell value using the SetCellValue(ISpreadsheet document, string sheetName, string reference, object value) method in the module.

  9. Save the change using the SaveSpreadsheet(ISpreadsheet document) method.

Walk-through: Make a spread sheet event handler function

This section describes how to make a spread sheet event handler script function. The spread sheet event handler is used to implement the functionality of executing a script by clicking a push button in the spread sheet. An event handler function should have two parameters. The first being EventSender which is a type of ISpreadsheetScriptEventSender and second parameter is Control which is a type of ISpreadsheetControl. These two parameters are required when defining an event handler script. The “Hints and best practices” section later in this document, will discuss these two parameters in more detail.

In order to make a spread sheet event handler function, you first need to create a new storage and then open the storage editor as described in the “Walk-Through: Get the values of a time series” section and name the storage “NameSelectedEvent”.

The following listing demonstrates what a spread sheet event handler function looks like.

Listing 10 Script of spread sheet event handler

The script in the above listing tries to populate a combo box in a spread sheet.

Note the following:

  1. Import List from the System.Collections.Generic module.

  2. Define an event handler script named “NameSelectedEvent” which has two parameters.

  3. Get the combo box name using the GetCellValue(string sheetName, string reference) method of EventSender.

  4. Define a name list which contains four items.

  5. Populate the specified combo box using the above defined name list. Use the Controls property of the EventSender to get the combo box.

  6. Set the second item as the selected one in the combo box.

  7. Set the text of the selected item to a specified cell using the SetCellValue(string sheetName, string reference, object value) method of EventSender.

The following figure shows a spread sheet that uses the above event handler.

Figure 7: Spread sheet using the populating drop down list event handler

Note the following:

  1. Right-click on this button and the following context menu is shown:

Figure 8: Menu strip of control in a spread sheet

By clicking the “Properties” menu, the relevant properties for this button will show in the property grid.

Figure 9: Button properties

By setting the path of the event handler script to the “Script” property and clicking this button, the event handler script will be executed.

  1. This is the dropdown list control. Its properties can be set just like the button. Set its name as “NameDropDown”.

  2. The value of cell “A1” is the name of the above dropdown list. It is used in the above event handler example.

Hints and best practices

This section provides more details on different aspects related to writing a script.

Spread sheet event handler

The event handler script for a push button in a spread sheet always has two arguments. One is the EventHandler and the other is the spread sheet control raising the executing script event.

The EventHandler is the ISpreadsheetScriptEventSender type. It contains the information of the spread sheet as well as information of all controls in the spread sheet. The user can utilise this information to implement special functionalities. The EventHandler also provides many methods similar to those in the spread sheet module to the user whilst working with a spread sheet. For example, the “Walk-through: Make a spread sheet event handler function” section uses the Controls property of the EventHandler to get the dropdown list control in the spread sheet so that the user can work with this control. It uses the GetCellValue and SetCellValue methods of the EventHandler to get values from the spread sheet and change values in the spread sheet. Table 1 lists some important properties and methods of the EventHandler.

Property/Method Description
EventAction Gets current sender’s event action, like ButtonClicked.
Spreadsheet Gets current spread sheet entity.
Controls Gets all controls’ info in the spread sheet.
EnableControl(string name) Enable a control by name.
DisableControl(string name) Disable a control by name.
GetAllControlNames() Gets all controls’ names
SaveSpreadsheet() Save the spread sheet entity.
GetCellValue(string sheetName, string reference) Gets cell’s value from the spread sheet.
SetCellValue(string sheetName, string reference, object value) Sets a cell’s value in the spread sheet.
SaveTimeseriesToDatabase(string sheetName, string reference, TimeSeriesProperty property) Save range data as a time series to the database.
SaveFeatureAttributesToDatabase(string sheetName, string reference, string featureClassPath) Save range data as a feature class to the database.
SaveTimeseriesFromRange(string sheetName, string dateRange, string valueRange, TimeSeriesProperty property) Save the data of date range and data of value range as a time series to the database.
SaveEnsembleTimeseriesFromRange(string sheetName, string reference, TimeSeriesProperty property) Save range data as an ensemble time series to the database.

Table 1: Properties and methods of EventHandler

The spread sheet control argument provides the information of the control which raises the event, to execute a specified script. The user can retrieve the control’s name, type or text etc. The MIKE OPERATIONS platform will now support executing a script by merely clicking a button. Table 2 lists the important properties of the spread sheet control.

Property/Method Description
Name Gets or sets control’s name.
Text Gets or sets control’s text.
Enabled Gets or sets a value indicating whether the control is enabled.
ControlType Gets the control’s type.

Table 2: Properties of the Control

ClearData() method

The ClearData() method is a method of IDataSeries entity in the time series manager. It is responsible for clearing the time series data cached in memory. It is useful after the user calls GetAll() method of IDataSeries entity to get all data of a time series, as the GetAll() method will cache the data in the memory. If these data are not cleared when they are no longer used, a memory leak may occur. It is therefore recommended that the user should call ClearData() after using GetAll() method in his script.

Inserting script snippets

The MIKE OPERATIONS platform provides functionality to insert script snippets in the script functions. The user can do this by making use of the script editor context menu. The following figure shows the menu for inserting a snippet.

Figure 10: Snippets menu

A snippets form will pop up after clicking the “Snippets…” menu (as shown in Figure 11). This form lists all of the available snippets in the platform.

Figure 11: Snippets form

The platform provides some useful snippets, like getting the manager module, fetching an entity, setting a cell value in a spread sheet or creating a spread sheet event handler function etc. Besides these default snippets, the user can add own snippets by means of the snippet manager as shown in the following figure. This snippet manager can be accessed through the tool button in the script editor.

Figure 12: Snippets manager

The user is able to add/edit/remove a snippet by making use of this manager.

Using tools from script

The MIKE OPERATIONS platform provides a number of tools to the user. Each tool can implement a specific function. If the user wants to implement a functionality which also has a tool available through script, he can use the tool in the script directly, to reduce the amount of script code.

For the convenient use of a tool in script, the platform provides the following two ways to auto-generate script functions for tool execution.

  1. The user can get the tool scripts by dragging a tool from the tool explorer and dropping it in the script editor. The following listing shows the scripts generated in this manner.

Listing 11 Auto-generated script by dragging and dropping a tool in the script editor

The auto-generated script contains necessary-import/from statements, definition of tool execution script function, argument descriptions corresponding to the tool’s property descriptions and a return value corresponding to the tool output.

  1. Another option is to use the tool wrapper functionality from the script editor context menu. Figure 13 demonstrates the context menu of the editor.

Figure 13: Tool wrapper menu of script editor

If the user clicks the “Tool wrapper…” menu, the following tool wrapper dialog which provides additional configuration options, will appear.

Figure 14: Tool wrapper dialog

The user can select one or more tools and opt to include the tool’s property descriptions as documentation in the tool wrapper script function or to have a sample function added to demonstrate how to call the tool execution function. The next listing depicts the result of including the caller method and argument descriptions.

Listing 12 Auto-generated script by clicking “Tool wrapper…” menu

The “DoExportDocument” function is the caller method that demonstrates how to call the tool wrapper function “ExportDocument”. At the same time, the “ExportDocument” method has descriptions of arguments.

The above listings illustrate that both ways lead to the same result, i.e. generation of a script function with input parameters corresponding to the properties of the tool and a return value corresponding to the output of the tool.

Using script from job

The job manager of the MIKE OPERATIONS platform has a task named “RunScript”. The user can find it in the “DSS Script Manager” category of the Task Selection Dialog. The following figure (Figure 15) illustrates this dialog.

Figure 15: RunScript task

This task can be added to a job. After setting the values of its input parameters like the script path, the user can execute a script by running a job. This task also has an output entry which is the return value of the executed script. If the script has print statements, the print results will be stored in the job log and shown under the “Log” node in the job data view.

Script Development

This section introduces the tool context menu in the script editor. The script editor has a lot of tool buttons which can assist the user to perform an action. The following figure indicates these tools.

Figure 16: Tools in the script editor

Note the following:

  1. Tools for debugging. The user can utilise these tools to step into/step over/step out a script function, pause or stop a debugging and disable or delete breakpoints.

  2. Tool to insert a script without arguments – the following listing shows this auto-generated script.

Listing 13 Script without arguments

If the user wants to add a script function without arguments, he just needs to update the above one without starting from the very beginning. In other words, the user does not need to add these comments word by word.

  1. Tool to insert a script with arguments. The auto-generated script is shown in the following listing.

Listing 14 Script with arguments

The user can update this script to create own script function with arguments, without having to start from scratch. In the above listing, the IClass and Member are rarely used. They may possibly be removed from the MIKE OPERATIONS platform in future.

  1. Tool to save a script storage in the database.

  2. Tools to execute a selected script.

  3. Tool to find a word in the storage.

  4. Tool to find a word and replace it with a new one in the storage.

  5. Tool to comment selected lines in the script functions.

  6. Tool to uncomment selected lines in the script functions.

  7. Tool to show the snippet manager dialog used to add customized snippets which can be inserted in a script function later. The script snippets have been introduced in detail in Inserting script snippets – Section 4.3.

Some tool functionalities mentioned above can also be found in the script editor context menu.