Utility functions (cgnsutils.py)

CGNS.PAT.cgnsutils.nodeCreate(name, value, children, type, parent=None, dienow=False)

Create a new node with and bind it to its parent:

import CGNS.PAT.cgnskeywords as CK
import numpy

n=createNode('Base',numpy.array([3,3]),[],CK.CGNSBase_ts)
z=createNode('ReferenceState',None,[],CK.ReferenceState_ts,parent=n)

# you can safely create a node without referencing its return,
# the actual new node is stored into the parent's children list
createNode('ReferenceState',None,[],CK.ReferenceState_ts,parent=n)
Parameters:
  • name (str) – new node name
  • value (numpy.ndarray) – node value
  • children (list) – list of node children (list of CGNS/Python nodes)
  • type (str) – CGNS/SIDS node type
  • parent (node) – node where to insert the new node (default: None)
  • dienow (bool) – If True raises an exception on error (default:False)
Returns:

the new node

Remarks :
  • If parent is None (default) node is orphan (see comment in example)
  • Adds checks with checkNodeCompliant() only if dienow is True
CGNS.PAT.cgnsutils.nodeCopy(node, newname=None, share=False)

Creates a new node sub-tree as a copy of the argument node sub-tree. A deep copy is performed on the node, including the values, which can lead to a very large memory use:

n1=getNodeByPath(T,'/Base/Zone1/ZoneGridConnectivity')
n2=getNodeByPath(T,'/Base/Zone1/ZoneGridConnectivity/Connect1')
n3=nodeCopy(n2,'Connect2')
nodeChild(n1,n3)
Parameters:
  • node (node) – node to copy
  • name (str) – new node (copy) name
  • share (bool) – if True then actual numpy.ndarray in not copied (if possible)
Returns:

The new node

Remarks :
  • The new node name is the same by default, thus user would have to check for potential duplicated name
  • The node value is a copy too, numpy.ndarray is duplicated
  • Default is to deep copy including numpy.ndarrays
CGNS.PAT.cgnsutils.nodeDelete(tree, node, legacy=False)

Deletes a node from a tree:

import CGNS.PAT.cgnslib as CL
import CGNS.PAT.cgnsutils as CU
import numpy
    
T =CL.newCGNSTree()
b1=CL.newBase(T,'Base',3,3)
z1=CL.newZone(b1,'Zone1',numpy.array([1,2,3]))
z2=CL.newZone(b1,'Zone2',numpy.array([1,2,3]))
print CU.getPathFullTree(T)
# ['/CGNSLibraryVersion', '/Base',
#  '/Base/Zone1','/Base/Zone1/ZoneType',
#  '/Base/Zone2', '/Base/Zone2/ZoneType']
CU.nodeDelete(T,z1)
print CU.getPathFullTree(T)
# ['/CGNSLibraryVersion', '/Base', '/Base/Zone2', '/Base/Zone2/ZoneType']
Parameters:
  • tree (node) – target tree where to find the node to remove
  • node – a CGNS/Python node or str (node name) as absolute path to remove
Return :

The tree argument (without the deleted node)

Remarks :
  • Uses checkSameNode().
  • Actual memory of the node is released only if there is no other reference
  • No action if the node to delete is not found
CGNS.PAT.cgnsutils.checkNodeName(node, dienow=False)

Checks if the name is CGNS/Python compliant node name:

if (not checkNodeName(node)):
    print 'Such name ',name,' not allowed'
Parameters:

node (CGNS/Python) – node to check

Returns:

True if the name has a correct syntax

Remarks :
CGNS.PAT.cgnsutils.checkName(name, dienow=False, strict=False)

Checks if the name is CGNS/Python compliant node name. The name should be a Python string of type str or unicode, but str is strongly recommanded. A name should follow these requirements:

  • No more than 32 chars
  • No / in the string
  • Empty name or name with only spaces is forbidden
  • Names . and .. are forbidden
  • Allowed chars are string.letters + string.digits + string.punctuation + ' '

Additional checks can be performed with the strict flag set to True, these checks are not CGNS compliant:

  • No prefix nor suffix spaces
  • No more than two consecutive spaces
  • Punctuation is limited to: !#$%&()*+,-.:;<=>?@[]^_{|}~

The check following pattern shows a two steps verification:

if (not checkName(name)):
   raise Exception('Such name %s not allowed'%name)
elif (not checkName(name,strict=True)):
   print 'name ok but unsafe'
Parameters:
  • name (str) – string to check
  • strict (bool) – forces the ‘strict’ mode checks (default is False)
Returns:

True if the name has a correct syntax

Remarks :
  • Type of name should be a str
  • Name cannot be empty
  • There is no way to check against a regular expression
Raises :

codes 22,23,24,25,29,31,32,33,34 if dienow is True

CGNS.PAT.cgnsutils.setAsChild(parent, node)

Adds a child node to the parent node children list:

n1=getNodeByPath(T,'/Base/Zone1/ZoneGridConnectivity')
n2=getNodeByPath(T,'/Base/Zone1/ZoneGridConnectivity/Connect1')
n3=nodeCopy(n2)
setChild(n1,n3)
Parameters:
  • parent (CGNS/Python) – the parent node
  • node (CGNS/Python) – the child node to add to parent
