# openalea.mtg package¶

## openalea.mtg.algo module¶

Implementation of a set of algorithms for the MTG datastructure

openalea.mtg.algo.alg_height(g, v1, v2=None)[source]
openalea.mtg.algo.alg_order(g, v1, v2=None)[source]
openalea.mtg.algo.alg_rank(g, v1, v2=None)[source]
openalea.mtg.algo.ancestors(g, vid, **kwds)[source]

Return the vertices from vid to the root.

Parameters: g: a tree or an MTG vid: a vertex id which belongs to g an iterator from vid to the root of the tree.
openalea.mtg.algo.axis(g, vtx_id, scale=-1, **kwds)[source]

TODO: see aml doc

openalea.mtg.algo.descendants(g, vtx_id, scale=-1, **kwds)[source]

TODO: see aml doc

openalea.mtg.algo.edge_type(g, v)[source]
openalea.mtg.algo.extremities(g, vid, **kwds)[source]

TODO see aml doc Implement the method more efficiently…

openalea.mtg.algo.father(g, vid, scale=-1, **kwds)[source]

See aml.Father function.

openalea.mtg.algo.full_ancestors(g, v1, **kwds)[source]

Return the vertices from v1 to the root.

openalea.mtg.algo.height(g, v1, v2=None)[source]
openalea.mtg.algo.heights(g, scale=-1)[source]

Compute the order of all vertices at scale scale.

If scale == -1, the compute the order for vertices at the finer scale.

openalea.mtg.algo.local_axis(g, vtx_id, scale=-1, **kwds)[source]

Return a sequence of vertices connected by ‘<’ edges. The first element of the sequence is vtx_id.

openalea.mtg.algo.location(g, vid, **kwds)[source]

TODO: see doc aml.Location.

openalea.mtg.algo.lookForCommonAncestor(g, commonAncestors, currentNode)[source]
openalea.mtg.algo.lowestCommonAncestor(g, nodes)[source]

LCA algorithm

openalea.mtg.algo.order(g, v1, v2=None)[source]
openalea.mtg.algo.orders(g, scale=-1)[source]

Compute the order of all vertices at scale scale.

If scale == -1, the compute the order for vertices at the finer scale.

openalea.mtg.algo.path(g, vid1, vid2=None)[source]

Compute the vertices between v1 and v2. If v2 is None, return the path between v1 and the root. Otherelse, return the path between v1 and v2. If the graph is oriented from v1 to v2, sign is positive. Else, sign is negative.

openalea.mtg.algo.predecessor(g, vid, **kwds)[source]
openalea.mtg.algo.rank(g, v1, v2=None)[source]
openalea.mtg.algo.root(g, vid, RestrictedTo='NoRestriction', ContainedIn=None)[source]

TODO: see aml.Root doc string.

openalea.mtg.algo.sons(g, vid, **kwds)[source]

TODO: see doc aml.sons.

openalea.mtg.algo.split(g, scale=1)[source]

Split at scale.

openalea.mtg.algo.successor(g, vid, **kwds)[source]

TODO: see aml.Successor doc string.

openalea.mtg.algo.topological_path(g, v1, v2=None, edge=None)[source]
openalea.mtg.algo.trunk(g, vtx_id, scale=-1, **kwds)[source]
openalea.mtg.algo.union(g1, g2, vid1=None, vid2=None, edge_type='<')[source]

Return the union of the MTGs g1 and g2.

Parameters: g1, g2 (MTG) : An MTG graph vid1 : the anchor vertex identid=fier that belong to g1 vid2 : the root of the sub_mtg that belong to g2 which will be added to g1. edge_type (str) : the type of the edge which will connect vid1 to vid2
openalea.mtg.algo.vertex_at_scale(g, vtx_id, scale)[source]

## openalea.mtg.aml module¶

Interface to use the new MTG implementation with the old AMAPmod interface.

openalea.mtg.aml.Activate(g)[source]

All the functions of the MTG module use an implicit MTG argument which is defined as the active MTG.

This function activates a MTG already loaded into memory which thus becomes the implicit argument of all functions of module MTG.

>>> Activate(g)

Parameters: g: MTG to be activated When several MTGs are loaded into memory, only one is active at a time. By default, the active MTG is the last MTG loaded using function MTG(). However, it is possible to activate an MTG already loaded using function Activate() The current active MTG can be identified using function Active(). MTG()
openalea.mtg.aml.Active()[source]

Returns the active MTG.

If no MTG is loaded into memory, None is returned.

>>> Active()

Returns: When several MTGs are loaded into memory, only one is active at a time. By default, the active MTG is the last MTG loaded using function MTG(). However, it is possible to activate an MTG already loaded using function Activate(). The current active MTG can be identified using function Active().

openalea.mtg.aml.AlgHeight(v1, v2)[source]

Algebraic value defining the number of components between two components.

This function is similar to function Height(v1, v2) : it returns the number of components between two components, at the same scale, but takes into account the order of vertices v1 and v2.

The result is positive if v1 is an ancestor of v2, and negative if v2 is an ancestor of v1.

AlgHeight(v1, v2)

Parameters: v1 (int) : vertex of the active MTG. v2 (int) : vertex of the active MTG. int If v1 is not an ancestor of v2 (or vise versa), or if v1 and v2 are not defined at the same scale, an error value None is returned.
openalea.mtg.aml.AlgOrder(v1, v2)[source]

Algebraic value defining the relative order of one vertex with respect to another one.

This function is similar to function Order(v1, v2) : it returns the number of +-type edges between two components, at the same scale, but takes into account the order of vertices v1 and v2.

The result is positive if v1 is an ancestor of v2, and negative if v2 is an ancestor of v1.

AlgOrder(v1, v2)

Parameters: v1 (int) : vertex of the active MTG. v2 (int) : vertex of the active MTG. int If v1 is not an ancestor of v2 (or vise versa), or if v1 and v2 are not defined at the same scale, an error value None is returned.
openalea.mtg.aml.AlgRank(v1, v2)[source]

Algebraic value defining the relative rank of one vertex with respect to another one.

This function is similar to function Rank(v1, v2) : it returns the number of <-type edges between two components, at the same scale, but takes into account the order of vertices v1 and v2.

The result is positive if v1 is an ancestor of v2, and negative if v2 is an ancestor of v1.

AlgRank(v1, v2)

Parameters: v1 (int) : vertex of the active MTG. v2 (int) : vertex of the active MTG. int If v1 is not an ancestor of v2 (or vise versa), or if v1 and v2 are not defined at the same scale, an error value None is returned.
openalea.mtg.aml.Alpha(e1, e2)[source]
openalea.mtg.aml.Ancestors(v, EdgeType='*', RestrictedTo='NoRestriction', ContainedIn=None)[source]

Array of all vertices which are ancestors of a given vertex

This function returns the array of vertices which are located before the vertex passed as an argument. These vertices are defined at the same scale as v. The array starts by v, then contains the vertices on the path from v back to the root (in this order) and finishes by the tree root.

Note

The anscestor array always contains at least the argument vertex v.

