inline.py 11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#! /usr/bin/env python
#
# Copyright (C) 2007 Tiago de Paula Peixoto <tiago@forked.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

18
import sys, string, hashlib, os.path, re, glob
19 20
from .. import core
from .. import libgraph_tool_core
Tiago Peixoto's avatar
Tiago Peixoto committed
21
import numpy
22 23 24 25 26 27 28

try:
    import scipy.weave
except ImportError:
    raise libgraph_tool_core.raise_error\
          ("You need to have scipy installed to use 'run_action'.")

Tiago Peixoto's avatar
Tiago Peixoto committed
29 30 31 32 33 34 35 36
prefix = None
for d in [d + "/graph_tool" for d in sys.path]:
    if os.path.exists(d):
        prefix = d
        break

inc_prefix = prefix + "/include"
cxxflags = libgraph_tool_core.mod_info().cxxflags + " -I%s" % inc_prefix
37 38

# this is the code template which defines the action function object
Tiago Peixoto's avatar
Tiago Peixoto committed
39 40
support_template = open(prefix + "/run_action/run_action_support.hh").read()
code_template = open(prefix + "/run_action/run_action_template.hh").read()
41

42 43 44 45 46
# hash all the headers to force recompilation if code changes
headers_hash = ""
for inc in glob.glob(inc_prefix + "/*"):
    headers_hash = hashlib.md5(headers_hash + open(inc).read()).hexdigest()

47
# property map types
Tiago Peixoto's avatar
Tiago Peixoto committed
48 49 50 51 52 53 54 55 56 57 58 59 60
props = """
typedef GraphInterface::vertex_index_map_t vertex_index_t;
typedef GraphInterface::edge_index_map_t edge_index_t;
typedef prop_bind_t<GraphInterface::vertex_index_map_t> vertex_prop_t;
typedef prop_bind_t<GraphInterface::edge_index_map_t> edge_prop_t;
typedef prop_bind_t<ConstantPropertyMap<size_t,graph_property_tag> > graph_prop_t;
"""

def clean_prop_type(t):
    return t.replace(" ","_").replace("::","_")\
           .replace("<","_").replace(">","_").\
           replace("__","_")

61 62
for d in ["vertex", "edge", "graph"]:
    for t in core.value_types():
Tiago Peixoto's avatar
Tiago Peixoto committed
63 64 65 66 67
        props += "typedef %s_prop_t::as<%s >::type %sprop_%s_t;\n" % \
                 (d,t,d[0],clean_prop_type(t))

def get_graph_type(g):
    return libgraph_tool_core.get_graph_type(g._Graph__graph)
68

Tiago Peixoto's avatar
Tiago Peixoto committed
69
def inline(code, arg_names=[], local_dict=None,
70
           global_dict=None, force=False, compiler="gcc", verbose=False,
71 72 73
           auto_downcast=1, support_code="", libraries=[],
           library_dirs=[], extra_compile_args=[],
           runtime_library_dirs=[], extra_objects=[],
Tiago Peixoto's avatar
Tiago Peixoto committed
74
           extra_link_args=[], mask_ret=[], debug=False):
75
    """Compile (if necessary) and run the C++ action specified by 'code',
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    using weave. The (possibly modified) variables in 'arg_names' are returned.

    Parameters
    ----------
    code : string
        C++ code to be used
    arg_names : list, optional (default: [])
        List of variables to be passed to the C++ code
    local_dict : dict, optional (default: None)
        Dictionary of variables to be used as local scope. If none is specified,
        the calling functions' local variables are used.
    global_dict : dict, optional (default: None)
        Dictionary of variables to be used as global scope. If none is
        specified, the calling functions' global variables are used.
    force : bool, optional (default: False)
        If true, compilation is forced.
    compiler : string, optional (default: "gcc")
        The name of compiler to use when compiling.  On windows, it understands
        'msvc' and 'gcc' as well as all the compiler names understood by
        distutils.  On Unix, it'll only understand the values understood by
        distutils.

        On windows, the compiler defaults to the Microsoft C++ compiler.  If
        this isn't available, it looks for mingw32 (the gcc compiler).

        On Unix, it'll probably use the same compiler that was used when
        compiling Python. Cygwin's behavior should be similar.


    [...]
    """
