hfd_layout

Contents

hfd_layout#

graph_tool.draw.hfd_layout(g, pos=None, vweight=None, eweight=None, rweight=None, K=1, rep_exp=1, att_exp=2, center_pull=0.0001, theta=0.6, exact_thres=500, b=None, group_grav=0.1, group_grav_fac=None, group_grav_offset=0.01, group_rep=0, group_rep_exp=1, group_conf_R=None, group_conf_exp=6, group_spring=1, group_spring_static=False, upper=None, barrier_r=None, barrier_sep=0.2, barrier_exact_thres=100, nmin_dist=None, nmu=100, gmin_dist=None, gmu=10, odist=None, omu=10, opair_dist=None, pmu=10, rank=None, rmin_dist=0, rmu=1, rcm_dist=None, rcmu=1000, rcm_xdist=None, rcmxu=1000, hierarchical=True, grouped=None, spring_G=20, spring_decay=2, center_pull_c=1, center_pull_L='mf', method='gradient', max_iter=None, epsilon=None, patience=3, sweep_args={}, adaptive_cooling=True, cooling_step=0.9, momentum_restart=True, backtrack=True, init_multipliers=True, tol=0.001, update_interval=3, draw_levels=False, return_state=False, verbose=False)[source]#

Obtain a hierarchical force-directed (HFD) layout of the graph.

Parameters:
gGraph

Graph to be laid out.

posVertexPropertyMap (optional, default: None)

Initial positions, as a vector<double> property map, which is updated in place. If not provided, they are chosen at random. They should be distinct, since the repulsion vanishes between coinciding vertices.

vweightVertexPropertyMap (optional, default: None)

Vertex weights, which multiply the repulsion and the central pull, but not the attraction. Vertices with zero weight are ignored, and keep their positions (their edges exert no force). If not provided, all weights are 1.

eweightEdgePropertyMap (optional, default: None)

Edge weights, i.e. the strengths of the attraction along the edges (which are not multiplied by the vertex weights). If not provided, all weights are 1.

rweightVertexPropertyMap (optional, default: None)

Factor of the vertex weights in the repulsion and central pull (e.g. the relative sizes of the groups represented by the vertices of a coarse graph). If not provided, all factors are 1.

Kfloat (optional, default: 1)

Strength of the repulsion, which sets the length scale of the layout.

rep_expfloat (optional, default: 1)

Exponent \(p\) of the repulsion, whose force decays as \(d^{-(p+1)}\) with the distance \(d\) (logarithmic for \(p = 0\)).

att_expfloat (optional, default: 2)

Exponent \(a\) of the attraction along the edges, whose force grows as \(d^{a-1}\) (logarithmic for \(a = 0\)).

center_pullfloat (optional, default: 1e-4)

Strength of the central pull, i.e. the harmonic attraction of every vertex toward the center of mass, which keeps disconnected parts of the layout together.

thetafloat (optional, default: 0.6)

Opening criterion of the Barnes-Hut approximation. Smaller values are more accurate and slower.

exact_thresint (optional, default: 500)

Graphs with fewer vertices are computed exactly, in time \(O(V^2)\), instead of with the Barnes-Hut approximation.

bVertexPropertyMap, numpy.ndarray or list of these (optional, default: None)

Group labels, as a single partition, or a hierarchical one in the format of get_bs() (b[0][v] is the group of vertex v, and b[l][r] the group at level l of group r of level l - 1). The group forces and constraints act at every level.

group_gravfloat or list of floats (optional, default: 0.1)

Strength of the logarithmic attraction between the members of every group, which dominates the repulsion beyond distances of about 1 / group_grav. A list gives one value per level. It is ignored by hfd_layout() with hierarchical == True and grouped == True, where the groups are kept together by springs instead.

group_grav_facnumpy.ndarray or list of numpy.ndarray (optional, default: None)

Factor of the group gravity of every group, indexed by its label, with one array per level.

group_grav_offsetfloat (optional, default: 0.01)

Offset \(c\) of the distance in the group gravity, \(\log(d + c)\), which keeps it finite.

group_repfloat or list of floats (optional, default: 0)

Additional repulsion between vertices of different groups, relative to the general one. A single value is halved at every level above.

group_rep_expfloat (optional, default: 1)

