HFDState#
- class graph_tool.draw.HFDState(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, nlambda=None, glambda=0, rclambda=0, rcxlambda=0, olambda=None, rlambda=None, plambda=None, group_spring_strength=None, nmu_force=None)[source]#
Bases:
PickleStateState of a hierarchical force-directed (HFD) layout of a graph.
- Parameters:
- g
Graph Graph to be laid out.
- pos
VertexPropertyMap(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.- vweight
VertexPropertyMap(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.- eweight
EdgePropertyMap(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.- rweight
VertexPropertyMap(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.
- b
VertexPropertyMap,numpy.ndarrayor 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 vertexv, andb[l][r]the group at levellof grouprof levell - 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 byhfd_layout()withhierarchical == Trueandgrouped == True, where the groups are kept together by springs instead.- group_grav_fac
numpy.ndarrayor list ofnumpy.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_R
numpy.ndarrayor list ofnumpy.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 (
2gives 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_springon average, and is updated withupdate_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.- upper
HFDState(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_r
VertexPropertyMap(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.
- rank
VertexPropertyMap(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 byrmin_dist(which can be disabled withrmu=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 withrank), this constraint is enabled.- rcmxufloat (optional, default:
1000) Penalty of the constraint given by
rcm_xdist.- nlambda
VertexPropertyMap(optional, default:None) Lagrange multipliers of the minimum distance constraint, one per vertex, updated in place.
- glambdafloat or list of floats (optional, default:
0) Lagrange multipliers of the group distance constraint, one per level.
- rclambdafloat or list of floats (optional, default:
0) Lagrange multipliers of the constraint given by
rcm_dist, one per pair of adjacent ranks.- rcxlambda
0or list of tuples (optional, default:0) Nonzero Lagrange multipliers of the constraint given by
rcm_xdist, one per pair of ranks, as a list of(a, b, lambda)with the indicesa < bof the ranks in increasing order.- olambdalist of
numpy.ndarray(optional, default:None) Lagrange multipliers of the overlap constraint, one per group and level, indexed by the group labels (which are copied, and updated in
HFDState.olambda).- rlambda
VertexPropertyMap(optional, default:None) Lagrange multipliers of the rank constraint, one per vertex, updated in place.
- plambda
VertexPropertyMap(optional, default:None) Lagrange multipliers of the distance of the groups of size two, one per level, stored at the member with the smallest index, updated in place.
- group_spring_strengthlist of
numpy.ndarray(optional, default:None) Strengths of the springs, one array per level indexed by the group labels, used instead of computing them (e.g. to restore the static springs of a copied state).
- nmu_force
numpy.ndarray(optional, default:None) Magnitudes of the forces on the vertices that set the penalties of their minimum distances (see
nmu), as computed byinit_multipliers().
- g
Notes
The layout minimizes the energy
\[U(\boldsymbol x) = \sum_{(u,v)\in E}w_{uv}A_a(d_{uv}) + K\sum_{u\neq v}m_um_v R_p(d_{uv}) + g\sum_u m_u|\boldsymbol x_u - \boldsymbol x_{\text{cm}}|^2 + K\sum_l g_l\sum_{u\neq v}\delta_{b^l_u,b^l_v}f^l_{b^l_u}m_um_v\log(d_{uv} + c) + K\sum_l r_l\sum_{u\neq v}(1-\delta_{b^l_u,b^l_v})m_um_v R_q(d_{uv}),\]with the distances \(d_{uv}\), the attraction \(A_a(d) = (2/a)d^a\) and repulsion \(R_p(d) = d^{-p}/p\) (whose forces are \(2d^{a-1}\) and \(d^{-(p+1)}\)), the edge and vertex weights \(w_{uv}\) and \(w_u\), the masses \(m_u = w_u\rho_u\) with \(\rho_u\) given by
rweight, the central pull \(g\) (center_pull), the groups \(b^l_u\), the group gravity \(g_l f^l_r\) (group_gravandgroup_grav_fac) and the group repulsion \(r_l\) (group_rep), with the exponent \(q\) given bygroup_rep_exp. The repulsive terms are computed with the Barnes-Hut approximation.The energy may have additional terms:
the attraction and repulsion of the vertices of the
upperstate, placed at the centers of mass of the groups, which move the groups rigidly; in this case,gradient_sweep()also moves every group as a whole;the confinement of the members of every group around its center of mass, \(\gamma_r\sum_u w_u(|\boldsymbol x_u - \boldsymbol x_r|/R_r)^\alpha\), with \(R_r\) given by
group_conf_Rand the strength \(\gamma_r\) set bygroup_spring; with springs, a packing term keeps also the groups with few or no edges together;a barrier between the vertices with radii (
barrier_r), which is not supported bylbfgs_sweep().
The constraints (minimum distances, group overlap, ranks) are imposed with the augmented Lagrangian method: the energy is minimized with
gradient_sweep()orlbfgs_sweep()for fixed Lagrange multipliers, which are then updated withupdate_constraints(), until the violation is small enough. The minimum distance has one multiplier per vertex, so that every vertex is pushed away from its own neighbors as strongly as needed. The functionhfd_layout()carries out this whole procedure.Each evaluation of the energy or its gradient has complexity \(O(V\log V + E)\), or \(O(V^2 + E)\) if \(V <\)
exact_thres.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.
Examples
>>> g = gt.collection.data["football"] >>> b = g.vp.value >>> R = np.sqrt(np.bincount(b.a)) / 2 # radii of the conferences >>> state = gt.HFDState(g, b=b, group_conf_R=R, group_conf_exp=2, ... group_spring=10) >>> for i in range(20): ... ret = state.lbfgs_sweep(max_iter=100) ... R = state.update_constraints() ... state.update_group_springs() >>> gt.graph_draw(g, pos=state.pos, vertex_fill_color=b, ... output="graph-draw-hfd.pdf") <...>
Force-directed layout of the football network, with the vertices of every conference kept together by a harmonic spring towards its center of mass.#
Methods
Return the total violation of all active constraints, without updating the Lagrange multipliers.
copy(**kwargs)Copies the state.
energy()Return the value of the augmented Lagrangian, i.e. the energy plus the constraint penalties for the current Lagrange multipliers.
Return the Lagrange multipliers of the group distance constraint, as a list with one value per hierarchy level.
Return the Lagrange multipliers of the minimum distance constraint, as a vertex property map with one value per vertex.
gradient_sweep([niter, step, mu, cap_grad])Perform
nitersteps of gradient descent with Nesterov momentum, for fixed Lagrange multipliers.Return order parameters that measure how well the groups are separated at every level of the partition, obtained from the Delaunay triangulation of the positions.
init_multipliers([margin])Initialize the Lagrange multipliers of all active constraints with estimates obtained from the current positions.
lbfgs_sweep([max_iter, step, epsilon, ...])Minimize the augmented Lagrangian with the L-BFGS algorithm, for fixed Lagrange multipliers.
Set the velocities used by the momentum of
gradient_sweep()to zero.Multiply the penalty parameters of all the constraints (
nmu,gmu,omu,pmu,rmu,rcmuandrcmxu) byc.set_glambda(glambda)Set the Lagrange multipliers of the group distance constraint, given as a single value for all hierarchy levels, or a list with one value per level.
set_nlambda(l)Set the Lagrange multipliers of the minimum distance constraint, given as a vertex property map, or a single value for all vertices.
Update the Lagrange multipliers of all active constraints.
Update the strengths of the confinement of the groups from the current pull of the edges that leave them, if
group_spring > 0(seeHFDState).visit_barnes_hut(x, y)Return the cells used in the Barnes-Hut approximation of the repulsion felt at point \((x, y)\).
- constraint_violation()[source]#
Return the total violation of all active constraints, without updating the Lagrange multipliers.
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.
- Returns:
- Rfloat
Total constraint violation, which is zero if all constraints are satisfied.
- copy(**kwargs)[source]#
Copies the state. The parameters override the state properties, and have the same meaning as in the constructor.
The Lagrange multipliers, the strengths of the springs and the forces that set the penalties of the minimum distances are copied as well, unless the parameters they depend on are overridden, in which case they are reset (as are the per-group parameters
group_conf_Randgroup_grav_fac, ifbis overridden). The partitionbcan only be replaced by one with the same number of levels, since the per-level parameters are kept.
- energy()[source]#
Return the value of the augmented Lagrangian, i.e. the energy plus the constraint penalties for the current Lagrange multipliers.
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.
- get_glambda()[source]#
Return the Lagrange multipliers of the group distance constraint, as a list with one value per hierarchy level.
- get_nlambda()[source]#
Return the Lagrange multipliers of the minimum distance constraint, as a vertex property map with one value per vertex.
- gradient_sweep(niter=10, step=0.01, mu=0.9, cap_grad=0.1)[source]#
Perform
nitersteps of gradient descent with Nesterov momentum, for fixed Lagrange multipliers.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.
- Parameters:
- niterint (optional, default:
10) Number of steps.
- stepfloat (optional, default:
0.01) Step size.
- mufloat (optional, default:
0.9) Momentum parameter, in the interval \([0, 1)\). If
mu == 0, plain gradient descent is used.- cap_gradfloat (optional, default:
0.1) If positive, the gradient contribution to the displacement of each vertex in a single step is capped at this value.
- niterint (optional, default:
- group_order_params()[source]#
Return order parameters that measure how well the groups are separated at every level of the partition, obtained from the Delaunay triangulation of the positions.
- Returns:
- kappa
numpy.ndarray Contiguity of the groups at every level: the fraction of the weight of each group that belongs to its largest biconnected component, in the graph of the Delaunay edges between members of the same group, averaged over the groups weighted by their total weight. It is
1if all groups are contiguous.- S
numpy.ndarray Fraction of the area between groups at every level, i.e. of the Delaunay triangles with corners in different groups, relative to all the triangles with corners in the same group of the level above (or all triangles, at the top level).
- G
numpy.ndarray Mean area of the triangles between groups at every level, relative to the mean area of the triangles within groups.
- kappa_groupslist of
numpy.ndarray Contiguity of every group, at every level, indexed by the group labels as they appear in
b(nanfor unused labels).
- kappa
Notes
Since a Delaunay edge exists only if no other vertex lies within some circle through its endpoints, members of a group that are separated by other groups are not connected, whereas those separated only by empty space are. The edges and triangles on the convex hull of the layout are ignored, since they can join distant vertices along its outer boundary.
This has complexity \(O(V\log V)\), and the levels are computed in parallel.
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.
- init_multipliers(margin=inf)[source]#
Initialize the Lagrange multipliers of all active constraints with estimates obtained from the current positions.
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.
- Parameters:
- marginfloat (optional, default:
numpy.inf) Constraints that are satisfied by a margin larger than this value get a multiplier of zero. By default, all constraints get an estimate.
- marginfloat (optional, default:
Notes
Writing each constraint as \(c(\boldsymbol x) \le 0\), its multiplier is estimated as
\[\lambda = \max\left(0, -\frac{\nabla U\cdot\nabla c}{|\nabla c|^2}\right),\]where \(U\) is the energy without the constraints, so that the force of the constraint cancels the other forces along its gradient. Otherwise, the constraints exert no force until they are violated. The forces on the vertices obtained here also set the penalties of their minimum distances (see
nmu).
- lbfgs_sweep(max_iter=10, step=1.0, epsilon=0.001, hist_size=10, line_search='wolfe', c1=0.0001, c2=0.9, rho=None, ls_max_iter=20, ftol=0, fatol=0, max_time=None)[source]#
Minimize the augmented Lagrangian with the L-BFGS algorithm, for fixed Lagrange multipliers.
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.
- Parameters:
- max_iterint (optional, default:
10) Maximum number of iterations.
- stepfloat (optional, default:
1.) Initial step size of the line search.
- epsilonfloat (optional, default:
1e-3) The minimization stops when the norm of the gradient falls below this value.
- hist_sizeint (optional, default:
10) Number of past updates used to approximate the inverse Hessian.
- line_search
"wolfe"or"armijo"(optional, default:"wolfe") Line search used to choose the step size: one that satisfies the strong Wolfe conditions, or Armijo backtracking.
- c1float (optional, default:
1e-4) Sufficient decrease parameter of the line search (Armijo condition).
- c2float (optional, default:
0.9) Curvature parameter of the strong Wolfe line search, with
0 < c1 < c2 < 1. It is ignored by the Armijo line search.- rhofloat (optional, default:
None) For the strong Wolfe line search, the factor by which the step grows while bracketing an acceptable step (default:
2). For the Armijo line search, the factor by which it shrinks while backtracking (default:0.5).- ls_max_iterint (optional, default:
20) Maximum number of iterations of each line search.
- ftolfloat (optional, default:
0) The minimization stops when the change of the objective between iterations falls below this value, relative to the maximum of
1and its absolute value. It is disabled ifftol == 0.- fatolfloat (optional, default:
0) The minimization stops when the absolute change of the objective between iterations falls below this value. It is disabled if
fatol == 0.- max_timefloat (optional, default:
None) If given, the minimization stops after this many seconds.
- max_iterint (optional, default:
- Returns:
- niterint
Number of iterations performed.
- Efloat
Final value of the augmented Lagrangian.
- convergedbool
Trueif one of the convergence criteria (epsilon,ftolorfatol) was met before the minimization was stopped.
- reset_momentum()[source]#
Set the velocities used by the momentum of
gradient_sweep()to zero.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.
- scale_penalties(c)[source]#
Multiply the penalty parameters of all the constraints (
nmu,gmu,omu,pmu,rmu,rcmuandrcmxu) byc.
- set_glambda(glambda)[source]#
Set the Lagrange multipliers of the group distance constraint, given as a single value for all hierarchy levels, or a list with one value per level.
- set_nlambda(l)[source]#
Set the Lagrange multipliers of the minimum distance constraint, given as a vertex property map, or a single value for all vertices.
- update_constraints()[source]#
Update the Lagrange multipliers of all active constraints.
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.
- Returns:
- Rfloat
Total constraint violation, which is zero if all constraints are satisfied. The violations of the minimum and group distances, \(\sum_v V_v\), are relative to \(\sum_v c_v^2\), i.e. the squared distance times the number of vertices, while those of the ranks, overlaps and pairs are lengths, summed over the constraints.
- update_group_springs()[source]#
Update the strengths of the confinement of the groups from the current pull of the edges that leave them, if
group_spring > 0(seeHFDState).
- visit_barnes_hut(x, y)[source]#
Return the cells used in the Barnes-Hut approximation of the repulsion felt at point \((x, y)\).
- Parameters:
- xfloat
\(x\) coordinate of the point.
- yfloat
\(y\) coordinate of the point.
- Returns:
- cellslist of tuples
List of
((x, y), w)tuples, with the center of mass and total vertex weight of each cell.