XDMF API

From XdmfWeb
Revision as of 11:36, 7 November 2014 by Burns (talk | contribs)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

XdmfLogo1.gif


Note code snippets on this page are from version 2 or 1 and need updating for xdmf 3.

XDMF API

Xdmf2 API Archive

While use of the XDMF API is not necessary to produce or consume valid XDMF datasets, there are many convenience features that make it attractive. The XDMF library give access to a C++ class library that is also wrapped for access from scripting languages like Python.


All XDMF Objects are derived from XdmfObject. Via this object, debug information can be turned on or off for each object or globally for all objects. The methods DebugOn/Off() and GlobalDebugOn/Off() perform these functions respectively.

Most examples here are written in Python for clarity.

XdmfDOM

To understand access to XDMF data, understanding of the XdmfDOM is critical. XDMF uses the libxml2 library to parse and generate XML documents. XdmfDOM is a slightly higher abstraction of the Document Object Model (DOM). The DOM is an in-memory tree structure that represents the XML file. Nodes of the tree are added, deleted, queried and serialized. The low level libxml2 nodes are typedefed as XdmfXmlNode.

The XdmfDOM can parse strings or files :

Status = XdmfDOM.Parse(MyXMLString)
or
Status = XdmfDOM.Parse("MyXMLFile.xmf")

As with many XDMF objects, status is either XDMF_SUCCESS or XDMF_FAIL which is defined in XdmfObject.h.

Once the XML has been parsed into the DOM, the tree can be navigated and modified. There are several useful query mechanisms in XdmfDOM. The first method finds the nth instance of an element below a parent node :

 XdmfXmlNode     FindElement (
                   XdmfConstString TagName, 
                   XdmfInt32 Index=0, 
                   XdmfXmlNode Node=NULL, 
                   XdmfInt32 IgnoreInfo=1
                 )

If Node==NULL the root node is assumed to be the desired parent node. IgnoreInfo allows for all "Information" elements to be ignored. For example, to find the third Grid element under the Domain element :

 DomainNode = XdmfDOM.FindElemet("Domain")       # Take all defaults
 GridNode = XdmfDOM.FindElement("Grid", 2, DomainNode)   # Index is zero based 

By utilizing the XPath functionality of libxml2, the same Grid element can be found by :

 GridNode = XdmfDOM.FindElementByPath("/Xdmf/Domain/Grid[3]")  # XPath is 1 based

Once the desired node is found, it can be queried and modified :

NumberOfChildElements = XdmfDOM.GetNumberOfChildren(GridNode)
Name = XdmfDOM.GetAttribute(GridNode, "Name")
SubGrid = XdmfDOM.InsertNew(GridNode, "Grid")
Status = XdmfDOM.Set(SubGrid, "Name", "My SubGrid")

And finally written back out :

XmlString = XdmfDOM.Serialize(GridNode)
or
Status = XdmfDOM.Write("MyFile.xmf")

XdmfElement

Each element type in an XDMF XML file has a corresponding XDMF object implementation. All of these are children of XdmfElement. Each XdmfElement must be provided with an XdmfDOM with which to operate. On input, the UpdateInformation() method will initialize the basic structure of the element from the XML without reading any HeavyData. The Update() method will access the HeavyData. Each derived object from XdmfElement (XdmfGrid for example) will override these methods.

GridNode = DOM.FindElementByPath("/Xdmf/Domain/Grid[3]")  
Grid = XdmfGrid()               # Create
Grid.SetDOM(DOM)
Grid.SetElement(GridNode)
Grid.UpdateInformation()        # Update Light Structure
Grid.Update()                   # Read HeavyData

Once the DOM has been set for an XdmfElement, there are convenience methods such as Set() and Get() which are equivalent to the XdmfDOM methods. GridName = Grid.Get("Name") Is the same as

DOM = Grid.GetDOM()
GridNode = Grid.GetElement()
GridName = DOM.Get(GridNode, "Name")

For output, the XdmfElement methods Insert() and Build() are used. Each derived object in XDMF will assure that only the proper type of element is inserted. For example, it is illegal to insert a Domain element directly below a Grid element.

Info = XdmfInformation() # Arbitrary Name=Value Facility
Info.SetName("Time")
Info.SetValue("0.0123")
Grid = XdmfGrid()
Grid.Set("Name", "My Grid")
Grid.Insert(Info)
Grid.Build()

Results in

<Grid Name="My Grid">
<Information Name="Time" Value="0.0123" />
</Grid>

The Build() method is recursive so that Build() will automatically be called for all child elements.

XdmfArray

The XdmfArray class is a self describing data structure. It is derived from the XdmfDataDesc class that gives it number type, precision, and shape (rank and dimensions). Many XDMF classes require an XdmfArray as input to methods. The following C++ example demonstrates creating an interlaced XYZ array from three separate variables:

