Commit 66cf8d87 authored by Tiago Peixoto's avatar Tiago Peixoto
Browse files

Fix some compatibility problems with Python 2

parent 4c4ff110
......@@ -652,14 +652,17 @@ CPU-bound. Here is an example for a somewhat larger graph:
.. testsetup:: gt_format
import sys
import tempfile
g = gt.collection.data["pgp-strong-2009"]
g.properties.clear()
tmpdir = tempfile.mkdtemp()
g.save("%s/pgp_graph.xml" % tmpdir)
g.save("%s/pgp_graph.xml.xz" % tmpdir)
if sys.version_info >= (3,):
g.save("%s/pgp_graph.xml.xz" % tmpdir)
g.save("%s/pgp_graph.gt" % tmpdir)
g.save("%s/pgp_graph.gt.xz" % tmpdir)
if sys.version_info >= (3,):
g.save("%s/pgp_graph.gt.xz" % tmpdir)
.. doctest:: gt_format
......
......@@ -84,6 +84,8 @@ from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
else:
unicode = str
__author__ = "Tiago de Paula Peixoto <tiago@skewed.de>"
__copyright__ = "Copyright 2006-2015 Tiago de Paula Peixoto"
......@@ -144,7 +146,7 @@ graph_tool = sys.modules[__name__]
def _prop(t, g, prop):
"""Return either a property map, or an internal property map with a given
name."""
if type(prop) == str:
if isinstance(prop, (str, unicode)):
try:
pmap = g.properties[(t, prop)]
except KeyError:
......@@ -232,7 +234,7 @@ def _gt_type(obj):
return "double"
if issubclass(t, numpy.float128):
return "long double"
if issubclass(t, str):
if issubclass(t, (str, unicode)):
return "string"
if issubclass(t, bool):
return "bool"
......@@ -250,12 +252,13 @@ def _converter(val_type):
elif vtype is object:
def convert(val):
return val
elif vtype is str:
return _c_str
else:
def convert(val):
return vtype(val)
return convert
def show_config():
"""Show ``graph_tool`` build configuration."""
info = libcore.mod_info()
......@@ -283,6 +286,15 @@ try:
except BaseException as e:
ArgumentError = type(e)
if sys.version_info < (3,):
def _c_str(s):
if isinstance(s, unicode):
return s.encode("utf-8")
return s
else:
def _c_str(s):
return s
################################################################################
# Property Maps
################################################################################
......@@ -2221,14 +2233,14 @@ class Graph(object):
"""
if isinstance(file_name, str):
if isinstance(file_name, (str, unicode)):
file_name = os.path.expanduser(file_name)
f = open(file_name) # throw the appropriate exception, if not found
if fmt == 'auto' and isinstance(file_name, str):
if fmt == 'auto' and isinstance(file_name, (str, unicode)):
fmt = self.__get_file_format(file_name)
elif fmt == "auto":
fmt = "gt"
if isinstance(file_name, str) and file_name.endswith(".xz"):
if isinstance(file_name, (str, unicode)) and file_name.endswith(".xz"):
try:
import lzma
file_name = lzma.open(file_name, mode="rb")
......@@ -2242,12 +2254,13 @@ class Graph(object):
ignore_ep = []
if ignore_gp is None:
ignore_gp = []
if isinstance(file_name, str):
props = self.__graph.read_from_file(file_name, None, fmt, ignore_vp,
if isinstance(file_name, (str, unicode)):
props = self.__graph.read_from_file(_c_str(file_name), None,
_c_str(fmt), ignore_vp,
ignore_ep, ignore_gp)
else:
props = self.__graph.read_from_file("", file_name, fmt, ignore_vp,
ignore_ep, ignore_gp)
props = self.__graph.read_from_file("", file_name, _c_str(fmt),
ignore_vp, ignore_ep, ignore_gp)
for name, prop in props[0].items():
self.vertex_properties[name] = PropertyMap(prop, self, "v")
for name, prop in props[1].items():
......@@ -2300,32 +2313,32 @@ class Graph(object):
u.graph_properties["_Graph__reversed"] = self.new_graph_property("bool")
u.graph_properties["_Graph__reversed"] = True
if type(file_name) == str:
if isinstance(file_name, (str, unicode)):
file_name = os.path.expanduser(file_name)
if fmt == 'auto' and isinstance(file_name, str):
if fmt == 'auto' and isinstance(file_name, (str, unicode)):
fmt = self.__get_file_format(file_name)
elif fmt == "auto":
fmt = "gt"
if fmt == "graphml":
fmt = "xml"
if isinstance(file_name, str) and file_name.endswith(".xz"):
if isinstance(file_name, (str, unicode)) and file_name.endswith(".xz"):
try:
import lzma
file_name = lzma.open(file_name, mode="wb")
except ImportError:
raise ValueError("lzma compression is only available in Python >= 3.3")
props = [(name[1], prop._PropertyMap__map) for name, prop in \
props = [(_c_str(name[1]), prop._PropertyMap__map) for name, prop in \
self.__properties.items()]
if isinstance(file_name, str):
if isinstance(file_name, (str, unicode)):
f = open(file_name, "w") # throw the appropriate exception, if
# unable to open
f.close()
u.__graph.write_to_file(file_name, None, fmt, props)
u.__graph.write_to_file(_c_str(file_name), None, _c_str(fmt), props)
else:
u.__graph.write_to_file("", file_name, fmt, props)
u.__graph.write_to_file("", file_name, _c_str(fmt), props)
# Directedness
......
......@@ -22,6 +22,8 @@ from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
else:
unicode = str
import os
import warnings
......@@ -1089,7 +1091,7 @@ def graph_draw(g, pos=None, vprops=None, eprops=None, vorder=None, eorder=None,
nodesfirst, geometry=output_size,
fit_area=fit_area, **kwargs)
else:
if isinstance(output, str):
if isinstance(output, (str, unicode)):
out, auto_fmt = open_file(output, mode="wb")
else:
out = output
......@@ -1171,12 +1173,12 @@ def graph_draw(g, pos=None, vprops=None, eprops=None, vorder=None, eorder=None,
img = IPython.display.Image(data=inl_out.getvalue())
srf.finish()
if output_file is not None:
if isinstance(output_file, str):
if isinstance(output_file, (str, unicode)):
ofile, auto_fmt = open_file(output_file, mode="wb")
else:
ofile = output_file
ofile.write(out.getvalue())
if isinstance(output_file, str):
if isinstance(output_file, (str, unicode)):
ofile.close()
IPython.display.display(img)
del srf
......@@ -1263,7 +1265,7 @@ def get_bb(g, pos, size, pen_width, size_scale=1, text=None, font_family=None,
if not isinstance(font_size, PropertyMap):
cr.set_font_size(fs)
t = text[v] if isinstance(text, PropertyMap) else text
if not isinstance(t, str):
if not isinstance(t, (str, unicode)):
t = str(t)
extents = cr.text_extents(t)
s = max(extents[2], extents[3]) * 1.4
......
......@@ -21,6 +21,10 @@
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
......@@ -28,7 +32,7 @@ import warnings
import ctypes
import ctypes.util
import tempfile
from .. import PropertyMap, group_vector_property, ungroup_vector_property
from .. import PropertyMap, group_vector_property, ungroup_vector_property, _c_str
import numpy
import numpy.random
import copy
......@@ -437,12 +441,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):
aset(n, "fillcolor", vcolor)
if isinstance(vcolor, (str, unicode)):
aset(n, "fillcolor", _c_str(vcolor))
else:
color = vcolor[v]
if isinstance(color, str):
aset(n, "fillcolor", color)
if isinstance(color, (str, unicode)):
aset(n, "fillcolor", _c_str(color))
else:
color = tuple([int(c * 255.0) for c in vcmap(vnorm(color))])
aset(n, "fillcolor", "#%.2x%.2x%.2x%.2x" % color)
......@@ -485,12 +489,12 @@ def graphviz_draw(g, pos=None, size=(15, 15), pin=False, layout=None,
aset(ge, "arrowhead", "vee")
# apply color
if isinstance(ecolor, str):
aset(ge, "color", ecolor)
if isinstance(ecolor, (str, unicode)):
aset(ge, "color", _c_str(ecolor))
else:
color = ecolor[e]
if isinstance(color, str):
aset(ge, "color", color)
if isinstance(color, (str, unicode)):
aset(ge, "color", _c_str(color))
else:
color = tuple([int(c * 255.0) for c in ecmap(enorm(color))])
aset(ge, "color", "#%.2x%.2x%.2x%.2x" % color)
......
......@@ -45,15 +45,20 @@ 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, libcore
from .. import Graph, GraphView, _check_prop_scalar, _prop, _limit_args, \
_gt_type, _get_rng, _c_str, libcore
from .. stats import label_parallel_edges, label_self_loops
import inspect
import types
import sys, numpy, numpy.random
import numpy
import numpy.random
__all__ = ["random_graph", "random_rewire", "predecessor_tree", "line_graph",
"graph_union", "triangulation", "lattice", "geometric_graph",
......@@ -809,7 +814,8 @@ def random_rewire(g, model="uncorrelated", n_iter=1, edge_sweep=True,
if pin.value_type() != "bool":
pin = pin.copy(value_type="bool")
pcount = libgraph_tool_generation.random_rewire(g._Graph__graph, model,
pcount = libgraph_tool_generation.random_rewire(g._Graph__graph,
_c_str(model),
n_iter, not edge_sweep,
self_loops, parallel_edges,
alias, traditional, persist,
......@@ -1208,7 +1214,8 @@ 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), type, periodic)
_prop("v", g, pos), _c_str(type),
periodic)
return g, pos
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment