Help build a random graph.

    :type result: networkx.Graph
    :type graph: networkx.Graph
549315
def _helper(result,
            graph,
            number_edges_remaining: int,
            node_blacklist: Set[BaseEntity],
            invert_degrees: Optional[bool] = None,
            ):
    
    original_node_count = graph.number_of_nodes()

    log.debug('adding remaining %d edges', number_edges_remaining)
    for _ in range(number_edges_remaining):

        source, possible_step_nodes, c = None, set(), 0
        while not source or not possible_step_nodes:
            source = get_random_node(result, node_blacklist, invert_degrees=invert_degrees)

            c += 1
            if c >= original_node_count:
                log.warning('infinite loop happening')
                log.warning('source: %s', source)
                log.warning('no grow: %s', node_blacklist)
                return  # Happens when after exhausting the connected components. Try increasing the number seed edges

            if source is None:
                continue  # maybe do something else?

            # Only keep targets in the original graph that aren't in the result graph
            possible_step_nodes = set(graph[source]) - set(result[source])

            if not possible_step_nodes:
                node_blacklist.add(
                    source)  # there aren't any possible nodes to step to, so try growing from somewhere else

        step_node = random.choice(list(possible_step_nodes))

        # it's not really a big deal which, but it might be possible to weight this by the utility of edges later
        key, attr_dict = random.choice(list(graph[source][step_node].items()))

        result.add_edge(source, step_node, key=key, **attr_dict)
746987
def get_random_node(graph,
                    node_blacklist: Set[BaseEntity],
                    invert_degrees: Optional[bool] = None,
                    ) -> Optional[BaseEntity]:
    
    try:
        nodes, degrees = zip(*(
            (node, degree)
            for node, degree in sorted(graph.degree(), key=itemgetter(1))
            if node not in node_blacklist
        ))
    except ValueError:  # something wrong with graph, probably no elements in graph.degree_iter
        return

    if invert_degrees is None or invert_degrees:
        # More likely to choose low degree nodes to explore, so don't make hubs
        degrees = [1 / degree for degree in degrees]

    wrg = WeightedRandomGenerator(nodes, degrees)
    return wrg.next()
1100357
def new_graph(self, graph, typ):
        """"""
        graph = self.pack(graph)
        return self.sql('new_graph', graph, typ)
595969
def to_networkx(graph):
    

    # import here so networkx is not always required.
    import networkx as nx

    nodes = graph["nodes"].keys()
    edges = [[start, end] for start, ends in graph["links"].items() for end in ends]

    g = nx.Graph()
    g.add_nodes_from(nodes)
    nx.set_node_attributes(g, dict(graph["nodes"]), "membership")

    g.add_edges_from(edges)

    return g
1368761
def _build_graph(self) -> nx.DiGraph:
        
        digraph = nx.DiGraph()
        for state in self.model.all_states():
            self._number_of_states += 1
            for next_state in self.model.available_state(state):
                self._number_of_transitions += 1
                digraph.add_edge(
                    self._transform_state_to_string(state),
                    self._transform_state_to_string(next_state)
                )
        return digraph
420645
def _buildGraph(self):
        
        for n in self.namespaces:
            self.rdflib_graph.bind(n[0], rdflib.Namespace(n[1]))
        if self.triples:
            for terzetto in self.triples:
                self.rdflib_graph.add(terzetto)