Exponent of the group repulsion, as rep_exp.

group_conf_Rnumpy.ndarray or list of numpy.ndarray (optional, default: None)

Radius of every group, indexed by its label, with one array per level. The members of a group with a positive radius are confined around its center of mass, within about this radius.

group_conf_expfloat (optional, default: 6)

Exponent of the confinement potential. The larger it is, the more sharply the members are kept inside the radius (2 gives a harmonic spring).

group_springfloat or list of floats (optional, default: 1)

If positive, the strength of the confinement of every group is chosen so that the edges leaving the group displace its members by group_conf_R / group_spring on average, and is updated with update_group_springs(). Otherwise, it is chosen so that the repulsion fills the radius.

group_spring_staticbool (optional, default: False)

If True, the strengths of the springs are computed once, from the positions of the groups, and not updated.

upperHFDState (optional, default: None)

State of the level above, whose vertices are the groups of the lowest level of b, with their total weights, and whose edge weights are those of the condensed graph divided by the weights of the endpoints. Its attraction and repulsion act on the centers of mass of the groups, and those of its own upper state on the levels above.

barrier_rVertexPropertyMap (optional, default: None)

Radius of every vertex. Vertices of the same group are kept from overlapping by a barrier.

barrier_sepfloat (optional, default: 0.2)

Range of the barrier, relative to the sum of the radii. It is disabled if zero.

barrier_exact_thresint (optional, default: 100)

The overlapping vertices are found exhaustively in groups up to this size, and with a kd-tree otherwise.

nmin_distfloat or VertexPropertyMap (optional, default: None)

Minimum distance between any two vertices. If given, the minimum distance constraint is enabled.

nmufloat (optional, default: 100)

Penalty of the minimum distance constraint, relative to the force that pushes the vertices together.

gmin_distfloat, list of floats or VertexPropertyMap (optional, default: None)

Minimum distance between vertices of different groups, for every level (a list, or a vector<double> property map, gives one value per level). If given, the group distance constraint is enabled.

gmufloat or list of floats (optional, default: 10)

Penalty of the group distance constraint. It is disabled at the levels where it is zero.

odistfloat or list of floats (optional, default: None)

Minimum distance between the convex hulls of different groups. If given, the overlap constraint is enabled.

omufloat or list of floats (optional, default: 10)

Penalty of the overlap constraint. It is disabled at the levels where it is zero.

opair_distfloat or list of floats (optional, default: None)

Maximum distance between the two members of groups of size two, which keeps other groups from passing between them. If given, the pair constraint is enabled.

pmufloat or list of floats (optional, default: 10)

Penalty of the pair constraint. It is disabled at the levels where it is zero.

rankVertexPropertyMap (optional, default: None)

Vertex ranks, ordered along the \(y\) direction, with higher ranks at smaller \(y\). If given, the rank constraint is enabled.

rmin_distfloat or VertexPropertyMap (optional, default: 0)

Minimum separation along \(y\) of every vertex from all the vertices of the next higher rank, so that the vertices of different ranks are strictly ordered.

rmufloat (optional, default: 1)

Penalty of the rank constraint.

rcm_distfloat (optional, default: None)

Minimum separation along \(y\) of the center of mass of the vertices of every rank from that of the next higher rank. If given (together with rank), this constraint is enabled, independently of the one given by rmin_dist (which can be disabled with rmu=0).

rcmufloat (optional, default: 1000)

Penalty of the constraint given by rcm_dist.

rcm_xdistfloat (optional, default: None)

Minimum separation along \(x\) between the centers of mass of the vertices of every pair of ranks (in any order), which compensates the squeezing of the layout along \(y\) by rcm_dist. If given (together with rank), this constraint is enabled.

rcmxufloat (optional, default: 1000)

Penalty of the constraint given by rcm_xdist.

hierarchicalbool (optional, default: True)

If True, the layout is obtained hierarchically, from the top of the partition b to the bottom (see below). If b is not given, a hierarchical partition is generated.

groupedbool (optional, default: None)

If hierarchical == True, whether the groups are kept together and apart from each other in the final layout. Otherwise, the hierarchy only guides the initial placement. If None, it is True if and only if b is given. If True, the groups are kept together by springs set by spring_G and spring_decay (which replace group_conf_R, group_conf_exp, group_spring and group_spring_static), and group_grav is ignored.