Returns:

The parent node

Remarks :
  • No check is performed on duplicated child name or any other validity.
CGNS.PAT.cgnsutils.checkDuplicatedName(parent, name, dienow=False)

Checks if the name is not already in the children list of the parent:

count=1
while (not checkDuplicatedName(node,'solution#%.3d'%count)): count+=1
Parameters:
  • parent (CGNS/Python) – the parent node
  • name (str) – the child name to look for
Returns:

  • True if the child IS NOT duplicated
  • False if the child IS duplicated

Remarks :
Raise :

cgnsNameError code 102 if dienow is True

CGNS.PAT.cgnsutils.checkChildName(parent, name, dienow=False)

Checks if the name is in the children list of the parent:

count=1
while (checkChildName(node,'solution#%.3d'%count)): count+=1
Parameters:
  • parent (CGNS/Python) – the parent node
  • name (str) – the child name to look for
Returns:

True if the child exists

Remarks :
  • Same function as checkDuplicatedName but with the NOT return
Raise :

cgnsNameError code 102 if dienow is True

CGNS.PAT.cgnsutils.getChildName(parent, name, dienow=False)

Checks if the name is in the children list of the parent, if the name already exists, a new name is returned. If the name doesn’t exist the name itself is returned:

z=CGU.setAsChild(T,CGU.getChildName(T,'BASE'))
Parameters:
  • parent (CGNS/Python) – the parent node
  • name (str) – the child name to look for
Returns:

  • arg name is it doesn’t exist
  • a new unique name if arg name already exists

CGNS.PAT.cgnsutils.checkNodeType(node, cgnstype=[], dienow=False)

Check the CGNS type of a node. The type can be a single value or a list of values. Each type to check is a string such as CGNS.PAT.cgnskeywords.CGNSBase_ts constant for example. If the list is empty, the check uses the list of all existing CGNS types:

import CGNS.PAT.cgnskeywords as CK

n=createNode('Base',numpy([3,3]),[],CK.CGNSBase_ts)
checkNodeType(n)
checkNodeType(n,['Zone_t',CK.CGNSBase_ts])
checkNodeType(n,CGK.FamilyName_ts)
Parameters:
  • node (node) – target node to check
  • cgnstype (list) – a list of strings with the CGNS/SIDS types to check
Returns:

  • True if the type is a CGNS/SIDS the argument list.
  • False if the type is a CGNSType or a type in the argument list.
  • None if the parent is None (may change to have consistent return)

Raises :

cgnsTypeError codes 103,104,40 if dienow is True

Remarks :
  • The default value for cgnstype is the list of all CGNS/SIDS types
CGNS.PAT.cgnsutils.checkType(parent, ltype, name, dienow=False)

same as checkNodeType

CGNS.PAT.cgnsutils.checkParentType(parent, stype)

same as checkType but checks the parent type instead of the current node

CGNS.PAT.cgnsutils.checkNode(node, dienow=False)

Checks if a node is a compliant CGNS/Python node structure of list. The syntax for a compliant node structure is:

[<name:string>, <value:numpy>, <children:list-of-nodes>, <cgnstype:string>]

With the following exception: a value can be None.

The function checks the syntax of the node and the types of its contents, it doesn’t perform sub checks such as checkNodeName, checkNodeType...

You should always check first the node structure, a function such as checkNodeName blindly access to the first item of the list and would raise an exception if the structure is not correct.

Parameters:

node (CGNS/Python) – the CGNS/Python node to check

Returns:

True if the node is ok

Remarks :
Raise :

cgnsNodeError codes 1,2,3,4,5 if dienow is True

CGNS.PAT.cgnsutils.checkRootNode(node, legacy=False, dienow=False)

Checks if a node is the CGNS/Python tree root node. If legacy is True, then [None, None, [children], None] is accepted as Root. If it is not True (default) then a CGNS/Python node of type CGNSTree_t is expected as root node. Children contains then the CGNSLibraryVersion and CGNSBase nodes as flat list. The flat pattern with a list containing CGNSLibraryVersion and zero or more CGNSBase nodes is not accepted. You should use a trick as the one above by giving this pattern as child of a fake node:

# flatpattern is a CGNS/Python list with a `CGNSLibraryVersion` node
# and `CGNSBase` nodes at the same level.
# we build a temporary children list

tmp=[None, None, [flatpattern], None]
if (checkRootNode(tmp,True)):
  print 'CGNS/Python tree has a legacy root node'
Parameters:
  • node (CGNS/Python) – the node to check
  • legacy (bool) – True means you accept non-CGNSTree_t node
Returns:

True if the node is a root node

Raises :

cgnsNodeError codes 90,91,99 if dienow is True

CGNS.PAT.cgnsutils.checkSameNode(nodeA, nodeB, dienow=False)

Checks if two nodes have the same contents: same name, same CGNS/SIDS type, same number of children, same value type (None of numpy). The children are not parsed, the value itself is not checked (see checkSameValue()):

