Beispiel #1
0
    def __init__(self,
                 graph=None,
                 seed_size=None,
                 model=None,
                 time_limit=None):
        """

        :type graph: Graph
        """
        start = perf_counter()

        args = self.input_parser()
        self.graph = graph_from_file(args.i) if not graph else graph
        self.seed_size = args.k if not seed_size else seed_size
        self.model = args.m if not model else model
        self.time_remain = args.t if not time_limit else time_limit
        self.seeds = set()
        self.last_ise = 0

        self.algorithms = {'CELF': self.celf}

        self.compute_n = compute_n(self.graph.node_size, self.graph.edge_size)
        # print(self.compute_n)

        self.time_remain -= perf_counter() - start
Beispiel #2
0
def random_walk(sample_size, fly_back_probability=0.15, graph=None, file_path=None):
	
	

	# Step 1: Initialization

	sample = nx.DiGraph()
	add_node_to_sample = sample.add_node
	add_edge_to_sample = sample.add_edge

	# Check if a file path was supplied.
	if file_path is not None:
		graph = graph_from_file(file_path) 	# Networkx object.

	# Check for a list of edges(source_node, destination_node, weight).
	elif graph is not None:
		graph = add_graph(file_path)		# Networkx object.

	
	nodes = graph.nodes()					# List of nodes
	nodes_size = graph.number_of_nodes() 	# Number of nodes

	# Step 2: Select a random node to be the starting point.
	starting_node = get_node_from_list(nodes)

	add_node_to_sample(starting_node) 		# Include this node in the sample.

	# Step 3: Random walking
	current_node = starting_node 			# Set the starting point for the random walk.
	steps_since_added_node = 0

	while sample.number_of_nodes() < sample_size:
		
		# Check if we're going to look for a neighbor or we're flying back to the initial node.
		walk_to_neighbor = random()

		if walk_to_neighbor > fly_back_probability:
			# Walk to a neighbor.

			# IMPORTANT: Only selects from outer edges
			neighbors = graph.neighbors(current_node)			# Get the list of neighbors. 
			selected_neighbor = get_node_from_list(neighbors)	# Choose one of the neighbors at random.
			add_edge_to_sample(current_node, selected_neighbor)	# Add the edge to the graph, it also adds the node.
			current_node = selected_neighbor					# Let's change the current node to the selected neighbor.
			steps_since_added_node = 0

		else:
			steps_since_added_node = steps_since_added_node + 1
			# Change starting point if steps since last added node if greater the limit.
			if(steps_since_added_node > 100):
				starting_node = get_node_from_list(nodes)

			current_node = starting_node 	# Fly back to the starting node.

	return sample 		# Networkx object.
Beispiel #3
0
    def __init__(self,
                 graph=None,
                 seeds=None,
                 model=None,
                 time_limit=None,
                 step_num=5000):
        """

        :type seeds: set
        :type graph: Graph
        """
        if not graph:
            args = self.input_parser()
        self.graph = graph_from_file(args.i) if not graph else graph
        self.seeds = seed_from_file(args.s) if not seeds else seeds
        self.model = args.m if not model else model
        self.time_limit = args.t if not graph else time_limit
        self.step_num = step_num
Beispiel #4
0
    def build_path(self, G, s):
        self.marked[s] = True
        queue = Queue()
        queue.enqueue(s)
        while not queue.is_empty():
            v = queue.dequeue()
            for w in G.adj[v]:
                if not self.marked[w]:
                    self.edge_to[w] = v
                    self.marked[w] = True
                    queue.enqueue(w)


def test_path(cls, g, s):
    gp = cls(g, s)
    for v in range(g.V):
        s_path = '-'.join([str(i) for i in gp.path_to(v)])
        if not s_path:
            s_path = "not connected"
        print("%d to %d: %s" % (s, v, s_path))


if __name__ == '__main__':
    import sys
    f = open(sys.argv[1])
    s = int(sys.argv[2])
    g = graph_from_file(f)
    for cls in DepthFirstPaths, BreadthFirstPaths:
        print cls
        test_path(cls, g, s)
Beispiel #5
0
            edge.get_connected_vertex(vertex) for edge in g.get_edges(vertex)
        ]
        objective_function += "+s_{}".format(vertex)
        list_of_binary_variables += " s_{},".format(vertex)
        attacker_indicator += "a_{} + s_{} = 1;\n".format(vertex, vertex)
        if vertex in starting_set:
            stalemate_contains_starting_set += "+s_{}".format(vertex)