float           *x, *y, *z;
XdmfInt64       total, dims[3];
XdmfArray       *xyz = new XdmfArray;
dims[0] = 10;
dims[1] = 20;
dims[2] = 30;
total = 10 * 20 * 30;
xyz->SetNumberType(XDMF_FLOAT64_TYPE)
xyz->SetShape(3, dims);    // KDim, JDim, IDim
xyz->SetValues(0, x, total, 3, 1);  //       SetValues (XdmfInt64 Index, XdmfFloat64 *Values,
                                    //           XdmfInt64 NumberOfValues, XdmfInt64 ArrayStride=1,
                                    //           XdmfInt64 ValuesStride=1)
xyz->SetValues(1, y, total, 3, 1);
xyz->SetValues(2, z, total, 3, 1);

When an XdmfArray is created, it is given a unique tag name. Array operations can be performed on XdmfArray data by using this name in an XdmfExpr(). The following Python program gives some examples.

from Xdmf import *

def Expression(*args) :
   e = 
   for arg in args :
       if hasattr(arg, 'GetTagName') :
           e += arg.GetTagName() + ' '
       else :
           e += arg + ' '
   return XdmfExpr(e)

if __name__ == '__main__' :
   a1 = XdmfArray()
   a1.SetNumberType(XDMF_FLOAT32_TYPE)
   a1.SetNumberOfElements(20)
   a1.Generate(1, 20)
   a2 = XdmfArray()
   a2.SetNumberType(XDMF_INT32_TYPE)
   a2.SetNumberOfElements(5)
   a2.Generate(2, 10)
   print 'a1 Values = ', a1.GetValues()
   print 'a1[2:10] = ' + Expression(a1 , '[ 2:10 ]').GetValues()
   print 'a2 Values = ', a2.GetValues()
   print 'a1[a2] = ' + Expression(a1 , '[', a2, ']').GetValues()
   print 'a1 + a2 = ' + Expression(a1 , ' + ', a2).GetValues()
   print 'a1 * a2 = ' + Expression(a1 , ' * ', a2).GetValues()
   a2.SetNumberType(XDMF_FLOAT32_TYPE)
   a2.SetNumberOfElements(20)
   a2.Generate(21, 40)
   print 'a2 Values = ', a2.GetValues()
   print 'a1 , a2 (Interlace) = ' + Expression(a1 , ' , ', a2).GetValues()
   print 'a1 , a2, a1 (Interlace) = ' + Expression(a1 , ' , ', a2, ' , ', a1).GetValues()
   print 'a1 ; a2 (Concat) = ' + Expression(a1 , ' ; ', a2).GetValues()
   print 'where(a1 > 10) = ' + Expression('Where( ', a1 , ' > 10)').GetValues()
   print 'a2[where(a1 > 10)] = ' + Expression(a2, '[Where( ', a1 , ' > 10)]').GetValues()


While most of the functions are self explanatory the WHERE function is not. WHERE will return the indexes of the XdmfArray where a certain condition is true. In this example WHERE returns the indexes of XdmfArra y a1 where a1 is greater than 10. Notice that the XdmfExpr() function makes it easy to extract part of an XdmfArray.

XdmfTime

When UpdateInformation() gets called for a Grid, an XdmfTime object is added to the Grid with TimeType set to XDMF_TIME_UNSET. If there is a <Time> element in the Grid the object is populated. If the Grid is Non-Uniform (i.e. Collection, Tree), the children are updated as well. If the parent is TimeType="HyperSlab" then the child is XDMF_TIME_SINGLE with the appropriate value set.

Methods :

XdmfInt32 XdmfTime::Evaluate(XdmfGrid *Grid, XdmfArray *ArrayToFill = NULL, XdmfInt32 Descend = 0, XdmfInt32 Append = 0)

This will populate the array with the valid times in the Grid. If Descend = 1 then it is recursive. If Append = 1 the values are appended to the given array not overwritten.

XdmfInt32 XdmfTime::IsValid(XdmfFloat64 TimeMin, XdmfFloat64 TimeMax)

this checks to see if the Time is entirely in Min/Max. Since this is a float comparison, I added an Epsilon member to XdmfTime with default value = 1e-7. This may be changed via XdmfTime::SetEpsilon()

XdmfInt32 XdmfGrid::FindGridsInTimeRange(XdmfFloat64 TimeMin, XdmfFloat64 TimeMax, XdmfArray *ArrayToFill)

This populates the array with the direct children that are entirely in min/max. For example if the range is 0.0 to 0.5 with TimeMin=0.25 and TimeMax=1.25 this will return XDMF_FAIL.


XdmfHDF