spring_Gfloat or list of floats (optional, default: 20)

Strength of the springs that keep the groups of the lowest level together, relative to the pull of their external edges. Larger values give more compact groups. A list gives one value per level, and spring_decay is then ignored.

spring_decayfloat (optional, default: 2)

Factor by which the strength of the springs decreases at every level above. Smaller values make the groups of the upper levels more compact and separated.

center_pull_cfloat (optional, default: 1)

If not None and grouped == True, the central pull is set relative to the size of the layout, so that a vertex without edges stays within this multiple of the radius of the layout, and center_pull is ignored. Smaller values give more compact layouts.

center_pull_L"mf" or "measured" (optional, default: "mf")

Radius of the layout used for center_pull_c: estimated in the mean field, or measured from the layout of the level above.

method"gradient" or "lbfgs" (optional, default: "gradient")

Minimization method, gradient_sweep() or lbfgs_sweep().

max_iterint (optional, default: None)

Maximum number of sweeps (1000 for "gradient" and 200 for "lbfgs", if None).

epsilonfloat (optional, default: None)

Tolerance for the relative change of the energy between sweeps (1e-6 with adaptive cooling, 1e-5 without it, and 1e-4 for "lbfgs", if None).

patienceint (optional, default: 3)

Number of consecutive sweeps within epsilon for the minimization to be considered converged.

sweep_argsdict (optional, default: {})

Additional parameters passed to every sweep.

adaptive_coolingbool (optional, default: True)

If True, the step size of gradient_sweep() starts proportional to \(\sqrt{V}\), and, if backtrack == False, is adapted to the progress of the energy [hu-multilevel-2005].

cooling_stepfloat (optional, default: 0.9)

Factor by which the step size is reduced when the energy increases, and whose inverse increases it otherwise. With backtrack == True, it only sets the increase.

momentum_restartbool (optional, default: True)

If True, the momentum is reset whenever a sweep increases the energy (which is always done with backtrack == True).

backtrackbool (optional, default: True)

If True, a sweep that increases the energy is undone and repeated with a smaller step.

init_multipliersbool (optional, default: True)

If True, the Lagrange multipliers are initialized from the initial positions with init_multipliers().

tolfloat (optional, default: 1e-3)

Tolerance for the total constraint violation (see update_constraints()).

update_intervalint (optional, default: 3)

Number of sweeps between the updates of the Lagrange multipliers.

draw_levelsbool or dict (optional, default: False)

If True, the graph of every level of the hierarchy is drawn with graph_draw() before and after its layout, colored by the groups of the level above, and sized by the weights it represents. A dict is passed as additional arguments to graph_draw(); an output file name gets the level and stage before its extension (e.g. levels-l2-before.pdf and levels-l2-after.pdf), so that every drawing is kept.

return_statebool (optional, default: False)

If True, the HFDState of the (lowest) layout is also returned. In the hierarchical layout, the labels of its partition are made contiguous (keeping their order).

verbosebool (optional, default: False)

If True, the progress of the minimization is printed.

Returns:
posVertexPropertyMap

Vector-valued vertex property map with the coordinates of the vertices.

stateHFDState

The state of the layout, which can be used to refine it further. Only returned if return_state == True.

Notes

The energy of a HFDState with the given parameters is minimized until its relative change falls below epsilon for patience consecutive sweeps. With constraints, the Lagrange multipliers are updated every update_interval sweeps, and whenever the minimization converges: the layout then stops if the violation is below tol, and otherwise the minimization is restarted, with the penalties doubled (up to a factor \(2^{10}\) in total) if the violation did not decrease enough.

Hierarchical layout. The graph is coarse-grained according to every level of the partition, by merging every group into a vertex that carries the weights it represents. The coarse graphs are laid out from the top down, each one placing the members of every group evenly inside a disk around its position, with the radius of the group in the mean field. The coarse graphs are minimized until the relative change of the energy falls below \(10^{-4}\) (epsilon and patience apply to the original graph).