# avoids making attacking regions also defend
        stalemate_condition += "+{}*a_{}".format(N, vertex)

        for n in neighbors:
            one_defender_condition += "+d_{}_{}".format(vertex, n)
            list_of_binary_variables += " d_{}_{},".format(vertex, n)
            stalemate_condition += "+d_{}_{} - a_{}".format(n, vertex, n)

        one_defender_condition += "+d_{}_{}-s_{}=0;\n".format(
            vertex, vertex, vertex)
        stalemate_condition += ">= 0;\n"
    objective_function += ";\n"
    stalemate_contains_starting_set += "= {};\n".format(M)

    return objective_function + attacker_indicator + one_defender_condition + stalemate_contains_starting_set + stalemate_condition + list_of_binary_variables[:
                                                                                                                                                               -1] + ";"

if __name__ == '__main__':
    g = graph_from_file("Diplomacy.g")
    s = stalemate_lines(g, {"Moscow", "Sevastopol"})
    with open("test_output.txt", "w") as f:
        f.write(s)
    return True


def is_bipartite_dfs(g):
    colors = {}
    for label in g.keys():
        if label not in colors:
            if not is_bipartite_dfs_helper(g, label, True, colors):
                return False
    return True


def is_bipartite_dfs_helper(g, label, color, colors):
    if label in colors:
        if colors[label] != color:
            return False
    else:
        colors[label] = color
        neighbors = g[label]
        for neighbor in neighbors:
            if not is_bipartite_dfs_helper(g, neighbor, not color, colors):
                return False
    return True


if __name__ == "__main__":
    print(is_bipartite_bfs(graph_from_file("input/sample1.txt")))
    print(is_bipartite_bfs(graph_from_file("input/sample2.txt")))
    print(is_bipartite_bfs(graph_from_file("input/sample3.txt")))
    print(is_bipartite_bfs(graph_from_file("input/sample4.txt")))
Beispiel #7
0
                 https://algs4.cs.princeton.edu/41graph/mediumDG.txt
                 https://algs4.cs.princeton.edu/41graph/largeDG.txt

   A graph, implemented using an array of sets.
   Parallel edges and self-loops are permitted.

   % python digraph.py tinyDG.txt
 """
from graph import Graph, graph_from_file


class Digraph(Graph):
    def add_edge(self, v, w):
        v, w = int(v), int(w)
        self.adj[v].add(w)
        self.E += 1

    def reverse(self):
        R = Digraph(self.V)
        for v in range(len(self.V)):
            for w in self.adj[v]:
                R.add_edge(w, v)
        return R


if __name__ == '__main__':
    import sys
    f = open(sys.argv[1])
    g = graph_from_file(f, Digraph)
    print(g)
Beispiel #8
0
                if state == names[v][-2:]:
                    color = "#{:02d}{:02d}{:02d}".format(
                        floor((count / 13) * 100) % 99, count * 2 % 100,
                        floor((count / 5) * 100) % 100)
                    state_[v] = color
            line = file.readline()
            count += 1
    return state_


if __name__ == "__main__":
    output_size = (595, 842)
    screen_output_size = (1500, 800)

    counties, counties_props = graph_from_file(
        "counties.txt", False, (PropertyType.Vertex, "string"),
        (PropertyType.Vertex, "float"), (PropertyType.Vertex, "vector<float>"))
    county_name_ = counties_props[0]
    county_fips_ = counties_props[1]
    county_pos_ = counties_props[2]
    edges_from_file(counties, "county_adjacency.txt", county_fips_)
    counties_lower = lower48(counties, county_name_)
    county_state = color_by_state(counties, county_name_)

    # graph_draw(counties, pos=county_pos_,output_size=output_size,vertex_fill_color=county_state, vertex_size=1.5, output="pdfs/counties_color_coded.pdf")
    # graph_draw(counties, pos=county_pos_,output_size=screen_output_size,vertex_fill_color=county_state, vertex_size=1.5)
    # graph_draw(counties_lower, pos=county_pos_,output_size=output_size,vertex_fill_color=county_state, vertex_size=3, output="pdfs/counties_lower48_color_coded.pdf")

    # graph_draw(counties, pos=county_pos_,output_size=output_size, vertex_size=1, output="pdfs/counties.pdf")
    # graph_draw(counties_lower, pos=county_pos_,output_size=output_size, vertex_size=1.5, output="pdfs/counties_lower48.pdf")