In XDMF, Light data is stored in XML while the Heavy data is typically stored in an HDF5 file. The XdmfHDF class simplifies access to HDF5 data, it is also derived from XdmfDataDesc. The following Python code demonstrates its use :


       from Xdmf import *
Geometry = "-1.75 -1.25 0 -1.25 -1.25 0 -0.75 
Connectivity = "3 2 5 1 .
Values = "100 200 300 ..

from Xdmf import *

# Geometry
GeometryArray = XdmfArray()
GeometryArray.SetValues(0, Geometry)
H5 = XdmfHDF()
H5.CopyType(GeometryArray)
H5.CopyShape(GeometryArray)
# Open for Writing. This will truncate the file.
H5.Open('Example1.h5:/Geometry', 'w')
H5.Write(GeometryArray)
H5.Close()

# Coneectivity
ConnectivityArray = XdmfArray()
ConnectivityArray.SetValues(0, Connectivity)
H5 = XdmfHDF()
H5.CopyType(ConnectivityArray)
H5.CopyShape(ConnectivityArray)
# Open for Reading and Writing. This will NOT truncate the file.
H5.Open('Example1.h5:/Connectivity', 'rw')
H5.Write(ConnectivityArray)
H5.Close()

# Values
ValueArray = XdmfArray()
ValueArray.SetValues(0, Values)
H5 = XdmfHDF()
H5.CopyType(ValueArray)
H5.CopyShape(ValueArray)
# Open for Reading and Writing. This will NOT truncate the file.
H5.Open('Example1.h5:/Values', 'rw')
H5.Write(ValueArray)
H5.Close()


For reading, XdmfHDF will allocate an array if none is specified :

Status = H5.Open("Example1.h5:/Values", "rw")
ValueArray = H5.Read()

Reading XDMF

Putting all of this together, assume Points.xmf is a valid XDMF XML file with a single uniform Grid. Here is a Python example to read and print values.

dom = XdmfDOM()
dom.Parse("Points.xmf")

ge = dom.FindElementByPath("/Xdmf/Domain/Grid")
grid = XdmfGrid()
grid.SetDOM(dom)
grid.SetElement(ge)
grid.UpdateInformation()
grid.Update() 

top = grid.GetTopology()
top.DebugOn()
conn = top.GetConnectivity()
print "Values = ", conn.GetValues()

geo = grid.GetGeometry()
points = geo.GetPoints()
print  "Geo Type =  ", geo.GetGeometryTypeAsString(), " #  Points = ",    geo.GetNumberOfPoints()
print  "Points =  ", points.GetValues(0, 6)

Writing XDMF

Using the Insert() and Build() methods, an XDMF dataset can be generated programmatically as well . Internally, as XDMF objects are inserted, the DOM is "decorated" with their pointers. In this manner, the api c an get a object from an node of the DOM if it has been created. For reading XDMF, this allows multiple references to the same DataItem not to result in additional IO. For writing, this allows Build() to work recursively.

d = XdmfDOM()

root = XdmfRoot()
root.SetDOM(d)
root.SetVersion(2.2) # Change the Version number because we can
root.Build()
# Information
i = XdmfInformation() # Arbitrary Name=Value Facility
i.SetName("Time")
i.SetValue("0.0123")
root.Insert(i) # XML DOM is used as the keeper of the structure
              # Insert() creates an XML node and inserts it under
              # the parent
# Domain
dm = XdmfDomain()
root.Insert(dm)
# Grid
g = XdmfGrid()
g.SetName("Structured Grid")
# Topology
t = g.GetTopology()
t.SetTopologyType(XDMF_3DCORECTMESH)
t.GetShapeDesc().SetShapeFromString('10 20 30')
# Geometry
geo = g.GetGeometry()
geo.SetGeometryType(XDMF_GEOMETRY_ORIGIN_DXDYDZ)
geo.SetOrigin(1, 2, 3)
geo.SetDxDyDz(0.1, 0.2, 0.3)
dm.Insert(g)
# Attribute
attr = XdmfAttribute()
attr.SetName("Pressure")
attr.SetAttributeCenter(XDMF_ATTRIBUTE_CENTER_CELL);
attr.SetAttributeType(XDMF_ATTRIBUTE_TYPE_SCALAR);
p = attr.GetValues()
p.SetNumberOfElements(10 * 20 * 30)
p.Generate(0.0, 1.0, 0, p.GetNumberOfElements() - 1)
# If an array is given a HeavyDataSetName, that is
# where it will be written
p.setHeavyDataSetName('MyData.h5:/Pressure')
g.Insert(attr)
# Update XML and Write Values to DataItems
root.Build() # DataItems > 100 values are heavy
print d.Serialize() # prints to stdout
d.Write('junk.xmf') # write to file