Beispiel #1
0
    def test_create_using_keyword_arguments(self):
        assert_raises(nx.NetworkXError, gn_graph, 100, create_using=Graph())
        assert_raises(nx.NetworkXError,
                      gnr_graph,
                      100,
                      0.5,
                      create_using=Graph())
        assert_raises(nx.NetworkXError, gnc_graph, 100, create_using=Graph())
        assert_raises(nx.NetworkXError,
                      scale_free_graph,
                      100,
                      create_using=Graph())
        G = gn_graph(100, seed=1)
        MG = gn_graph(100, create_using=MultiDiGraph(), seed=1)
        assert_equal(sorted(G.edges()), sorted(MG.edges()))
        G = gnr_graph(100, 0.5, seed=1)
        MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1)
        assert_equal(sorted(G.edges()), sorted(MG.edges()))
        G = gnc_graph(100, seed=1)
        MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1)
        assert_equal(sorted(G.edges()), sorted(MG.edges()))

        G = scale_free_graph(100,
                             alpha=0.3,
                             beta=0.4,
                             gamma=0.3,
                             delta_in=0.3,
                             delta_out=0.1,
                             create_using=MultiDiGraph,
                             seed=1)
        assert_raises(ValueError, scale_free_graph, 100, 0.5, 0.4, 0.3)
        assert_raises(ValueError, scale_free_graph, 100, alpha=-0.3)
        assert_raises(ValueError, scale_free_graph, 100, beta=-0.3)
        assert_raises(ValueError, scale_free_graph, 100, gamma=-0.3)
Beispiel #2
0
 def test_create_using_keyword_arguments(self):
     assert_raises(networkx.exception.NetworkXError,
                   gn_graph,
                   100,
                   create_using=Graph())
     assert_raises(networkx.exception.NetworkXError,
                   gnr_graph,
                   100,
                   0.5,
                   create_using=Graph())
     assert_raises(networkx.exception.NetworkXError,
                   gnc_graph,
                   100,
                   create_using=Graph())
     assert_raises(networkx.exception.NetworkXError,
                   scale_free_graph,
                   100,
                   create_using=Graph())
     G = gn_graph(100, seed=1)
     MG = gn_graph(100, create_using=MultiDiGraph(), seed=1)
     assert_equal(sorted(G.edges()), sorted(MG.edges()))
     G = gnr_graph(100, 0.5, seed=1)
     MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1)
     assert_equal(sorted(G.edges()), sorted(MG.edges()))
     G = gnc_graph(100, seed=1)
     MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1)
     assert_equal(sorted(G.edges()), sorted(MG.edges()))
Beispiel #3
0
def add_node(g: Graph, node):
    # zones are used to prevent cyclies
    if not node['role']:
        g.add_node(node['name'], **node_attrs(type='zone'))

    # if you do not supply a zone, the node is interpreted as being a machine
    # the role is attached as tag to the AWS instance and can be used to run
    # tasks only on machines with a certain role (see mockfog_application.yml notebook)
    else:
        g.add_node(node['name'], **node_attrs(role=node.get('role', None), flavor=node.get('flavor', None), image=node.get('image', None)))
def order_influencers(g: Graph, n=5):
    '''
        Takes a networkx graph object and returns the n most connected vertices.
        In a social network, these would be the most influential accounts.
    '''
    influencers = {}
    for account in g.get_vertices():
        influencers[account] = len(g.get_vertex(account).get_neighbors())

    influencers = Counter(influencers)
    return influencers.most_common(n)
def simple_topology(g: Graph):
    # zones are used to prevent cyclies
    g.add_node('cloud1', **node_attrs(type='zone'))

    # if you do not supply a zone, the node is interpreted as being a machine
    # the role is attached as tag to the AWS instance and can be used to run tasks only on machines with a certain role (see mockfog_application.yml notebook)
    g.add_node('cloud1_broker1', **node_attrs(role='broker'))
    g.add_node('cloud1_client1', **node_attrs(role='client'))
    g.add_node('cloud1_client2', **node_attrs(role='client'))

    g.add_edge('cloud1_broker1', 'cloud1', **edge_attrs(delay=4))
    g.add_edge('cloud1_client1', 'cloud1', **edge_attrs(delay=2))
    g.add_edge('cloud1_client2', 'cloud1', **edge_attrs(delay=2))
Beispiel #6
0
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.g = grid_2d_graph(width, height)

        for node, node_data in self.g.nodes(data=True):
            node_data['barrier'] = False
        for src, dst, edge_data in self.g.edges(data=True):
            edge_data['weight'] = min_int

        self.walls = set()
        self.boxes = set()
        self.bombs = {}  # mapping from bomb to rounds

        self.players = set()
        self.enemies = set()

        self.boost_remain = 0
        self.boost_renew = 0

        max_radius = distance((0, 0), (self.width-1, self.height-1))

        self.in_boost_sequence = [False] * max_radius

        self.radii = range(0, max_radius)

        self.points = list(product(range(self.width), range(self.height)))

        self.point_bomb_rounds = {p: max_int for p in self.points}

        self.bomb_ranges_graph = Graph()
        self.bomb_ranges_sub_graphs = connected_components(self.bomb_ranges_graph)