107 108 109

    # each term on the expansion will properly unwrap a tuple pointer value
    # to a reference with the appropriate name and type
Tiago Peixoto's avatar
Tiago Peixoto committed
110 111
    exp_term = """typename boost::remove_pointer<typename tr1::tuple_element<%d,Args>::type>::type& %s =
                          *tr1::get<%d>(_args);"""
112 113 114 115 116 117 118
    arg_expansion = "\n".join([ exp_term % (i,arg_names[i],i) for i in \
                                xrange(0, len(arg_names))])

    # we need to get the locals and globals of the _calling_ function. Thus, we
    # need to go deeper into the call stack
    call_frame = sys._getframe(1)
    if local_dict is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
119
        local_dict = call_frame.f_locals
120 121
    if global_dict is None:
        global_dict = call_frame.f_globals
Tiago Peixoto's avatar
Tiago Peixoto committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

    # convert variables to boost::python::object, except some known convertible
    # types
    arg_def = props
    arg_conv = ""
    arg_alias = []
    alias_dict = {}
    for arg in arg_names:
        if arg not in local_dict.keys() and arg not in global_dict.keys():
            raise ValueError("undefined variable: "+ arg)
        if arg in local_dict.keys():
            arg_val = local_dict[arg]
        else:
            arg_val = global_dict[arg]
        if issubclass(type(arg_val), core.Graph):
            alias = "__gt__" + arg
            gi = "__gt__" + arg + "__gi"
            graph_type = get_graph_type(arg_val)
            gi_val = arg_val._Graph__graph
            arg_def += "typedef GraphWrap<%s > %s_graph_t;\n" % (graph_type, arg);
            arg_def += "GraphInterface& %s = python::extract<GraphInterface&>(%s);\n" %\
                        (gi, alias)
            arg_def += "%s_graph_t %s = graph_wrap(*boost::any_cast<%s*>(%s.GetGraphView()), %s);\n" % \
                        (arg, arg, graph_type, gi, gi)
            arg_alias.append(alias)
            alias_dict[alias] = gi_val
        elif type(arg_val) == core.PropertyMap:
            alias = "__gt__" + arg
            if arg_val == arg_val.get_graph().vertex_index:
                prop_name = "GraphInterface::vertex_index_map_t"
            elif arg_val == arg_val.get_graph().edge_index:
                prop_name = "GraphInterface::edge_index_map_t"
            else:
                prop_name = "%sprop_%s_t" % \
                            (arg_val.key_type(),
                             clean_prop_type(arg_val.value_type()))
            arg_def  += "%s %s;\n" % (prop_name, arg)
            arg_conv += "%s = get_prop<%s>(%s);\n" % \
                        (arg, prop_name, alias)
            arg_alias.append(alias)
            alias_dict[alias] = arg_val
        elif type(arg_val) not in [int, bool, float, string, numpy.ndarray]:
            alias = "__gt__" + arg
            obj_type = "python::object"
            if type(arg_val) == list:
                obj_type = "python::list"
            elif type(arg_val) == dict:
                obj_type = "python::dict"
            elif type(arg_val) == tuple:
                obj_type = "python::tuple"
            arg_def += "%s %s;\n" % (obj_type, arg)
            arg_conv += "%s = %s(python::object(python::handle<>" % (arg, obj_type) + \
                        "(python::borrowed((PyObject*)(%s)))));\n" % alias
            arg_alias.append(alias)
            alias_dict[alias] = arg_val
        elif type(arg_val) == bool:
            #weave is dumb with bools
            alias = "__gt__" + arg
            arg_def += "bool %s;\n" % arg;
            arg_conv += "%s = python::extract<bool>(python::object(python::handle<>" % arg + \
                        "(python::borrowed((PyObject*)(%s)))));\n" % alias
            arg_alias.append(alias)
            alias_dict[alias] = arg_val
        else:
            arg_alias.append(arg)
            if arg in local_dict.keys():
                alias_dict[arg] = local_dict[arg]
            else:
                alias_dict[arg] = global_dict[arg]

    # handle returned values
    return_vals = ""
    for arg in arg_names:
        if arg in local_dict.keys():
            arg_val = local_dict[arg]
        else:
            arg_val = global_dict[arg]
        if arg not in mask_ret and \
               type(arg_val) not in [numpy.ndarray, core.PropertyMap] and \
               not issubclass(type(arg_val), core.Graph):
            return_vals += 'return_vals["%s"] = %s;\n' % (arg, arg)

    support_code += globals()["support_template"]

    # set debug flag and disable optimization in debug mode
    compile_args = [cxxflags] + extra_compile_args
    if debug:
        compile_args = [re.sub("-O[^ ]*", "", x) for x in compile_args] + ["-g"]

    # insert a hash value into the code below, to force recompilation when
    # support_code (and module version) changes
    support_hash = hashlib.md5(support_code + code + \
                               " ".join(libraries + library_dirs +
                                        [cxxflags] + \
                                        extra_compile_args +\
                                        extra_objects + \
                                        extra_link_args) + \
219
                               headers_hash + core.__version__).hexdigest()
