def __init__(self):
     self.g = build_factor_synonyms_graph()
     self.component_map = self.g.add_vertex_property(
         name='connected_components', type='integer')
     self.num_components = bgl.connected_components(self.g,
                                                    self.component_map)
     self._build_partition_synonyms()
Exemple #2
0
def graph_component_map( g ):
    """Returns (component_map, num_components)
    """
    import boost.graph as bgl
    try: g.component_map
    except:
        g.component_map = g.add_vertex_property( 'components', 'integer' )
        g.num_components = bgl.connected_components( g, g.component_map )
    return ( g.component_map, g.num_components )
Exemple #3
0
def graph_component_map(g):
    """Returns (component_map, num_components)
    """
    import boost.graph as bgl
    try:
        g.component_map
    except:
        g.component_map = g.add_vertex_property('components', 'integer')
        g.num_components = bgl.connected_components(g, g.component_map)
    return (g.component_map, g.num_components)
Exemple #4
0
def write_as_connected_components( g, file_prefix ):
    import boost.graph as bgl
    components = g.add_vertex_property( 'integer' )
    num_components = bgl.connected_components( g, components )
    for i in range( num_components ):
        filename = file_prefix + '_' + str( i ) + '.mm'
        f = open( filename, 'w' )
        # print f
        ( num_vertices, num_non_zeros, vertex_indices ) = \
                write_matrix_market_format(
                        g,
                        f,
                        lambda v: components[ v ] == i )
        # print i, num_vertices, num_non_zeros
    return ( components, num_components )
Exemple #5
0
def write_as_connected_components(g, file_prefix):
    import boost.graph as bgl
    components = g.add_vertex_property('integer')
    num_components = bgl.connected_components(g, components)
    for i in range(num_components):
        filename = file_prefix + '_' + str(i) + '.mm'
        f = open(filename, 'w')
        # print f
        ( num_vertices, num_non_zeros, vertex_indices ) = \
                write_matrix_market_format(
                        g,
                        f,
                        lambda v: components[ v ] == i )
        # print i, num_vertices, num_non_zeros
    return (components, num_components)
Exemple #6
0
def graph_2_distance_map( g, components_dir, name, beta, eps ):
    """Calculates the distances between all nodes in the graph

    Returns a dict where tuples of node_ids in the graph are the keys and
    the distances are the values. Distances below eps are not returned.

    beta is the parameter for the diffusion kernel on the graph

    components_dir is a directory to place working files in

    name is a string to use when generating file names
    """
    import boost.graph as bgl

    #
    # Calculate the connected components
    #
    # print 'Calculating connected components'
    components = g.add_vertex_property( 'integer' )
    num_components = bgl.connected_components( g, components )
    # print num_components, 'connected component(s)'


    result = { }

    #
    # For each component
    #
    if not os.path.exists( components_dir ):
        os.mkdir( components_dir )
    components_prefix = os.path.join( components_dir, name )
    for i in range( num_components ): # for each component

        # for testing just do one component
        # if 2 != i: continue


        # create an adjacency matrix for this component
        adj_filename = components_prefix + '_' + str( i ) + '_adj.mm'
        predicate = lambda v: components[ v ] == i
        ( num_vertices, num_non_zeros, vertex_indices, index_vertices ) = \
                write_matrix_market_format(
                        g,
                        open( adj_filename, 'w' ),
                        predicate )


        # we need a map from adjacency matrix row/col indices to nodes
        adjacency_nodes = { }
        idx = 1
        for v in filter( predicate, g.vertices ):
            adjacency_nodes[ idx ] = v
            idx += 1

        # create and run matlab script to calculate the kernel
        kernel_filename = components_prefix + '_' + str( i ) + '_ker.mm'
        if not os.path.exists( kernel_filename ):
            tmp_script = "\
A = mmread( '%ADJACENCY_FILE%' );\n\
size( A )\n\
L = calc_laplacian( A );\n\
K = calc_kernel( L, %BETA% );\n\
K_sp = sparsify( K, %EPSILON% );\n\
mmwrite( '%KERNEL_FILE%', K_sp );\n\
exit\n"
            script_text = tmp_script. \
                    replace( '%ADJACENCY_FILE%', adj_filename ). \
                    replace( '%EPSILON%', str( eps ) ). \
                    replace( '%BETA%', str( beta ) ). \
                    replace( '%KERNEL_FILE%', kernel_filename )
            script_filename = 'tmp_script.m'
            open( script_filename, 'w' ).write( script_text )
            matlab_command = 'C:\\apps\\MATLAB7\\bin\\win32\\MATLAB.exe /nosplash ' \
                    + '/r ' + script_filename.strip( '.m' )
            # print matlab_command
            os.system( matlab_command )



        # once we have the kernel we can populate the edge weights
        # are the kernel's values
        f = open( kernel_filename, 'r' )
        n = m = nnz = 0
        node_ids = g.vertex_properties[ 'node_id' ]
        for line in f: # this for loop reads a matrix market format file

            if line.startswith( '%' ): continue

            line = line.strip( '\n' )
            split = line.split()
            # Is this the first line of data with matrix sizes?
            if n == 0:
                ( n, m, nnz ) = [ int( x ) for x in split ]
                # print n, m, nnz
            else:
                idx1 =  int( split[ 0 ] )
                idx2 =  int( split[ 1 ] )
                prot1 = node_ids[ adjacency_nodes[ idx1 ] ]
                prot2 = node_ids[ adjacency_nodes[ idx2 ] ]

                # we are only interested in 'A' -> 'B' weights
                if prot1.startswith( 'A_' ) and prot2.startswith( 'B_' ):
                    prot1 = prot1[ 2: ]
                    prot2 = prot2[ 2: ]
                    distance = float( split[ 2 ] )

                    # only put value in if prot1 < prot2
                    if prot1 <= prot2:
                        result[ ( prot1, prot2 ) ] = distance

    return result