Beispiel #7
0
def empty_graph(n=0, create_using=None):
    """Return the empty graph with n nodes and zero edges.

    Parameters
    ==========
    n : int or iterable container of nodes (default = 0)
        If n is an integer, nodes are from `range(n)`.
        If n is a container of nodes, those nodes appear in the graph.
    create_using : Graph, optional (default Graph())
        If provided this graph is cleared of nodes and edges and filled
        with the new graph. Usually used to set the type of the graph.

    For example:
    >>> G = nx.empty_graph(10)
    >>> G.number_of_nodes()
    10
    >>> G.number_of_edges()
    0
    >>> G = nx.empty_graph("ABC")
    >>> G.number_of_nodes()
    3
    >>> sorted(G)
    ['A', 'B', 'C']

    Notes
    =====
    The variable create_using should point to a "graph"-like object that
    will be cleared (nodes and edges will be removed) and refitted as
    an empty "graph" with nodes specified in n. This capability
    is useful for specifying the class-nature of the resulting empty
    "graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).

    The variable create_using has two main uses:
    Firstly, the variable create_using can be used to create an
    empty digraph, multigraph, etc.  For example,

    >>> n = 10
    >>> G = nx.empty_graph(n, create_using=nx.DiGraph())

    will create an empty digraph on n nodes.

    Secondly, one can pass an existing graph (digraph, multigraph,
    etc.) via create_using. For example, if G is an existing graph
    (resp. digraph, multigraph, etc.), then empty_graph(n, create_using=G)
    will empty G (i.e. delete all nodes and edges using G.clear())
    and then add n nodes and zero edges, and return the modified graph.

    See also create_empty_copy(G).

    """
    if create_using is None:
        # default empty graph is a simple graph
        G = Graph()
    else:
        G = create_using
        G.clear()

    n_name, nodes = n
    G.add_nodes_from(nodes)
    return G
def make_graph():
    g = Graph()
    accounts = listdir(DATA_PATH)

    for account in accounts:
        g.add_node(account)

    direct_connections = open(
        '../data/instagram/ikeybenz/connections.txt').read().splitlines()
    for connection in direct_connections:
        g.add_edge('ikeybenz', connection)
        g.add_edge(connection, 'ikeybenz')

    for account in accounts:
        try:  # Some connections have no mutual followers with me
            mutual_followers_of_account = open(
                f'{DATA_PATH}/{account}/mutuals_with_ikeybenz.txt').read().splitlines()
        except:  # In that case, skip current account
            continue

        for follower in mutual_followers_of_account:
            g.add_edge(follower, account)

    return g