Tiago Peixoto's avatar
Tiago Peixoto committed
220 221 222 223
    code += "\n// support code hash: " + support_hash
    inline_code = string.Template(globals()["code_template"]).\
                  substitute(var_defs=arg_def, var_extract=arg_conv,
                             code=code, return_vals=return_vals)
224 225 226 227 228 229 230 231 232

    # RTLD_GLOBAL needs to be set in dlopen() if we want typeinfo and
    # friends to work properly across DSO boundaries. See
    # http://gcc.gnu.org/faq.html#dso
    orig_dlopen_flags = sys.getdlopenflags()
    sys.setdlopenflags(core.RTLD_NOW|core.RTLD_GLOBAL)

    # call weave and pass all the updated kw arguments
    ret_vals = \
233
             scipy.weave.inline(inline_code, arg_alias, force=int(force),
Tiago Peixoto's avatar
Tiago Peixoto committed
234
                                local_dict=alias_dict, global_dict=global_dict,
235
                                compiler=compiler, verbose=int(verbose),
236 237 238 239
                                auto_downcast=auto_downcast,
                                support_code=support_code,
                                libraries=libraries,
                                library_dirs=sys.path + library_dirs,
Tiago Peixoto's avatar
Tiago Peixoto committed
240
                                extra_compile_args=compile_args,
241 242
                                runtime_library_dirs=runtime_library_dirs,
                                extra_objects=extra_objects,
Tiago Peixoto's avatar
Tiago Peixoto committed
243
                                extra_link_args=["-Wl,-E "] + extra_link_args)
244 245 246
    # check if exception was thrown
    if ret_vals["__exception_thrown"]:
        libgraph_tool_core.raise_error(ret_vals["__exception_error"])
247 248 249
    else:
        del ret_vals["__exception_thrown"]
        del ret_vals["__exception_error"]
250 251
    sys.setdlopenflags(orig_dlopen_flags) # reset dlopen to normal case to
                                          # avoid unnecessary symbol collision
Tiago Peixoto's avatar
Tiago Peixoto committed
252 253 254 255 256 257 258
    # set return vals
    for arg in arg_names:
        if ret_vals.has_key(arg):
            if local_dict.has_key(arg):
                local_dict[arg] = ret_vals[arg]
            else:
                global_dict[arg] = ret_vals[arg]
Tiago Peixoto's avatar
Tiago Peixoto committed
259
    return ret_vals