If grouped == True, the groups of every level are kept apart by the attraction and repulsion of their centers of mass, given by the coarse graphs above, with the repulsion between two groups proportional to their relative sizes; and kept together by springs whose strengths follow from the pull of their external edges (spring_G and spring_decay). In this case, K can be a list with one value for the vertices followed by one for the groups of every level, which sets how strongly they are pushed apart (the central pull of every level, and the radii of the groups whose members are its vertices, follow its value). The central pull of every level is set by center_pull_c. The group gravity (group_grav) is not used in this case.

If no partition is given, one with at most \(\lceil\log_2 V\rceil\) levels is generated by halving the number of groups at every level, with minimize_blockmodel_dl() and ModularityState.

If pos is given, it is used as the initial layout, and only the original vertices are laid out, e.g. to refine an existing layout with different parameters.

Each sweep has complexity \(O(V\log V + E)\).

Parallel implementation.

If enabled during compilation, this algorithm will run in parallel using OpenMP. See the parallel algorithms section for information about how to control several aspects of parallelization.

References

[hu-multilevel-2005]

Yifan Hu, “Efficient, High-Quality Force-Directed Graph Drawing”, Mathematica Journal, vol. 10, Issue 1, pp. 37-71, (2005) http://www.mathematica-journal.com/issue/v10i1/graph_draw.html

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> state = gt.minimize_nested_blockmodel_dl(g, simple_init=True)
>>> bs = state.get_bs()
>>> b = state.project_level(6).get_blocks()
>>> cmap = matplotlib.colormaps["tab20"]
>>> def draw(pos, output):
...     return gt.graph_draw(g, pos=pos, vertex_fill_color=b, vcmap=cmap,
...                          vcnorm=lambda x: np.asarray(x) % cmap.N,
...                          vertex_size=1.5, vertex_pen_width=0,
...                          edge_pen_width=.3,
...                          edge_color=[.2, .2, .2, .06],
...                          output_size=(800, 800), output=output)
>>> pos0 = gt.hfd_layout(g, b=bs)
>>> draw(pos0, "graph-draw-hfd-layout-default.pdf")
<...>

The layout with the default parameters is then used as the starting point of the layouts with other parameters, so that their effect can be compared directly:

>>> for c in [.25, 5]:
...     pos = gt.hfd_layout(g, b=bs, pos=pos0, center_pull_c=c)
...     draw(pos, f"graph-draw-hfd-layout-{c}.pdf")
<...>
>>> for G in [2, 200]:
...     pos = gt.hfd_layout(g, b=bs, pos=pos0, spring_G=G)
...     draw(pos, f"graph-draw-hfd-layout-G-{G}.pdf")
<...>
>>> for f in [1.2, 4]:
...     pos = gt.hfd_layout(g, b=bs, pos=pos0, spring_decay=f)
...     draw(pos, f"graph-draw-hfd-layout-decay-{f}.pdf")
<...>
>>> for k in [.1, 10]:
...     pos = gt.hfd_layout(g, b=bs, pos=pos0, K=[1] + [k] * len(bs))
...     draw(pos, f"graph-draw-hfd-layout-K-{k}.pdf")
<...>
../_images/graph-draw-hfd-layout-0.25.png ../_images/graph-draw-hfd-layout-default.png ../_images/graph-draw-hfd-layout-5.png ../_images/graph-draw-hfd-layout-G-2.png ../_images/graph-draw-hfd-layout-default.png ../_images/graph-draw-hfd-layout-G-200.png ../_images/graph-draw-hfd-layout-decay-1.2.png ../_images/graph-draw-hfd-layout-default.png ../_images/graph-draw-hfd-layout-decay-4.png ../_images/graph-draw-hfd-layout-K-0.1.png ../_images/graph-draw-hfd-layout-default.png ../_images/graph-draw-hfd-layout-K-10.png

Hierarchical layout of the PGP web of trust, grouped by the nested stochastic block model, and colored by its groups at the sixth level. The middle column has the default parameters, and the others a smaller (left) and larger (right) value of one parameter, from top to bottom: center_pull_c (\(0.25\) and \(5\)), which compresses or loosens the layout; spring_G (\(2\) and \(200\)), which makes the groups diffuse or compact; spring_decay (\(1.2\) and \(4\)), which makes the upper levels compact and separated, or blended; and K of the groups (\(0.1\) and \(10\)), which lets them crowd or pushes them apart.