if (checkSameNode(nodeA,nodeB)):
  nodeB=copyNode(nodeB)
Parameters:
  • nodeA (CGNS/Python) – first node to compare
  • nodeB (CGNS/Python) – seconf node to compare
Returns:

True if the nodes are same

Remarks :
Raise :

cgnsNodeError code 30 if dienow is True

CGNS.PAT.cgnsutils.checkSameValue(nodeA, nodeB, dienow=False)

Checks if two nodes have the same value. There is no tolerance on actual array values when these are compared one to one. This could lead to time consuming operations for large arrays:

if (not checkSameValue(nodeA,nodeB)):
  raise Exception('Not the same value')
Parameters:
  • nodeA (CGNS/Python) – first node to compare the value with
  • nodeB (CGNS/Python) – second node to compare the value with
Returns:

True if the nodes have same value

Raise :

cgnsNodeError code 30 if dienow is True

CGNS.PAT.cgnsutils.checkArray(a, dienow=False, orNone=True)

Check if the array value of a node is a numpy array:

if (not checkArray(node[1])):
  raise Exception('Bad array (for a CGNS/Python node)')
Parameters:a (object) – value to check
Returns:True if the arg array is suitable as CGNS/Python value
Raise :error codes 109,170 if dienow is True
CGNS.PAT.cgnsutils.checkArrayChar(a, dienow=False)

same as checkArray for an array of type C1

CGNS.PAT.cgnsutils.checkArrayReal(a, dienow=False)

same as checkArray for an array of type R4 or R8

CGNS.PAT.cgnsutils.checkArrayInteger(a, dienow=False)

same as checkArray for an array of type I4 or I8

CGNS.PAT.cgnsutils.checkNodeCompliant(node, parent=None, dienow=False)

Performs all possible checks on a node. Can raise any of the exceptions related to node checks (checkNodeName(), checkNodeType(), checkArray()...):

if (not checkNodeCompliant(node)):
  raise Exception('Bad Node')
Parameters:
  • node (CGNS/Python) – the CGNS/Python node to check
  • parent (CGNS/Python) – CGNS/Python parent node to check (if not None)
Returns:

True if all controls are ok

Remarks :
CGNS.PAT.cgnsutils.concatenateForArrayChar2D(nlist)

Creates a numpy.ndarray of chars from a list of python strings:

udims=['Kilogram','Meter','Second','Kelvin','Gradian']
a=concatenateForArrayChar2D(udims)

The result is a numpy.ndarray of type ‘S’ with a shape of (32,N) for N strings. In the example above the value of a[:,1] is ‘Meter’ with an added padding of 27 ‘spaces’. The order of the values in the second axis is kept unchanged.

CGNS.PAT.cgnsutils.concatenateForArrayChar3D(nlist)

Creates a numpy.ndarray of chars from a list of list of python strings

CGNS.PAT.cgnsutils.getValueType(v)

Returns the node’s value type as CGNS/MLL type. The return value is a string in: Character, RealSingle, RealDouble, Integer, LongInteger

CGNS.PAT.cgnsutils.setStringByPath(T, path, s)

Creates a 1D numpy.ndarray from one string, set to node by path:

p=’/{Base#1}/BaseIterativeData/DataClass’ setStringByPath(T,p,’UserDefined’)

CGNS.PAT.cgnsutils.setStringAsArray(a)

Creates a numpy.ndarray from a string:

setStringAsArray(‘UserDefined’)

CGNS.PAT.cgnsutils.setIntegerByPath(T, path, *i)

Creates a 1D numpy.ndarray from one or more integers, set to node by path. Same as setLongByPath() but with a numpy.int32 data type.

CGNS.PAT.cgnsutils.setIntegerAsArray(*i)

Creates a 1D numpy.ndarray from one or more integers. Same as setLongAsArray() but with a numpy.int32 data type.

CGNS.PAT.cgnsutils.setLongByPath(T, path, *l)

Creates a 1D numpy.ndarray from one or more longs, set to node by path:

p='/{Base#1}/BaseIterativeData/NumberOfZones'
setFloatByPath(T, p, 2)

p='/{Base#1}/BaseIterativeData/IterationValues'
setFloatByPath(T, p, 1, 2, 3, 4, 5)
setFloatByPath(T, p, tuple(range(10,1010,10)))

The set value has numpy.int64 data type

CGNS.PAT.cgnsutils.setLongAsArray(*l)

Creates a 1D numpy.ndarray from one or more longs:

setLongAsArray(2)
setLongAsArray(1, 2, 3, 4, 5)
setLongAsArray(tuple(range(10,1010,10)))

The set value has numpy.int64 data type

CGNS.PAT.cgnsutils.setFloatByPath(T, path, *f)

Creates a 1D numpy.ndarray from one or more floats, set to node by path:

p='/{Base#1}/{Zone-A}/ReferenceState/Coef_PressureDynamic'
setFloatByPath(T, p, 2837.153)

p='/{Base#1}/{Zone-A}/ReferenceState/Coef_Local'
setFloatByPath(T, p, 2.1, 2.2, 2.3, 2.4)

The set value has numpy.float32 data type

CGNS.PAT.cgnsutils.setFloatAsArray(*f)

Creates a 1D numpy.ndarray from one or more floats:

setFloatAsArray(2837.153)
setFloatAsArray(2.1, 2.2, 2.3, 2.4)
setFloatAsArray(tuple(range(10,1010,10)))

The returned array has numpy.float32 data type

CGNS.PAT.cgnsutils.setDoubleByPath(T, path, *d)

Creates a 1D numpy.ndarray from one or more doubles, set to node by path. Same as setFloatByPath() but with a numpy.float64 data type.

CGNS.PAT.cgnsutils.setDoubleAsArray(*d)

Creates a 1D numpy.ndarray from one or more doubles. Same as setFloatByArray() but with a numpy.float64 data type.

CGNS.PAT.cgnsutils.getValue(node)

Returns node value, could be None or a numpy.ndarray.

CGNS.PAT.cgnsutils.hasFortranFlag(node)

Returns node value fortran flag.

CGNS.PAT.cgnsutils.getValueShape(node)

Returns the value data shape for a CGNS/Python node for display purpose. If the shape cannot be determined a - is returned:

print 'node data shape is %s'%getValueShape(node)
Parameters:node (CGNS/Python) – the target node
Returns:A string with the shape
CGNS.PAT.cgnsutils.getAuthNames(node)

Returns the authorized names for a CGNS/Python node. If the names cannot be determined a None is returned:

node=['gasmodel',None,[],'GasModel_t']
if (node[0] not in getAuthNames(node)):
  print 'not SIDS compliant name'
Parameters:node (CGNS/Python) – the target node
Returns:A list of authorized names
CGNS.PAT.cgnsutils.getAuthDataTypes(node)

Returns the authorized types for a CGNS/Python node. If the types cannot be determined a None is returned:

if (getValueType(node) not in getAuthDataTypes(node)):
  print 'Type of node value is not SIDS comliant'
Parameters:node (CGNS/Python) – the target node
Returns:A list of authorized data types
CGNS.PAT.cgnsutils.getAuthParentTypes(node)

Returns the authorized parent types for a CGNS/Python node. If the parent types cannot be determined a None is returned:

np=getParentFromNode(T,node)
if (np[3] not in getAuthParentTypes(node)):
   p=getPathByNode(T,node)
   print '[%s] cannot have parent of type [%s]'%(p,np[3])
Parameters:node (CGNS/Python) – the target node
Returns:A list of authorized parent types
CGNS.PAT.cgnsutils.getAuthShapes(node)

Returns the authorized shapes for a CGNS/Python node. If the shapes cannot be determined a None is returned:

if (getShape(node) not in getAuthShapes(node)):
  p=getPathByNode(T,node)
  print '[%s] cannot have shape [%s]'%(p,getShape(node))
Parameters:node (CGNS/Python) – the target node
Returns:A list of authorized shapes
CGNS.PAT.cgnsutils.getAuthChildren(node)

Returns the authorized children for a CGNS/Python node. If the children types cannot be determined a None is returned:

if (hasChildNodeOfType(node) not in getAuthChildren(node)):
  p=getPathByNode(T,node)
  print '[%s] cannot have [%s] of type [%s] as child'%(p,node[0],node[3])
Parameters:node (node) – target node
Returns:list of str, authorized CGNS/SIDS types for children
CGNS.PAT.cgnsutils.getValueDataType(node)

Returns the value data type for a CGNS/Python node for display purpose:

print 'node data type is %s'%getValueDataType(node)
Parameters:

node (CGNS/Python) – function target

Returns:

A data type as string in [`C1`,`I4`,`I8`,`R4`,`R8`,`??`]

Remarks :
  • ?? returned if datatype is not one of [`C1`,`I4`,`I8`,`R4`,`R8`]
  • Then None value returns ??
  • There is no LK link type with the CGNS/Python mapping
CGNS.PAT.cgnsutils.hasFirstPathItem(path, item='CGNSTree')

True if the arg string is the item of the path

p=’/{Base#1}/{Zone-A}/ZoneGridConnectivity’ print hasFirstPathItem(p,’{Base#1}’) # True
Parameters:
  • path (str) – path to process
  • item (str) – item to check against
Return bool:

True if first item matches arg

Remarks :
CGNS.PAT.cgnsutils.removeFirstPathItem(path)

Return the path without the first item:

print removeFirstPathItem('/{Base#1}/{Zone-A}/ZoneGridConnectivity')
# '/{Zone-A}/ZoneGridConnectivity'
Parameters:

path (str) – path to process

Returns:

path without first token

Remarks :
CGNS.PAT.cgnsutils.getNodeByPath(tree, path)

Returns the CGNS/Python node with the argument path:

zbc=getNodeByPath(T,'/Base/Zone001/ZoneBC')
nchildren=len(childrenNames(zbc))

The path is compared as a string, you should provide the exact path if you have a sub-tree or a tree with its CGNSTree fake node. The following lines are not equivalent (sic!):

zbc=getNodeByPath(T,'/Base/Zone001/ZoneBC')
zbc=getNodeByPath(T,'/CGNSTree/Base/Zone001/ZoneBC')

You can change the relative root by giving any sub-node of the complete tree. For example, to get a specific BC node in a zone, you first look for the ZoneBC of the zone and you use the returned node a the new root:

zbc=getNodeByPath(T,'/Base/Zone001/ZoneBC')
nbc=getNodeByPath(zbc,'./wall01')
Parameters:
  • tree (node) – the target tree to parse
  • path (str) – absolute or relative path
Returns:

  • The CGNS/Python node matching the path
  • Returns None if the path is not found

Remarks :
CGNS.PAT.cgnsutils.getValueByPath(tree, path)

Returns the value of a CGNS/Python node with the argument path:

import CGNS.PAT.cgnskeywords as CK

v=getNodeByPath(T,'/Base/Zone001/ZoneType')
if (v == CK.Structured_s): print 'Structured Zone Found'
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • path (str) – absolute or relative path
Returns:

  • CGNS/Python node value matching the path
  • Returns None if the path is not found

Remark :
CGNS.PAT.cgnsutils.getChildrenByPath(tree, path)

Returns the children list of a CGNS/Python node with the argument path:

import CGNS.PAT.cgnskeywords as CK

for bc in getChildrenByPath(T,'/Base/Zone01/ZoneBC'):
  if (bc[3] == CK.BC_ts): 
    print 'BC found:', bc[0]
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • path (str) – absolute or relative path
Returns:

  • The CGNS/Python node children list of node matching the path
  • Returns None if the path is not found

Remark :
CGNS.PAT.cgnsutils.getNextChildSortByType(node, parent=None, criteria=None)

Iterator returns the children list of the argument CGNS/Python sorted using the CGNS type then the name. The sortlist gives an alternate sort list/dictionnary:

for child in getNextChildSortByType(node):
    print 'Next child:', child[0]

zonesort=[CGK.Elements_ts, CGK.Family_ts, CGK.ZoneType_ts]
for child in getNextChildSortByType(node,criteria=mysort):
    print 'Next child:', child[0]

mysort={CGK.Zone_t: zonesort}
for child in getNextChildSortByType(node,parent,mysort):
    print 'Next child:', child[0]
Parameters:
  • node (CGNS/Python) – the target
  • parent (CGNS/Python) – the parent
  • criteria (list) – a list or a dictionnary used as the sort criteria
Returns:

  • This is an iterator, it returns a CGNS/Python node

Remarks :
  • The function is an iterator
  • If criteria is a list of type, the sort order for the type is the list order. If it is a dictionnary, its keys are the parent types and the values are list of types.
  • Default value for criteria is CGNS.PAT.cgnskeywords.cgnstypes
CGNS.PAT.cgnsutils.getTypeByPath(tree, path)

Returns the CGNS type of a CGNS/Python node with the argument path:

import CGNS.PAT.cgnskeywords as CK

if (getTypeByPath(T,'/Base/Zone01/ZoneBC/')):
  if (bc[3] == CK.BC_ts): 
    print 'BC found:', bc[0]
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • path (str) – absolute or relative path
Returns:

  • the CGNS/SIDS type (str)
  • None if the path is not found

Remark :
CGNS.PAT.cgnsutils.getPathsByNameFilter(tree, filter)

Returns a list of paths from T matching the filter. The filter is a regular expression used to match the path of node names:

import CGNS.PAT.cgnskeywords as CK

for path in getPathsByNameFilter(T,'/Base[0-1]/domain\..*/.*/.*/FamilyName'):
   print 'FamilyName ',path,' is ',path[2]
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • filter (str) – a regular expression for the complete path to match to
Returns:

  • A list of paths (strings) matching the path pattern
  • Returns empty list if no match

Remarks :
  • The ‘/’ is the separator for the path tokens, so you cannot use it in the regular expression for any other purpose
  • Always skips CGNSTree_t
CGNS.PAT.cgnsutils.getPathsByTypeFilter(tree, filter)

Returns a list of paths from T matching the filter. The filter is a regular expression used to match the path of node types:

# gets GridConnectivity_t and GridConnectivity1to1_t
allconnectivities=getPathsByTypeFilter(T,'/.*/.*/.*/GridConnectivity.*')
Parameters:
  • tree (node) – the target tree to parse
  • filter (str) – a regular expression for the complete path to match to
Return :
  • A list of paths (str) matching the types-path pattern
  • Returns empty list if no match
Remarks :
  • The ‘/’ is the separator for the path tokens, so you cannot use it

in the regular expression for any other purpose

  • Always skips CGNSTree_t
CGNS.PAT.cgnsutils.removeChildByName(parent, name)

Remove the child from the parent node.

Parameters:
  • node (CGNS/Python) – node where to find the child name
  • name (str) – name of the child to delete (with all its sub-tree)
Returns:

None

Remarks :
  • node name to delete is a direct child of the parent node
  • See also nodeDelete()
CGNS.PAT.cgnsutils.getParentFromNode(tree, node)

Returns the parent node of a node. If the node is root node, itself is returned:

parent=getParentFromNode(T,node)
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • node (CGNS/Python) – child node
Returns:

  • the parent node
  • arg node itself if node is root

CGNS.PAT.cgnsutils.getAncestorByType(tree, node, ptype)

Returns the parent node of a node which has the CGNS/SIDS type. If the node is root node, itself is returned:

>>> import CGNS.PAT.keywords as CGK
>>> base=getParentByType(T,node,CGK.CGNSBase_ts)
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • node (CGNS/Python) – child node
  • type (CGNS/SIDS) – required type of the parent
Returns:

  • the parent node with CGNS/SIDS type
  • arg node itself if node is root
  • None if CGNS/SIDS type not in parents node

CGNS.PAT.cgnsutils.getPathFromRoot(tree, node)

Same as getPathFromNode() but takes into account the root node name:

n=CGU.nodeCreate('Base',numpy.array([3,3]),[],CGK.CGNSBase_ts)
r=CGU.nodeCreate('State',None,[],CGK.ReferenceState_ts,parent=n)
d=CGU.nodeCreate('Data',numpy.array([3.14]),[],CGK.DataArray_ts,parent=r)

CGU.getPathFromRoot(n,d)
# '/Base/State/Data'
CGU.getPathFromRoot(r,d)
# '/Base/Data'
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • node (CGNS/Python) – target node
Returns:

  • the path of the node (str)

CGNS.PAT.cgnsutils.getPathFromNode(tree, node, path='')

Returns the path from a node in a tree. The argument tree is parsed and a path is built-up until the node is found. Then the start node name is not taken into account. For example:

n=CGU.nodeCreate('Base',numpy.array([3,3]),[],CGK.CGNSBase_ts)
r=CGU.nodeCreate('State',None,[],CGK.ReferenceState_ts,parent=n)
d=CGU.nodeCreate('Data',numpy.array([3.14]),[],CGK.DataArray_ts,parent=r)

CGU.getPathFromNode(n,d)
# '/State/Data'
CGU.getPathFromNode(r,d)
# '/Data'

In the case you want to add the name of the root node (start node) in the path, you should use the path argument (see also getPathFromRoot()):

CGU.getPathFromNode(n,d,'/'+n[0])
# '/Base/ReferenceState/Data'

The functions behaves like this for historical reasons, the root of a CGNS/Python tree is CGNSTree but is not CGNS/SIDS compliant. So the path of a CGNSBase_t, starting from the root node, is /Base instead of the logically expected /CGNSTree/CGNSBase.

The node object is compared to the tree nodes, if you have multiple references to the same node, the first found is used for the path:

# T is a compliant CGNS/Python tree
path=getPathFromNode(T,node)
getNodeByPath(T,getPathAncestor(path))
Parameters:
  • tree (CGNS/Python) – target tree to parse
  • node (CGNS/Python) – target node to find
  • path (string) – name of the root node to add if desired
Returns:

  • path as string
  • None if not found

Remark :
CGNS.PAT.cgnsutils.getPathsByTypeOrNameList(tree, typeornamelist)

Returns a list of paths from the argument tree with nodes matching the list of types or names. The list you give is the list you would have if you pick the node type or the node name during the parse:

tnlist=['CGNSTree_t','Base#001','Zone_t']

for path in getPathsByTypeOrNameList(T,tnlist):
   node=getNodeByPath(T,path)
   # do something with node

Would return all the zones of the named base. See also getPathsByTypeSet() See also getPathsByTypeList()

Parameters:
  • tree (CGNS/Python) – the start node of the CGNS tree to parse
  • typeornamelist (list) – the (ordered) list of CGNS/SIDS types
Returns:

a list of strings, each string is the path to a matching node

Remarks :
  • only plain strings allowed, no regular expression
  • the first comparison is performed on name, then on type. If you have a node name that matches a type, the node is included in the result.
CGNS.PAT.cgnsutils.getAuthParentTypePaths(nodetype)

Return all type paths allowed by CGNS/SIDS for the node type. For example, to check all possible places where you can set a FamilyName_t you call getAllParentTypePaths, it returns you a list of all types paths allowed by CGNS/SIDS.

Parameters:

nodetype (str) – a CGNS/SIDS type as string

Returns:

a list of list of strings, each string is a CGNS/SIDS type path

Remarks :
CGNS.PAT.cgnsutils.getPathsByTypeList(tree, typelist)

Returns a list of paths from the argument tree with nodes matching the list of types. The list you give is the list you would have if you pick the node type during the parse:

tlist=['CGNSTree_t','CGNSBase_t','Zone_t']

for path in getPathsByTypeList(T,tlist):
   node=getNodeByPath(T,path)
   # do something with node

Would return all the zones of your tree. See also getPathsByTypeSet()

Parameters:
  • tree (CGNS/Python) – the start node of the CGNS tree to parse
  • typelist (list) – the (ordered) list of types
Returns:

  • a list of strings, each string is the path to a matching node

CGNS.PAT.cgnsutils.stackPathItem(path, *items)

Add the items to the path:

p='/base'
p1=stackPathItem(p,'Zone','FlowSolution')
p2=stackPathItem(p,'ReferenceState')
Parameters:
  • path (str) – original path
  • items (*str) –

    tuple of strings to be de-referenced

Returns:

a new path with concatenation of items as path tokens

CGNS.PAT.cgnsutils.getPathsFullTree(tree, width=False)

Returns the list of all possible node paths of a CGNS/Python tree:

for path in getPathsFullTree(T):
   print path
Parameters:

tree (CGNS/Python) – target tree to parse

Arb bool width:

set to True (default is False) for width sorting

Returns:

  • A list of strings, each is a path
  • Empty list if tree is empty or invalid

Remarks :
CGNS.PAT.cgnsutils.checkPath(path, dienow=False)

Checks the compliance of a path, which is basically a UNIX-like path with constraints on each node name:

checkPath('/Base/Zone/ZoneBC')
Parameters:path (str) – path to check
Returns:True if the path is ok, False if a problem is found
CGNS.PAT.cgnsutils.hasSameRootPath(pathroot, pathtocompare)

Compares two paths:

hasSameRootPath('/Base/Zone/ZoneBC','/Base/Zone/ZoneBC/BC#2/Data')
# True
hasSameRootPath('/Base/Zone/ZoneBC','/Base/ZoneBC#2')
# False
Parameters:
  • pathroot (str) – root path to compare
  • pathtocompare (str) – path which is supposed to have rootpath as substring
Returns:

True if ‘rootpath’ is a prefix of ‘pathtocompare’

Remark :
  • Each node name is a token, see example below: the second example doesn’t match as a path while it matches as a string.
CGNS.PAT.cgnsutils.getPathListCommonAncestor(pathlist)

Finds the common ancestor for all paths in list:

p=['/Base/Zone/Data-A','/Base/Zone/Data-D','/Base/Zone/ZoneBC/BC1']
print getPathListCommonAncestor(p)
# '/Base/Zone'
Args list pathlist:
 list of path strings
Returns:The common root path (at least ‘/’)
CGNS.PAT.cgnsutils.getPathToList(path, nofirst=False, noroot=True)

Return the path as a list of node names:

print getPathToList('/Base/Zone/ZoneBC')
# ['','Base','Zone','ZoneBC']
print getPathToList('/Base/Zone/ZoneBC',True)
# ['Base','Zone','ZoneBC']
print getPathToList('/') 
# []
Parameters:
  • path (str) – path string to split
  • nofirst (bool) – removes first empty string for absolute paths (default: False)
  • noroot (bool) – If true then removes the CGNS/HDF5 root if found (default: True)
Returns:

  • The list of path elements as strings
  • with ‘/’ as argument, the function returns an empty list

Remarks :
CGNS.PAT.cgnsutils.getPathAncestor(path, level=1, noroot=True)

Return the path of the node parent of the argument node path:

print getPathAncestor('/Base/Zone/ZoneBC')
# '/Base/Zone'
Parameters:
  • path (str) – string of the child node
  • level (int) – number of levels back from the child (default: 1 means the father of the node)
Returns:

  • The ancestor path
  • If the path is ‘/’ its ancestor is None.

CGNS.PAT.cgnsutils.getPathLeaf(path)

Return the leaf node name of the path:

print getPathLeaf('/Base/Zone/ZoneBC')
# 'ZoneBC'
Parameters:path (str) – a CGNS/Python path
Returns:
  • The leaf node name (the last token of the path)
  • If the path is ‘/’ the function returns ‘’ (empty string)
CGNS.PAT.cgnsutils.getPathNoRoot(path)

Return the path without the implementation nodes ‘HDF5 Mother node’ or ‘CGNSTree’ if detected as first element:

print getPathNoRoot('/HDF5 Mother Node/Base/Zone/ZoneBC')
# ['Base','Zone','ZoneBC']
Parameters:

path (str) – the path of the node

Returns:

The new path without root implementation node if found

Remarks :
  • The path is processed by getPathNormalize()
  • Implementation root can be CGNS.PAT.cgnskeywords.CGNSHDF5ROOT_s as well as CGNS.PAT.cgnskeywords.CGNSTree_s
CGNS.PAT.cgnsutils.getPathAsTypes(tree, path, legacy=True)

Return the list of types corresponding to the argument path in the tree:

getPathAsTypes(T,'/Base/Zone/ZoneBC')
# ['CGNSBase_t','Zone_t','ZoneBC_t']
Parameters:
  • tree (CGNS/Python) – target tree
  • path (str) – path to parse get
Returns:

  • The list of CGNS/SIDS types found (as strings)
  • None if the path is not found

CGNS.PAT.cgnsutils.getPathNormalize(path)

Return the same path as minimal string, removes //// and /./ and other simplifiable UNIX-like path elements:

# a checkPath here would fail, because single or double dots are not
# allowed as a node name. But actually this is allowed as a
# path description
p=getPathNormalize('///Base/././//Zone/../Zone/./ZoneBC//.')

# would return '/Base/Zone/ZoneBC'
if (not checkPath(p)):
   print 'something bad happens'
Parameters:

path (str) – the path of the node

Returns:

The simplified path

Remarks :
  • Uses os.path.normpath and replaces if windows os.path
  • Before its normalization a path can be non-compliant
CGNS.PAT.cgnsutils.childrenNames(node)

Gets the children names as a list of strings:

for c in childNames(node):
  print '%s/%s'%(node[0],c)
Parameters:node (CGNS/Python) – the parent node
Returns:List of children names (str)
CGNS.PAT.cgnsutils.getPathsByNameSet(tree, nameset)

Returns a list of paths from the argument tree with nodes matching one of the names in the list:

#  Would return all the nodes with names *BCWall* or  *BCExt*
tset=['BCWall','BCExt']

for path in getPathsByNameSet(T,tset):
   node=getNodeByPath(T,path)
   # do something
Parameters:
  • tree (CGNS/Python) – start node of the CGNS tree to parse
  • nameset (list) – the list of names
Returns:

a list of strings, each string is the path to a matching node

Remarks :

See also getPathsByTypeSet()

CGNS.PAT.cgnsutils.getPathsByTypeSet(tree, typeset)

Returns a list of paths from the argument tree with nodes matching one of the types in the list:

#  Would return all the zones and BCs of your tree.
tset=['BC_t','Zone_t']

for path in getPathsByTypeSet(T,tset):
   node=getNodeByPath(T,path)
   # do something
Parameters:
  • tree (CGNS/Python) – start node of the CGNS tree to parse
  • typeset (list) – the list of CGNS/SIDS types as strings
Returns:

a list of strings, each string is the path to a matching node

Remarks :

See also getPathsByTypeList()

CGNS.PAT.cgnsutils.getPathListAsWidthFirstIndex(paths, fileindex=1)

The order of the paths for a given depth is the alphabetical order of the full path to the node. The width parse goes through all the children of a given depth, for all parents.

For example, you want to loop on a list of nodes you retrieved from another function call. You want to make sure that your loop actually follows a width-first constraint for parse purpose. You first call getPathListAsWidthFirstIndex to get the list in the right order.

As the returned value also contains the index of the path, you can perform you simple loop by getting only the path:

listpath=someFonctionReturnsPathList( ... )
sortedlistpath=[s[2] for s in getPathListAsWidthFirstIndex(lispath)]
Parameters:
  • paths (list) – list of paths to order
  • fileindex (int) – index of the current “file” (default is 1)
Returns:

ordered list with the pattern [ [<int:file-index>, <int:child-index>, <string:path>] ... ]

Remarks :
  • Children index goes from 0 to N-1
CGNS.PAT.cgnsutils.hasChildType(parent, ntype)

Checks if the parent node has a child with given type:

node=getNodeByPath(T,'/Base/Zone/BC')
nl=hasChildType(node, 'AdditionalFamily_t')
for n in nl:
  v=getValue(n)
Parameters:
  • parent (CGNS/Python) – target node
  • ntype (str) – CGNS/SIDS node type to look for
Returns:

List of nodes with this type (can be empty)

CGNS.PAT.cgnsutils.hasChildNode(parent, name, dienow=False)

Returns a child node if it exists:

n=hasChildNode(zone,CGK.ZoneType_s)
if ((n is not None) and (stringValueMatches(n,CGK.Unstructured_s)):
  # found unstructured zone
Parameters:
  • parent (CGNS/Python) – the parent node
  • name (str) – the child name to look for
Returns:

  • the actual child node if the child exists
  • None if the child is not found

Raises :

cgnsNameError code 102 if dienow is True

CGNS.PAT.cgnsutils.stringMatches(string, reval)

Returns re.group if the pattern matches the string, None otherwise

CGNS.PAT.cgnsutils.stringNameMatches(node, reval)

Returns re.group if the pattern matches the node name, None otherwise

CGNS.PAT.cgnsutils.stringValueMatches(node, reval)

True if the string matches the node value

CGNS.PAT.cgnsutils.copyArray(a)

Copy a numpy.ndarray with flags

CGNS.PAT.cgnsutils.toString(tree, readable=False, shift=0)

Returns the full sub-tree as a single line string:

s=toString(tree)
print s
Parameters:

tree (CGNS/Python) – the CGNS/Python tree to parse

Returns:

A string representation of the whole tree

Remarks :
  • the numpy module is used, the values strings are actual string representation of a numpy array, include dtype and order
CGNS.PAT.cgnsutils.toFile(tree, filename)

Writes the CGNS/Python tree as an import-able string in a file:

tofile(tree,'NACA0012.py')
import NACA0012 as M
T=M.T

The actual node variable is T, we retrieve this value from the module M, which is the result of the import.

Parameters:
  • tree (CGNS/Python) – the tree structure to save
  • filename (str) – the name of the file
Remarks :
  • you have to use the``.py`` file extension if you use usual imports
  • calls toString()