DHI MATLAB Toolbox User Guide
DHI MATLAB Toolbox User Guide
dhi_matlab_toolbox_user_guide.docx/JGR/2020-12-17 - © DHI
CONTENTS
DHI MATLAB Toolbox
User Guide for Version 19 (2021)
1 Introduction ...................................................................................................................... 1
1.1 Why a DHI MATLAB Toolbox ............................................................................................................. 1
1.2 DFS Support ....................................................................................................................................... 1
1.3 Release notes ..................................................................................................................................... 1
1.4 User Support ....................................................................................................................................... 2
1.5 Disclaimer ........................................................................................................................................... 2
2 Installation........................................................................................................................ 3
2.1 Requirements ...................................................................................................................................... 3
2.2 Installing the DHI MATLAB Toolbox ................................................................................................... 3
2.2.1 Examples ............................................................................................................................................ 4
3 Functionality .................................................................................................................... 5
3.1 Making References available to consumption .................................................................................... 5
3.2 Examples ............................................................................................................................................ 5
3.3 Example: Reading dfs0 files ............................................................................................................... 6
3.3.1 Open a file for reading......................................................................................................................... 6
3.3.2 Getting header information / object properties .................................................................................... 6
3.3.3 Setting header information / object properties .................................................................................... 8
3.3.4 Show item definitions .......................................................................................................................... 8
3.3.5 Building a dfs0 file from scratch .......................................................................................................... 8
3.3.6 Reading item data ............................................................................................................................. 10
3.3.7 Closing a file ...................................................................................................................................... 11
3.3.8 Saving file .......................................................................................................................................... 11
3.3.9 Read time information ....................................................................................................................... 11
3.3.10 Adding timesteps and editing time .................................................................................................... 12
i
DHI MATLAB Toolbox
1 Introduction
This document constitutes the user guide and documentation for the DHI MATLAB
Toolbox, and especially for how to read and write DFS files.
For more details and examples on working with DFS and other file types, consult the DFS
user guide and .NET API documentation
https://manuals.mikepoweredbydhi.help/2021/MIKE_SDK.htm
Data produced or required by DHI Software packages are most often stored in DHI's file
formats like DFS (Data File System). DHI MATLAB Toolbox provides tools and examples
to read and write different DHI files, and other tasks related to DHI files.
The DHI MATLAB toolbox provides the required software components for working with
DFS files, and it also provides a number of convenience tools and a number of examples
of reading and writing different DFS files.
https://manuals.mikepoweredbydhi.help/2021/MIKE_SDK.htm
1
DHI MATLAB Toolbox
>> NETaddAssembly('DHI.Generic.MikeZero.DFS.dll');
Note that now the file extension '.dll' is also included, which was not the case in
previous versions of the toolbox. Check Section 3.1 for details.
The dfsTSO class has been removed from version 19 (2021) of the DHI MATLAB
toolbox, since the underlying TSObject is no longer a part of the MIKE software suite. To
continue using the dfsTSO class and its functionality, download instead the version 18
(Release 2020) or earlier of the toolbox. Check out the user guide in that release zip file
for details of using and installing the toolbox.
If you find any bugs, have comments, questions or requests for new features, the source
code is publicly available on github, where you are welcome to contribute and comment:
https://github.com/DHI/DHI-MATLAB-Toolbox
You are also welcome to contact mikebydhi@dhigroup.com – please add ‘DHI MATLAB
Toolbox’ in the email subject line.
1.5 Disclaimer
A disclaimer is included in the installation2 .
2 Installation
2.1 Requirements
The DHI MATLAB toolbox works on Windows only.
MATLAB
MATLAB must be installed.
Only the 64 bit version of MATLAB will work with the latest version of the DHI MATLAB
Toolbox. Prior to Mike Release 2017, also a 32 bit version is available.
The current version of the toolbox has been tested on MATLAB R2018b, but earlier
versions may also work. To read and write DFS files, MATLAB must be able to interact
with .NET objects, which was introduced in MATLAB R2012b.
MIKE Software
The current version of the DHI MATLAB toolbox does not require any MIKE Software to
be installed. The toolbox contains all software required to work with DFS files.
These redistributables are often already installed. They are installed automatically when
installing MIKE Zero, MIKE+, MIKE Urban or MIKE SDK. In case they are not already
installed, they can be downloaded and installed from:
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-
downloads
https://github.com/DHI/DHI-MATLAB-Toolbox/releases
Get the DHIMatlabToolbox_XXXX.zip, where XXXX represents the version number. Unzip
its content. Assuming you unzip to the folder:
C:\Matlab
C:\Matlab\mbin
should be created, including a lot files and a couple of subfolders. Note that the
C:\Matlab folder can be replaced with any other folder, according to user preferences;
just replace it in the following.
3
DHI MATLAB Toolbox
The C:\Matlab\mbin folder should be added to the MATLAB path. Start MATLAB, in
the MATLAB command window, issue the command:
>> addpath(genpath('C:\Matlab\mbin'));
This will add recursively the folder to the MATLAB path for this MATLAB session only. To
add the folder permanently to the path, instead add the command to your startup.m file, or
use the menu ‘file’ - ‘Set Path’ and add the needed folders there. Two folders are required
to be in that path, the \mbin and the \mbin\windows folder.
2.2.1 Examples
Examples are included with the Toolbox zip, and extracted to:
C:\Matlab\Example
Change the current directory to this folder and run any of the read_xxx.m or
create_xxx.m scripts.
There are examples for reading and creating a number of file types. Included are also
some small data files.
3 Functionality
Notation: Text from the MATLAB command window is typeset in courier font. Input written
at the MATLAB command prompt starts with >>, while remaining lines are output, i.e.,
looking like the MATLAB command window. If output is too long, three dots ... will
indicate that the long lines have been truncated.
The DHI MATLAB Toolbox consists of a DFS class for a fast preview of the content of dfs
files.
For handling of Dfs0 files, the compiled binary named MatlabDfsUtil.dll provides more
compact and efficient handling of dfs0 file data than the pure DHI.Generic.MikeZero.DFS
component does. MatlabDfsUtil.dll is compiled based on the DHI.Generic.MikeZero.DFS
component, and provides method for extracting data much faster.
>> NET.addAssembly(
'c:\matlab\mbin\windows\DHI.Generic.MikeZero.DFS.dll');
>> import DHI.Generic.MikeZero.DFS.*;
In the toolbox there is a convenience method named NETaddAssembly that takes only
the name of the .NET library and it will search the MATLAB search path to find and use it:
>> NETaddAssembly('DHI.Generic.MikeZero.DFS.dll');
>> NETaddAssembly('DHI.Generic.MikeZero.EUM.dll');
>> import DHI.Generic.MikeZero.DFS.*;
>> import DHI.Generic.MikeZero.*.*;
These lines above are the most necessary lines to work editing dfs files. Now you are
ready to start. If you want to enable the Matlab DFSutil, you can do it by typing:
>> H = NETaddDfsUtil();
3.2 Examples
With the DHI MATLAB toolbox follows a series of examples that covers the different
functionality.
5
DHI MATLAB Toolbox
dfs0File =
To review the header information, you can just enter the object variable at the command
prompt
>> dfs0File.FileInfo
ans =
The get function will return header data. The content will depend on the file being loaded.
To view available header data, use the FileInfo property:
>> dfs0File.FileInfo
ans =
If you want a certain part of the header information, it can be put as sub Property (case
sensitive).
>> dfs0File.FileInfo.Projection.WKTString
ans =
NON-UTM
7
DHI MATLAB Toolbox
You can update header data using direct assignment into the settable properties.
For instance, if I want to rename the first item of the file you can simply type:
dfs0File =
You can obtain the number of items by using the object properties:
>> dfs0File.ItemInfo
ans =
ReadOnlyCollection< ... > with properties:
Count: 5
A textual detailed description of each item can be obtained by using its index. For
instance if I want to check the last item I would used the index 4 (zero-based):
>> dfs0File.ItemInfo.Item(4)
ans =
DfsDynamicItemInfoWrapper with properties:
AssociatedStaticItemNumbers: [1×1 System.Collections.Obj ...
ValueType: Instantaneous
MaxValue: 359.9213
MinValue: 0.4069
ItemNumber: 5
Name: [1×1 System.String]
Quantity: [1×1 DHI.Generic.MikeZero.e ...
DataType: Float
[... remaining output omitted ...]
The number following the EUM type and unit is the unique integer identifying the type/unit.
To create a new dfs (dfs0) file, you need two factors, a Factory and a build object, which
are objects that can create items, spatial and temporal axis. The builder is used to create
items.
factory = DfsFactory();
We need a map projection to relate the data and a time axis. These are created by the
factory object:
proj = factory.CreateProjectionGeoOrigin('UTM-33',12,54,2.6);
date = System.DateTime(2002,2,25,13,45,32);
unit = eumUnit.eumUsec;
tAxis = factory.CreateTemporalNonEqCalendarAxis(unit, date);
Then, you need to specify the type of data you want to use in the file you are creating:
builder.SetDataType(0);
builder.SetGeographicalProjection(proj);
builder.SetTemporalAxis(tAxis);
Setting the DataType is required. Check out the MIKE SDK User guide for a list of data
type numbers being used in different applications. The other two lines set the projection
and time axis to the recently created ones.
Then we need to create the quantities to be stores in the time series file:
eumWl = eumItem.eumIWaterLevel;
eumMt = eumUnit.eumUmeter;
quantity = DHI.Generic.MikeZero.eumQuantity(eumWl, eumMt);
This quantity, which is a water level measured in meters, will be used in the created file.
Then we need to create an item and include this quantity in the builder:
item1 = builder.CreateDynamicItemBuilder();
item1.Set('WaterLevel item', quantity, dfsdataType);
item1.SetValueType(DataValueType.Instantaneous);
item1.SetAxis(factory.CreateAxisEqD0());
In the lines above we create the item and set the basic item information. Once we have
the item ready, we have to add the item to the file builder:
builder.AddDynamicItem(item1.GetDynamicItemInfo());
Then, we create the file with a single item on it, and get a handle to the file stream:
builder.CreateFile(filename);
dfs = builder.GetFile();
Now we have created the file and we could put data on it.
Writing item data
Writing item data follows the reading functionality. We start by creating a file to write on it:
9
DHI MATLAB Toolbox
The data to write must have the same format as the data returned when reading.
If you are writing a large amount of data into a file, this method will be called inside a
double loop (through all items and through all time steps) which can be highly time
consuming. The alternative is to use the DfsUtil, which will make the writing operations
much faster, and in a single line of code (i.e., no need to make a loop):
netTime = NET.convertArray(times);
nbTimes = size(data,1); % number of time steps
nItems = size(data,2); % number of time steps X number of items
nbType = 'System.Double';
netData = NET.convertArray(data, nbType, nbTimes, nItems);
mu = MatlabDfsUtil;
mu.DfsUtil.WriteDfs0DataDouble(dfs, netTime, netData);
MatlabDfsUtil.DfsUtil.WriteDfs0DataDouble(dfs,
NET.convertArray(times), NET.convertArray(data, 'System.Double',
size(data,1), 1));
You can choose which version to use in your scrips, depending on your scripting
preferences.
To read Data: Use the DfsUtil for bulk-reading all data and time steps in one line. You
need to import it first from the dfs0 library:
import DHI.Generic.MikeZero.DFS.dfs0.*;
dd = double(Dfs0Util.ReadDfs0DataDouble(dfs0File));
time = dd(:,1);
data = dd(:,2:end);
If you want to read a single value, you just get it from the data array. For example, to
obtain the value from item 2, timestep 14, use:
val =
-0.3700
You may retrieve more than one timestep at a time as standard Matlab vector access,
e.g.,
You can use the end keyword to read the last item or the last timestep, i.e.
will read the last timestep of the last item. For more tricks, use the Matlab documentation.
When done working with a file, and you wish to free memory associated with the objects,
use the close function.
>> dfs0File.Close();
>> dfs.Close();
>> dfs.FileInfo.TimeAxis
ans =
>> t = dfs0.ReadItemTimeStep(3,13)
11
DHI MATLAB Toolbox
which will add 1 timestep after the last timestep, incremented with the default timestep
interval. Each item will have delete values added to the added timestep.
factory = DfsFactory();
builder = Dfs1Builder.Create('Matlab dfs1 file','Matlab DFS',0);
builder.SetDataType(0);
The time axis can be created with one of the factory methods, which are summarized in
the following table:
To set the time of each timestep, the procedure depends on the time axis type.
Note that changing the time definition affects all items of the file. Item data values for
removed timesteps are automatically deleted.
Each timestep time can be set individually after creating the file and having items added:
tAxis = factory.CreateTemporalNonEqCalendarAxis(unit,D);
builder.SetTemporalAxis(timeAxis);
builder.CreateFile(filename);
item1 = builder.CreateDynamicItemBuilder();
eumWl = eumItem.eumIWaterLevel;
eumMt = eumUnit.eumUmeter;
quantity = DHI.Generic.MikeZero.eumQuantity(eumWl, eumMt);
The lines above will create a single item and time step in a non equidistant dfs0 file.
Check the installed example to see more details on the edition of dfs files.
When setting times for new timesteps, setting a time value bigger than or equal to the
next Timestep time value or smaller than or equal to the previous Timestep time value is
not possible.
13
DHI MATLAB Toolbox
4 Other Tools
As a part of the DHI MATLAB toolbox a number of tools have been implemented in order
to help the processing of data. They include:
Other tools are available for plotting dfsu data, calculating gradients and more. The tools
are located in the mbin folder (see the installation section), and have an mz prefix.
Elmts is the element-node-connectivity table. Nodes consist of 4 columns, the first 3 are x,
y, and z coordinates for each node, and the last column is a boundary code, telling which
boundary this node belongs to. proj is a text string representing the projection which the
coordinates use.
>> mzWriteMesh(filename,Elmts,Nodes,proj)
Furthermore, there are tools to reorder and refine meshes, see help mzReorderMesh
and help mzRefineMesh for details.
1. Simulation timestep (dt) based on a CFL condition for the shallow water equations
(sqrt(g*h)). Using this measure, the user can decrease simulation runtime. By only
editing a few elements, often a significant amount of time is saved.
2. Smallest angle of elements. Elements with small angles give more inaccurate results
and should be avoided.
3. Smallest area of elements. Small elements close to larger elements can give more
inaccurate results
You can zoom in to the "bad" elements and manually edit the mesh.
1. Collapse a face: Select a face, and the two end-nodes of the face is collapsed to one
node at the center of the face.
2. Collapse an element: Select an element, and the element nodes are collapsed to one
node at the center of the element.
3. Create a quad from two neighbouring triangles, by deleting the face in between the
two.
4. Delete a node: Mesh is updated accordingly.
5. Mode a node
6. Add a node
The tool is based on the concepts and initial analysis code presented in Lambkin, D.O.
(2007), 'Optimising mesh design in MIKE FM', DHI website and in: Dix, J.K., Lambkin,
D.O. and Cazenave, P.W. (2008) 'Development of a Regional Sediment Mobility Model
for Submerged Archaeological Sites', English Heritage ALSF project 5224.
This report considers many important aspects of mesh creation, and is worth reading
before creating your next mesh.
x1 y1 z1 [text]
x2 y2 z2 [text]
where the text is optional. There are two functions provided, for reading and writing xyz
files:
See help mzReadxyz and help mzWritexyz for details on arguments and usage.
15
DHI MATLAB Toolbox
For a 2D file consisting of mixed triangles/quadrilaterals, trimesh will not work, instead
use:
>> mzPlotMesh(t,Nodes);
Plotting dfsu item data cannot be done directly in MATLAB. The reason is that standard
MATLAB triangular plotting routines are based on node values (finite element data), while
most items in the dfsu files contain element centre values (finite volume data). There are
several ways to plot dfsu data in MATLAB:
• Create a triangular mesh based on element centre nodes. Then the raw data will be
plotted, but not on the original mesh
• Interpolate element centre values to node positions. Data values are slightly modified,
but are plotted on the original mesh
• Use the supplied mzPlot routine.
There are routines included supporting the first two options. See the read_dfsu_2D.m
example for details.