示例#1
0
文件: parsers.py 项目: emiapwil/fnss
def parse_ashiip(path):
    """
    Parse a topology from an output file generated by the aShiip topology
    generator

    Parameters
    ----------
    path : str
        The path to the aShiip output file

    Returns
    -------
    topology : Topology
    """
    topology = Topology(type='ashiip')

    for line in open(path, "r").readlines():
        # There is no documented aShiip format but we assume that if the line
        # does not start with a number it is not part of the topology
        if line[0].isdigit():
            node_ids = re.findall("\d+", line)
            if len(node_ids) < 3:
                raise ValueError('Invalid input file. Parsing failed while '\
                                 'trying to parse a line')
            node = int(node_ids[0])
            level = int(node_ids[1])
            topology.add_node(node, level=level)
            for i in range(2, len(node_ids)):
                topology.add_edge(node, int(node_ids[i]))
    return topology
示例#2
0
文件: mn.py 项目: wangxi0414/fnss
def from_mininet(topology):
    """Convert a Mininet topology to an FNSS one.
    
    Parameters
    ----------
    topology : Mininet Topo
        A Mininet topology object
    
    Returns
    -------
    topology : Topology
        An FNSS Topology object
    """
    fnss_topo = Topology(capacity_unit='Mbps')
    for v in topology.switches():
        fnss_topo.add_node(v, type='switch')
    for v in topology.hosts():
        fnss_topo.add_node(v, type='host')
    for u, v in topology.links():
        fnss_topo.add_edge(u, v)
        opts = topology.linkInfo(u, v)
        if 'bw' in opts:
            fnss_topo.edge[u][v]['capacity'] = opts['bw']
        if 'delay' in opts:
            delay = opts['delay']
            val = re.findall("\d+\.?\d*", delay)[0]
            unit = delay.strip(val).strip(' ')
            set_delays_constant(fnss_topo, val, unit, [(u,v)])
    return fnss_topo
示例#3
0
文件: parsers.py 项目: daisyhey/fnss
def parse_ashiip(path):
    """
    Parse a topology from an output file generated by the aShiip topology 
    generator
    
    Parameters
    ----------
    path : str
        The path to the aShiip output file
    
    Returns
    -------
    topology : Topology
    """
    topology = Topology(type='ashiip')
    
    for line in open(path, "r").readlines():
        # There is no documented aShiip format but we assume that if the line
        # does not start with a number it is not part of the topology
        if line[0].isdigit():
            node_ids = re.findall("\d+", line)
            if len(node_ids) < 3:
                raise ValueError('Invalid input file. Parsing failed while '\
                                 'trying to parse a line')
            node = int(node_ids[0])
            level = int(node_ids[1])
            topology.add_node(node, level=level)
            for i in range(2, len(node_ids)):
                topology.add_edge(node, int(node_ids[i]))
    return topology