163003
def create_graph(grid):
    
    try:
        import numpy as np
    except ImportError:
        print(
            "NumPY is not installed. segraph needs NumPY to function. Please use 'pip install numpy' to install numpy.")
        exit(0)
    print("Creating a graph using segmented grid..")
    # get an array of unique labels
    try:
        vertices = np.unique(grid)

        # get number of vertices
        num_vertices = len(vertices)

        # map these unique labels to [1,...,N], where N is the number of labels (vertices)
        mapping = dict(zip(vertices, np.arange(num_vertices)))
        mapped_grid = np.array([mapping[x] for x in grid.flat]).reshape(grid.shape)

        # create edges, going left to right and top to bottom
        l2r = np.c_[mapped_grid[:, :-1].ravel(), mapped_grid[:, 1:].ravel()]
        t2b = np.c_[mapped_grid[:-1, :].ravel(), mapped_grid[1:, :].ravel()]

        # stack for entire graph
        edges = np.vstack([l2r, t2b])
        edges = edges[edges[:, 0] != edges[:, 1], :]
        edges = np.sort(edges, axis=1)

        # create a edge map, a hashmap
        edge_map = edges[:, 0] + num_vertices * edges[:, 1]

        # filter unique connections as edges
        edges = np.unique(edge_map)

        # reverse map and form edges as pairs
        edges = [[vertices[edge % num_vertices],
                  vertices[edge // num_vertices]] for edge in edges]
    except:
        print("Invalid argument supplied !")
        return None

    return vertices, edges
158167
def _neighbors_graph(self, **params) -> Dict:
        
        response = self._get_response("graph/neighbors", format="json", **params)
        return response.json()
611598
def run(self, graph):
        
        if not self:
            log.debug('no seeding, returning graph: %s', graph)
            return graph

        subgraphs = []

        for seed in self:
            seed_method, seed_data = seed[SEED_METHOD], seed[SEED_DATA]

            log.debug('seeding with %s: %s', seed_method, seed_data)
            subgraph = get_subgraph(graph, seed_method=seed_method, seed_data=seed_data)

            if subgraph is None:
                log.debug('seed returned empty graph: %s', seed)
                continue

            subgraphs.append(subgraph)

        if not subgraphs:
            log.debug('no subgraphs returned')
            return

        return union(subgraphs)
716458
def get_nx_graph(ea):
    """"""
    nx_graph = networkx.DiGraph()
    func = idaapi.get_func(ea)
    flowchart = FlowChart(func)
    for block in flowchart:
        # Make sure all nodes are added (including edge-less nodes)
        nx_graph.add_node(block.startEA)

        for pred in block.preds():
            nx_graph.add_edge(pred.startEA, block.startEA)
        for succ in block.succs():
            nx_graph.add_edge(block.startEA, succ.startEA)

    return nx_graph
444035
def add_graph(self, other):
        
        self.add_nodes( n for n in other.nodes() if not n in self.nodes() )
        
        for each_node in other.nodes():
            for each_edge in other.neighbors(each_node):
                if (not self.has_edge((each_node, each_edge))):
                    self.add_edge((each_node, each_edge))
533157
def random_connection(self):
        ''''''
        # While at the moment there's no need for this to be a context manager
        # per se, I would like to use that interface since I anticipate
        # adding some wrapping around it at some point.
        yield random.choice(
            [conn for conn in self.connections() if conn.alive()])
320241
def show_graph(cn_topo, showintfs=False, showaddrs=False):
    '''
     
    '''
    __do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)
    pyp.show()
1032041
def setup_random_indices_local_geometry(self, coordination):
        
        self.icentral_site = 0
        self.indices = list(range(1, coordination + 1))
        np.random.shuffle(self.indices)
1098899
def make_graph(node, inputs):
        
        initializer = []
        tensor_input_info = []
        tensor_output_info = []

        # Adding input tensor info.
        for index in range(len(node.input)):
            tensor_input_info.append(
                helper.make_tensor_value_info(str(node.input[index]), TensorProto.FLOAT, [1]))

            # Creating an initializer for Weight params.
            # Assumes that weight params is named as 'W'.
            # TODO: Handle multiple weight params.
            # TODO: Add for "bias" if needed
            if node.input[index] == 'W':
                dim = inputs[index].shape
                param_tensor = helper.make_tensor(
                    name=node.input[index],
                    data_type=TensorProto.FLOAT,
                    dims=dim,
                    vals=inputs[index].flatten())

                initializer.append(param_tensor)

        # Adding output tensor info.
        for index in range(len(node.output)):
            tensor_output_info.append(
                helper.make_tensor_value_info(str(node.output[index]), TensorProto.FLOAT, [1]))

        # creating graph proto object.
        graph_proto = helper.make_graph(
            [node],
            "test",
            tensor_input_info,
            tensor_output_info,
            initializer=initializer)

        return graph_proto
406742
def generate_network(user=None, reset=False):
    

    token = collect_token()

    try:
        gh = login(token=token)
        root_user = gh.user(user)
    except Exception, e:
        # Failed to login using the token, github3.models.GitHubError
        raise e

    graph_nodes = []
    graph_edges = []

    username = user if user is not None else root_user.login

    if not is_cached(username_to_file(username)) or reset:
        graph_nodes.append(username)

        # @TODO: take care of the 'rate limit exceeding' if imposed
        try:
            for person in gh.iter_following(username):
                graph_nodes.append(str(person))
                graph_edges.append((root_user.login, str(person)))

            for i in range(1, root_user.following):
                user = gh.user(graph_nodes[i])
                user_following_edges = [(user.login, str(person)) for person in gh.iter_following(
                    user) if str(person) in graph_nodes]
                graph_edges += user_following_edges
        except Exception, e:
            raise e

        generate_gml(username, graph_nodes, graph_edges, True)
    else:
        reuse_gml(username)

    return username
1348439
def build(self):
        ''''''
        # right now we do not worry about status of nodes
        # connecting the output to the input of other nodes
        #
        # NOTE: This is implemented in the least efficient way just for
        # testing. It has to be re-implemented.
        #
        # refer to http://stackoverflow.com/questions/33494376/networkx-add-edges-to-graph-from-node-attributes
        #
        # several cases triggers dependency.
        if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
            env.log_to_file('DAG', 'build DAG')
        for wf in range(self._forward_workflow_id + 1):
            indexed = [x for x in self.nodes() if x._wf_index == wf]
            indexed.sort(key=lambda x: x._node_index)

            for idx, node in enumerate(indexed):
                # 1. if a node changes context (using option alias), all later steps
                # has to rely on it.
                if node._context['__changed_vars__']:
                    for later_node in indexed[idx + 1:]:
                        if node._context['__changed_vars__'] & (
                                later_node._context['__signature_vars__']
                                | later_node._context['__environ_vars__']):
                            self.add_edge(node, later_node)

                # 2. if the input of a step is undetermined, it has to be executed
                # after all its previous steps.
                if not node._input_targets.valid() and idx > 0:
                    # if there is some input specified, it does not use default
                    # input, so the relationship can be further looked before
                    if node._input_targets.undetermined():
                        # if the input is dynamic, has to rely on previous step...
                        if 'dynamic' in node._context['__environ_vars__']:
                            self.add_edge(indexed[idx - 1], node)
                        else:
                            # otherwise let us look back.
                            for prev_node in indexed[idx - 1::-1]:
                                if node._context[
                                        '__environ_vars__'] & prev_node._context[
                                            '__changed_vars__']:
                                    self.add_edge(prev_node, node)
                    else:
                        self.add_edge(indexed[idx - 1], node)
        #
        # 3. if the input of a step depends on the output of another step
        for target, in_node in self._all_depends_files.items():
            if target not in self._all_output_files:
                continue
            # it is possible that multiple nodes satisfy the same target
            out_node = self._all_output_files[target]
            for i in in_node:
                for j in out_node:
                    if j != i:
                        self.add_edge(j, i)
        self.mark_dirty()