Ancestors(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father EdgeType (str): cf. Father list of vertices’s id (int)
>>> v # prints vertex v
78
>>> Ancestors(v) # set of ancestors of v at the same scale
[78,45,32,10,4]
>>> list(reversed(Ancestors(v))) # To get the vertices in the order from the root to the vertex v
[4,10,32,45,78]


openalea.mtg.aml.Axis(v, Scale=-1)[source]

Array of vertices constituting a botanical axis

An axis is a maximal sequence of vertices connected by ‘<’-type edges. Axis return the array of vertices representing the botanical axis which the argument v belongs to. The optional argument enables the user to choose the scale at which the axis decomposition is required.

Axis(v)
Axis(v, Scale=s)

Parameters: Optional Parameters: v (int) : Vertex of the active MTG Scale (str): scale at which the axis components are required. list of vertices ids

openalea.mtg.aml.Beta(e1, e2)[source]
openalea.mtg.aml.BottomCoord(e1, e2)[source]
openalea.mtg.aml.BottomDiameter(e1, e2)[source]
openalea.mtg.aml.Class(vid)[source]

Class of a vertex

The Class() of a vertex is a feature always defined and independent of time (like the index). It is represented by an alphabetic character in upper or lower case (lower cases characters are considered different from upper cases). The label of a vertex is the string defined by the concatenation of its class and its index. The label thus provides general information about a vertex and enables us to encode the plant components.

Usage: >>> Class(v)  vid (int) : vertex of the active MTG The class of the vertex.

openalea.mtg.aml.ClassScale(c)[source]

Scale at which appears a given class of vertex

Every vertex is associated with a unique class. Vertices from a given class only appear at a given scale which can be retrieved using this function.

ClassScale(c)

Parameters: c (str) : symbol of the considered class int
openalea.mtg.aml.Complex(v, Scale=-1)[source]

Complex of a vertex.

Returns the complex of v. The complex of a vertex v has a scale lower than v : Scale(v) - 1. In a MTG, every vertex except for the MTG root (cf. MTGRoot), has a uniq complex. None is returned if the argument is the MTG Root or if the vertex is undefined.

Complex(v)
Complex(v, Scale=2)

Parameters: Optional Parameters: v (int) : vertex of the active MTG Scale (int) : scale of the complex Returns vertex’s id (int) When a scale different form Scale(v)-1 is specified using the optional parameter Scale, this scale must be lower than that of the vertex argument.

Todo

Complex(v, Scale=10) returns v why ? is this expected

openalea.mtg.aml.ComponentRoots(v, Scale=-1)[source]

Set of roots of the tree graphs that compose a vertex

In a MTG, a vertex may have be decomposed into components. Some of these components are connected to each other, while other are not. In the most general case, the components of a vertex are organized into several tree-graphs. This is for example the case of a MTG containing the description of several plants: the MTG root vertex can be decomposed into tree graphs (not connected) that represent the different plants. This function returns the set of roots of these tree graphs at scale Scale(v)+1. The order of these roots is not significant.

When a scale different from Scale(v)+1 is specified using the optional argument Scale(), this scale must be greater than that of the vertex argument.

ComponentRoots(v)
ComponentRoots(v, Scale=s)

Parameters: Optional Parameters: v (int) : vertex of the active MTG Scale (str): scale of the component roots. list of vertices’s id (int)
>>> v=MTGRoot() # global MTG root
0
>>> ComponentRoots(v) # set of first vertices at scale 1
[1,34,76,100,199,255]
>>> ComponentRoots(v, Scale=2) # set of first vertices at scale 2
[2,35,77,101,200,256]

openalea.mtg.aml.Components(v, Scale=-1)[source]

Set of components of a vertex.

The set of components of a vertex is returned as a list of vertices. If s defines the scale of v, components are defined at scale s + 1. The array is empty if the vertex has no components. The order of the components in the array is not significant.

When a scale is specified using optional argument :arg:Scale, it must be necessarily greater than the scale of the argument.

Components(v)
Components(v, Scale=2)

Parameters: Optional Parameters: v (int) : vertex of the active MTG Scale (int) : scale of the components. list of int

openalea.mtg.aml.Coord(e1, e2)[source]
openalea.mtg.aml.DateSample(e1)[source]

Array of observation dates of a vertex.

Returns the set of dates at which a given vertex (passed as an argument) has been observed as an array of ordered dates. Options can be specified to define a temporal window and the total list of observation dates will be truncated according to the corresponding temporal window.

DateSample(v)
DateSample(v, MinDate=d1, MaxDate=d2)

Parameters: Optional Parameters: v (VTX) : vertex of the active MTG. MinDate (date) : defines a minimum date of interest. MaxDate (date) : defines a maximum date of interest. list of date
openalea.mtg.aml.Defined(vid)[source]

Test whether a given vertex belongs to the active MTG.

Defined(v)

Parameters: v (int) : vertex of the active MTG True or False

openalea.mtg.aml.Descendants(v, EdgeType='*', RestrictedTo='NoRestriction', ContainedIn=None)[source]

Set of vertices in the branching system borne by a vertex.

This function returns the set of descendants of its argument as an array of vertices. The array thus consists of all the vertices, at the same scale as v, that belong to the branching system starting at v. The order of the vertices in the array is not significant.

Note

The argument always belongs to the set of its descendants.

Descendants(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father EdgeType (str): cf. Father list of int.
>>> v
78
>>> Sons(v) # set of sons of v
[78,99,101]
>>> Descendants(v) # set of descendants of v
[78,99,101,121,133,135,156,171,190]


openalea.mtg.aml.DressingData(e1)[source]

Use openalea.mtg.dresser.DressingData instead of this function

openalea.mtg.aml.EdgeType(v1, v2)[source]

Type of connection between two vertices.

Returns the symbol of the type of connection between two vertices (either < or +). If the vertices are not connected, None is returned.

EdgeType(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG ‘<’ (successor), ‘+’ (branching) or None

openalea.mtg.aml.Extremities(v, RestrictedTo='NoRestriction', ContainedIn=None)[source]

Set of vertices that are the extremities of the branching system born by a given vertex.

This function returns the extremities of the branching system defined by the argument as a list of vertices. These vertices have the same scale as v and their order in the list is not signifiant. The result is always a non empty array.

Extremities(v)

Properties: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father() ContainedIn (int): cf. Father() list of vertices’s id (int)
>>> Descendants(v)
[3, 45, 47, 78, 102]
>>> Extremities(v)
[47, 102]

openalea.mtg.aml.Father(v, EdgeType='*', RestrictedTo='NoRestriction', ContainedIn=None, Scale=-1)[source]

Topological father of a given vertex.

Returns the topological father of a given vertex. And None if the father does not exist. If the argument is not a valid vertex, None is returned.

Father(v)
Father(v, EdgeType='<')
Father(v, RestrictedTo='SameComplex')
Father(v, ContainedIn=complex_id)
Father(v, Scale=s)

Parameters: Optional Parameters: v (int) : vertex of the active MTG If no optional argument is specified, the function returns the topological father of the argument (vertex that bears or precedes to the vertex passed as an argument). It may be usefull in some cases to consider that the function only applies to a subpart of the MTG (e.g. an axis). The following options enables us to specify such restrictions: EdgeType (str) : filter on the type of edge that connect the vertex to its father. Values can be ‘<’, ‘+’, and ‘*’. Values ‘*’ means both ‘<’ and ‘+’. Only the vertex connected with the specified type of edge will be considered. RestrictedTo (str) : filter defining a subpart of the MTG where the father must be considered. If the father is actually outside this subpart, the result is None. Possible subparts are defined using keywords in [‘SameComplex’, ‘SameAxis’, ‘NoRestriction’]. For instance, if RestrictedTo is set to ‘SameComplex’, Father(v)() returns a defined vertex only if the father f of v existsin the MTG and if v and f have the same complex. ContainedIn (int) : filter defining a subpart of the MTG where the father must be considered. If the father is actually outside this subpart, the result is None. In this case, the subpart of the MTG is made of the vertices that composed composite_id (at any scale). Scale (int) : the scale of the considered father. Returns the vertex from scale s which either bears and precedes the argument. The scale s can be lower than the argument’s (corresponding to a question such as ‘which axis bears the internode?’) or greater (e.g. ‘which internodes bears this annual shoot?’). the vertex id of the Father (int)
openalea.mtg.aml.Feature(vid, fname, date=None)[source]

Extracts the attributes of a vertex.

Returns the value of the attribute fname of a vertex in a MTG.

If the value of an attribute is not defined in the coding file, the value None is returned.

Feature(vid, fname)
Feature(vid, fname, date)

Parameters: vid (int) : vertex of the active MTG. fname (str) : name of the attribute (as specified in the coding file). date (date) : (for a dynamic MTG) date at which the attribute of the vertex is considered. int, str, date or float If for a given attribute, several values are available(corresponding to different dates), the date of interest must be specified as a third attribute. This date must be a valid date appearing in the coding file for a considered vertex. Otherwise None is returned. MTGs and Dynamic MTGs.

Todo

specify the format of date

openalea.mtg.aml.FirstDefinedFeature(e1, e2)[source]

Date of first observation of a vertex.

Returns the date d for which the attribute fname is defined for the first time on the vertex v passed as an argument. This date must be greater than the option MinDate and/or less than the maximum MaxData when specified. Otherwise the returned date is None.

FirstDefinedFeature(v, fname)
FirstDefinedFeature(v, fname, MinDate=d1, MaxDate=d2)

Properties: Optional Properties: v (int) : vertex of the active MTG fname (str) : name of the considered property MinDate (date) : minimum date of interest. MaxData (date) : maximum date of interest. date
openalea.mtg.aml.Height(v1, v2=None)[source]

Number of components existing between two components in a tree graph.

The height of a vertex (v2) with respect to another vertex (v1) is the number of edges (of either type ‘+’ or ‘<’) that must be crossed when going from v1 to v2 in the graph.

This is a non-negative integer. When the function has only one argument v1, the height of v1 correspond to the height of v1with respect to the root of the branching system containing v1.

Height(v1)
Height(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG int

Note

When the function takes two arguments, the order of the arguments is not important provided that one is an ancestor of the other. When the order is relevant, use function AlgHeight.

openalea.mtg.aml.Index(vid)[source]

Index of a vertex

The Index() of a vertex is a feature always defined and independent of time (like the index). It is represented by a non negative integer. The label of a vertex is the string defined by the concatenation of its class and its index. The label thus provides general information about a vertex and enables us to encode the plant components.

Usage: >>> Index(v)  vid (int) : vertex of the active MTG int
openalea.mtg.aml.Label(v)[source]

Label of a vertex

Usage: >>> Label(v) #doctest: +SKIP  vid (int) : vertex of the active MTG The class and Index of the vertex (str).
openalea.mtg.aml.LastDefinedFeature(e1, e2)[source]

Date of last observation of a given attribute of a vertex.

Returns the date d for which the attribute fname is defined for the last time on the vertex v passed as an argument. This date must be greater than the option MinDate and/or less than the maximum MaxData when specified. Otherwise the returned date is None.

FirstDefinedFeature(v, fname)
FirstDefinedFeature(v, fname, MinDate=d1, MaxDate=d2)

Properties: Optional Properties: v (int) : vertex of the active MTG fname (str) : name of the considered property MinDate (date) : minimum date of interest. MaxData (date) : maximum date of interest. date
openalea.mtg.aml.Length(e1, e2)[source]
openalea.mtg.aml.Location(v, Scale=-1, ContainedIn=None)[source]

Vertex defining the father of a vertex with maximum scale.

If no options are supplied, this function returns the vertex defining the father of a vertex with maximum scale (cf. Father()). If it does not exist, None is returned. If a scale is specified, the function is equivalent to Father(v, Scale=s).

Location(v)
Location(v, Scale=s)
Location(v, ContainedIn=complex_id)

Parameters: Optional Parameters: v (int) : vertex of the active MTG. Scale (int) : scale at which the location is required. ContainedIn (int) : cf. Father() Returns vertex’s id (int)
>>> Father(v, EdgeType='+')
7
>>> Complex(v)
4
>>> Components(7)
[9,19,23, 34, 77, 89]
>>> Location(v)
23
>>> Location(v, Scale= Scale(v)+1)
23
>>> Location(v, Scale= Scale(v))
7
>>> Location(v, Scale= Scale(v)-1)
4


openalea.mtg.aml.MTG(filename)[source]

MTG constructor.

Builds a MTG from a coding file (text file) containing the description of one or several plants.

MTG(filename)

Parameters: filename (str): name of the coding file describing the mtg If the parsing process succeeds, returns an object of type MTG(). Otherwise, an error is generated, and the formerly active MTG remains active. If the MTG() is built, the new MTG() becomes the active MTG() (i.e. the MTG() implicitly used by other functions such as Father(), Sons(), VtxList(), …). The parsing process is approximatively proportional to the number of components defined in the coding file. MTG is an acronyme for Multiscale Tree Graph.
openalea.mtg.aml.MTGRoot()[source]

Returns the root vertex of the MTG.

It is the only vertex at scale 0 (the coarsest scale).

>>> MTGRoot()

Returns: vtx identifier This vertex is the complex of all vertices from scale 1. It is a mean to refer to the entire database.
openalea.mtg.aml.NextDate(e1)[source]

Next date at which a vertex has been observed after a specified date

Returns the first observation date at which the vertex has been observed starting at date d and proceeding forward in time. None is returned if it does not exists.

NextDate(v, d)

Parameters: v (int) : vertex of the active MTG. d (date) : departure date. date
openalea.mtg.aml.Order(v1, v2=None)[source]

Order of a vertex in a graph.

The order of a vertex (v2) with respect to another vertex (v1) is the number of edges of either type ‘+’ that must be crossed when going from v1 to v2 in the graph. This is thus a non negative integer which corresponds to the “botanical order”.

When the function only has one argument v1, the order of v1 correspond to the order of v1 with respect to the root of the branching system containing v1.

Order(v1)
Order(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG int

Note

When the function takes two arguments, the order of the arguments is not important provided that one is an ancestor of the other. When the order is relevant, use function AlgOrder().

Warning

The value returned by function Order is 0 for trunks, 1 for branches etc. This might be different with some botanical conventions where 1 is the order of the trunk, 2 the order of branches, etc.

openalea.mtg.aml.PDir(e1, e2)[source]
openalea.mtg.aml.Path(v1, v2)[source]

List of vertices defining the path between two vertices

This function returns the list of vertices defining the path between two vertices that are in an ancestor relationship. The vertex v1 must be an ancestor of vertex v2. Otherwise, if both vertices are valid, then the empty array is returned and if at least one vertex is undefined, None is returned.

Path(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG list of vertices’s id (int)
>>> v # print the value of v
78
>>> Ancestors(v)
[78,45,32,10,4]
>>> Path(10,v)
[10,32,45,78]
>>> Path(9,v) # 9 is not an ancestor of 78
[]


Note

v1 can be equal to v2.

openalea.mtg.aml.PlantFrame(e1)[source]

Use openalea.mtg.plantframe.PlantFrame insteead of this function

openalea.mtg.aml.Plot(e1)[source]
openalea.mtg.aml.Predecessor(v, **kwds)[source]

Father of a vertex connected to it by a ‘<’ edge

This function is equivalent to Father(v, EdgeType-> ‘<’). It thus returns the father (at the same scale) of the argument if it is located in the same botanical. If it does not exist, None is returned.

Predecessor(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father return the vertex id (int)
>>> Predecessor(v)
7
>>> Father(v, EdgeType='+')
>>> Father(v, EdgeType-> '<')
7

openalea.mtg.aml.PreviousDate(e1)[source]

Previous date at which a vertex has been observed after a specified date.

Returns the first observation date at which the vertex has been observed starting at date d and proceeding backward in time. None is returned if it does not exists.

PreviousDate(v, d)

Parameters: v (int) : vertex of the active MTG. d (date) : departure date. date
openalea.mtg.aml.Rank(v1, v2=None)[source]

Rank of one vertex with respect to another one.

This function returns the number of consecutive ‘<’-type edges between two components, at the same scale, and does not take into account the order of vertices v1 and v2. The result is a non negative integer.

Rank(v1)
Rank(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG int If v1 is not an ancestor of v2 (or vise versa) within the same botanical axis, or if v1 and v2 are not defined at the same scale, an error value Undef id returned.
openalea.mtg.aml.RelBottomCoord(e1, e2)[source]
openalea.mtg.aml.RelTopCoord(e1, e2)[source]
openalea.mtg.aml.Root(v, RestrictedTo='*', ContainedIn=None)[source]

Root of the branching system containing a vertex

This function is equivalent to Ancestors(v, EdgeType=’<’)[-1]. It thus returns the root of the branching system containing the argument. This function never returns None.

Root(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father return vertex’s id (int)
>>> Ancestors(v) # set of ancestors of v
[102,78,35,33,24,12]
>>> Root(v) # root of the branching system containing v
12


openalea.mtg.aml.SDir(e1, e2)[source]
openalea.mtg.aml.Scale(vid)[source]

Scale of a vertex

Returns the scale at which is defined the argument.

Usage: >>> Scale(vid)  vid (int) : vertex of the active MTG vid (PlantFrame) : a PlantFrame object computed on the active MTG vid (LineTree) : a LineTree computed on a PlantFrame representing the active MTG int
openalea.mtg.aml.Sons(v, RestrictedTo='NoRestriction', EdgeType='*', Scale=-1, ContainedIn=None)[source]

Set of vertices born or preceded by a vertex

The set of sons of a given vertex is returned as an array of vertices. The order of the vertices in the array is not significant. The array can be empty if there are no son vertices.

from openalea.mtg.aml import Sons
Sons(v)
Sons(v, EdgeType= '+')
Sons(v, Scale= 3)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str) : cf. Father ContainedIn (int) : cf. Father EdgeType (str) : filter on the type of sons. Scale (int) : set the scale at which sons are considered. list(vid) When the option EdgeType is applied, the function returns the set of sons that are connected to the argument with the specified type of relation.

Note

Sons(v, EdgeType= ‘<’) is not equivalent to Successor(v). The first function returns an array of vertices while the second function returns a vertex.

The returned vertices have the same scale as the argument. However, coarser or finer vertices can be obtained by specifying the optional argument Scale at which the sons are considered.

>>> Sons(v)
[3,45,47,78,102]
>>>  Sons(v, EdgeType= '+') # set of vertices borne by v
[3,45,47,102]
>>>  Sons(v, EdgeType= '<') # set of successors of v on the same axis
[78]

openalea.mtg.aml.Successor(v, RestrictedTo='NoRestriction', ContainedIn=None)[source]

Vertex that is connected to a given vertex by a ‘<’ edge type (i.e. in the same botanical axis).

This function is equivalent to Sons(v, EdgeType=’<’)[0]. It returns the vertex that is connected to a given vertex by a ‘<’ edge type (i.e. in the same botanical axis). If many such vertices exist, an arbitrary one is returned by the function. If no such vertex exists, None is returned.

Successor(v)

Parameters: Optional Parameters: v1 (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father Returns vertex’s id (int)
>>> Sons(v)
[3, 45, 47, 78, 102]
>>> Sons(v, EdgeType='+') # set of vertices borne by v
[3, 45, 47, 102]
>>> Sons(v, EdgeType-> '<') # set of successors of v
[78]
>>> Successor(v)
78

openalea.mtg.aml.TopCoord(e1, e2)[source]
openalea.mtg.aml.TopDiameter(e1, e2)[source]
openalea.mtg.aml.Trunk(v, Scale=-1)[source]

List of vertices constituting the bearing botanical axis of a branching system.

Trunk returns the list of vertices representing the botanical axis defined as the bearing axis of the whole branching system defined by v. The optional argument enables the user to choose the scale at which the trunk should be detailed.

Trunk(v)
Trunk(v, Scale= s)

Parameters: Optional Parameters: v (int) : Vertex of the active MTG. Scale (str): scale at which the axis components are required. list of vertices ids

Todo

check the usage of the optional argument Scale

openalea.mtg.aml.VirtualPattern(e1)[source]
openalea.mtg.aml.VtxList(Scale=-1)[source]

Array of vertices contained in a MTG

The set of all vertices in the MTG() is returned as an array. Vertices from all scales are returned if no option is used. The order of the elements in this array is not significant.

>>> VtxList()
>>> VtxList(Scale=2)

Optional Parameters:

• Scale (int): used to select components at a particular scale.
Returns:
• list of vid
Background:

MTGs()

## openalea.mtg.draw module¶

### Matplotlib¶

Draw MTG with matplotlib.

matplotlib
http://matplotlib.sourceforge.net/
openalea.mtg.draw.draw(g, pos=None, ax=None, hold=None, ax_size=(0, 0, 1, 1), **kwds)[source]

Draw the graph g with Matplotlib.

Draw the graph as a simple representation with no node labels or edge labels and using the full Matplotlib figure area and no axis labels by default. See draw_mtg() for more full-featured drawing that allows title, axis labels etc.

Parameters: g (graph) – A MTG graph pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See mtg.layout for functions that compute node positions. ax (Matplotlib Axes object, optional) – Draw the graph in specified Matplotlib axes. hold (bool, optional) – Set the Matplotlib hold state. If True subsequent draw commands will be added to the current axes. **kwds (optional keywords) – See draw.draw_mtg() for a description of optional keywords.

Examples

>>> g = om.random_mtg()
>>> draw.draw(g)
>>> draw.draw(g,pos=om.spring_layout(G)) # use spring layout


Notes

This function has the same name as pylab.draw and pyplot.draw so beware when using

>>> from openalea.mtg.draw import *


since you might overwrite the pylab.draw function.

With pyplot use

>>> import matplotlib.pyplot as plt
>>> import openalea.mtg as om
>>> g=om.random_mtg()
>>> om.draw(g)  # mtg draw()
>>> plt.draw()  # pyplot draw()


Also see the openalea.mtg drawing examples at openalea gallery.

openalea.mtg.draw.draw_mtg(G, pos=None, with_labels=True, with_edge_labels=False, **kwds)[source]

Draw the graph G using Matplotlib.

Draw the graph with Matplotlib with options for node positions, labeling, titles, and many other drawing features. See draw() for simple drawing without labels or axes.

Parameters: G (graph) – A MTG graph pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See MTG.layout for functions that compute vertex positions. with_labels (bool, optional (default=True)) – Set to True to draw labels on the nodes. ax (Matplotlib Axes object, optional) – Draw the graph in the specified Matplotlib axes. nodelist (list, optional (default G.nodes())) – Draw only specified nodes edgelist (list, optional (default=G.edges())) – Draw only specified edges node_size (scalar or array, optional (default=300)) – Size of nodes. If an array is specified it must be the same length as nodelist. node_color (color string, or array of floats, (default='r')) – Node color. Can be a single color format string, or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details. node_shape (string, optional (default='o')) – The shape of the node. Specification is as matplotlib.scatter marker, one of ‘so^>v

Examples

>>> g = om.random_mtg()
>>> om.draw(g)
>>> om.draw(g, pos=om.spring_layout(g)) # use spring layout

>>> import matplotlib.pyplot as plt
>>> limits=plt.axis('off') # turn of axis

openalea.mtg.draw.draw_mtg_edge_labels(G, pos, edge_labels=None, label_pos=0.5, font_size=10, font_color='k', font_family='sans-serif', font_weight='normal', alpha=0.5, bbox=None, ax=None, rotate=False, **kwds)[source]

Draw edge labels.

Parameters: G (graph) – A MTG graph pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See mtg.layout for functions that compute node positions. ax (Matplotlib Axes object, optional) – Draw the graph in the specified Matplotlib axes. alpha (float) – The text transparency (default=1.0) edge_labels (dictionary) – Edge labels in a dictionary keyed by edge two-tuple of text labels (default=None). Only labels for the keys in the dictionary are drawn. label_pos (float) – Position of edge label along edge (0=head, 0.5=center, 1=tail) font_size (int) – Font size for text labels (default=12) font_color (string) – Font color string (default=’k’ black) font_weight (string) – Font weight (default=’normal’) font_family (string) – Font family (default=’sans-serif’) bbox (Matplotlib bbox) – Specify text box shape and colors. clip_on (bool) – Turn on clipping at axis boundaries (default=True)

Examples

>>> G=om.random_graph()
>>> edge_labels=om.draw_mtg_edge_labels(G,pos=om.layout.spring_layout(G))


Also see the MTG drawing examples at gallery

openalea.mtg.draw.draw_mtg_edges(g, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=None, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, **kwds)[source]

Draw the edges of the graph g.

This draws only the edges of the graph g.

Parameters: g (graph) – A MTG graph pos (dictionary) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See mtg.layout for functions that compute node positions. edgelist (collection of edge tuples) – Draw only specified edges(default=G.edges()) width (float) – Line width of edges (default =1.0) edge_color (color string, or array of floats) – Edge color. Can be a single color format string (default=’r’), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style (string) – Edge line style (default=’solid’) (solid|dashed|dotted,dashdot) alpha (float) – The edge transparency (default=1.0) cmap (edge) – Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax (floats) – Minimum and maximum for edge colormap scaling (default=None) ax (Matplotlib Axes object, optional) – Draw the graph in the specified Matplotlib axes. arrows (bool, optional (default=True)) – For directed graphs, if True draw arrowheads. label ([None| string]) – Label for legend

Notes

For directed graphs, “arrows” (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. Yes, it is ugly but drawing proper arrows with Matplotlib this way is tricky.

Examples

>>> g = om.random_mtg()
>>> edges = om.draw_mtg_edges(g, pos=om.simple_layout(G))

openalea.mtg.draw.draw_mtg_labels(G, pos, nodelist=None, labels=None, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0, ax=None, **kwds)[source]

Draw node labels on the graph G.

Parameters: G (graph) – A MTG graph pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See mtg.layout for functions that compute node positions. labels (dictionary, optional (default=None)) – Node labels in a dictionary keyed by node of text labels font_size (int) – Font size for text labels (default=12) font_color (string) – Font color string (default=’k’ black) font_family (string) – Font family (default=’sans-serif’) font_weight (string) – Font weight (default=’normal’) alpha (float) – The text transparency (default=1.0) ax (Matplotlib Axes object, optional) – Draw the graph in the specified Matplotlib axes.

Examples

>>> G=om.dodecahedral_graph()
>>> labels=om.draw_mtg_labels(G,pos=om.spring_layout(G))


Also see the MTG drawing examples at gallery.html

openalea.mtg.draw.draw_mtg_vertices(g, pos, nodelist=None, node_size=300, node_color='r', node_shape='o', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, linewidths=None, label=None, **kwds)[source]

Draw the nodes of the graph G.

This draws only the nodes of the graph G.

Parameters: G (graph) – A MTG graph pos (dictionary) – A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. ax (Matplotlib Axes object, optional) – Draw the graph in the specified Matplotlib axes. nodelist (list, optional) – Draw only specified nodes (default G.nodes()) node_size (scalar or array) – Size of nodes (default=300). If an array is specified it must be the same length as nodelist. node_color (color string, or array of floats) – Node color. Can be a single color format string (default=’r’), or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details. node_shape (string) – The shape of the node. Specification is as matplotlib.scatter marker, one of ‘so^>v

Examples

>>> g = MTG()
>>> random_tree(g, vid)
>>> nodes=om.draw_mtg_vertices(G,pos=om.spring_layout(G))


## openalea.mtg.io module¶

This module provides functions to read / write mtg data structure.

class openalea.mtg.io.Reader(string, has_line_as_param=True, mtg=None, has_date=False)[source]

Bases: object

Parse a MTG string from a classic MTG file format.

The mtg format is composed of a header and the mtg code. The header is used to construct and validate the mtg. The code contains topology relations and properties.

build_mtg()[source]
check()[source]

Check the validity of the MTG without building it.

classes()[source]

CLASSES: SYMBOL SCALE DECOMPOSITION INDEXATION DEFINITION …

code()[source]

Parse the code and populate the MTG.

code_form()[source]

CODE: FORM-A / FORM-B

description()[source]

DESCRIPTION: LEFT RIGHT RELTYPE MAX U U,I + ? …

errors()[source]
features()[source]

FEATURES: NAME TYPE nb_plant INT

header()[source]

Parse an MTG header and create the mtg datastructure.

An mtg header contains different parts:
• code: definition
• classes: symbol name and scale
• description: allowed relationship between symbols
• features: property name and type
next_line_iter()[source]
parse()[source]
preprocess_code()[source]
preprocess_line(s, diff_space, indent, nb_spaces, edge_type)[source]

Preprocess a line.

class openalea.mtg.io.Writer(g, header='')[source]

Bases: object

Write a MTG string from a mtg object.

The mtg format is composed of a header and the mtg code. The header is used to construct and validate the mtg. The code contains topology relations and properties.

code(property_names, nb_tab=12, display_id=False, display_scale=False, filter=None)[source]

Traverse the MTG and write the code.

header()[source]

Build the MTG header from the datastructure.

An mtg header contains different parts:
• code: definition
• classes: symbol name and scale
• description: allowed relationship between symbols
• features: property name and type
openalea.mtg.io.axialtree2mtg(tree, scale, scene, parameters=None)[source]

Create an MTG from an AxialTree.

Tha axial tree has been generated by LPy. It contains both modules with parameters. The geometry is provided by the scene. The shape ids are the same that the module ids in the axial tree. For each module name in the axial tree, a scale and a list of parameters should be defined. The scale dict allow to add a module at a given scale in the MTG. The parameters dict map for each module name a list of parameter name that are added to the MTG.

Parameters: tree: The axial tree generated by the L-system scale: A dict containing the scale for each symbol name. scene: The scene containing the geometry. parameters: list of parameter names for each module. mtg
tree # axial tree
scales = {}
scales['P'] = 1
scales['A'] = 2
scales['GU'] = 3

params ={}
params['P'] = []
params['GU'] = ['nb_flower']

g = axialtree2mtg(tree, scales, scene, params)

openalea.mtg.io.display(g, max_scale=0, display_id=True, display_scale=False, nb_tab=12, **kwds)[source]

Display MTG

openalea.mtg.io.get_args(s)[source]
openalea.mtg.io.get_expr(s, expr)[source]
openalea.mtg.io.get_float(s)[source]
openalea.mtg.io.get_index(s)[source]
openalea.mtg.io.get_label(s)[source]
openalea.mtg.io.get_name(s)[source]
openalea.mtg.io.log(*args)[source]
openalea.mtg.io.lpy2mtg(axial_tree, lsystem, scene=None)[source]
openalea.mtg.io.mtg2axialtree(g, parameters=None, axial_tree=None)[source]

Create a MTG from an AxialTree with scales.

Parameters: axial_tree: The axial tree managed by the L-system. Use an empty AxialTree if you do not want to concatenate this axial_tree with previous results. parameters: list of parameter names for each module. mtg
params = dict()
params ['P'] = []
params['GU']=['nb_flower']
tree = mtg2axialtree(g, params)

openalea.mtg.io.mtg2lpy(g, lsystem, axial_tree=None)[source]

Create an AxialTree from a MTG with scales.

tree = mtg2lpy(g,lsystem)

Parameters: Optional Parameters: g: The mtg which have been generated by an LSystem. lsystem: A lsystem object containing various information. The lsystem is only used to retrieve the context and the parameters associated with each module name. axial_tree: an empty axial tree. It is used to avoid complex import in the code. axial tree
openalea.mtg.io.mtg2mss(name, mtg, scene, envelop_type='CvxHull')[source]

Convert an MTG into the multi-scale structure implemented by fractalysis.

Parameters: name: name of the structure mtg: the mtg to convert scene: the scene containing the geometry envelop_type: algorithm used to fit the geometry.between scales. mss data structure.
openalea.mtg.io.mtg_display(g, vtx_id, tab=' ', edge_type=None, label=None)[source]

Test the traversal of an mtg. A first step before writing it.

openalea.mtg.io.multiscale_edit(s, symbol_at_scale={}, class_type={}, has_date=False, mtg=None)[source]

Construction of an MTG from a string.

• s: The string representing the MTG.
• symbol_at_scale: A dict containing the scale for each symbol name.
Optional parameters:

• class_type: A dict containing the type of the properties.
• has_date: Is the MTG is a Dynamic MTG?
• mtg: An existing MTG
Return: MTG object
openalea.mtg.io.read_lsystem_string(string, symbol_at_scale, functional_symbol={}, mtg=None)[source]

Read a string generated by a lsystem.

• string: The lsystem string representing the axial tree.
• symbol_at_scale: A dict containing the scale for each symbol name.
Optional parameters:

• functional_symbol: A dict containing a function for specific symbols.
The args of the function have to be coherent with those in the string. The return type of the functions have to be a dictionary of properties: dict(name, value)
Return: MTG object
openalea.mtg.io.read_mtg(s, mtg=None, has_date=False)[source]

Create an MTG from its string representation in the MTG format.

Parameter: s (string) - a multi-lines string an MTG
f = open('test.mtg')



openalea.mtg.io.read_mtg_file(fn, mtg=None, has_date=False)[source]

Create an MTG from a filename.

Usage: >>> g = read_mtg_file('test.mtg') 

openalea.mtg.io.replace_date(s, format)[source]

Replace the date / by -

openalea.mtg.io.write_mtg(g, properties=[], class_at_scale=None, nb_tab=12, display_id=False)[source]

Transform an MTG into a multi-line string in the MTG format.

This method build a generic header, then traverses the MTG and transform each vertex into a line with its label, topoloical relationship and specific properties.

Parameters: Optional Parameters: g (MTG) properties (list): a list of tuples associating a property name with its type. Only these properties will be written in the out file. class_at_scale (dict(name->int)): a map between a class name and its scale. If class _at_scale is None, its value will be computed from g. nb_tab (int): the number of tabs used to write the code. display_id (bool): display the id for each vertex a list of strings.
# Export all the properties defined in g.
# We consider that all the properties are real numbers.

properties = [(p, 'REAL') for p in g.property_names() if p not in ['edge_type', 'index', 'label']]
mtg_lines = write_mtg(g, properties)

# Write the result into a file example.mtg

filename = 'example.mtg'
f = open(filename, 'w')
f.write(mtg_lines)
f.close()


## openalea.mtg.layout module¶

openalea.mtg.layout.fruchterman_reingold_layout(g, dim=2, k=None, pos=None, fixed=None, iterations=50, weight='weight', scale=1.0)[source]

Position nodes using Fruchterman-Reingold force-directed algorithm.

Parameters: G (NetworkX graph) – dim (int) – Dimension of layout k (float (default=None)) – Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart.
pos : dict or None optional (default=None)
Initial positions for nodes as a dictionary with node as keys and values as a list or tuple. If None, then nuse random initial positions.
fixed : list or None optional (default=None)
Nodes to keep fixed at initial position.
iterations : int optional (default=50)
Number of iterations of spring-force relaxation
weight : string or None optional (default=’weight’)
The edge attribute that holds the numerical value used for the edge weight. If None, then all edge weights are 1.
scale : float (default=1.0)
Scale factor for positions. The nodes are positioned in a box of size [0,scale] x [0,scale].
Returns: A dictionary of positions keyed by node dict

Examples

>>> G=nx.path_graph(4)
>>> pos=nx.spring_layout(G)


# The same using longer function name >>> pos=nx.fruchterman_reingold_layout(G)

openalea.mtg.layout.layout2d(g, vid=None, origin=(0, 0), steps=(4, 8), property_name='position')[source]

Compute 2d coordinates for each vertex.

This method compute a 2D layout of a tree or a MTG at a specific scale. This will allow to plot tree in matplotlib for instance.

>>> g.reindex()
>>> g1 = g.reindex(copy=True)
>>> mymap = dict(zip(list(traversal.iter_mtg2(g,g.root)), range(len(g))))
>>> g2 = g.reindex(mapping=mymap, copy=True)

Optional Parameters:

• origin : a 2D point for the root of the tree.
• property (str) : Name of the property storing the 2D coordinates.
Returns:
• a MTG
openalea.mtg.layout.random() → x in the interval [0, 1).
openalea.mtg.layout.simple_layout(g, vid=None, origin=(0, 0), steps=(4, 8), property_name='position', multiscale=True)[source]

Compute 2d coordinates for each vertex.

This method compute a 2D layout of a tree or a MTG at a specific scale. This will allow to plot tree in matplotlib for instance.

>>> g = simple_layout(g)

Optional Parameters:

• origin : a 2D point for the root of the tree.
• property (str) : Name of the property storing the 2D coordinates.
Returns:
• a MTG
openalea.mtg.layout.spring_layout(g, dim=2, k=None, pos=None, fixed=None, iterations=50, weight='weight', scale=1.0)

Position nodes using Fruchterman-Reingold force-directed algorithm.

Parameters: G (NetworkX graph) – dim (int) – Dimension of layout k (float (default=None)) – Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart.
pos : dict or None optional (default=None)
Initial positions for nodes as a dictionary with node as keys and values as a list or tuple. If None, then nuse random initial positions.
fixed : list or None optional (default=None)
Nodes to keep fixed at initial position.
iterations : int optional (default=50)
Number of iterations of spring-force relaxation
weight : string or None optional (default=’weight’)
The edge attribute that holds the numerical value used for the edge weight. If None, then all edge weights are 1.
scale : float (default=1.0)
Scale factor for positions. The nodes are positioned in a box of size [0,scale] x [0,scale].
Returns: A dictionary of positions keyed by node dict

Examples

>>> G=nx.path_graph(4)
>>> pos=nx.spring_layout(G)


# The same using longer function name >>> pos=nx.fruchterman_reingold_layout(G)

## openalea.mtg.matrix module¶

This module provides functions to convert MTG to and from other matrix formats.

The code comes from NetworkX.

openalea.mtg.matrix.to_scipy_sparse_matrix(g, vertexlist=None, dtype=None, weight='weight', format='csr')[source]

Return the graph adjacency matrix as a SciPy sparse matrix.

Parameters: g (graph) – The MTG used to construct the NumPy matrix. vertexlist (list, optional) – The rows and columns are ordered according to the nodes in vertexlist. If vertexlist is None, then the ordering is produced by g.vertices(). dtype (NumPy data-type, optional) – A valid NumPy dtype used to initialize the array. If None, then the NumPy default is used. weight (string or None optional (default='weight')) – The edge attribute that holds the numerical value used for the edge weight. If None then all edge weights are 1. format (str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'}) – The type of the matrix to be returned (default ‘csr’). For some algorithms different implementations of sparse matrices can perform better. See [1] for details. M – Graph adjacency matrix. SciPy sparse matrix

Notes

The matrix entries are populated using the edge attribute held in parameter weight. When an edge does not have that attribute, the value of the entry is 1.

For multiple edges the matrix values are the sums of the edge weights.

When vertexlist does not contain every node in G, the matrix is built from the subgraph of G that is induced by the nodes in vertexlist.

Uses coo_matrix format. To convert to other formats specify the format= keyword.

Examples

>>> G = nx.MultiDiGraph()
>>> S = nx.to_scipy_sparse_matrix(G, vertexlist=[0,1,2])
>>> print(S.todense())
[[0 2 0]
[1 0 0]
[0 0 4]]


References

 [1] Scipy Dev. References, “Sparse Matrices”, http://docs.scipy.org/doc/scipy/reference/sparse.html

## openalea.mtg.mtg module¶

This module provides an implementation of Multiscale Tree Graph. For interface definition, see openalea.container.interface package.

todo: MTG definition and usage.
class openalea.mtg.mtg.MTG(filename='', has_date=False)[source]

A Multiscale Tree Graph (MTG) class.

MTGs describe tree structures at different levels of details, named scales. For example, a botanist can described plants at different scales :

• at scale 0, the whole scene.
• at scale 1, the individual plants.
• at scale 2, the axes of each plants.
• at scale 3, the growth units of each axis, and so on.

Each scale can have a label, e.g. :

• scale 1 : P(lant)
• scale 2 : A(xis)
• sclae 3 : U(nit of growth)

Compared to a classical tree, complex() can be seen as parent() and components() as children(). An element at scale() N belongs to a complex() at scale() N-1 and has components() at scale N+1:

• /P/A/U (decomposition is noted using “/”)

Each scale is itself described as a tree or a forest (i.e. set of trees), e.g.:

• /P1/P2/P3
• A1+A2<A3
AlgHeight(v1, v2)[source]

Algebraic value defining the number of components between two components.

This function is similar to function Height(v1, v2) : it returns the number of components between two components, at the same scale, but takes into account the order of vertices v1 and v2.

The result is positive if v1 is an ancestor of v2, and negative if v2 is an ancestor of v1.

AlgHeight(v1, v2)

Parameters: v1 (int) : vertex of the active MTG. v2 (int) : vertex of the active MTG. int If v1 is not an ancestor of v2 (or vise versa), or if v1 and v2 are not defined at the same scale, an error value None is returned.

AlgOrder(v1, v2)[source]

Algebraic value defining the relative order of one vertex with respect to another one.

This function is similar to function Order(v1, v2) : it returns the number of +-type edges between two components, at the same scale, but takes into account the order of vertices v1 and v2.

The result is positive if v1 is an ancestor of v2, and negative if v2 is an ancestor of v1.

AlgOrder(v1, v2)

Parameters: v1 (int) : vertex of the active MTG. v2 (int) : vertex of the active MTG. int If v1 is not an ancestor of v2 (or vise versa), or if v1 and v2 are not defined at the same scale, an error value None is returned.

AlgRank(v1, v2)[source]

Algebraic value defining the relative rank of one vertex with respect to another one.

This function is similar to function Rank(v1, v2) : it returns the number of <-type edges between two components, at the same scale, but takes into account the order of vertices v1 and v2.

The result is positive if v1 is an ancestor of v2, and negative if v2 is an ancestor of v1.

AlgRank(v1, v2)

Parameters: v1 (int) : vertex of the active MTG. v2 (int) : vertex of the active MTG. int If v1 is not an ancestor of v2 (or vise versa), or if v1 and v2 are not defined at the same scale, an error value None is returned.

Ancestors(v, EdgeType='*', RestrictedTo='NoRestriction', ContainedIn=None)[source]

Array of all vertices which are ancestors of a given vertex

This function returns the array of vertices which are located before the vertex passed as an argument. These vertices are defined at the same scale as v. The array starts by v, then contains the vertices on the path from v back to the root (in this order) and finishes by the tree root.

Note

The anscestor array always contains at least the argument vertex v.

g.Ancestors(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father EdgeType (str): cf. Father list of vertices’s id (int)
>>> v # prints vertex v
78
>>> g.Ancestors(v) # set of ancestors of v at the same scale
[78,45,32,10,4]
>>> list(reversed(g.Ancestors(v))) # To get the vertices in the order from the root to the vertex v
[4,10,32,45,78]


Axis(v, Scale=-1)[source]

Array of vertices constituting a botanical axis

An axis is a maximal sequence of vertices connected by ‘<’-type edges. Axis return the array of vertices representing the botanical axis which the argument v belongs to. The optional argument enables the user to choose the scale at which the axis decomposition is required.

Axis(v)
Axis(v, Scale=s)

Parameters: Optional Parameters: v (int) : Vertex of the active MTG Scale (str): scale at which the axis components are required. list of vertices ids

Class(vid)

Class of a vertex.

The Class of a vertex are the first characters of the label. The label of a vertex is the string defined by the concatenation of the class and its index.

The label thus provides general information about a vertex and enable to encode the plant components.

The class_name may be not defined. Then, an empty string is returned.

Usage: >>> g.class_name(1)  vid (int) The class name of the vertex (str).
ClassScale(c)[source]

Scale at which appears a given class of vertex

Every vertex is associated with a unique class. Vertices from a given class only appear at a given scale which can be retrieved using this function.

ClassScale(c)

Parameters: c (str) : symbol of the considered class int
Complex(v, Scale=-1)[source]

Complex of a vertex.

Returns the complex of v. The complex of a vertex v has a scale lower than v : Scale(v) - 1. In a MTG, every vertex except for the MTG root (cf. MTGRoot), has a uniq complex. None is returned if the argument is the MTG Root or if the vertex is undefined.

g.Complex(v)
g.Complex(v, Scale=2)

Parameters: Optional Parameters: v (int) : vertex of the active MTG Scale (int) : scale of the complex Returns vertex’s id (int) When a scale different form Scale(v)-1 is specified using the optional parameter Scale, this scale must be lower than that of the vertex argument.

Todo

Complex(v, Scale=10) returns v why ? is this expected

ComponentRoots(v, Scale=-1)[source]

Set of roots of the tree graphs that compose a vertex

In a MTG, a vertex may have be decomposed into components. Some of these components are connected to each other, while other are not. In the most general case, the components of a vertex are organized into several tree-graphs. This is for example the case of a MTG containing the description of several plants: the MTG root vertex can be decomposed into tree graphs (not connected) that represent the different plants. This function returns the set of roots of these tree graphs at scale Scale(v)+1. The order of these roots is not significant.

When a scale different from Scale(v)+1 is specified using the optional argument Scale(), this scale must be greater than that of the vertex argument.

g.ComponentRoots(v)
g.ComponentRoots(v, Scale=s)

Parameters: Optional Parameters: v (int) : vertex of the active MTG Scale (str): scale of the component roots. list of vertices’s id (int)
>>> v=g.MTGRoot() # global MTG root
0
>>> g.ComponentRoots(v) # set of first vertices at scale 1
[1,34,76,100,199,255]
>>> g.ComponentRoots(v, Scale=2) # set of first vertices at scale 2
[2,35,77,101,200,256]

Components(v, Scale=-1)[source]

Set of components of a vertex.

The set of components of a vertex is returned as a list of vertices. If s defines the scale of v, components are defined at scale s + 1. The array is empty if the vertex has no components. The order of the components in the array is not significant.

When a scale is specified using optional argument :arg:Scale, it must be necessarily greater than the scale of the argument.

Components(v)
Components(v, Scale=2)

Parameters: Optional Parameters: v (int) : vertex of the active MTG Scale (int) : scale of the components. list of int

Defined(vid)[source]

Test whether a given vertex belongs to the active MTG.

Defined(v)

Parameters: v (int) : vertex of the active MTG True or False

Descendants(v, EdgeType='*', RestrictedTo='NoRestriction', ContainedIn=None)[source]

Set of vertices in the branching system borne by a vertex.

This function returns the set of descendants of its argument as an array of vertices. The array thus consists of all the vertices, at the same scale as v, that belong to the branching system starting at v. The order of the vertices in the array is not significant.

Note

The argument always belongs to the set of its descendants.

g.Descendants(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father EdgeType (str): cf. Father list of int.
>>> v
78
>>> g.Sons(v) # set of sons of v
[78,99,101]
>>> g.Descendants(v) # set of descendants of v
[78,99,101,121,133,135,156,171,190]


EdgeType(v1, v2)[source]

Type of connection between two vertices.

Returns the symbol of the type of connection between two vertices (either < or +). If the vertices are not connected, None is returned.

EdgeType(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG ‘<’ (successor), ‘+’ (branching) or None

Extremities(v, RestrictedTo='NoRestriction', ContainedIn=None)[source]

Set of vertices that are the extremities of the branching system born by a given vertex.

This function returns the extremities of the branching system defined by the argument as a list of vertices. These vertices have the same scale as v and their order in the list is not signifiant. The result is always a non empty array.

Extremities(v)

Properties: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father() ContainedIn (int): cf. Father() list of vertices’s id (int)
>>> g.Descendants(v)
[3, 45, 47, 78, 102]
>>> g.Extremities(v)
[47, 102]

Father(v, EdgeType='*', RestrictedTo='NoRestriction', ContainedIn=None, Scale=-1)[source]

Topological father of a given vertex.

Returns the topological father of a given vertex. And None if the father does not exist. If the argument is not a valid vertex, None is returned.

g.Father(v)
g.Father(v, EdgeType='<')
g.Father(v, RestrictedTo='SameComplex')
g.Father(v, ContainedIn=complex_id)
g.Father(v, Scale=s)

Parameters: Optional Parameters: v (int) : vertex of the active MTG If no optional argument is specified, the function returns the topological father of the argument (vertex that bears or precedes to the vertex passed as an argument). It may be usefull in some cases to consider that the function only applies to a subpart of the MTG (e.g. an axis). The following options enables us to specify such restrictions: EdgeType (str) : filter on the type of edge that connect the vertex to its father. Values can be ‘<’, ‘+’, and ‘*’. Values ‘*’ means both ‘<’ and ‘+’. Only the vertex connected with the specified type of edge will be considered. RestrictedTo (str) : filter defining a subpart of the MTG where the father must be considered. If the father is actually outside this subpart, the result is None. Possible subparts are defined using keywords in [‘SameComplex’, ‘SameAxis’, ‘NoRestriction’]. For instance, if RestrictedTo is set to ‘SameComplex’, Father(v)() returns a defined vertex only if the father f of v existsin the MTG and if v and f have the same complex. ContainedIn (int) : filter defining a subpart of the MTG where the father must be considered. If the father is actually outside this subpart, the result is None. In this case, the subpart of the MTG is made of the vertices that composed composite_id (at any scale). Scale (int) : the scale of the considered father. Returns the vertex from scale s which either bears and precedes the argument. The scale s can be lower than the argument’s (corresponding to a question such as ‘which axis bears the internode?’) or greater (e.g. ‘which internodes bears this annual shoot?’). the vertex id of the Father (int)
Height(v1, v2=None)[source]

Number of components existing between two components in a tree graph.

The height of a vertex (v2) with respect to another vertex (v1) is the number of edges (of either type ‘+’ or ‘<’) that must be crossed when going from v1 to v2 in the graph.

This is a non-negative integer. When the function has only one argument v1, the height of v1 correspond to the height of v1with respect to the root of the branching system containing v1.

Height(v1)
Height(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG int

Note

When the function takes two arguments, the order of the arguments is not important provided that one is an ancestor of the other. When the order is relevant, use function AlgHeight.

Index(vid)

Index of a vertex

The Index of a vertex is a feature always defined and independent of time (like the index). It is represented by a non negative integer. The label of a vertex is the string defined by the concatenation of its class and its index. The label thus provides general information about a vertex and enables us to encode the plant components.

Label(vid)

Label of a vertex.

Usage: >>> g.label(v)  vid (int) : vertex of the MTG The class and Index of the vertex (str).
Path(v1, v2)[source]

List of vertices defining the path between two vertices

This function returns the list of vertices defining the path between two vertices that are in an ancestor relationship. The vertex v1 must be an ancestor of vertex v2. Otherwise, if both vertices are valid, then the empty array is returned and if at least one vertex is undefined, None is returned.

g.Path(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG list of vertices’s id (int)
>>> v # print the value of v
78
>>> g.Ancestors(v)
[78,45,32,10,4]
>>> g.Path(10,v)
[10,32,45,78]
>>> g.Path(9,v) # 9 is not an ancestor of 78
[]


Note

v1 can be equal to v2.

Predecessor(v, **kwds)[source]

Father of a vertex connected to it by a ‘<’ edge

This function is equivalent to Father(v, EdgeType-> ‘<’). It thus returns the father (at the same scale) of the argument if it is located in the same botanical. If it does not exist, None is returned.

Predecessor(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father return the vertex id (int)
>>> Predecessor(v)
7
>>> Father(v, EdgeType='+')
>>> Father(v, EdgeType-> '<')
7

Rank(v1, v2=None)[source]

Rank of one vertex with respect to another one.

This function returns the number of consecutive ‘<’-type edges between two components, at the same scale, and does not take into account the order of vertices v1 and v2. The result is a non negative integer.

Rank(v1)
Rank(v1, v2)

Parameters: v1 (int) : vertex of the active MTG v2 (int) : vertex of the active MTG int If v1 is not an ancestor of v2 (or vise versa) within the same botanical axis, or if v1 and v2 are not defined at the same scale, an error value Undef id returned.

Root(v, RestrictedTo='*', ContainedIn=None)[source]

Root of the branching system containing a vertex

This function is equivalent to Ancestors(v, EdgeType=’<’)[-1]. It thus returns the root of the branching system containing the argument. This function never returns None.

g.Root(v)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father return vertex’s id (int)
>>> g.Ancestors(v) # set of ancestors of v
[102,78,35,33,24,12]
>>> g.Root(v) # root of the branching system containing v
12


Scale(vid)

Returns the scale of a vertex.

All vertices should belong to a given scale.

g.scale(vid)

Parameters: vid (int) - vertex identifier. The scale of the vertex. It is a positive int in [0,g.max_scale()].
Sons(v, RestrictedTo='NoRestriction', EdgeType='*', Scale=-1, ContainedIn=None)[source]

Set of vertices born or preceded by a vertex

The set of sons of a given vertex is returned as an array of vertices. The order of the vertices in the array is not significant. The array can be empty if there are no son vertices.

g.Sons(v)
g.Sons(v, EdgeType= '+')
g.Sons(v, Scale= 3)

Parameters: Optional Parameters: v (int) : vertex of the active MTG RestrictedTo (str) : cf. Father() ContainedIn (int) : cf. Father() EdgeType (str) : filter on the type of sons. Scale (int) : set the scale at which sons are considered. list(vid) When the option EdgeType is applied, the function returns the set of sons that are connected to the argument with the specified type of relation.

Note

Sons(v, EdgeType= ‘<’) is not equivalent to Successor(v). The first function returns an array of vertices while the second function returns a vertex.

The returned vertices have the same scale as the argument. However, coarser or finer vertices can be obtained by specifying the optional argument Scale at which the sons are considered.

>>> g.Sons(v)
[3,45,47,78,102]
>>>  g.Sons(v, EdgeType= '+') # set of vertices borne by v
[3,45,47,102]
>>>  g.Sons(v, EdgeType= '<') # set of successors of v on the same axis
[78]

Successor(v, RestrictedTo='NoRestriction', ContainedIn=None)[source]

Vertex that is connected to a given vertex by a ‘<’ edge type (i.e. in the same botanical axis).

This function is equivalent to Sons(v, EdgeType=’<’)[0]. It returns the vertex that is connected to a given vertex by a ‘<’ edge type (i.e. in the same botanical axis). If many such vertices exist, an arbitrary one is returned by the function. If no such vertex exists, None is returned.

g.Successor(v)

Parameters: Optional Parameters: v1 (int) : vertex of the active MTG RestrictedTo (str): cf. Father ContainedIn (int): cf. Father Returns vertex’s id (int)
>>> g.Sons(v)
[3, 45, 47, 78, 102]
>>> g.Sons(v, EdgeType='+') # set of vertices borne by v
[3, 45, 47, 102]
>>> g.Sons(v, EdgeType-> '<') # set of successors of v
[78]
>>> g.Successor(v)
78

Trunk(v, Scale=-1)[source]

List of vertices constituting the bearing botanical axis of a branching system.

Trunk returns the list of vertices representing the botanical axis defined as the bearing axis of the whole branching system defined by v. The optional argument enables the user to choose the scale at which the trunk should be detailed.

Trunk(v)
Trunk(v, Scale= s)

Parameters: Optional Parameters: v (int) : Vertex of the active MTG. Scale (str): scale at which the axis components are required. list of vertices ids

Todo

check the usage of the optional argument Scale

VtxList(Scale=-1)[source]

Array of vertices contained in a MTG

The set of all vertices in the MTG() is returned as an array. Vertices from all scales are returned if no option is used. The order of the elements in this array is not significant.

>>> VtxList()
>>> VtxList(Scale=2)

Optional Parameters:

• Scale (int): used to select components at a particular scale.
Returns:
• list of vid
Background:

MTGs()

add_child(parent, child=None, **properties)[source]

Add a child to a parent. Child is appended to the parent’s child list.

Parameters: parent (int) - The parent identifier. child (int or None) - The child identifier. If None, an ID is generated. Identifier of the inserted vertex (child) int
add_child_and_complex(parent, child=None, complex=None, **properties)[source]

Add a child at the end of children that belong to an other complex.

Parameters: parent: The parent identifier. child: Set the child identifier to this value if defined. complex: Set the complex identifier to this value if defined. (vid, vid): child and complex ids.
add_component(complex_id, component_id=None, **properties)[source]

Add a component at the end of the components

Parameters: complex_id: The complex identifier. component_id: Set the component identifier to this value if defined. The id of the new component or the component_id if given.
add_element(parent_id, edge_type='/', scale_id=None)[source]

Add an element to the graph, if vid is not provided create a new vid ??? .. warning: Not Implemented.

• parent_id (int) - The id of the parent vertex
• edge_type (str) - The type of relation:
• “/” : component (default)
• “+” : branch
• “<” : successor.
• scale_id (int) - The id of the scale in which to
Returns: The vid of the created vertex
backward_rewriting_traversal()
class_name(vid)[source]

Class of a vertex.

The Class of a vertex are the first characters of the label. The label of a vertex is the string defined by the concatenation of the class and its index.

The label thus provides general information about a vertex and enable to encode the plant components.

The class_name may be not defined. Then, an empty string is returned.

Usage: >>> g.class_name(1)  vid (int) The class name of the vertex (str).
clear()[source]

Remove all vertices and edges from the MTG.

This also removes all vertex properties. Don’t change references to object such as internal dictionaries.

Example: >>> g.clear() >>> g.nb_vertices() 0 >>> len(g) 0 
clear_properties(exclude=[])[source]

Remove all the properties of the MTG.

Example: >>> g.clear_properties() 
complex(vtx_id)[source]

Returns the complex of vtx_id.

Parameters: vtx_id (int) - The vertex identifier. complex identifier or None if vtx_id has no parent. int
complex_at_scale(vtx_id, scale)[source]

Returns the complex of vtx_id at scale scale.

Parameters: vtx_id: The vertex identifier. scale: The scale identifier. vertex identifier int
component_roots(vtx_id)[source]

Return the set of roots of the tree graphs that compose a vertex.

component_roots_at_scale(vtx_id, scale)[source]

Return the list of roots of the tree graphs that compose a vertex.

component_roots_at_scale_iter(vtx_id, scale)[source]

Return the set of roots of the tree graphs that compose a vertex.

component_roots_iter(vtx_id)[source]

Return an iterator of the roots of the tree graphs that compose a vertex.

components(vid)[source]

returns the components of a vertex

Parameters: vid – The vertex identifier. list of vertex identifier
components_at_scale(vid, scale)[source]

returns a vertex iterator

Parameters: vid: The vertex identifier. iter of vertex identifier
components_at_scale_iter(vid, scale)[source]

returns a vertex iterator

Parameters: vid: The vertex identifier. iter of vertex identifier
components_iter(vid)[source]

returns a vertex iterator

Parameters: vid – The vertex identifier. iter of vertex identifier
copy()[source]

Return a copy of the graph.

Returns: g (MTG) - A copy of the MTG
display(max_scale=0, display_id=True, display_scale=False, nb_tab=12, **kwds)[source]

Print an MTG on the console.

Optional Parameters:

• max_scale: do not print vertices of scale greater than max_scale
• display_id: display the vid of the vertices
• display_scale: display the scale of the vertices
• nb_tab: display the MTG using nb_tab columns
edge_type(vid)[source]

Type of the edge between a vertex and its parent.

The different values are ‘<’ for successor, and ‘+’ for ramification.

edges(scale=-1)[source]
Parameters: scale (int) - Scale at which to iterate. Iterator on the edges of the MTG at a given scale or on all edges if scale < 0. iter
forward_rewriting_traversal()
has_vertex(vid)[source]

Tests whether a vertex belongs to the graph.

Parameters: vid (int) - vertex id to test bool
index(vid)[source]

Index of a vertex

The Index of a vertex is a feature always defined and independent of time (like the index). It is represented by a non negative integer. The label of a vertex is the string defined by the concatenation of its class and its index. The label thus provides general information about a vertex and enables us to encode the plant components.

insert_parent(vtx_id, parent_id=None, **properties)[source]

Insert parent_id between vtx_id and its actual parent. Inherit of the complex of the parent of vtx_id.

Parameters: vtx_id (int): a vertex identifier parent_id (int): a vertex identifier Identifier of the inserted vertex (parent_id). int
insert_scale(inf_scale=None, partition=None, default_label=None, preserve_order=True)[source]

• inf_scale (int) - New scale is inserted between inf_scale and inf_scale-1
• partition (lambda v: bool) - Function defining new scale by quotienting vertices at inf_scale
• default_label (str) - default label of inserted vertices
• preserve_order (bool) - True iif children at new scale are ordered consistently
with children at inf_scale
Returns: MTG with inserted scale New scale is inserted in self as well. function partition should return True at roots of subtrees where partition changes and False elsewhere.
insert_sibling(vtx_id1, vtx_id2=None, **properties)[source]

Insert a sibling of vtk_id1. The vertex in inserted before vtx_id1.

Parameters: vtx_id1 (int) : a vertex identifier vtx_id2 (int) : the vertex to insert Identifier of the inserted vertex (vtx_id2) int
is_valid()[source]

Tests the validity of the graph. Currently always returns True.

Returns Type: bool Implement this function.
iter_edges(scale=-1)[source]
Parameters: scale (int) - Scale at which to iterate. Iterator on the edges of the MTG at a given scale or on all edges if scale < 0. iter
iteredges(scale=-1)[source]

Iter on the edges of the tree.

label(vid)[source]

Label of a vertex.

Usage: >>> g.label(v)  vid (int) : vertex of the MTG The class and Index of the vertex (str).
max_scale()[source]

Return the max scale identifier.

By convention, the mtg contains scales in $$[0,max\_scale]$$.

Usage: >>> print g.max_scale()  S, the maximum scale identifier.

Note

The complexity is $$O(n)$$.

nb_components(vid)[source]

returns the number of components

Parameters: vid: The vertex identifier. int
nb_scales()[source]
Returns: The number of scales defined in the mtg.. int

Note

The complexity is $$O(n)$$.

nb_vertices(scale=-1)[source]

Returns the number of vertices.

Usage: >>> g.nb_vertices() 100 >>> g.nb_vertices(scale=3) 68  scale (int) - Id of scale for which to count vertices. Number of vertices at scale or total number of vertices if scale < 0.
node(vid, klass=None)[source]

Return a node associated to the vertex vid.

It allows to access to the properties with an object oriented interface.

node = g.node(1)
print node.edge_type
print node.label
node.label = 'B'
print g.label(1)

print node.parent
print list(node.children)

order(v1)[source]

Order of a vertex in a graph.

The order of a vertex in a graph is the number of ‘+’ edges crossed when going from v1to v2.

If v2 is None, the order of v1 correspond to the order of v1 with respect to the root.

plot_property(prop, **kwds)[source]

Plot properties of MTG using matplotlib

Example: >>> g.plot_property('length') 
reindex(mapping=None, copy=False)[source]

Assign a new identifier to each vertex.

This method assigns a new identifier to each vertex of the MTG. The mapping can be user defined or is implicit (mapping). This method modify the MTG in place or return a new MTG (copy).

>>> g.reindex()
>>> g1 = g.reindex(copy=True)
>>> mymap = dict(zip(list(traversal.iter_mtg2(g,g.root)), range(len(g))))
>>> g2 = g.reindex(mapping=mymap, copy=True)

Optional Parameters:

• mapping (dict): define a mapping between old and new vertex identifiers.
• copy (bool) : modify the object in place or return a new MTG.
Returns:
• a MTG
Background:

MTGs()

remove_scale(scale)[source]

Remove all the vertices at a given scale.

The upper and lower scale are then connected.

• scale : the scale that have to be removed
Returns: - g (the input MTG modified in place.) - results (a list of dict) – all the vertices that have been removed
remove_vertex(vid, reparent_child=False)[source]

Remove a specified vertex of the graph and remove all the edges attached to it.

Parameters: vid (int) : the id of the vertex to remove reparent_child (bool) : reparent the children of vid to its parent. None
replace_parent(vtx_id, new_parent_id, **properties)[source]

Change the parent of vtx_id to new_parent_id. The new parent of vtx_id is new_parent_id. vtx_id and new_parent_id must have the same scale.

This function do not change the edge_type between vtx_id and its parent.

Inherit of the complex of the parent of vtx_id.

Parameters: vtx_id (int): a vertex identifier new_parent_id (int): a vertex identifier None
roots(scale=0)[source]

Returns a list of the roots of the tree graphs at a given scale.

In an MTG, the MTG root vertex, namely the vertex g.root, can be decomposed into several, non-connected, tree graphs at a given scale. This is for example the case of an MTG containing the description of several plants.

Usage: roots = g.roots(scale=g.max_scale() list on vertex identifiers of root vertices at a given scale. list of vid
roots_iter(scale=0)[source]

Returns an iterator of the roots of the tree graphs at a given scale.

In an MTG, the MTG root vertex, namely the vertex g.root, can be decomposed into several, non-connected, tree graphs at a given scale. This is for example the case of an MTG containing the description of several plants.

Usage: roots = list(g.roots(scale=g.max_scale()) iterator on vertex identifiers of root vertices at a given scale. iter
scale(vid)[source]

Returns the scale of a vertex.

All vertices should belong to a given scale.

g.scale(vid)

Parameters: vid (int) - vertex identifier. The scale of the vertex. It is a positive int in [0,g.max_scale()].
scales()[source]

Return the different scales of the mtg.

Returns: Iterator on scale identifiers (ints).

Note

The complexity is $$O(n)$$.

scales_iter()[source]

Return the different scales of the mtg.

Returns: Iterator on scale identifiers (ints).

Note

The complexity is $$O(n)$$.

sub_mtg(vtx_id, copy=True)[source]

Return the submtg rooted on vtx_id.

The induced sub mtg of the mtg are all the vertices which have vtx_id has a complex plus vtx_id.

Parameters: vtx_id: A vertex of the original tree. copy: If True, return a new tree holding the subtree. If False, the subtree is created using the original tree by deleting all vertices not in the subtree. A sub mtg of the mtg. If copy=True, a new MTG is returned. Else the sub mtg is created inplace by modifying the original tree.
vertices(scale=-1)[source]

Return a list of the vertices contained in an MTG.

The set of all vertices in the MTG is returned. Vertices from all scales are returned if no scale is given. Otherwise, it returns only the vertices of the given scale. The order of the elements in this array is not significant.

g = MTG()
len(g) == len(list(g.vertices()))
for vid in g.vertices(scale=2):
print g.class_name(vid)

Optional Parameters:

• scale (int): used to select vertices at a given scale.
Returns:

Iterator on vertices at “scale” or on all vertices if scale < 0.

Returns Type:

list of vid

Background:
vertices_iter(scale=-1)[source]

Return an iterator of the vertices contained in an MTG.

The set of all vertices in the MTG is returned. Vertices from all scales are returned if no scale is given. Otherwise, it returns only the vertices of the given scale. The order of the elements in this array is not significant.

g = MTG()
len(g) == len(list(g.vertices()))
for vid in g.vertices(scale=2):
print g.class_name(vid)

Optional Parameters:

• scale (int): used to select vertices at a given scale.
Returns:

Iterator on vertices at “scale” or on all vertices if scale < 0.

Returns Type:

iter of vid

Background:

openalea.mtg.mtg.colored_tree(tree, colors)[source]

Compute a mtg from a tree and the list of vertices to be quotiented.

Note

The tree has to be a real tree and not an MTG

from random import randint, sample
g = MTG()
random_tree(g, g.root, nb_vertices=200)

# At each scale, define the vertices which will define a complex
nb_scales=4
colors = {}
colors[3] = g.vertices()
colors[2] = random.sample(colors[3], randint(1,len(g)))
colors[2].sort()
if g.root not in colors[2]:
colors[2].insert(0, g.root)
colors[1] = [g.root]

g, mapping = colored_tree(g, colors)

openalea.mtg.mtg.display_mtg(mtg, vid)[source]

Display an MTG

..todo:: Write doc.

openalea.mtg.mtg.display_tree(tree, vid, tab='', labels={}, edge_type={})[source]

Display a tree structure.

openalea.mtg.mtg.fat_mtg(slim_mtg, preserve_order=False)[source]

Compute missing edges at each scales based on the explicit edges defines at finer scales and decomposition relationship. If preserve_order is True, the order of children at coarsest scales is deduced from the order of children at finest scale

openalea.mtg.mtg.proxy(f)[source]
openalea.mtg.mtg.random_mtg(tree, nb_scales)[source]

Convert a tree into an MTG of nb_scales.

Add a random sub tree at a given vertex id position root. The length of the sub_tree is nb_vertices. Each new vertex has at most nb_children children.

Parameters: mtg: the mtg to modified root (id): vertex id on which the sub tree will be added. The last added vid. g = MTG() random_tree(g, g.root, nb_children=2, nb_vertices=20) print len(g) # 21 
openalea.mtg.mtg.random_tree(mtg, root, nb_children=3, nb_vertices=20)[source]

Generate and add a random tree to an existing one.

Add a random sub tree at a given vertex id position root. The length of the sub_tree is nb_vertices. The number of children for each vertex is sampled according to nb_children distribution. If nb_children is an interger, the random distribution is uniform between [1, nb_children]. Otherwise, you can give your own discrete distribution sampling function.

Parameters: Optional Parameters: mtg: the mtg to modified root (id): vertex id on which the sub tree will be added. nb_vertices nb_children : an int or a discrete distribution sampling function. The last added vid. g = MTG() vid = g.add_component(g.root) random_tree(g, vid, nb_children=2, nb_vertices=20) print len(g) # 22 
openalea.mtg.mtg.return_iter_proxy(f)[source]
openalea.mtg.mtg.return_proxy(f)[source]
openalea.mtg.mtg.return_tuple_proxy(f)[source]
openalea.mtg.mtg.simple_tree(tree, vtx_id, nb_children=3, nb_vertices=20)[source]

Generate and add a regular tree to an existing one at a given vertex.

Add a regular tree at a given vertex id position vtx_id. The length of the sub_tree is nb_vertices. Each new vertex has at most nb_children children.

Parameters: tree: the tree thaat will be modified vtx_id (id): vertex on which the sub tree will be added. nb_children (int) : number of children that are added to each vertex nb_vertices (int) : number of vertices to add The modified tree g = MTG() vid = g.add_component(g.root) simple_tree(g, vid, nb_children=2, nb_vertices=20) print len(g) # 22 

## openalea.mtg.rewriting module¶

MTG rewriting facilities

class openalea.mtg.rewriting.EB[source]
class openalea.mtg.rewriting.MTGLsystem[source]

Bases: object

animate(nbiter=1, dt=0.1)[source]
axiom()[source]
init()[source]
interpret(inputmtg=None, turtle=None)[source]
iterate(inputmtg=None)[source]
plot(inputmtg=None)[source]
rules = {}
run(nbiter=1)[source]
sceneInterpretation(inputmtg=None)[source]
class openalea.mtg.rewriting.MTGProducer[source]

Bases: object

To produce an MTG in several steps

nproduce(*modules)[source]
produce(*modules)[source]
class openalea.mtg.rewriting.Module(name, scale, **parameters)[source]

Bases: object

class openalea.mtg.rewriting.RewritableNode(mtg, vid)[source]

Bases: openalea.mtg.mtg._ProxyNode

is_valid()[source]
nproduce(*modules)[source]
produce(*modules)[source]
class openalea.mtg.rewriting.SB[source]
openalea.mtg.rewriting.interpretation(f)[source]
openalea.mtg.rewriting.macro_children_at_maxscale(mtg, vid, macroscale)[source]
openalea.mtg.rewriting.module(name, scale, namespace)[source]

declare a module in the namespace

openalea.mtg.rewriting.nodes_forward_traversal(mtg, pre_order, post_order)[source]
openalea.mtg.rewriting.produce(*modules)[source]

Function that produce an MTG from a serie of modules

openalea.mtg.rewriting.production(f)[source]
openalea.mtg.rewriting.retrieve_modules(mtg, namespace)[source]

## openalea.mtg.stat module¶

This module implements methods to create statistical sequences from an MTG.

Principles: Extract sequence identifier as a property and add it as input of the sequence explicit identifier for sequence (e.g. year of growth or date of observation)
exception openalea.mtg.stat.InvalidVariable[source]

Bases: exceptions.Exception

exception openalea.mtg.stat.InvalidVertex[source]

Bases: exceptions.Exception

openalea.mtg.stat.build_sequences(g, vid_sequences, variables=[], **kwds)[source]

Extract a set of Vectors from an MTG.

• g: an MTG
• vid_sequences: a list of list ofvertex ids that belong to the MTG Each element of the lsit represents a sequence.
• variables: a list of property names that represent the vectors variables.
• a Sequence object
length = g.property('Length')
leaves = (vid for vid in g.vertices(scale=g.max_scale()) if g.is_leaf(vid))
seqs = [list(reversed([vid for vid in algo.ancestors(g, lid) if vid in leaves])) for lid in leaves]

sequences = build_sequences(g,seqs,['Length'])

openalea.mtg.stat.check_variables(g, variables)[source]
openalea.mtg.stat.check_vids(g, vids)[source]
openalea.mtg.stat.extract_axes(g, scale=0, **kwds)[source]
openalea.mtg.stat.extract_extremities(g, scale=0, **kwds)[source]
openalea.mtg.stat.extract_sequences(g, variables=[], vid=-1, scale=0, mode='axes', **kwds)[source]

Implement different strategies to extract a set of vids.

The different modes are:
• extremities: seqs from root to leaves.
• axes: split each sequence when a + is found
openalea.mtg.stat.extract_vectors(g, vids, variables=[], **kwds)[source]

Extract a set of Vectors from an MTG.

• g: an MTG
• vid: a list of vertex ids that belong to the MTG
• variables: a list of property names that represent the vectors variables.
• a Vectors object
length = g.property('Length')
vids = [vid for vid in g.vertices(scale=2) if vid in length]
vectors = extract_vectors(g, vids, ['Length'])

# or an equivalent

length = g.property('Length')
vids = [vid for vid in g.vertices(scale=2) if vid in length]
vectors = extract_vectors(g, vids, [length])

openalea.mtg.stat.filter_sequence(seq, pred)[source]

Select a Sequence if only the predicate is true for each element.

openalea.mtg.stat.first_component_root(g, vid)[source]
openalea.mtg.stat.property_list(g, vid, variables)[source]
openalea.mtg.stat.vectors_as_txt(vectors)[source]

Write Vectors objects into a txt file.

openalea.mtg.stat.write_sequences(seqs, variables, VertexIdentifiers)[source]

Write Sequences into a txt file.

## openalea.mtg.traversal module¶

Tree and MTG Traversals

class openalea.mtg.traversal.Visitor[source]

Bases: object

Used during a tree traversal.

post_order(vtx_id)[source]
pre_order(vtx_id)[source]
openalea.mtg.traversal.iter_mtg(mtg, vtx_id)[source]

Iterate on an MTG by traversiong vtx_id and all its components.

This function traverse a complex before its components and a parent before its children.

for vid in iter_mtg(g,g.root):
print vid

Parameters: mtg: the multi-scale graph vtx_id: the root of the sub-mtg which is traversed. iter of vid. Traverse all the vertices contained in the sub_mtg defined by vtx_id.

Note

Do not use this function. Use iter_mtg2() instead. If several trees belong to vtx_id, only the first one will be traversed.

Note

This is a recursive implementation. It can be problematic for large MTG with lots of scales (e.g. >40).

openalea.mtg.traversal.iter_mtg2(mtg, vtx_id)[source]

Iterate on an MTG by traversiong vtx_id and all its components.

This function traverse a complex before its components and a parent before its children.

for vid in iter_mtg2(g,g.root):
print vid

Parameters: mtg: the multi-scale graph vtx_id: the root of the sub-mtg which is traversed. iter of vid. Traverse all the vertices contained in the sub_mtg defined by vtx_id.

Note

Use this function instead of iter_mtg()

openalea.mtg.traversal.iter_mtg2_with_filter(mtg, vtx_id, pre_order_filter=None, post_order_visitor=None)[source]

Iterate on an MTG by traversiong vtx_id and all its components.

If defined, apply the two visitor functions before and after having visited all the successor of a vertex.

This function traverse a complex before its components and a parent before its children.

def pre_order_visitor(vid):
print vid
return True
def post_order_visitor(vid):
print vid
for vid in iter_mtg_with_filter(g,g.root, pre_order_visitor, post_order_visitor):
pass

Parameters: Optional Parameters: mtg: the multi-scale graph vtx_id: the root of the sub-mtg which is traversed. pre_order_visitor: function called before traversing the children or components. This function returns a boolean. If False, the sub-mtg rooted on the vertex is skipped. post_order_visitor : function called after the traversal of all the children and components. iter of vid. Traverse all the vertices contained in the sub_mtg defined by vtx_id.

Note

Use this function instead of iter_mtg_with_filter()

openalea.mtg.traversal.iter_mtg_with_filter(mtg, vtx_id, pre_order_filter=None, post_order_visitor=None)[source]

Iterate on an MTG by traversiong vtx_id and all its components.

If defined, apply the two visitor functions before and after having visited all the successor of a vertex.

This function traverse a complex before its components and a parent before its children.

def pre_order_visitor(vid):
print vid
return True
def post_order_visitor(vid):
print vid
for vid in iter_mtg_with_filter(g,g.root, pre_order_visitor, post_order_visitor):
pass

Parameters: Optional Parameters: mtg: the multi-scale graph vtx_id: the root of the sub-mtg which is traversed. pre_order_visitor: function called before traversing the children or components. This function returns a boolean. If False, the sub-mtg rooted on the vertex is skipped. post_order_visitor : function called after the traversal of all the children and components. iter of vid. Traverse all the vertices contained in the sub_mtg defined by vtx_id.

Note

Do not use this function. Instead use iter_mtg2_with_filter()

openalea.mtg.traversal.iter_scale(g, vtx_id, visited)[source]

Internal method used by iter_mtg() and iter_mtg_with_visitor().

Warning

Do not use. This function may be removed in other version.

openalea.mtg.traversal.iter_scale2(g, vtx_id, complex_id, visited)[source]

Internal method used by iter_mtg() and iter_mtg_with_visitor().

Warning

Do not use. This function may be removed in other version.

openalea.mtg.traversal.post_order(tree, vtx_id, complex=None, visitor_filter=None)[source]

Traverse a tree in a postfix way. (from leaves to root) This is a recursive implementation

openalea.mtg.traversal.post_order2(tree, vtx_id, complex=None, pre_order_filter=None, post_order_visitor=None)[source]

Traverse a tree in a postfix way. (from leaves to root)

Same algorithm than post_order. The goal is to replace the post_order implementation.

openalea.mtg.traversal.pre_order(tree, vtx_id, complex=None, visitor_filter=None)[source]

Traverse a tree in a prefix way. (root then children)

This is a non recursive implementation.

openalea.mtg.traversal.pre_order2(tree, vtx_id, complex=None, visitor_filter=None)[source]

Traverse a tree in a prefix way. (root then children)

This is an iterative implementation.

openalea.mtg.traversal.pre_order2_with_filter(tree, vtx_id, complex=None, pre_order_filter=None, post_order_visitor=None)[source]

Same algorithm than pre_order2. The goal is to replace the pre_order2 implementation.

The problem is for the pre_order filter when it is also a visitor

openalea.mtg.traversal.pre_order_in_scale(tree, vtx_id, visitor_filter=None)[source]

Traverse a tree in a prefix way. (root then children)

This is a non recursive implementation.

openalea.mtg.traversal.pre_order_with_filter(tree, vtx_id, pre_order_filter=None, post_order_visitor=None)[source]

Traverse a tree in a prefix way. (root then children)

This is an iterative implementation.

TODO: make the naming and the arguments more consistent and user friendly. pre_order_filter is a functor which has to return a boolean. If the return value is False, the vertex is not visited. Otherelse, some computation can be done.

The post_order_visitor is used to execute, store, compute a function when the tree rooted on the vertex has been visited.

openalea.mtg.traversal.topological_sort(g, vtx_id, visited=None)[source]

Topological sort of a directed acyclic graph.

This is not a fully recursive implementation.

openalea.mtg.traversal.traverse_tree(tree, vtx_id, visitor)[source]

Traverse a tree in a prefix or postfix way.

We call a visitor for each vertex. This is usefull for printing, computing or storing vertices in a specific order.

See boost.graph.

## openalea.mtg.tree module¶

This is a copy of the file in openalea.container. This copy is used only for dependencies management before moving MTG in openalea.container.

This module provides an implementation of a rooted tree graph. For interface definition, see openalea.container.interface.tree.

exception openalea.mtg.tree.GraphError[source]

Bases: exceptions.Exception

base class of all graph exceptions

exception openalea.mtg.tree.InvalidVertex[source]

Bases: openalea.mtg.tree.GraphError, exceptions.KeyError

exception raised when a wrong vertex id is provided

class openalea.mtg.tree.PropertyTree(*args, **kwds)[source]
add_child(parent, child=None, **properties)[source]

Add a child at the end of children

Parameters: parent – The parent identifier. child – The child identifier. vertex id
add_child_tree(parent, tree)[source]

Add a tree after the children of the parent vertex. Complexity have to be O(1) if tree == sub_tree()

Parameters: parent – vertex identifier tree – a rooted tree
add_property(property_name)[source]

Add a new map between vid and a data Do not fill this property for any vertex

get_vertex_property(vid)[source]

Returns all the properties defined on a vertex.

graph_properties()[source]

return a dict containing the graph properties/

Return type: dict of {property_name:data}
insert_parent(vtx_id, parent_id=None, **properties)[source]

Insert parent_id between vtx_id and its actual parent. Inherit of the complex of the parent of vtx_id.

Parameters: vtx_id: a vertex identifier parent_id: a vertex identifier
insert_sibling(vtx_id1, vtx_id2=None, **properties)[source]

Insert vtx_id2 before vtx_id1.

Parameters: vtx_id1: a vertex identifier vtx_id2: the vertex to insert
insert_sibling_tree(vid, tree)[source]

Insert a tree before the vid. vid and the root of the tree are siblings. Complexity have to be O(1) if tree comes from the actual tree ( tree= self.sub_tree() )

Parameters: vid – vertex identifier tree – a rooted tree
properties()[source]

Returns all the property maps contain in the graph.

property(name)[source]

Returns the property map between the vid and the data. :returns: dict of {vid:data}

property_names()[source]

names of all property maps. Properties are defined only on vertices, even edge properties. return iter of names

property_names_iter()[source]

iter on names of all property maps. Properties are defined only on vertices, even edge properties. return iter of names

remove_property(property_name)[source]

Remove the property map called property_name from the graph.

remove_tree(vtx_id)[source]

Remove the sub tree rooted on vtx_id.

Returns: bool
remove_vertex(vid, reparent_child=False)[source]

remove a specified vertex of the graph remove all the edges attached to it

Parameters: vid (vid) – the id of the vertex to remove
sub_tree(vtx_id, copy=True)[source]

Return the subtree rooted on vtx_id.

The induced subtree of the tree has the vertices in the ancestors of vtx_id.

Parameters: vtx_id: A vertex of the original tree. copy: If True, return a new tree holding the subtree. If False, the subtree is created using the original tree by deleting all vertices not in the subtree. A sub tree of the tree. If copy=True, a new Tree is returned. Else the subtree is created inplace by modifying the original tree.
class openalea.mtg.tree.Tree(root=0, tree=None)[source]

Bases: object

Implementation of a rooted Tree, with methods to add and remove vertex.

add_child(parent, child=None, **properties)[source]

Add a child at the end of children

Parameters: parent – The parent identifier. child – The child identifier. vertex id
add_child_tree(parent, tree)[source]

Add a tree after the children of the parent vertex. Complexity has to be O(1) if tree == sub_tree() This method copies the tree and renumbers its vertices.

Returns a map between original tree vids and the newly added vids.

Parameters: parent – vertex identifier tree – a rooted tree dict (original tree id -> new id)
children(vtx_id)[source]

returns a vertex iterator

Parameters: vtx_id – The vertex identifier. iter of vertex identifier
children_iter(vtx_id)[source]

returns a vertex iterator

Parameters: vtx_id – The vertex identifier. iter of vertex identifier
clear()[source]

remove all vertices and edges don’t change references to objects

copy()[source]

Deep copy of the tree.

get_root()[source]

Return the tree root.

Returns: vertex identifier
has_vertex(vid)[source]

Test wether a vertex belong to the graph

Parameters: vid (vid) – vertex id to test bool
insert_parent(vtx_id, parent_id=None, **properties)[source]

Insert parent_id between vtx_id and its actual parent. Inherit of the complex of the parent of vtx_id.

Parameters: vtx_id: a vertex identifier parent_id: a vertex identifier
insert_sibling(vtx_id1, vtx_id2=None, **properties)[source]

Insert vtx_id2 before vtx_id1.

Parameters: vtx_id1: a vertex identifier vtx_id2: the vertex to insert
insert_sibling_tree(vid, tree)[source]

Insert a tree before the vid. vid and the root of the tree are siblings. Complexity have to be O(1) if tree comes from the actual tree ( tree= self.sub_tree() )

Parameters: vid – vertex identifier tree – a rooted tree
is_leaf(vtx_id)[source]

Test if vtx_id is a leaf.

Returns: bool
is_valid()[source]

test the validity of the graph

Return type: bool
iteredges()[source]

Iter on the edges of the tree.

nb_children(vtx_id)[source]

returns the number of children

Parameters: vtx_id: The vertex identifier. int
nb_siblings(vtx_id)[source]

returns the number of siblings

Returns: int
nb_vertices()[source]

returns the number of vertices.

Returns: int
parent(vtx_id)[source]

Return the parent of vtx_id.

Parameters: vtx_id: The vertex identifier. vertex identifier
remove_tree(vtx_id)[source]

Remove the sub tree rooted on vtx_id.

Returns: bool
remove_vertex(vid, reparent_child=False)[source]

remove a specified vertex of the graph remove all the edges attached to it

Parameters: vid (vid) – the id of the vertex to remove
replace_parent(vtx_id, new_parent_id, **properties)[source]

Change the parent of vtx_id to new_parent_id. The new parent of vtx_id is new_parent_id.

This function do not change the edge_type between vtx_id and its parent.

Parameters: vtx_id (int): a vertex identifier new_parent_id (int): a vertex identifier None
root

Return the tree root.

Returns: vertex identifier
set_root(vtx_id)[source]

Set the tree root.

Parameters: vtx_id – The vertex identifier.
siblings(vtx_id)[source]

returns an iterator of vtx_id siblings. vtx_id is not include in siblings.

Parameters: vtx_id: The vertex identifier. iter of vertex identifier
siblings_iter(vtx_id)[source]

returns an iterator of vtx_id siblings. vtx_id is not include in siblings.

Parameters: vtx_id: The vertex identifier. iter of vertex identifier
sub_tree(vtx_id, copy=True)[source]

Return the subtree rooted on vtx_id.

The induced subtree of the tree has the vertices in the ancestors of vtx_id.

Parameters: vtx_id: A vertex of the original tree. copy: If True, return a new tree holding the subtree. If False, the subtree is created using the original tree by deleting all vertices not in the subtree. A sub tree of the tree. If copy=True, a new Tree is returned. Else the subtree is created inplace by modifying the original tree.
vertices()[source]
Returns: iter of vertex_id
vertices_iter()[source]
Returns: iter of vertex_id

## openalea.mtg.util module¶

Different utilities such as plot2D, plot3D, and so on…

openalea.mtg.util.mtg_plot(g, scales=1)[source]
openalea.mtg.util.plot2d(g, image_name, scale=None, orientation=90)[source]

Compute an image of the tree via graphviz.

Parameters: Optional parameters: g (int) : an MTG object image_name (str) : output filename e.g. test.png scale (int): represents the MTG’s scale to look at (default max) orientation (int): orientation angle (default 90)
openalea.mtg.util.plot3d(g, scale=None)[source]
Compute a 3d view of the MTG in a simple way:
• sphere for the nodes and thin cylinder for the edges.
openalea.mtg.util.plot_nx(g, *args, **kwds)[source]

## openalea.mtg.version module¶

openalea.mtg.version.major = 2

(int) Version major component.

openalea.mtg.version.minor = 0

(int) Version minor component.

openalea.mtg.version.post = 1

(int) Version post or bugfix component.