示例#4
0
def extended_barabasi_albert_topology(n, m, m0, p, q, seed=None):
    r"""
    Return a random topology using the extended Barabasi-Albert preferential
    attachment model.

    Differently from the original Barabasi-Albert model, this model takes into
    account the presence of local events, such as the addition of new links or
    the rewiring of existing links.

    More precisely, the Barabasi-Albert topology is built as follows. First, a
    topology with *m0* isolated nodes is created. Then, at each step:
    with probability *p* add *m* new links between existing nodes, selected
    with probability:

    .. math::
        \Pi(i) = \frac{deg(i) + 1}{\sum_{v \in V} (deg(v) + 1)}

    with probability *q* rewire *m* links. Each link to be rewired is selected as
    follows: a node i is randomly selected and a link is randomly removed from
    it. The node i is then connected to a new node randomly selected with
    probability :math:`\Pi(i)`,
    with probability :math:`1-p-q` add a new node and attach it to m nodes of
    the existing topology selected with probability :math:`\Pi(i)`

    Repeat the previous step until the topology comprises n nodes in total.

    Parameters
    ----------
    n : int
        Number of nodes
    m : int
        Number of edges to attach from a new node to existing nodes
    m0 : int
        Number of edges initially attached to the network
    p : float
        The probability that new links are added
    q : float
        The probability that existing links are rewired
    seed : int, optional
        Seed for random number generator (default=None).

    Returns
    -------
    G : Topology

    References
    ----------
    .. [1] A. L. Barabasi and R. Albert "Topology of evolving networks: local
       events and universality", Physical Review Letters 85(24), 2000.
    """
    def calc_pi(G):
        """Calculate extended-BA Pi function for all nodes of the graph"""
        degree = G.degree()
        den = float(sum(degree.values()) + G.number_of_nodes())
        return {node: (degree[node] + 1) / den for node in G.nodes_iter()}

    # input parameters
    if n < 1 or m < 1 or m0 < 1:
        raise ValueError('n, m and m0 must be a positive integer')
    if m >= m0:
        raise ValueError('m must be <= m0')
    if n < m0:
        raise ValueError('n must be > m0')
    if p > 1 or p < 0:
        raise ValueError('p must be included between 0 and 1')
    if q > 1 or q < 0:
        raise ValueError('q must be included between 0 and 1')
    if p + q > 1:
        raise ValueError('p + q must be <= 1')
    if seed is not None:
        random.seed(seed)
    G = Topology(type='extended_ba')
    G.name = "ext_ba_topology(%d, %d, %d, %f, %f)" % (n, m, m0, p, q)
    # Step 1: Add m0 isolated nodes
    G.add_nodes_from(range(m0))

    while G.number_of_nodes() < n:
        pi = calc_pi(G)
        r = random.random()

        if r <= p:
            # add m new links with probability p
            n_nodes = G.number_of_nodes()
            n_edges = G.number_of_edges()
            max_n_edges = (n_nodes * (n_nodes - 1)) / 2
            if n_edges + m > max_n_edges:  # cannot add m links
                continue  # rewire or add nodes
            new_links = 0
            while new_links < m:
                u = random_from_pdf(pi)
                v = random_from_pdf(pi)
                if u is not v and not G.has_edge(u, v):
                    G.add_edge(u, v)
                    new_links += 1

        elif r > p and r <= p + q:
            # rewire m links with probability q
            rewired_links = 0
            while rewired_links < m:
                i = random.choice(G.nodes())  # pick up node randomly (uniform)
                if len(G.edge[i]) is 0:  # if i has no edges, I cannot rewire
                    break
                j = random.choice(list(
                    G.edge[i].keys()))  # node to be disconnected
                k = random_from_pdf(pi)  # new node to be connected
                if i is not k and j is not k and not G.has_edge(i, k):
                    G.remove_edge(i, j)
                    G.add_edge(i, k)
                    rewired_links += 1
        else:
            # add a new node with probability 1 - p - q
            new_node = G.number_of_nodes()
            G.add_node(new_node)
            new_links = 0
            while new_links < m:
                existing_node = random_from_pdf(pi)
                if not G.has_edge(new_node, existing_node):
                    G.add_edge(new_node, existing_node)
                    new_links += 1
    return G
示例#5
0
def barabasi_albert_topology(n, m, m0, seed=None):
    r"""
    Return a random topology using Barabasi-Albert preferential attachment
    model.

    A topology of n nodes is grown by attaching new nodes each with m links
    that are preferentially attached to existing nodes with high degree.

    More precisely, the Barabasi-Albert topology is built as follows. First, a
    line topology with m0 nodes is created. Then at each step, one node is
    added and connected to m existing nodes. These nodes are selected randomly
    with probability

    .. math::
            \Pi(i) = \frac{deg(i)}{sum_{v \in V} deg V}.

    Where i is the selected node and V is the set of nodes of the graph.

    Parameters
    ----------
    n : int
        Number of nodes
    m : int
        Number of edges to attach from a new node to existing nodes
    m0 : int
        Number of nodes initially attached to the network
    seed : int, optional
        Seed for random number generator (default=None).

    Returns
    -------
    G : Topology

    Notes
    -----
    The initialization is a graph with with m nodes connected by :math:`m -1`
    edges.
    It does not use the Barabasi-Albert method provided by NetworkX because it
    does not allow to specify *m0* parameter.
    There are no disconnected subgraphs in the topology.

    References
    ----------
    .. [1] A. L. Barabasi and R. Albert "Emergence of scaling in
       random networks", Science 286, pp 509-512, 1999.
    """
    def calc_pi(G):
        """Calculate BA Pi function for all nodes of the graph"""
        degree = G.degree()
        den = float(sum(degree.values()))
        return {node: degree[node] / den for node in G.nodes_iter()}

    # input parameters
    if n < 1 or m < 1 or m0 < 1:
        raise ValueError('n, m and m0 must be positive integers')
    if m >= m0:
        raise ValueError('m must be <= m0')
    if n < m0:
        raise ValueError('n must be > m0')
    if seed is not None:
        random.seed(seed)
    # Step 1: Add m0 nodes. These nodes are interconnected together
    # because otherwise they will end up isolated at the end
    G = Topology(nx.path_graph(m0))
    G.name = "ba_topology(%d,%d,%d)" % (n, m, m0)
    G.graph['type'] = 'ba'

    # Step 2: Add one node and connect it with m links
    while G.number_of_nodes() < n:
        pi = calc_pi(G)
        u = G.number_of_nodes()
        G.add_node(u)
        new_links = 0
        while new_links < m:
            v = random_from_pdf(pi)
            if not G.has_edge(u, v):
                G.add_edge(u, v)
                new_links += 1
    return G