def reference_topology_bridge(g: Graph):
    # Cloud nodes
    g.add_node('cloud1', **node_attrs(type='zone'))
    g.add_node(
        'cloud1_client1',
        **node_attrs(role='client',
                     client_config=[
                         pub_config(
                             connect_to='cloud1_broker1',
                             topic='/push-infos/road-conditions',
                             frequency=5,
                             payload_size=10000,
                         ),
                         sub_config(
                             connect_to='cloud1_broker1',
                             topic='/car-telemetry/aggregated/#',
                         ),
                         sub_config(
                             connect_to='cloud1_broker1',
                             topic='/traffic-control/camera-feed/#',
                         ),
                     ]))
    g.add_node('cloud1_broker1', **node_attrs(role='broker',
                                              flavor='t3.small'))
    # Edge zone #1
    g.add_node('edge1', **node_attrs(type='zone'))
    g.add_node(
        'edge1_client1',
        **node_attrs(role='client',
                     client_config=[
                         pub_config(
                             connect_to='edge1_broker1',
                             topic='/traffic-control/camera-feed/1',
                             frequency=20,
                             payload_size=500000,
                         ),
                     ]))
    g.add_node(
        'edge1_client2',
        **node_attrs(role='client',
                     client_config=[
                         sub_config(
                             connect_to='edge1_broker2',
                             topic='/car-telemetry/realtime/3',
                         ),
                         sub_config(
                             connect_to='edge1_broker2',
                             topic='/car-telemetry/realtime/4',
                         ),
                         pub_config(
                             connect_to='edge1_broker2',
                             topic='/car-telemetry/aggregated/2',
                             frequency=5,
                             payload_size=4000,
                         ),
                         pub_config(
                             connect_to='edge1_broker2',
                             topic='/car-telemetry/realtime/2',
                             frequency=100,
                             payload_size=200,
                         ),
                     ]))
    g.add_node(
        'edge1_client3',
        **node_attrs(role='client',
                     client_config=[
                         sub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/realtime/2',
                         ),
                         sub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/realtime/4',
                         ),
                         pub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/aggregated/3',
                             frequency=5,
                             payload_size=4000,
                         ),
                         pub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/realtime/3',
                             frequency=100,
                             payload_size=200,
                         ),
                     ]))
    g.add_node(
        'edge1_client4',
        **node_attrs(role='client',
                     client_config=[
                         sub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/realtime/2',
                         ),
                         sub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/realtime/3',
                         ),
                         pub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/aggregated/4',
                             frequency=5,
                             payload_size=4000,
                         ),
                         pub_config(
                             connect_to='edge1_broker3',
                             topic='/car-telemetry/realtime/4',
                             frequency=100,
                             payload_size=200,
                         ),
                     ]))
    g.add_node('edge1_broker1', **node_attrs(role='broker', flavor='t3.small'))
    g.add_node('edge1_broker2', **node_attrs(role='broker', flavor='t3.small'))
    g.add_node('edge1_broker3', **node_attrs(role='broker', flavor='t3.small'))

    # Connect cloud
    g.add_edge('cloud1_broker1', 'cloud1', **edge_attrs(delay=2))
    g.add_edge('cloud1_client1', 'cloud1', **edge_attrs(delay=2))
    # Connect edge #1
    g.add_edge('edge1_client1', 'edge1_broker1', **edge_attrs(delay=2))
    g.add_edge('edge1_client2', 'edge1_broker2', **edge_attrs(delay=2))
    g.add_edge('edge1_client3', 'edge1_broker3', **edge_attrs(delay=2))
    g.add_edge('edge1_client4', 'edge1_broker3', **edge_attrs(delay=2))
    g.add_edge('edge1_broker1', 'edge1_broker2', **edge_attrs(delay=2))
    g.add_edge('edge1_broker2', 'edge1_broker3', **edge_attrs(delay=2))
    g.add_edge('edge1', 'edge1_broker1', **edge_attrs())

    # Connect to cloud
    g.add_edge('edge1', 'cloud1', **edge_attrs(delay=20))
Beispiel #10
0
def complete_multipartite_graph(*subset_sizes):
    """Returns the complete multipartite graph with the specified subset sizes.

    Parameters
    ----------
    subset_sizes : tuple of integers or tuple of node iterables
       The arguments can either all be integer number of nodes or they
       can all be iterables of nodes. If integers, they represent the
       number of vertices in each subset of the multipartite graph.
       If iterables, each is used to create the nodes for that subset.
       The length of subset_sizes is the number of subsets.

    Returns
    -------
    G : NetworkX Graph
       Returns the complete multipartite graph with the specified subsets.

       For each node, the node attribute 'subset' is an integer
       indicating which subset contains the node.

    Examples
    --------
    Creating a complete tripartite graph, with subsets of one, two, and three
    vertices, respectively.

        >>> import networkx as nx
        >>> G = nx.complete_multipartite_graph(1, 2, 3)
        >>> [G.nodes[u]['subset'] for u in G]
        [0, 1, 1, 2, 2, 2]
        >>> list(G.edges(0))
        [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
        >>> list(G.edges(2))
        [(2, 0), (2, 3), (2, 4), (2, 5)]
        >>> list(G.edges(4))
        [(4, 0), (4, 1), (4, 2)]

        >>> G = nx.complete_multipartite_graph('a', 'bc', 'def')
        >>> [G.nodes[u]['subset'] for u in sorted(G)]
        [0, 1, 1, 2, 2, 2]

    Notes
    -----
    This function generalizes several other graph generator functions.

    - If no subset sizes are given, this returns the null graph.
    - If a single subset size `n` is given, this returns the empty graph on
      `n` nodes.
    - If two subset sizes `m` and `n` are given, this returns the complete
      bipartite graph on `m + n` nodes.
    - If subset sizes `1` and `n` are given, this returns the star graph on
      `n + 1` nodes.

    See also
    --------
    complete_bipartite_graph
    """
    # The complete multipartite graph is an undirected simple graph.
    G = Graph()

    if len(subset_sizes) == 0:
        return G

    # set up subsets of nodes
    try:
        extents = pairwise(accumulate((0,) + subset_sizes))
        subsets = [range(start, end) for start, end in extents]
    except TypeError:
        subsets = subset_sizes

    # add nodes with subset attribute
    # while checking that ints are not mixed with iterables
    try:
        for (i, subset) in enumerate(subsets):
            G.add_nodes_from(subset, subset=i)
    except TypeError:
        raise NetworkXError("Arguments must be all ints or all iterables")

    # Across subsets, all vertices should be adjacent.
    # We can use itertools.combinations() because undirected.
    for subset1, subset2 in itertools.combinations(subsets, 2):
        G.add_edges_from(itertools.product(subset1, subset2))
    return G
def debug_topology(g: Graph):
    # Cloud zone #1
    g.add_node('cloud1', **node_attrs(type='zone'))

    g.add_node('cloud1_broker1', **node_attrs(role='broker'))
    g.add_node(
        'cloud1_client1',
        **node_attrs(role='client',
                     client_config=[
                         pub_config(connect_to='cloud1_broker1',
                                    topic='topic1',
                                    frequency=100),
                         pub_config(connect_to='cloud1_broker1',
                                    topic='topic2',
                                    frequency=10,
                                    payload_size=2000)
                     ]))
    g.add_node(
        'cloud1_client2',
        **node_attrs(role='client',
                     client_config=[
                         sub_config(connect_to='cloud1_broker1',
                                    topic='topic1'),
                         sub_config(connect_to='cloud1_broker1',
                                    topic='topic2')
                     ]))

    g.add_edge('cloud1_broker1', 'cloud1', **edge_attrs(delay=2))
    g.add_edge('cloud1_client1', 'cloud1', **edge_attrs(delay=2))
    g.add_edge('cloud1_client2', 'cloud1', **edge_attrs(delay=2))
Beispiel #12
0
def complete_multipartite_graph(*subset_sizes):
    """Returns the complete multipartite graph with the specified subset sizes.

    Parameters
    ----------
    subset_sizes : tuple of integers or tuple of node iterables
       The arguments can either all be integer number of nodes or they
       can all be iterables of nodes. If integers, they represent the
       number of vertices in each subset of the multipartite graph.
       If iterables, each is used to create the nodes for that subset.
       The length of subset_sizes is the number of subsets.

    Returns
    -------
    G : NetworkX Graph
       Returns the complete multipartite graph with the specified subsets.

       For each node, the node attribute 'subset' is an integer
       indicating which subset contains the node.

    Examples
    --------
    Creating a complete tripartite graph, with subsets of one, two, and three
    vertices, respectively.

        >>> import networkx as nx
        >>> G = nx.complete_multipartite_graph(1, 2, 3)
        >>> [G.nodes[u]['subset'] for u in G]
        [0, 1, 1, 2, 2, 2]
        >>> list(G.edges(0))
        [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
        >>> list(G.edges(2))
        [(2, 0), (2, 3), (2, 4), (2, 5)]
        >>> list(G.edges(4))
        [(4, 0), (4, 1), (4, 2)]

        >>> G = nx.complete_multipartite_graph('a', 'bc', 'def')
        >>> [G.nodes[u]['subset'] for u in sorted(G)]
        [0, 1, 1, 2, 2, 2]

    Notes
    -----
    This function generalizes several other graph generator functions.

    - If no subset sizes are given, this returns the null graph.
    - If a single subset size `n` is given, this returns the empty graph on
      `n` nodes.
    - If two subset sizes `m` and `n` are given, this returns the complete
      bipartite graph on `m + n` nodes.
    - If subset sizes `1` and `n` are given, this returns the star graph on
      `n + 1` nodes.

    See also
    --------
    complete_bipartite_graph
    """
    # The complete multipartite graph is an undirected simple graph.
    G = Graph()

    if len(subset_sizes) == 0:
        return G

    # set up subsets of nodes
    try:
        extents = pairwise(accumulate((0, ) + subset_sizes))
        subsets = [range(start, end) for start, end in extents]
    except TypeError:
        subsets = subset_sizes

    # add nodes with subset attribute
    # while checking that ints are not mixed with iterables
    try:
        for (i, subset) in enumerate(subsets):
            G.add_nodes_from(subset, subset=i)
    except TypeError:
        raise NetworkXError("Arguments must be all ints or all iterables")

    # Across subsets, all vertices should be adjacent.
    # We can use itertools.combinations() because undirected.
    for subset1, subset2 in itertools.combinations(subsets, 2):
        G.add_edges_from(itertools.product(subset1, subset2))
    return G
Beispiel #13
0
def hexagonal_lattice_graph(m,
                            n,
                            periodic=False,
                            with_positions=True,
                            create_using=None):
    """Returns an `m` by `n` hexagonal lattice graph.

    The *hexagonal lattice graph* is a graph whose nodes and edges are
    the `hexagonal tiling`_ of the plane.

    The returned graph will have `m` rows and `n` columns of hexagons.
    `Odd numbered columns`_ are shifted up relative to even numbered columns.

    Positions of nodes are computed by default or `with_positions is True`.
    Node positions creating the standard embedding in the plane
    with sidelength 1 and are stored in the node attribute 'pos'.
    `pos = nx.get_node_attributes(G, 'pos')` creates a dict ready for drawing.

    .. _hexagonal tiling: https://en.wikipedia.org/wiki/Hexagonal_tiling
    .. _Odd numbered columns: http://www-cs-students.stanford.edu/~amitp/game-programming/grids/

    Parameters
    ----------
    m : int
        The number of rows of hexagons in the lattice.

    n : int
        The number of columns of hexagons in the lattice.

    periodic : bool
        Whether to make a periodic grid by joining the boundary vertices.
        For this to work `n` must be odd and both `n > 1` and `m > 1`.
        The periodic connections create another row and column of hexagons
        so these graphs have fewer nodes as boundary nodes are identified.

    with_positions : bool (default: True)
        Store the coordinates of each node in the graph node attribute 'pos'.
        The coordinates provide a lattice with vertical columns of hexagons
        offset to interleave and cover the plane.
        Periodic positions shift the nodes vertically in a nonlinear way so
        the edges don't overlap so much.

    create_using : NetworkX graph
        If specified, this must be an instance of a NetworkX graph
        class. It will be cleared of nodes and edges and filled
        with the new graph. Usually used to set the type of the graph.
        If graph is directed, edges will point up or right.

    Returns
    -------
    NetworkX graph
        The *m* by *n* hexagonal lattice graph.
    """
    G = create_using if create_using is not None else Graph()
    G.clear()
    if m == 0 or n == 0:
        return G
    if periodic and (n % 2 == 1 or m < 2 or n < 2):
        msg = "periodic hexagonal lattice needs m > 1, n > 1 and even n"
        raise NetworkXError(msg)

    M = 2 * m  # twice as many nodes as hexagons vertically
    rows = range(M + 2)
    cols = range(n + 1)
    # make lattice
    col_edges = (((i, j), (i, j + 1)) for i in cols for j in rows[:M + 1])
    row_edges = (((i, j), (i + 1, j)) for i in cols[:n] for j in rows
                 if i % 2 == j % 2)
    G.add_edges_from(col_edges)
    G.add_edges_from(row_edges)
    # Remove corner nodes with one edge
    G.remove_node((0, M + 1))
    G.remove_node((n, (M + 1) * (n % 2)))

    # identify boundary nodes if periodic
    if periodic:
        for i in cols[:n]:
            G = contracted_nodes(G, (i, 0), (i, M))
        for i in cols[1:]:
            G = contracted_nodes(G, (i, 1), (i, M + 1))
        for j in rows[1:M]:
            G = contracted_nodes(G, (0, j), (n, j))
        G.remove_node((n, M))

    # calc position in embedded space
    ii = (i for i in cols for j in rows)
    jj = (j for i in cols for j in rows)
    xx = (0.5 + i + i // 2 + (j % 2) * ((i % 2) - .5) for i in cols
          for j in rows)
    h = sqrt(3) / 2
    if periodic:
        yy = (h * j + .01 * i * i for i in cols for j in rows)
    else:
        yy = (h * j for i in cols for j in rows)
    # exclude nodes not in G
    pos = {(i, j): (x, y) for i, j, x, y in zip(ii, jj, xx, yy) if (i, j) in G}
    set_node_attributes(G, pos, 'pos')
    return G
Beispiel #14
0
def bomb_range_graph(u):
    x, y = u
    g = Graph()
    g.add_path([(x-2, y), (x-1, y), (x, y), (x+1, y), (x+2, y)])
    g.add_path([(x, y-2), (x, y-1), (x, y), (x, y+1), (x, y+2)])
    return g
Beispiel #15
0
class Map(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.g = grid_2d_graph(width, height)

        for node, node_data in self.g.nodes(data=True):
            node_data['barrier'] = False
        for src, dst, edge_data in self.g.edges(data=True):
            edge_data['weight'] = min_int

        self.walls = set()
        self.boxes = set()
        self.bombs = {}  # mapping from bomb to rounds

        self.players = set()
        self.enemies = set()

        self.boost_remain = 0
        self.boost_renew = 0

        max_radius = distance((0, 0), (self.width-1, self.height-1))

        self.in_boost_sequence = [False] * max_radius

        self.radii = range(0, max_radius)

        self.points = list(product(range(self.width), range(self.height)))

        self.point_bomb_rounds = {p: max_int for p in self.points}

        self.bomb_ranges_graph = Graph()
        self.bomb_ranges_sub_graphs = connected_components(self.bomb_ranges_graph)

    def set_barrier(self, point):
        self.g.node[point]['barrier'] = True
        for neighbor, edge_data in self.g[point].items():
            edge_data['weight'] = max_int

    def clear_barrier(self, point):
        self.g.node[point]['barrier'] = False
        for neighbor, edge_data in self.g[point].items():
            if not self.g.node[neighbor]['barrier']:
                edge_data['weight'] = min_int

    def is_barrier(self, u):
        return self.g.node[u]['barrier']

    def reset(self):
        for box in self.boxes:
            self.clear_barrier(box)
        for bomb in self.bombs:
            self.clear_barrier(bomb)
        self.boxes.clear()
        self.bombs.clear()

        self.players.clear()
        self.enemies.clear()

        self.point_bomb_rounds = {p: max_int for p in self.points}

        self.bomb_ranges_graph.clear()

    def add_wall(self, u):
        self.set_barrier(u)
        self.walls.add(u)

    def add_box(self, u):
        self.set_barrier(u)
        self.boxes.add(u)

    def remove_box(self, u):
        # self.clear_barrier(u)
        self.boxes.remove(u)

    def add_bomb(self, u, rounds, update=False):
        self.set_barrier(u)
        self.bombs[u] = rounds
        self.bomb_ranges_graph.add_edges_from(bomb_range_graph(u).edges())
        if update:
            self.update_bomb_rounds()

    def remove_bomb(self, u):
        self.clear_barrier(u)
        del self.bombs[u]
        self.bomb_ranges_graph.remove_edges_from(bomb_range_graph(u).edges())
        self.update_bomb_rounds()

    def update_bomb_rounds(self):
        self.bomb_ranges_sub_graphs = connected_components(self.bomb_ranges_graph)
        for sub_graph in self.bomb_ranges_sub_graphs:
            rounds = max_int
            for n in sub_graph:
                if n in self.bombs and self.bombs[n] < rounds:
                    rounds = self.bombs[n]
            for n in sub_graph:
                self.point_bomb_rounds[n] = rounds

    def is_safe(self, u, rounds):
        return self.point_bomb_rounds[u] != rounds

    def add_player(self, u):
        self.players.add(u)

    def add_enemy(self, u):
        self.enemies.add(u)

    def update_boost(self, boost_remain, boost_renew):
        self.boost_remain = boost_remain
        self.boost_renew = boost_renew
        if boost_remain:
            self.in_boost_sequence[:boost_remain] = [True] * boost_remain
            of = boost_remain
            cycles = cycle([False] * boost_renew_rounds + [True] * boost_remain_rounds)
        else:
            self.in_boost_sequence[:boost_renew] = [False] * boost_renew
            of = boost_renew
            cycles = cycle([True] * boost_remain_rounds + [False] * boost_renew_rounds)
        for i, c in enumerate(cycles):
            if of + i >= len(self.in_boost_sequence):
                break
            self.in_boost_sequence[of + i] = c
        log.debug('in_boost_sequence: %s' % self.in_boost_sequence)

    def is_boost(self):
        return self.in_boost_sequence[0]

    def update(self):
        self.update_bomb_rounds()

    def barriers(self):
        return self.walls.union(self.boxes, self.bombs)

    def path_len(self, path):
        for p in path[1:-1]:
            if self.g.node[p]['barrier']:
                return max_int
        return len(path) - 1

    def shortest_path_and_len(self, src, dst):
        path = dijkstra_path(self.g, src, dst, 'weight')
        path_len = self.path_len(path)
        if path_len >= max_int:
            return None, None
        log.debug('path_len: %s, path: %s' % (path_len, path))
        return path, path_len

    def offset_points(self, u, offsets):
        points = []
        x, y = u
        for i, j in offsets:
            xn, yn = x + i, y + j
            if pre_origin < xn < self.width and pre_origin < yn < self.height:
                points.append((xn, yn))
        return points

    def step_points(self, u, step):
        return self.offset_points(u, find_steps_offsets(step))

    def bomb_range(self, u):
        points = self.offset_points(u, bomb_range_offsets)
        log.debug('bomb_range, range = %s' % points)
        return points

    def places_after_bury(self, u, boost=False):
        return self.offset_points(u, walk_offsets) if boost else self.offset_points(u, walk_one_offsets)

    def find_box_path(self, u):
        # one_step_enemies = [e for e in self.enemies if e in self.offset_points(u, walk_one_offsets)]
        # two_step_enemies = [e for e in self.enemies if e in self.offset_points(u, walk_two_offsets)]
        # log.debug('self.boxes: %s' % self.boxes)
        for step in self.radii:
            path = None
            path_len = max_int
            for v in self.step_points(u, step):
                # log.debug(str(v))
                if v in (self.boxes or self.enemies):
                    p, pl = self.shortest_path_and_len(u, v)
                    if p:  # path found
                        if pl >= 3:  # two or more steps
                            log.debug('is_boost')
                            if self.is_boost():
                                log.debug('is_boost')
                                if not self.is_safe(p[2], 1):  # bomb with rounds 1
                                    log.debug('is_boost: %s, %s' % (p[2], self.point_bomb_rounds[u]))
                                    continue
                                if p[1] in self.enemies or p[2] in self.enemies:  # has enemy
                                    log.debug('is_boost: %s, %s' % (p[1], p[2]))
                                    continue
                            elif not self.is_safe(p[2], 2):  # bomb with rounds 2
                                continue
                        elif pl == 2:  # one step
                            if not self.is_safe(p[1], 1):  # bomb with rounds 1
                                continue
                            if p[1] in self.enemies:  # has enemy
                                continue
                        elif pl == 1:
                            if not self.is_safe(p[0], 1):
                                log.debug(str(self.point_bomb_rounds[p[0]]))
                                continue

                        if pl < path_len:
                            path = p
                            path_len = pl
            if path:
                self.remove_box(path[-1])
                return path[-1], path[1:-1]
        return None, None

    def find_enemy_path(self, u):
        return None, None

    def find_safe_path(self, u):
        if self.is_safe(u, 1) and self.is_safe(u, 2):
            return u, []

        if self.is_boost():
            steps = [1, 2]
        else:
            steps = [1]

        for step in steps:
            path = None
            path_len = max_int
            for v in self.step_points(u, step):
                if v in self.barriers():
                    continue
                #TODO: should not walk to neighborhood of enemy

                p, pl = self.shortest_path_and_len(u, v)
                if p:
                    if pl == 1:  # one step
                        if not self.is_safe(p[1], 1):
                            continue
                    elif pl == 2:  # two steps
                        if not self.is_safe(p[2], 1):
                            continue

                if pl < path_len:
                    path = p
                    path_len = pl
            if path:
                return path[-1], path[1:]

        return None, None

    def need_bomb(self, u, place_bomb=True):
        has_add_bomb = False
        for v in self.bomb_range(u):

            if v in self.players:
                if not has_add_bomb:
                    self.add_bomb(u, 3, True)
                    has_add_bomb = True
                if not self.is_safe(v, 1):
                    self.remove_bomb(u)
                    return False

            if (v in self.boxes or v in self.enemies) and center(u, v) not in self.walls.union(self.bombs):
                if not has_add_bomb and place_bomb:
                    self.add_bomb(u, 3, True)
                if has_add_bomb and not place_bomb:
                    self.remove_bomb(u)
                return True

        if has_add_bomb:
            self.remove_bomb(u)
        return False

    def need_bomb_b(self, u):
        for v in self.bomb_range(u):
            if v in self.players:
                return False
            if (v in self.boxes or v in self.enemies) and center(u, v) not in self.walls.union(self.bombs.keys()):
                return True
        return False

    def steps_places(self, u, steps, full=False):
        if steps == 2:
            steps_offsets = bomb_2steps_offsets
            if full:
                steps_offsets = twosteps_offsets
        else:
            steps_offsets = find_steps_offsets(steps)

        ps = []
        x, y = u
        for i, j in steps_offsets:
            xn = x + i
            yn = y + j
            if (pre_origin < xn < self.width) and (pre_origin < yn < self.height):
                ps.append((xn, yn))
        log.debug('steps_places: %s' % ps)
        return ps

    def hide_places(self, u, before=True):
        # if before:
        #     steps = 3
        # else:
        #     steps = 2
        ps = []
        barriers = self.walls.union(self.boxes, self.bombs.keys(), self.enemies)
        log.debug('hide_places: %s' % barriers)
        for steps in [3, 2, 1]:
            for v in self.steps_places(u, steps):
                if v not in barriers:
                    ps.append(v)
        return ps

    def is_safe_b(self, u, first=True, next_bomb=None):
        # for u in self.steps_places(u, 2):
        #     if u in self.bombs:
        #         return False
        # return True
        bomb_scope = []
        if next_bomb:
            bomb_scope = self.bomb_range(next_bomb)
        ps = self.bomb_range(u)
        log.debug('bombs: %s' % self.bombs)
        for p in chain(ps, bomb_scope):
            if p in self.bombs:
                rounds = self.bombs[p]
                if first and (rounds == 1 or (rounds == 2 and distance(u, p) == 1)):
                    return False
                if next_bomb and (p in bomb_scope or p in ps) and first and distance(u, next_bomb) == 1:
                    return False
                if not first and rounds in (1, 2):
                    return False
        return True

    def places(self, u, offsets):
        ps = []
        x, y = u
        for i, j in offsets:
            xn = x + i
            yn = y + j
            if pre_origin < xn < self.width and pre_origin < yn < self.height:
                ps.append((xn, yn))
        return ps

    def is_safe_for_others(self, u, others):
        barriers = self.walls.union(self.boxes, self.bombs.keys())
        barriers.add(u)
        ps = []
        for o in others:
            ps.append(o.cur)
            ps.append(o.last_want)
        for p in ps:
            places = self.places(p, onestep_offsets)
            if len([q for q in places if q in barriers]) == len(places):
                return False
            # if len([q for q in self.places(p, onestep_offsets) if q in barriers]) == 4:
            #     return False
        return True

    def safe_place(self, u, is_boost):
        bomb_list = []
        for v in self.bomb_range(u):
            if v in self.bombs:
                dis = distance(v, u)
                if dis == 2 and self.center(v, u) not in self.walls.union(self.boxes):
                    bomb_list.append(v)
                elif dis == 1:
                    bomb_list.append(v)
        if u in self.bombs:
            bomb_list.append(u)
        if not bomb_list:
            return u
        # if not [v for v in self.bomb_range(u) if v in self.bombs]:
        #     return u

        vs = []
        rounds = 0
        t = None
        barriers = self.walls.union(self.boxes, self.bombs.keys())
        log.debug('bombs: %s' % self.bombs)
        for steps in [1, 2]:
            for v in self.steps_places(u, steps, full=True):
                if v not in barriers:
                    vs.append(v)
                    if not [w for w in self.bomb_range(v) if w in self.bombs
                            and (distance(w, v) <= 2 or self.bombs[w] > steps)]:
                        places = self.places(v, onestep_offsets)
                        if len([q for q in places if q in barriers]) != len(places):
                            log.debug('safe_place: %s' % str(v))
                            return v
            log.debug('vs safe_place: %s' % vs)
            if steps == 1:
                b_num = max_int
                for r in vs:
                    has_bomb = False
                    places = self.places(r, onestep_offsets)
                    bs = len([q for q in places if q in barriers])
                    if bs == len(places):
                        log.debug('places: %s' % [([q for q in places if q in barriers]), places])
                        continue
                    # if bs < b_num:
                    #     b_num = bs
                    rs = max_int
                    for s in self.bomb_range(r):
                        if s in self.bombs:
                            has_bomb = True
                            # if self.bombs[s] > rounds:
                            if self.bombs[s] < rs:
                                rs = self.bombs[s]
                                # t = r
                                log.debug('bomb safe_place: %s' % [self.bombs[s], t])
                    log.debug('rs: %s, bs: %s' % (rs, bs))
                    if (rs != max_int and rs > rounds) or (rs != max_int and rs == rounds and bs > b_num):
                        log.debug('rs: %s, bs: %s' % (rs, bs))
                        rounds = rs
                        t = r
                        b_num = bs
                    if not has_bomb:
                        rounds = max_int
                        t = r
                        log.debug('bomb safe_place: %s' % str(t))
                if not is_boost and t:
                    return t
                del vs[:]
            elif is_boost:
                b_num = max_int
                for r in vs:
                    has_bomb = False
                    places = self.places(r, onestep_offsets)
                    bs = len([q for q in places if q in barriers])
                    if bs == len(places):
                        log.debug('places: %s' % [([q for q in places if q in barriers]), places])
                        continue
                    # if bs < b_num:
                    #     b_num = bs
                    rs = max_int
                    for s in self.bomb_range(r):
                        if s in self.bombs:
                            has_bomb = True
                            # if self.bombs[s] >= rounds:
                            if self.bombs[s] < rs:
                                rs = self.bombs[s]
                                # rounds = self.bombs[s]
                                # t = r
                                log.debug('bomb safe_place: %s' % [self.bombs[s], t])
                    log.debug('rs: %s, bs: %s' % (rs, bs))
                    if (rs != max_int and rs > rounds) or (rs != max_int and rs == rounds and bs > b_num):
                        log.debug('rs: %s, bs: %s' % (rs, bs))
                        rounds = rs
                        t = r
                        b_num = bs
                    if not has_bomb:
                        rounds = max_int
                        t = r
                        log.debug('bomb safe_place: %s' % str(t))
                if t:
                    return t

        log.error('safe_place error')
        return None
Beispiel #16
0
 def get_graph(self, word_len: int) -> Graph:
     """
     Get a graph by the word length
     """
     return self.graphs.get(word_len, Graph())
Beispiel #17
0
def simple_topology(g: Graph):
    # zones are used to prevent cyclies
    g.add_node('cloud1', **node_attrs(type='zone'))

    # if you do not supply a zone, the node is interpreted as being a machine
    # the role is attached as tag to the AWS instance and can be used to run tasks only on machines with a certain role (see mockfog_application.yml notebook)
    g.add_node(
        'cloud1_broker1',
        **node_attrs(
            role='broker',
            # there can be multiple app configs, if needed
            app_configs=[
                app_config(
                    # this automatically adds an internal_ip field to the output with the respective node ip
                    connect_to='cloud1_client1',
                    # you can define in commons whether fields are mandatory
                    timeout=10)
            ]))
    g.add_node(
        'cloud1_client1',
        **node_attrs(
            role='client',
            app_configs=[app_config(connect_to='cloud1_client2', timeout=10)]))
    g.add_node(
        'cloud1_client2',
        **node_attrs(
            role='client',
            app_configs=[app_config(connect_to='cloud1_client1', timeout=10)]))

    g.add_edge('cloud1_broker1', 'cloud1', **edge_attrs(delay=4))
    g.add_edge('cloud1_client1', 'cloud1', **edge_attrs(delay=2))
    g.add_edge('cloud1_client2', 'cloud1', **edge_attrs(delay=2))
Beispiel #18
0
def add_edge(g: Graph, edge):
    g.add_edge(edge['u_of_edge'], edge['v_of_edge'], **edge_attrs(delay=edge.get('delay', 0)))