...
 
Commits (14)
......@@ -8,11 +8,11 @@ as we demonstrate in the following.
.. note::
Since ``graph-tool`` uses `cairo <https://cairographics.org>`_ for
drawing, it is necessary to one of matplotlib's cairo-based backend,
otherwise integration is not possible. Currently, two backends can be
chosen: ``cairo`` or ``GTK3Cairo``. The latter should be chosen for
interactive GUI-based figures. The backend can be changed by calling
:func:`matplotlib.pyplot.switch_backend`:
drawing, it is necessary to use one of matplotlib's cairo-based
backends, otherwise integration is not possible. Currently, two
backends can be chosen: ``cairo`` or ``GTK3Cairo``. The latter should
be chosen for interactive GUI-based figures. The backend can be
changed by calling :func:`matplotlib.pyplot.switch_backend`:
.. code::
......
......@@ -129,17 +129,17 @@ public:
for (auto e : edges_range(g))
beta[e] = std::log1p(-_beta[e]);
_beta = beta;
}
for (auto v : vertices_range(g))
{
for (auto e : in_or_out_edges_range(v, g))
for (auto v : vertices_range(g))
{
auto w = (source(e, g) != v) ? source(e, g) : target(e, g);
if (_s[w] == State::I)
_m[v] += get_p(e);
for (auto e : in_or_out_edges_range(v, g))
{
auto w = (source(e, g) != v) ? source(e, g) : target(e, g);
if (_s[w] == State::I)
_m[v] += get_p(e);
}
_m_temp[v] = _m[v];
}
_m_temp[v] = _m[v];
}
}
};
......@@ -182,6 +182,9 @@ public:
}
else
{
if constexpr (!constant_beta)
return;
if constexpr (sync)
{
for (auto e : out_edges_range(v, g))
......@@ -233,13 +236,26 @@ public:
return 1;
}
auto m = _m[v];
double prob = 0;
if constexpr (!weighted)
prob = _prob[m];
if constexpr (!weighted || constant_beta)
{
auto m = _m[v];
if constexpr (!weighted)
prob = _prob[m];
else
prob = 1 - std::exp(m);
}
else
prob = 1 - std::exp(m);
{
for (auto e : in_or_out_edges_range(v, g))
{
auto w = source(e, g);
if (_s[w] == State::I)
prob += std::log1p(-_beta[e]);
}
prob = 1 - std::exp(prob);
}
std::bernoulli_distribution minfect(prob);
if (prob > 0 && minfect(rng))
......
......@@ -59,11 +59,10 @@ namespace mpl
// run-time bridge than the simpler mpl::for_each().
struct stop_iteration: public std::exception {};
// this is a functor wrapper that will perform an any_cast<> in each in an array
// of arguments according to the called types. If the cast is successful, the
// function will be called with those types, and stop_iteration will be thrown.
// function will be called with those types, and true will be returned.
template <class Action, std::size_t N>
struct all_any_cast
{
......@@ -72,45 +71,41 @@ struct all_any_cast
template <class... Ts>
[[gnu::always_inline]]
void operator()(Ts*... vs) const
bool operator()(Ts*... vs) const
{
dispatch(std::make_index_sequence<sizeof...(Ts)>(), vs...);
return dispatch(std::make_index_sequence<sizeof...(Ts)>(), vs...);
}
struct fail_cast {};
template <class T>
T& try_any_cast(boost::any& a) const
T* try_any_cast(boost::any& a) const
{
try
{
return any_cast<T&>(a);
}
catch (bad_any_cast&)
{
try
{
return any_cast<std::reference_wrapper<T>>(a);
}
catch (bad_any_cast&)
{
throw fail_cast();
}
}
T* t = any_cast<T>(&a);
if (t != nullptr)
return t;
std::reference_wrapper<T>* tr = any_cast<std::reference_wrapper<T>>(&a);
if (tr != nullptr)
return &(tr->get());
return nullptr;
}
template <std::size_t... Idx, class... Ts>
[[gnu::always_inline]]
void dispatch(std::index_sequence<Idx...>, Ts*...) const
bool dispatch(std::index_sequence<Idx...>, Ts*...) const
{
try
static_assert(sizeof...(Idx) == N,
"all_any_cast: wrong number of arguments");
std::tuple<std::add_pointer_t<Ts>...> args;
if (((std::get<Idx>(args) = try_any_cast<Ts>(*_args[Idx])) && ...))
{
static_assert(sizeof...(Idx) == N,
"all_any_cast: wrong number of arguments");
_a(try_any_cast<Ts>(*_args[Idx])...);
throw stop_iteration();
// successful set of casts. Dereference and call action.
std::apply([this](auto*... arg){ _a(*arg...); }, args);
return true;
}
catch (fail_cast) {}
return false;
}
Action _a;
......@@ -124,10 +119,10 @@ struct for_each_variadic;
template <class F, class... Ts>
struct for_each_variadic<F,std::tuple<Ts...>>
{
void operator()(F f)
bool operator()(F f)
{
auto call = [&](auto&& arg){f(std::forward<decltype(arg)>(arg)); return 0;};
(void) std::initializer_list<int> {call(typename std::add_pointer<Ts>::type())...};
auto call = [&](auto&& arg) -> bool {return f(std::forward<decltype(arg)>(arg));};
return (call(typename std::add_pointer<Ts>::type()) || ...);
}
};
......@@ -160,9 +155,9 @@ struct inner_loop<Action, std::tuple<Ts...>>
template <class T>
[[gnu::always_inline]]
void operator()(T*) const
{ _a(typename std::add_pointer<Ts>::type()...,
typename std::add_pointer<T>::type()); } // innermost loop
bool operator()(T*) const
{ return _a(typename std::add_pointer<Ts>::type()...,
typename std::add_pointer<T>::type()); } // innermost loop
Action _a;
};
......@@ -173,11 +168,11 @@ struct inner_loop<Action, std::tuple<Ts...>, TR1, TRS...>
template <class T>
[[gnu::always_inline]]
void operator()(T*) const
bool operator()(T*) const
{
typedef inner_loop<Action, std::tuple<Ts..., T>, TRS...> inner_loop_t;
typedef typename to_tuple<TR1>::type tr_tuple;
for_each_variadic<inner_loop_t, tr_tuple>()(inner_loop_t(_a));
return for_each_variadic<inner_loop_t, tr_tuple>()(inner_loop_t(_a));
}
Action _a;
};
......@@ -189,30 +184,22 @@ bool nested_for_each(Action a, Args&&... args)
{
std::array<any*, sizeof...(args)> as{{&args...}};
auto b = all_any_cast<Action, sizeof...(args)>(a, as);
try
{
typedef decltype(b) action_t;
typedef typename to_tuple<TR1>::type tr_tuple;
typedef inner_loop<action_t, std::tuple<>, TRS...> inner_loop_t;
for_each_variadic<inner_loop_t, tr_tuple>()(inner_loop_t(b));
return false;
}
catch (stop_iteration&)
{
return true;
}
typedef decltype(b) action_t;
typedef typename to_tuple<TR1>::type tr_tuple;
typedef inner_loop<action_t, std::tuple<>, TRS...> inner_loop_t;
return for_each_variadic<inner_loop_t, tr_tuple>()(inner_loop_t(b));
}
template <class TR1, class... TRS, class Action>
void nested_for_each(Action a)
{
try
{
typedef typename to_tuple<TR1>::type tr_tuple;
typedef inner_loop<Action, std::tuple<>, TRS...> inner_loop_t;
for_each_variadic<inner_loop_t, tr_tuple>()(inner_loop_t(a));
}
catch (stop_iteration&) {}
typedef typename to_tuple<TR1>::type tr_tuple;
// wrap action into a bool-returning function
auto ab = [=](auto*... args) -> bool { a(args...); return false; };
typedef inner_loop<decltype(ab), std::tuple<>, TRS...> inner_loop_t;
for_each_variadic<inner_loop_t, tr_tuple>()(inner_loop_t(ab));
}
......
......@@ -28,11 +28,11 @@ namespace graph_tool
using namespace boost;
template <class Graph, class Partition, class Weight, class Mate>
void maximum_bipartite_weighted_perfect_matching(Graph& g, Partition partition,
Weight weight, Mate mate)
void maximum_bipartite_weighted_perfect_matching(Graph& g, Partition&& partition,
Weight&& weight, Mate&& mate)
{
typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
typedef typename property_traits<Weight>::value_type weight_t;
typedef typename property_traits<std::remove_reference_t<Weight>>::value_type weight_t;
adj_list<> G;
G.set_keep_epos(true);
......@@ -258,11 +258,11 @@ void maximum_bipartite_weighted_perfect_matching(Graph& g, Partition partition,
template <class Graph, class Partition, class Weight, class Mate>
void maximum_bipartite_weighted_imperfect_matching(Graph& g,
Partition partition,
Weight weight, Mate mate)
Partition&& partition,
Weight&& weight, Mate&& mate)
{
typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
typedef typename property_traits<Weight>::value_type oweight_t;
typedef typename property_traits<std::remove_reference_t<Weight>>::value_type oweight_t;
typedef typename std::conditional<std::is_integral_v<oweight_t>,
std::make_signed_t<std::conditional_t
<std::is_integral_v<oweight_t>,
......@@ -272,7 +272,7 @@ void maximum_bipartite_weighted_imperfect_matching(Graph& g,
adj_list<> u_base;
undirected_adaptor<adj_list<>> u(u_base);
typedef typename property_traits<Partition>::value_type pval_t;
typedef typename property_traits<std::remove_reference_t<Partition>>::value_type pval_t;
typename vprop_map_t<pval_t>::type u_partition;
typename eprop_map_t<weight_t>::type u_weight;
typename vprop_map_t<vertex_t>::type u_mate;
......@@ -346,7 +346,9 @@ void maximum_bipartite_weighted_imperfect_matching(Graph& g,
u_weight[e.first] = -4 * ((max_weight + 1) * T.size());
}
maximum_bipartite_weighted_perfect_matching(u, u_partition, u_weight, u_mate);
maximum_bipartite_weighted_perfect_matching(u, u_partition.get_unchecked(),
u_weight.get_unchecked(),
u_mate.get_unchecked(num_vertices(u)));
for (auto v : vertices_range(g))
{
......@@ -362,16 +364,16 @@ void maximum_bipartite_weighted_imperfect_matching(Graph& g,
template <class Graph, class Partition, class Weight, class Mate>
void maximum_bipartite_weighted_matching(Graph& g,
Partition partition,
Weight weight, Mate mate)
Partition&& partition,
Weight&& weight, Mate&& mate)
{
typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
typedef typename property_traits<Weight>::value_type weight_t;
typedef typename property_traits<std::remove_reference_t<Weight>>::value_type weight_t;
adj_list<> u_base;
undirected_adaptor<adj_list<>> u(u_base);
typedef typename property_traits<Partition>::value_type pval_t;
typedef typename property_traits<std::remove_reference_t<Partition>>::value_type pval_t;
typename vprop_map_t<pval_t>::type u_partition;
typename eprop_map_t<weight_t>::type u_weight;
typename vprop_map_t<vertex_t>::type u_mate;
......@@ -421,7 +423,10 @@ void maximum_bipartite_weighted_matching(Graph& g,
u_weight[e.first] = 0;
}
maximum_bipartite_weighted_imperfect_matching(u, u_partition, u_weight, u_mate);
maximum_bipartite_weighted_imperfect_matching(u,
u_partition.get_unchecked(),
u_weight.get_unchecked(),
u_mate.get_unchecked(num_vertices(u)));
for (auto v : vertices_range(g))
{
......
This diff is collapsed.
......@@ -22,7 +22,6 @@
Utility module which includes all the sub-modules in graph_tool
"""
from __future__ import division, absolute_import, print_function
import warnings
from graph_tool import *
......
......@@ -44,14 +44,11 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_centrality")
from .. import _prop, ungroup_vector_property, Vector_size_t
from .. topology import shortest_distance
import sys
import numpy
import numpy.linalg
......@@ -514,8 +511,6 @@ def central_point_dominance(g, betweenness):
Examples
--------
.. doctest:: central_point_dominance
>>> g = gt.collection.data["polblogs"]
>>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
>>> vp, ep = gt.betweenness(g)
......
......@@ -41,8 +41,6 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_clustering as _gt")
......@@ -54,7 +52,6 @@ from .. stats import vertex_hist
from collections import defaultdict
from numpy import *
from numpy import random
import sys
__all__ = ["local_clustering", "global_clustering", "extended_clustering",
"motifs", "motif_significance"]
......
......@@ -264,11 +264,6 @@ Contents
"""
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
import os.path
import textwrap
from .. import load_graph
......
......@@ -18,28 +18,10 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
import os.path
import tempfile
if sys.version_info < (3,):
from urllib2 import urlopen, URLError
import shutil
class TemporaryDirectory(object):
def __init__(self, suffix="", prefix="", dir=None):
self.name = tempfile.mkdtemp(suffix, prefix, dir)
def __enter__(self):
return self.name
def __exit__(self, exc, value, tb):
shutil.rmtree(self.name)
else:
from urllib.request import urlopen, URLError
from tempfile import TemporaryDirectory
from urllib.request import urlopen, URLError
from tempfile import TemporaryDirectory
import tarfile
import warnings
import numpy
......
......@@ -39,8 +39,6 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_correlations")
......
......@@ -21,11 +21,8 @@
Some useful decorators
"""
from __future__ import division, absolute_import, print_function
import inspect
import functools
import sys
import types
################################################################################
......@@ -33,48 +30,7 @@ import types
# Some useful function decorators which will be used
################################################################################
# exec statement in python 2.7 and exec() function in 3.2 are mutually exclusive
if sys.hexversion > 0x03000000:
def exec_function(source, filename, global_map):
exec(compile(source, filename, "exec"), global_map)
else:
eval(compile("""\
def exec_function(source, filename, global_map):
exec compile(source, filename, "exec") in global_map
""","<exec_function>", "exec"))
if sys.hexversion > 0x03000000:
_wraps = functools.wraps
else:
def _wraps(func):
"""This decorator works like the functools.wraps meta-decorator, but
also preserves the function's argument signature. This uses eval, and is
thus a bit of a hack, but there no better way I know of to do this."""
def decorate(f):
argspec = inspect.getargspec(func)
___wrap_defaults = defaults = argspec[-1]
if defaults is not None:
def_string = ["___wrap_defaults[%d]" % d for
d in range(len(defaults))]
def_names = argspec[0][-len(defaults):]
else:
def_string = None
def_names = None
args_call = inspect.formatargspec(argspec[0], defaults=def_names)
argspec = inspect.formatargspec(argspec[0], defaults=def_string)
argspec = argspec.lstrip("(").rstrip(")")
wf = "def %s(%s):\n return f%s\n" % \
(func.__name__, argspec, args_call)
if def_string is not None:
for d in def_string:
wf = wf.replace("'%s'" % d, "%s" % d)
for d in def_names:
wf = wf.replace("'%s'" % d, "%s" % d)
exec_function(wf, __file__, locals())
return functools.wraps(func)(locals()[func.__name__])
return decorate
_wraps = functools.wraps
def _attrs(**kwds):
"""Decorator which adds arbitrary attributes to methods"""
......@@ -93,7 +49,7 @@ def _limit_args(allowed_vals):
def decorate(func):
@_wraps(func)
def wrap(*args, **kwargs):
arg_names = inspect.getargspec(func)[0]
arg_names = inspect.getfullargspec(func)[0]
arguments = list(zip(arg_names, args))
arguments += [(k, kwargs[k]) for k in list(kwargs.keys())]
for a in arguments:
......
......@@ -18,8 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
import os.path
......
......@@ -66,8 +66,6 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
from .. import Graph, GraphView, _check_prop_vector, _check_prop_scalar, \
group_vector_property, ungroup_vector_property, infect_vertex_property, \
_prop, _get_rng
......@@ -78,7 +76,6 @@ from .. stats import label_parallel_edges
from .. generation import predecessor_tree, condensation_graph
import numpy.random
from numpy import sqrt
import sys
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_layout")
......
......@@ -18,13 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
else:
unicode = str
import os
import warnings
import numpy
......@@ -237,7 +230,7 @@ def shape_from_prop(shape, enum):
prop.fa %= rg[1] - rg[0] + 1
prop.fa += rg[0]
return prop
if isinstance(shape, (str, unicode)):
if isinstance(shape, str):
return int(getattr(enum, shape))
else:
return shape
......@@ -301,7 +294,7 @@ def surface_from_prop(surface):
surface.value_type())
return prop
if isinstance(surface, (str, unicode)):
if isinstance(surface, str):
return gen_surface(surface)
elif isinstance(surface, cairo.Surface) or surface is None:
return surface
......@@ -409,7 +402,7 @@ def _convert(attr, val, cmap, pmap_default=False, g=None, k=None):
new_val = val
elif isinstance(val, (tuple, np.ndarray)):
new_val = list(val)
elif isinstance(val, (str, unicode)):
elif isinstance(val, str):
new_val = list(color_converter.to_rgba(val))
elif isinstance(val, PropertyMap):
if val.value_type() in ["vector<double>", "vector<long double>"]:
......@@ -708,7 +701,7 @@ def color_contrast(color):
def auto_colors(g, bg, pos, back):
if not isinstance(bg, PropertyMap):
if isinstance(bg, (str, unicode)):
if isinstance(bg, str):
bg = color_converter.to_rgba(bg)
bg = g.new_vertex_property("vector<double>", val=bg)
if not isinstance(pos, PropertyMap):
......@@ -1143,10 +1136,10 @@ def graph_draw(g, pos=None, vprops=None, eprops=None, vorder=None, eorder=None,
x, y, zoom = fit_to_view_ink(g, pos, output_size, vprops,
eprops, adjust_aspect, pad=pad)
else:
x, y, zoom = x, y, 1
x, y, zoom = 0, 0, 1
if isinstance(output, (str, unicode)):
if isinstance(output, str):
out, auto_fmt = open_file(output, mode="wb")
else:
out = output
......
......@@ -18,13 +18,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
else:
unicode = str
import os
import os.path
import time
......@@ -32,7 +26,7 @@ import warnings
import ctypes
import ctypes.util
import tempfile
from .. import PropertyMap, group_vector_property, ungroup_vector_property, _c_str
from .. import PropertyMap, group_vector_property, ungroup_vector_property
import numpy
import numpy.random
import copy
......@@ -441,12 +435,12 @@ def graphviz_draw(g, pos=None, size=(15, 15), pin=False, layout=None,
aset(n, "style", "filled")
aset(n, "color", "#2e3436")
# apply color
if isinstance(vcolor, (str, unicode)):
aset(n, "fillcolor", _c_str(vcolor))
if isinstance(vcolor, str):
aset(n, "fillcolor", vcolor)
else:
color = vcolor[v]
if isinstance(color, (str, unicode)):
aset(n, "fillcolor", _c_str(color))
if isinstance(color, str):
aset(n, "fillcolor", color)
else:
color = tuple([int(c * 255.0) for c in vcmap(vnorm(color))])
aset(n, "fillcolor", "#%.2x%.2x%.2x%.2x" % color)
......@@ -492,12 +486,12 @@ def graphviz_draw(g, pos=None, size=(15, 15), pin=False, layout=None,
aset(ge, "dir", "none")
# apply color
if isinstance(ecolor, (str, unicode)):
aset(ge, "color", _c_str(ecolor))
if isinstance(ecolor, str):
aset(ge, "color", ecolor)
else:
color = ecolor[e]
if isinstance(color, (str, unicode)):
aset(ge, "color", _c_str(color))
if isinstance(color, str):
aset(ge, "color", color)
else:
color = tuple([int(c * 255.0) for c in ecmap(enorm(color))])
aset(ge, "color", "#%.2x%.2x%.2x%.2x" % color)
......
......@@ -18,8 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import numpy
from .. import GraphView, PropertyMap, VertexPropertyMap, \
......
......@@ -67,8 +67,6 @@ Contents
"""
from __future__ import division, absolute_import, print_function
from .. import _degree, _prop, Graph, GraphView, _get_rng, PropertyMap, \
EdgePropertyMap, VertexPropertyMap, _check_prop_scalar
from .. stats import label_self_loops
......@@ -164,8 +162,8 @@ class EpidemicStateBase(DiscreteStateBase):
if weighted:
_check_prop_scalar(beta, "beta")
if beta.value_type() != "double":
if constant_beta:
raise ValueError("if constant_beta == True, the type of beta must be double")
if not constant_beta:
raise ValueError("if constant_beta == False, the type of beta must be double")
beta = beta.copy("double")
params["beta"] = beta
......@@ -219,7 +217,7 @@ class SIState(EpidemicStateBase):
-----
This implements an SI epidemic process [pastor-satorras-epidemic-2015]_,
where nodes in the susceptible state (value 0) are infectious by neighbours
where nodes in the susceptible state (value 0) are infected by neighbours
in the infectious state (value 1).
If a node :math:`i` is updated at time :math:`t`, the transition
......@@ -327,7 +325,7 @@ class SISState(DiscreteStateBase):
This implements an SIS epidemic process
[pastor-satorras-epidemic-2015]_, where nodes in the susceptible state
(value 0) are infectious by neighbours in the infectious state (value 1),
(value 0) are infected by neighbours in the infectious state (value 1),
which can then eventually recover to a susceptible state.
If a node :math:`i` is updated at time :math:`t`, the transition
......@@ -436,7 +434,7 @@ class SIRState(DiscreteStateBase):
This implements an SIR epidemic process
[pastor-satorras-epidemic-2015]_, where nodes in the susceptible state
(value 0) are infectious by neighbours in the infectious state (value 1),
(value 0) are infected by neighbours in the infectious state (value 1),
which can then eventually recover to a recovered state (value 2).
If a node :math:`i` is updated at time :math:`t`, the transition
......@@ -558,7 +556,7 @@ class SIRSState(DiscreteStateBase):
This implements an SIRS epidemic process
[pastor-satorras-epidemic-2015]_, where nodes in the susceptible state
(value 0) are infectious by neighbours in the infectious state (value 1),
(value 0) are infected by neighbours in the infectious state (value 1),
which can then eventually recover to a recovered state (value 2), and
finally back to the susceptible state.
......
......@@ -77,8 +77,6 @@ The following network will be used as an example throughout the documentation.
"""
from __future__ import division, absolute_import, print_function
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_flow")
......
......@@ -48,16 +48,11 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_generation")
from .. import Graph, GraphView, _check_prop_scalar, _prop, _limit_args, \
_gt_type, _get_rng, _c_str, libcore, Vector_double
_gt_type, _get_rng, libcore, Vector_double
from .. stats import label_parallel_edges, label_self_loops
import inspect
import types
......@@ -805,7 +800,7 @@ def random_rewire(g, model="configuration", n_iter=1, edge_sweep=True,
if not fast:
g.set_fast_edge_removal(True)
pcount = libgraph_tool_generation.random_rewire(g._Graph__graph,
_c_str(model),
model,
n_iter, not edge_sweep,
self_loops, parallel_edges,
configuration, traditional,
......@@ -1763,7 +1758,7 @@ def triangulation(points, type="simple", periodic=False):
g = Graph(directed=False)
pos = g.new_vertex_property("vector<double>")
libgraph_tool_generation.triangulation(g._Graph__graph, points,
_prop("v", g, pos), _c_str(type),
_prop("v", g, pos), type,
periodic)
return g, pos
......
......@@ -18,12 +18,9 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import pickle
import base64
import atexit
import sys
from io import BytesIO
from . import libgraph_tool_core
......@@ -72,8 +69,6 @@ def pickler(stream, obj):
def unpickler(stream):
data = stream.read()
sstream = BytesIO(data)
if sys.version_info < (3,):
return pickle.load(sstream)
return pickle.load(sstream, encoding="bytes")
libgraph_tool_core.set_pickler(pickler)
......
......@@ -153,11 +153,6 @@ Contents
"""
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
__all__ = ["minimize_blockmodel_dl",
"minimize_nested_blockmodel_dl",
"BlockState",
......
......@@ -18,11 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
import numpy
import numpy.random
import bisect
......
......@@ -18,14 +18,9 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, \
PropertyMap, VertexPropertyMap, conv_pickle_state, Vector_size_t, \
Vector_double, group_vector_property, perfect_prop_hash
PropertyMap, VertexPropertyMap, Vector_size_t, Vector_double, \
group_vector_property, perfect_prop_hash
from .. generation import condensation_graph, random_rewire, generate_sbm, \
solve_sbm_fugacities, generate_maxent_sbm
from .. stats import label_self_loops, remove_parallel_edges, remove_self_loops
......@@ -669,7 +664,6 @@ class BlockState(object):
return state
def __setstate__(self, state):
conv_pickle_state(state)
self.__init__(**state)
def get_block_state(self, b=None, vweight=False, **kwargs):
......
......@@ -18,13 +18,8 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap, \
conv_pickle_state, Vector_size_t, Vector_double, group_vector_property
Vector_size_t, Vector_double, group_vector_property
from .. generation import condensation_graph
from .. stats import label_self_loops
from .. spectral import adjacency
......@@ -128,7 +123,6 @@ class EMBlockState(object):
return state
def __setstate__(self, state):
conv_pickle_state(state)
g, B, vm, em_s, em_t, wr, prs = state
self.__init__(g, B)
g.copy_property(vm, self.vm)
......
......@@ -18,13 +18,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap, \
conv_pickle_state
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap
import random
from numpy import *
import numpy
......@@ -405,7 +399,6 @@ class LayeredBlockState(OverlapBlockState, BlockState):
return state
def __setstate__(self, state):
conv_pickle_state(state)
self.__init__(**state)
def __copy__(self):
......
......@@ -18,11 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import Vector_size_t, Vector_double
import numpy
......
......@@ -18,11 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
import numpy
from . util import *
from . mcmc import *
......@@ -119,7 +114,7 @@ def minimize_blockmodel_dl(g, B_min=None, B_max=None, b_min=None, b_max=None,
mcmc_args={}, anneal_args={},
mcmc_equilibrate_args={}, shrink_args={},
mcmc_multilevel_args={}, verbose=False):
"""Fit the stochastic block model, by minimizing its description length using an
r"""Fit the stochastic block model, by minimizing its description length using an
agglomerative heuristic.
Parameters
......@@ -286,7 +281,7 @@ def minimize_nested_blockmodel_dl(g, B_min=None, B_max=None, b_min=None,
mcmc_args={}, anneal_args={},
mcmc_equilibrate_args={}, shrink_args={},
mcmc_multilevel_args={}, verbose=False):
"""Fit the nested stochastic block model, by minimizing its description length
r"""Fit the nested stochastic block model, by minimizing its description length
using an agglomerative heuristic.
Parameters
......@@ -479,4 +474,4 @@ def minimize_nested_blockmodel_dl(g, B_min=None, B_max=None, b_min=None,
**dmask(hierarchy_minimize_args,
["B_max", "B_min", "bisection_args", "verbose"]))
return state
\ No newline at end of file
return state
......@@ -18,12 +18,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, conv_pickle_state
from .. import _degree, _prop, Graph, GraphView
from . blockmodel import *
from . blockmodel import _bm_test
from . overlap_blockmodel import *
......@@ -213,10 +208,6 @@ class NestedBlockState(object):
return state
def __setstate__(self, state):
conv_pickle_state(state)
if "kwargs" in state: # backwards compatibility
state["state_args"] = state["kwargs"]
del state["kwargs"]
self.__init__(**state)
def get_bs(self):
......@@ -999,7 +990,7 @@ class NestedBlockState(object):
def hierarchy_minimize(state, B_min=None, B_max=None, b_min=None, b_max=None,
frozen_levels=None, bisection_args={},
epsilon=1e-8, verbose=False):
"""Attempt to find a fit of the nested stochastic block model that minimizes the
r"""Attempt to find a fit of the nested stochastic block model that minimizes the
description length.
Parameters
......
......@@ -18,13 +18,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap, \
conv_pickle_state
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, PropertyMap
import random
from numpy import *
......@@ -361,7 +355,6 @@ class OverlapBlockState(BlockState):
return state
def __setstate__(self, state):
conv_pickle_state(state)
self.__init__(**state)
def get_E(self):
......
......@@ -18,11 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, _get_rng, Vector_size_t
from . blockmodel import DictState, get_entropy_args, _bm_test
......
......@@ -18,11 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, _get_rng, Vector_int32_t, \
Vector_size_t
from . blockmodel import DictState, get_entropy_args, _bm_test
......
......@@ -18,11 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. import _degree, _prop, Graph, GraphView, libcore, _get_rng, \
PropertyMap, edge_endpoint_property
......@@ -528,7 +523,7 @@ class MeasuredBlockState(UncertainBaseState):
positive measurements for each edge.
n_default : ``int`` (optional, default: ``1``)
Total number of measurements for each non-edge.
x_default : ``int`` (optional, default: ``1``)
x_default : ``int`` (optional, default: ``0``)
Total number of positive measurements for each non-edge.
fn_params : ``dict`` (optional, default: ``dict(alpha=1, beta=1)``)
Beta distribution hyperparameters for the probability of missing
......
......@@ -18,11 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
import scipy.special
from numpy import *
......
......@@ -77,11 +77,6 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_search")
......
......@@ -39,8 +39,6 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
from .. import _degree, _prop, Graph, GraphView, _limit_args, Vector_int64_t, \
Vector_double
from .. stats import label_self_loops
......
......@@ -44,15 +44,12 @@ Contents
"""
from __future__ import division, absolute_import, print_function
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_stats")
from .. import _degree, _prop, _get_rng, GraphView, PropertyMap
from numpy import *
import numpy
import sys
__all__ = ["vertex_hist", "edge_hist", "vertex_average", "edge_average",
"label_parallel_edges", "remove_parallel_edges",
......
......@@ -71,8 +71,6 @@ Contents
"""
from __future__ import division, absolute_import, print_function
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_topology")
......@@ -81,7 +79,7 @@ from .. import _prop, Vector_int32_t, Vector_size_t, _check_prop_writable, \
EdgePropertyMap, PropertyMap, GraphView, libcore, _get_rng, _degree, \
perfect_prop_hash, _limit_args
from .. stats import label_self_loops
import random, sys, numpy, collections
import random, numpy, collections
__all__ = ["isomorphism", "subgraph_isomorphism", "mark_subgraph",
"max_cliques", "max_cardinality_matching",
......@@ -849,7 +847,7 @@ def max_cliques(g):
yield c
def min_spanning_tree(g, weights=None, root=None, tree_map=None):
"""
r"""
Return the minimum spanning tree of a given graph.
Parameters
......@@ -1043,7 +1041,7 @@ def random_spanning_tree(g, weights=None, root=None, tree_map=None):
def dominator_tree(g, root, dom_map=None):
"""Return a vertex property map the dominator vertices for each vertex.
r"""Return a vertex property map the dominator vertices for each vertex.
Parameters
----------
......@@ -1777,7 +1775,7 @@ def shortest_distance(g, source=None, target=None, weights=None,
negative_weights=False, max_dist=None, directed=None,
dense=False, dist_map=None, pred_map=False,
return_reached=False, dag=False):
"""Calculate the distance from a source to a target vertex, or to of all
r"""Calculate the distance from a source to a target vertex, or to of all
vertices from a given source, or the all pairs shortest paths, if the source
is not specified.
......@@ -2034,7 +2032,7 @@ def shortest_distance(g, source=None, target=None, weights=None,
def shortest_path(g, source, target, weights=None, negative_weights=False,
pred_map=None, dag=False):
"""Return the shortest path from ``source`` to ``target``.
r"""Return the shortest path from ``source`` to ``target``.
Parameters
----------
......@@ -2552,7 +2550,7 @@ def all_circuits(g, unique=False):
def pseudo_diameter(g, source=None, weights=None):
"""
r"""
Compute the pseudo-diameter of the graph.
Parameters
......@@ -3180,7 +3178,7 @@ def edge_reciprocity(g):
def tsp_tour(g, src, weight=None):
"""Return a traveling salesman tour of the graph, which is guaranteed to be
r"""Return a traveling salesman tour of the graph, which is guaranteed to be
twice as long as the optimal tour in the worst case.
Parameters
......@@ -3277,4 +3275,4 @@ def sequential_vertex_coloring(g, order=None, color=None):
return color
from .. flow import libgraph_tool_flow
\ No newline at end of file
from .. flow import libgraph_tool_flow
......@@ -37,8 +37,6 @@ Contents
++++++++
"""
from __future__ import division, absolute_import, print_function
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_util")
......