Exemple #7
0
def graph_2_distance_map(g, components_dir, name, beta, eps):
    """Calculates the distances between all nodes in the graph

    Returns a dict where tuples of node_ids in the graph are the keys and
    the distances are the values. Distances below eps are not returned.

    beta is the parameter for the diffusion kernel on the graph

    components_dir is a directory to place working files in

    name is a string to use when generating file names
    """
    import boost.graph as bgl

    #
    # Calculate the connected components
    #
    # print 'Calculating connected components'
    components = g.add_vertex_property('integer')
    num_components = bgl.connected_components(g, components)
    # print num_components, 'connected component(s)'

    result = {}

    #
    # For each component
    #
    if not os.path.exists(components_dir):
        os.mkdir(components_dir)
    components_prefix = os.path.join(components_dir, name)
    for i in range(num_components):  # for each component

        # for testing just do one component
        # if 2 != i: continue

        # create an adjacency matrix for this component
        adj_filename = components_prefix + '_' + str(i) + '_adj.mm'
        predicate = lambda v: components[v] == i
        ( num_vertices, num_non_zeros, vertex_indices, index_vertices ) = \
                write_matrix_market_format(
                        g,
                        open( adj_filename, 'w' ),
                        predicate )

        # we need a map from adjacency matrix row/col indices to nodes
        adjacency_nodes = {}
        idx = 1
        for v in filter(predicate, g.vertices):
            adjacency_nodes[idx] = v
            idx += 1

        # create and run matlab script to calculate the kernel
        kernel_filename = components_prefix + '_' + str(i) + '_ker.mm'
        if not os.path.exists(kernel_filename):
            tmp_script = "\
A = mmread( '%ADJACENCY_FILE%' );\n\
size( A )\n\
L = calc_laplacian( A );\n\
K = calc_kernel( L, %BETA% );\n\
K_sp = sparsify( K, %EPSILON% );\n\
mmwrite( '%KERNEL_FILE%', K_sp );\n\
exit\n"
            script_text = tmp_script. \
                    replace( '%ADJACENCY_FILE%', adj_filename ). \
                    replace( '%EPSILON%', str( eps ) ). \
                    replace( '%BETA%', str( beta ) ). \
                    replace( '%KERNEL_FILE%', kernel_filename )
            script_filename = 'tmp_script.m'
            open(script_filename, 'w').write(script_text)
            matlab_command = 'C:\\apps\\MATLAB7\\bin\\win32\\MATLAB.exe /nosplash ' \
                    + '/r ' + script_filename.strip( '.m' )
            # print matlab_command
            os.system(matlab_command)

        # once we have the kernel we can populate the edge weights
        # are the kernel's values
        f = open(kernel_filename, 'r')
        n = m = nnz = 0
        node_ids = g.vertex_properties['node_id']
        for line in f:  # this for loop reads a matrix market format file

            if line.startswith('%'): continue

            line = line.strip('\n')
            split = line.split()
            # Is this the first line of data with matrix sizes?
            if n == 0:
                (n, m, nnz) = [int(x) for x in split]
                # print n, m, nnz
            else:
                idx1 = int(split[0])
                idx2 = int(split[1])
                prot1 = node_ids[adjacency_nodes[idx1]]
                prot2 = node_ids[adjacency_nodes[idx2]]

                # we are only interested in 'A' -> 'B' weights
                if prot1.startswith('A_') and prot2.startswith('B_'):
                    prot1 = prot1[2:]
                    prot2 = prot2[2:]
                    distance = float(split[2])

                    # only put value in if prot1 < prot2
                    if prot1 <= prot2:
                        result[(prot1, prot2)] = distance

    return result
Exemple #8
0
 def __init__(self):
     self.g = build_factor_synonyms_graph()
     self.component_map = self.g.add_vertex_property(name='connected_components', type='integer')
     self.num_components = bgl.connected_components(self.g, self.component_map)
     self._build_partition_synonyms()
Exemple #9
0
# Copyright (C) 2006 The Trustees of Indiana University.

# Use, modification and distribution is subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
# http:#www.boost.org/LICENSE_1_0.txt)

#  Authors: Douglas Gregor
#           Andrew Lumsdaine

# Test property conversions

import boost.graph as bgl
g = bgl.Graph([(1, 2), (1, 3), (4, 6), (5, 6)])

color = g.add_vertex_property('color')

bgl.connected_components(g, color)

for v in g.vertices:
    print color[v]