示例#6
0
文件: parsers.py 项目: emiapwil/fnss
def parse_inet(path):
    """
    Parse a topology from an output file generated by the Inet topology
    generator

    Parameters
    ----------
    path : str
        The path to the Inet output file

    Returns
    -------
    topology : Topology

    Notes
    -----
    Each node of the returned topology object is labeled with *latitude* and
    *longitude* attributes. These attributes are not expressed in degrees but
    in Kilometers.
    """
    topology = Topology(type='inet', distance_unit='Km')
    lines = open(path, "r").readlines()
    sep = re.compile('[\s\t]')
    first_line = sep.split(lines[0].strip())
    try:
        n_nodes = int(first_line[0])
        n_links = int(first_line[1])
    except (ValueError, IndexError):
        raise ValueError('Invalid input file. '\
                         'Cannot parse the number of nodes and links')
    if len(lines) != 1 + n_nodes + n_links:
        raise ValueError('Invalid input file. '\
                         'It does not have as many lines as expected')
    i = 0
    for line in lines[1:]:
        entry = sep.split(line.strip())
        if i < n_nodes:
            i += 1
            try:
                node_id = int(entry[0])
                longitude = int(entry[1])
                latitude = int(entry[2])
            except (ValueError, IndexError):
                raise ValueError('Invalid input file. Parsing failed while '\
                                 'trying to parse a node')
            topology.add_node(node_id, latitude=latitude, longitude=longitude)
        else:
            try:
                u = int(entry[0])
                v = int(entry[1])
                weight = int(entry[2])
                x_u = topology.node[u]['longitude']
                y_u = topology.node[u]['latitude']
                x_v = topology.node[v]['longitude']
                y_v = topology.node[v]['latitude']
                length = float(math.sqrt((x_v - x_u)**2 + (y_v - y_u)**2))
            except (ValueError, IndexError):
                raise ValueError('Invalid input file. Parsing failed while '\
                                 'trying to parse a link')
            topology.add_edge(u, v, weight=weight, length=length)
    return topology
示例#7
0
文件: parsers.py 项目: daisyhey/fnss
def parse_inet(path):
    """
    Parse a topology from an output file generated by the Inet topology
    generator
    
    Parameters
    ----------
    path : str
        The path to the Inet output file
        
    Returns
    -------
    topology : Topology
    
    Notes
    -----
    Each node of the returned topology object is labeled with *latitude* and
    *longitude* attributes. These attributes are not expressed in degrees but
    in Kilometers.
    """
    topology = Topology(type='inet', distance_unit='Km')
    lines = open(path, "r").readlines()
    sep = re.compile('[\s\t]')
    first_line = sep.split(lines[0].strip())
    try:
        n_nodes = int(first_line[0])
        n_links = int(first_line[1])
    except (ValueError, IndexError):
        raise ValueError('Invalid input file. '\
                         'Cannot parse the number of nodes and links')
    if len(lines) != 1 + n_nodes + n_links:
        raise ValueError('Invalid input file. '\
                         'It does not have as many lines as expected')
    i = 0
    for line in lines[1:]:
        entry = sep.split(line.strip())
        if i < n_nodes:
            i += 1
            try:
                node_id = int(entry[0])
                longitude = int(entry[1])
                latitude = int(entry[2])
            except (ValueError, IndexError):
                raise ValueError('Invalid input file. Parsing failed while '\
                                 'trying to parse a node')
            topology.add_node(node_id, latitude=latitude, longitude=longitude)
        else:
            try:
                u = int(entry[0])
                v = int(entry[1])
                weight = int(entry[2])
                x_u = topology.node[u]['longitude']
                y_u = topology.node[u]['latitude']
                x_v = topology.node[v]['longitude']
                y_v = topology.node[v]['latitude']
                length = float(math.sqrt((x_v - x_u)**2 + (y_v - y_u)**2))
            except (ValueError, IndexError):
                raise ValueError('Invalid input file. Parsing failed while '\
                                 'trying to parse a link')
            topology.add_edge(u, v, weight=weight, length=length)
    return topology
示例#8
0
文件: randmodels.py 项目: fnss/fnss
def extended_barabasi_albert_topology(n, m, m0, p, q, seed=None):
    r"""
    Return a random topology using the extended Barabasi-Albert preferential
    attachment model.

    Differently from the original Barabasi-Albert model, this model takes into
    account the presence of local events, such as the addition of new links or
    the rewiring of existing links.

    More precisely, the Barabasi-Albert topology is built as follows. First, a
    topology with *m0* isolated nodes is created. Then, at each step:
    with probability *p* add *m* new links between existing nodes, selected
    with probability:

    .. math::
        \Pi(i) = \frac{deg(i) + 1}{\sum_{v \in V} (deg(v) + 1)}

    with probability *q* rewire *m* links. Each link to be rewired is selected as
    follows: a node i is randomly selected and a link is randomly removed from
    it. The node i is then connected to a new node randomly selected with
    probability :math:`\Pi(i)`,
    with probability :math:`1-p-q` add a new node and attach it to m nodes of
    the existing topology selected with probability :math:`\Pi(i)`

    Repeat the previous step until the topology comprises n nodes in total.

    Parameters
    ----------
    n : int
        Number of nodes
    m : int
        Number of edges to attach from a new node to existing nodes
    m0 : int
        Number of edges initially attached to the network
    p : float
        The probability that new links are added
    q : float
        The probability that existing links are rewired
    seed : int, optional
        Seed for random number generator (default=None).

    Returns
    -------
    G : Topology

    References
    ----------
    .. [1] A. L. Barabasi and R. Albert "Topology of evolving networks: local
       events and universality", Physical Review Letters 85(24), 2000.
    """
    def calc_pi(G):
        """Calculate extended-BA Pi function for all nodes of the graph"""
        degree = dict(G.degree())
        den = float(sum(degree.values()) + G.number_of_nodes())
        return {node: (degree[node] + 1) / den for node in G.nodes()}

    # input parameters
    if n < 1 or m < 1 or m0 < 1:
        raise ValueError('n, m and m0 must be a positive integer')
    if m >= m0:
        raise ValueError('m must be <= m0')
    if n < m0:
        raise ValueError('n must be > m0')
    if p > 1 or p < 0:
        raise ValueError('p must be included between 0 and 1')
    if q > 1 or q < 0:
        raise ValueError('q must be included between 0 and 1')
    if p + q > 1:
        raise ValueError('p + q must be <= 1')
    if seed is not None:
        random.seed(seed)
    G = Topology(type='extended_ba')
    G.name = "ext_ba_topology(%d, %d, %d, %f, %f)" % (n, m, m0, p, q)
    # Step 1: Add m0 isolated nodes
    G.add_nodes_from(range(m0))

    while G.number_of_nodes() < n:
        pi = calc_pi(G)
        r = random.random()

        if r <= p:
            # add m new links with probability p
            n_nodes = G.number_of_nodes()
            n_edges = G.number_of_edges()
            max_n_edges = (n_nodes * (n_nodes - 1)) / 2
            if n_edges + m > max_n_edges:  # cannot add m links
                continue  # rewire or add nodes
            new_links = 0
            while new_links < m:
                u = random_from_pdf(pi)
                v = random_from_pdf(pi)
                if u is not v and not G.has_edge(u, v):
                    G.add_edge(u, v)
                    new_links += 1

        elif r > p and r <= p + q:
            # rewire m links with probability q
            rewired_links = 0
            while rewired_links < m:
                i = random.choice(list(G.nodes()))  # pick up node randomly (uniform)
                if len(G.adj[i]) is 0:  # if i has no edges, I cannot rewire
                    break
                j = random.choice(list(G.adj[i].keys()))  # node to be disconnected
                k = random_from_pdf(pi)  # new node to be connected
                if i is not k and j is not k and not G.has_edge(i, k):
                    G.remove_edge(i, j)
                    G.add_edge(i, k)
                    rewired_links += 1
        else:
            # add a new node with probability 1 - p - q
            new_node = G.number_of_nodes()
            G.add_node(new_node)
            new_links = 0
            while new_links < m:
                existing_node = random_from_pdf(pi)
                if not G.has_edge(new_node, existing_node):
                    G.add_edge(new_node, existing_node)
                    new_links += 1
    return G
示例#9
0
文件: randmodels.py 项目: fnss/fnss
def barabasi_albert_topology(n, m, m0, seed=None):
    r"""
    Return a random topology using Barabasi-Albert preferential attachment
    model.

    A topology of n nodes is grown by attaching new nodes each with m links
    that are preferentially attached to existing nodes with high degree.

    More precisely, the Barabasi-Albert topology is built as follows. First, a
    line topology with m0 nodes is created. Then at each step, one node is
    added and connected to m existing nodes. These nodes are selected randomly
    with probability

    .. math::
            \Pi(i) = \frac{deg(i)}{sum_{v \in V} deg V}.

    Where i is the selected node and V is the set of nodes of the graph.

    Parameters
    ----------
    n : int
        Number of nodes
    m : int
        Number of edges to attach from a new node to existing nodes
    m0 : int
        Number of nodes initially attached to the network
    seed : int, optional
        Seed for random number generator (default=None).

    Returns
    -------
    G : Topology

    Notes
    -----
    The initialization is a graph with with m nodes connected by :math:`m -1`
    edges.
    It does not use the Barabasi-Albert method provided by NetworkX because it
    does not allow to specify *m0* parameter.
    There are no disconnected subgraphs in the topology.

    References
    ----------
    .. [1] A. L. Barabasi and R. Albert "Emergence of scaling in
       random networks", Science 286, pp 509-512, 1999.
    """
    def calc_pi(G):
        """Calculate BA Pi function for all nodes of the graph"""
        degree = dict(G.degree())
        den = float(sum(degree.values()))
        return {node: degree[node] / den for node in G.nodes()}

    # input parameters
    if n < 1 or m < 1 or m0 < 1:
        raise ValueError('n, m and m0 must be positive integers')
    if m >= m0:
        raise ValueError('m must be <= m0')
    if n < m0:
        raise ValueError('n must be > m0')
    if seed is not None:
        random.seed(seed)
    # Step 1: Add m0 nodes. These nodes are interconnected together
    # because otherwise they will end up isolated at the end
    G = Topology(nx.path_graph(m0))
    G.name = "ba_topology(%d,%d,%d)" % (n, m, m0)
    G.graph['type'] = 'ba'

    # Step 2: Add one node and connect it with m links
    while G.number_of_nodes() < n:
        pi = calc_pi(G)
        u = G.number_of_nodes()
        G.add_node(u)
        new_links = 0
        while new_links < m:
            v = random_from_pdf(pi)
            if not G.has_edge(u, v):
                G.add_edge(u, v)
                new_links += 1
    return G
示例#10
0
def dumbbell_topology(m1, m2):
    """
    Return a dumbbell topology consisting of two star topologies
    connected by a path.

    More precisely, two star graphs :math:`K_{m1}` form the left and right
    bells, and are connected by a path :math:`P_{m2}`.

    The :math:`2*m1+m2`  nodes are numbered as follows.
     * :math:`0,...,m1-1` for the left barbell,
     * :math:`m1,...,m1+m2-1` for the path,
     * :math:`m1+m2,...,2*m1+m2-1` for the right barbell.

    The 3 subgraphs are joined via the edges :math:`(m1-1,m1)` and
    :math:`(m1+m2-1,m1+m2)`. If m2 = 0, this is merely two star topologies
    joined together.

    Please notice that this dumbbell topology is different from the barbell
    graph generated by networkx's barbell_graph function. That barbell graph
    consists of two complete graphs connected by a path. This consists of two
    stars whose roots are connected by a path. This dumbbell topology is
    particularly useful for simulating transport layer protocols.

    All nodes and edges of this topology have an attribute *type* which can be
    either *right bell*, *core* or *left_bell*

    Parameters
    ----------
    m1 : int
        The number of nodes in each bell
    m2 : int
        The number of nodes in the path

    Returns
    -------
    topology : A Topology object
    """
    if not isinstance(m1, int) or not isinstance(m2, int):
        raise TypeError('m1 and m2 arguments must be of int type')
    if m1 < 2:
        raise ValueError("Invalid graph description, m1 should be >= 2")
    if m2 < 1:
        raise ValueError("Invalid graph description, m2 should be >= 1")

    G = Topology(type='dumbbell')
    G.name = "dumbbell_topology(%d,%d)" % (m1, m2)

    # left bell
    G.add_node(m1)
    for v in range(m1):
        G.add_node(v, type='left_bell')
        G.add_edge(v, m1, type='left_bell')

    # right bell
    for v in range(m1):
        G.add_node(v + m1 + m2, type='right_bell')
        G.add_edge(v + m1 + m2, m1 + m2 - 1, type='right_bell')

    # connecting path
    for v in range(m1, m1 + m2 - 1):
        G.node[v]['type'] = 'core'
        G.add_edge(v, v + 1, type='core')
    G.node[m1 + m2 - 1]['type'] = 'core'

    return G
示例#11
0
文件: simplemodels.py 项目: fnss/fnss
def dumbbell_topology(m1, m2):
    """
    Return a dumbbell topology consisting of two star topologies
    connected by a path.

    More precisely, two star graphs :math:`K_{m1}` form the left and right
    bells, and are connected by a path :math:`P_{m2}`.

    The :math:`2*m1+m2`  nodes are numbered as follows.
     * :math:`0,...,m1-1` for the left barbell,
     * :math:`m1,...,m1+m2-1` for the path,
     * :math:`m1+m2,...,2*m1+m2-1` for the right barbell.

    The 3 subgraphs are joined via the edges :math:`(m1-1,m1)` and
    :math:`(m1+m2-1,m1+m2)`. If m2 = 0, this is merely two star topologies
    joined together.

    Please notice that this dumbbell topology is different from the barbell
    graph generated by networkx's barbell_graph function. That barbell graph
    consists of two complete graphs connected by a path. This consists of two
    stars whose roots are connected by a path. This dumbbell topology is
    particularly useful for simulating transport layer protocols.

    All nodes and edges of this topology have an attribute *type* which can be
    either *right bell*, *core* or *left_bell*

    Parameters
    ----------
    m1 : int
        The number of nodes in each bell
    m2 : int
        The number of nodes in the path

    Returns
    -------
    topology : A Topology object
    """
    if not isinstance(m1, int) or not isinstance(m2, int):
        raise TypeError('m1 and m2 arguments must be of int type')
    if m1 < 2:
        raise ValueError("Invalid graph description, m1 should be >= 2")
    if m2 < 1:
        raise ValueError("Invalid graph description, m2 should be >= 1")

    G = Topology(type='dumbbell')
    G.name = "dumbbell_topology(%d,%d)" % (m1, m2)

    # left bell
    G.add_node(m1)
    for v in range(m1):
        G.add_node(v, type='left_bell')
        G.add_edge(v, m1, type='left_bell')

    # right bell
    for v in range(m1):
        G.add_node(v + m1 + m2, type='right_bell')
        G.add_edge(v + m1 + m2, m1 + m2 - 1, type='right_bell')

    # connecting path
    for v in range(m1, m1 + m2 - 1):
        G.node[v]['type'] = 'core'
        G.add_edge(v, v + 1, type='core')
    G.node[m1 + m2 - 1]['type'] = 'core'

    return G