Ejemplo n.º 1
0
 def test_raises_exception_if_H_not_B_hypegraph(self):
     H = DirectedHypergraph()
     H.add_nodes([1, 2, 3])
     H.add_hyperedge([1], [2, 3])
     source, destination = 1, 2
     self.assertRaises(TypeError, ksh.k_shortest_hyperpaths, H, source,
                       destination, 1)
Ejemplo n.º 2
0
def from_networkx_digraph(nx_digraph):
    """Returns a DirectedHypergraph object that is the graph equivalent of the
    given NetworkX DiGraph object.

    :param nx_digraph: the NetworkX directed graph object to transform.
    :returns: DirectedHypergraph -- hypergraph object equivalent to the
            NetworkX directed graph.
    :raises: TypeError -- Transformation only applicable to directed
            NetworkX graphs

    """
    import networkx as nx

    if not isinstance(nx_digraph, nx.DiGraph):
        raise TypeError("Transformation only applicable to directed \
                        NetworkX graphs")

    G = DirectedHypergraph()

    for node in nx_digraph.nodes():
        G.add_node(node, **copy.copy(nx_digraph.nodes[node]))

    for edge in nx_digraph.edges():
        tail_node = edge[0]
        head_node = edge[1]
        G.add_hyperedge(tail_node, head_node,
                        copy.copy(nx_digraph[tail_node][head_node]))

    return G
Ejemplo n.º 3
0
def reset_pheromone(hg):
    '''
    Reset the pheromone level to a default (0.5)
    :param hg:
    '''
    hg_copy = DirectedHypergraph()
    for edge in hg.get_hyperedge_id_set():
        #hg_copy = hg.copy()
        PHERO_DEFAULT = 0.5
        head_edge = hg.get_hyperedge_head(edge)
        #head_edge = ast.literal_eval(head_edge)
        #print(head_edge)
        for head_node in head_edge:
            #print(head_node)
            attrs = hg.get_node_attributes(head_node)
            hg_copy.add_node(head_node, attrs)
        tail_edge = hg.get_hyperedge_tail(edge)
        #tail_edge = ast.literal_eval(tail_edge)
        for tail_node in tail_edge:
            attrs = hg.get_node_attributes(tail_node)
            hg_copy.add_node(tail_node, attrs)
        hg_copy.add_hyperedge(tail_edge,
                              head_edge,
                              phero=PHERO_DEFAULT,
                              id=edge,
                              name=edge)

    return hg_copy
Ejemplo n.º 4
0
def test_get_predecessors():
    node_a = 'A'
    node_b = 'B'
    node_c = 'C'
    node_d = 'D'
    node_e = 'E'

    tail1 = set([node_a, node_b])
    head1 = set([node_c, node_d])
    frozen_tail1 = frozenset(tail1)
    frozen_head1 = frozenset(head1)

    tail2 = set([node_b, node_c])
    head2 = set([node_d, node_a])
    frozen_tail2 = frozenset(tail2)
    frozen_head2 = frozenset(head2)

    tail3 = set([node_d])
    head3 = set([node_e])
    frozen_tail3 = frozenset(tail3)
    frozen_head3 = frozenset(head3)

    hyperedges = [(tail1, head1), (tail2, head2), (tail3, head3), (tail3, "F")]

    H = DirectedHypergraph()
    hyperedge_names = H.add_hyperedges(hyperedges)

    assert 'e1' in H.get_predecessors(head1)
    assert 'e2' in H.get_predecessors(head2)
    assert 'e3' in H.get_predecessors(head3)
    assert 'e4' in H.get_predecessors("F")

    assert H.get_predecessors([node_a]) == set()
Ejemplo n.º 5
0
def convert_bpmn_to_process_hgraph(bpmn_file_name):
    '''
    Convert a bpmn model into a hypergraph
    UNTESTED AND TO BE COMPLETED: DO NOT USE
    :param bpmn_file_name: file containing the BPMN xml
    '''
    hyperg = DirectedHypergraph()
    #namespace
    ns = {'bpmn': 'http://www.omg.org/spec/BPMN/20100524/MODEL'}
    #parse bpmn file
    tree = ET.parse(bpmn_file_name)
    bpmndiagram = tree.getroot()
    #parse process
    processes = bpmndiagram.findall("./bpmn:process", ns)
    for process in processes:
        #pick start event
        starts = bpmndiagram.findall("./bpmn:process/bpmn:startEvent", ns)
        for start in starts:
            hyperg.add_node(start.attrib['id'],
                            name=start.attrib['name'],
                            cost=0.1,
                            qual=0.1,
                            avail=0.1,
                            time=0.1)
            #logger.info(get_tag(start))
            visited = []
            hyperg = inspect_task(start, hyperg, bpmndiagram, [])
    print_hg_std_out_only(hyperg)
    return hyperg
Ejemplo n.º 6
0
def convert_pnet_to_hypergraph_andgatewayonly(pnet):
    hg = DirectedHypergraph()
    #scan all transitions and create hyperedges
    transitions = get_transitions(pnet)
    for transition in transitions:
        #get all incoming arcs, the source of these become the tail of hyperedge
        inc_arcs = get_incoming_arcs(transition, pnet)
        tail = []
        for inc_arc in inc_arcs:
            source = str(get_arc_source(inc_arc))
            tail.append(source)
        #get all outgoing arcs, the target of these become the head of the hyperedge
        out_arcs = get_outgoing_arcs(transition, pnet)
        head = []
        for out_arc in out_arcs:
            target = str(get_arc_target(out_arc))
            head.append(target)
        name = get_transition_name(transition)
        hg.add_hyperedge(tail,
                         head,
                         name=name,
                         phero=0.5,
                         cost=0.4,
                         avail=0.6,
                         qual=0.2,
                         time=0.99)
    #print the result before exit
    print_hg_std_out_only(hg)
    return hg
Ejemplo n.º 7
0
def test_get_hyperedge_weight():
    node_a = 'A'
    node_b = 'B'
    node_c = 'C'
    node_d = 'D'

    tail1 = set([node_a, node_b])
    head1 = set([node_c, node_d])
    frozen_tail1 = frozenset(tail1)
    frozen_head1 = frozenset(head1)

    tail2 = set([node_b, node_c])
    head2 = set([node_d, node_a])
    frozen_tail2 = frozenset(tail2)
    frozen_head2 = frozenset(head2)

    attrib = {'weight': 6, 'color': 'black'}
    common_attrib = {'sink': False}

    hyperedges = [(tail1, head1, attrib), (tail2, head2)]

    H = DirectedHypergraph()
    hyperedge_names = \
        H.add_hyperedges(hyperedges, common_attrib, color='white')

    weight_e1 = H.get_hyperedge_weight('e1')
    weight_e2 = H.get_hyperedge_weight('e2')
    assert weight_e1 == 6
    assert weight_e2 == 1
Ejemplo n.º 8
0
def test_visit():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    visited_nodes, Pv, Pe = directed_paths.visit(H, 's')

    assert visited_nodes == set(['s', 'x', 'y', 'z', 'u', 't', 'a'])

    assert Pv['s'] is None
    assert (Pe['e1'], Pe['e2'], Pe['e3']) == ('s', 's', 's')
    assert Pv['x'] in ('e1', 'e2')
    assert Pv['y'] == 'e2'
    assert Pv['z'] == 'e3'
    assert Pe['e4'] in ('x', 'y', 'z')
    assert Pv['u'] == 'e4'
    assert Pv['t'] == 'e8'
    assert Pv['a'] == 'e7'
    assert Pe['e5'] == 'a'
    assert Pe['e6'] == 'x'
    assert Pe['e7'] == 't'
    assert Pe['e8'] == 's'
    assert Pv['b'] is None

    try:
        directed_paths.visit('s', 't')
        assert False
    except TypeError:
        pass
    except BaseException as e:
        assert False, e
Ejemplo n.º 9
0
def test_get_hyperedge_attributes():
    node_a = 'A'
    node_b = 'B'
    node_c = 'C'
    node_d = 'D'

    tail = set([node_a, node_b])
    head = set([node_c, node_d])
    frozen_tail = frozenset(tail)
    frozen_head = frozenset(head)

    attrib = {'weight': 6, 'color': 'black'}

    H = DirectedHypergraph()
    H.add_node(node_a, label=1337)
    hyperedge_name = H.add_hyperedge(tail, head, attrib, weight=5)

    assert H.get_hyperedge_attributes(hyperedge_name) == \
        {'tail': tail, 'head': head, 'weight': 5, 'color': 'black'}

    # Test getting non-existent hyperedge's attributes
    try:
        H.get_hyperedge_attributes("e10")
        assert False
    except ValueError:
        pass
    except BaseException as e:
        assert False, e
Ejemplo n.º 10
0
def test_get_node_attributes():
    node_a = 'A'
    node_b = 'B'
    node_c = 'C'
    attrib_c = {'alt_name': 1337}
    node_d = 'D'
    attrib_d = {'label': 'black', 'sink': True}

    # Test adding unadded nodes with various attribute settings
    H = DirectedHypergraph()
    H.add_node(node_a)
    H.add_node(node_b, source=True)
    H.add_node(node_c, attrib_c)
    H.add_node(node_d, attrib_d, sink=False)

    assert H.get_node_attributes(node_a) == {}
    assert H.get_node_attributes(node_d) == {'label': 'black', 'sink': False}

    # Test getting non-existent node's attributes
    try:
        H.get_node_attributes("X")
        assert False
    except ValueError:
        pass
    except BaseException as e:
        assert False, e
Ejemplo n.º 11
0
def test_from_networkx_digraph():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    nxG = directed_graph_transformations.to_networkx_digraph(H)

    G = directed_graph_transformations.from_networkx_digraph(nxG)

    nxG_nodes = nxG.node.keys()
    G_nodes = G.get_node_set()

    assert G_nodes == set(nxG_nodes)

    for edge in nxG.edges_iter():
        tail_node = edge[0]
        head_node = edge[1]
        assert G.has_hyperedge(tail_node, head_node)

    # Try transforming an invalid directed hypergraph
    try:
        directed_graph_transformations.from_networkx_digraph("G")
        assert False
    except TypeError:
        pass
    except BaseException as e:
        assert False, e
Ejemplo n.º 12
0
def test_to_networkx_digraph():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    G = directed_graph_transformations.to_networkx_digraph(H)

    H_nodes = H.get_node_set()
    G_nodes = G.node.keys()

    assert H_nodes == set(G_nodes)

    H_nodes_attributes = [H.get_node_attributes(node) for node in H_nodes]
    for node in G_nodes:
        assert G.node[node] in H_nodes_attributes

    for hyperedge_id in H.hyperedge_id_iterator():
        tail_set = H.get_hyperedge_tail(hyperedge_id)
        head_set = H.get_hyperedge_head(hyperedge_id)
        for tail_node in tail_set:
            for head_node in head_set:
                assert G[tail_node][head_node]

    # Try transforming an invalid directed hypergraph
    try:
        directed_graph_transformations.to_networkx_digraph("invalid H")
        assert False
    except TypeError:
        pass
    except BaseException as e:
        assert False, e
Ejemplo n.º 13
0
def to_graph_decomposition(H):
    """Returns a DirectedHypergraph object that has the same nodes (and
    corresponding attributes) as the given hypergraph, except that for all
    hyperedges in the given hypergraph, each node in the tail of the hyperedge
    is pairwise connected to each node in the head of the hyperedge in the
    new hypergraph.
    Said another way, each of the original hyperedges are decomposed in the
    new hypergraph into fully-connected bipartite components.

    :param H: the hypergraph to decompose into a graph.
    :returns: DirectedHypergraph -- the decomposed hypergraph.
    :raises: TypeError -- Transformation only applicable to
            directed hypergraphs

    """
    if not isinstance(H, DirectedHypergraph):
        raise TypeError("Transformation only applicable to \
                        directed hypergraphs")

    G = DirectedHypergraph()

    nodes = [(node, H.get_node_attributes(node_attributes))
             for node in G.node_iterator()]
    G.add_nodes(nodes)

    edges = [([tail_node], [head_node])
             for hyperedge_id in H.hyperedge_id_iterator()
             for tail_node in H.get_hyperedge_tail(hyperedge_id)
             for head_node in H.get_hyperedge_head(hyperedge_id)]
    G.add_hyperedges(edges)

    return G
Ejemplo n.º 14
0
def random_generate_hg(level_size, block_size_min, block_size_max):
    '''
    Generate a random hypergraph
    :param level_size: number of rewriting levels (at each level an 'and' or 'xor' block is randomly chosen for rewriting)
    :param block_size: min size of a block (number of branches)
    :param block_size: max size of a block (number of branches)
    '''
    hg = DirectedHypergraph()
    # create source and sink nodes
    source_attrs = generate_random_node_attributes()
    source_attrs['source'] = True
    sink_attrs = generate_random_node_attributes()
    sink_attrs['sink'] = True
    source = 'source'
    hg.add_node(source, source_attrs)
    sink = 'sink'
    hg.add_node(sink, sink_attrs)
    edge_attrs = {'phero' : 0.5}
    source_list = []
    sink_list = []
    source_list.append(source)
    sink_list.append(sink)
    hg.add_hyperedge(source_list, sink_list, edge_attrs)
    
    
    node_start_list = source_list
    node_end_list = sink_list
    
    # add 1 node
    node_middle = generate_random_node_list(hg, 1)
    hg.add_hyperedge(source_list, node_middle, edge_attrs)
    hg.add_hyperedge(node_middle, sink_list, edge_attrs)
    hg.remove_hyperedge(hg.get_hyperedge_id(source_list, sink_list))
    
    #print_hg_std_out_only(hg)
    
    # add one xor block
    #hg = rewrite_xor_block(hg, node_middle[0], 2)[0]
    #hg = rewrite_and_block(hg, node_middle[0], 4)[0]
    
    
    #print_hg_std_out_only(hg)
    
    # generation of test hypergraph
    current_node = node_middle[0]
    
    SIZE = level_size
    for i in range(0, SIZE, 1):
        size = randint(block_size_min, block_size_max)                                # pick size randomly
        if uniform(0,1) > 0.5:                              # make an and block
            out = rewrite_and_block(hg, current_node, size)
            hg, current_node = out[0], out[1]
            
        else:                                               # make a xor block
            out = rewrite_xor_block(hg, current_node, size)
            hg, current_node = out[0], out[1]
    
    #print_hg_std_out_only(hg)
    
    return hg
Ejemplo n.º 15
0
def get_hypertree_from_predecessors(H,
                                    Pv,
                                    source_node,
                                    node_weights=None,
                                    attr_name="weight"):
    """Gives the hypertree (i.e., the subhypergraph formed from the union of
    the set of paths from an execution of, e.g., the SBT algorithm) defined by
    Pv beginning at a source node. Returns a dictionary mapping each node to
    the ID of the hyperedge that preceeded it in the path (i.e., a Pv vector).
    Assigns the node weights (if provided) as attributes of the nodes (e.g.,
    the rank of that node in a specific instance of the SBT algorithm, or the
    cardinality of that node in a B-Visit traversal, etc.).

    :note: The IDs of the hyperedges in the subhypergraph returned may be
        different than those in the original hypergraph (even though the
        tail and head sets are identical).

    :param H: the hypergraph which the path algorithm was executed on.
    :param Pv: dictionary mapping each node to the ID of the hyperedge that
            preceeded it in the path.
    :param source_node: the root of the executed path algorithm.
    :param node_weights: [optional] dictionary mapping each node to some weight
                        measure.
    :param attr_name: key into the nodes' attribute dictionaries for their
                    weight values (if node_weights is provided).
    :returns: DirectedHypergraph -- subhypergraph induced by the path
            algorithm specified by the predecessor vector (Pv) from a
            source node.
    :raises: TypeError -- Algorithm only applicable to directed hypergraphs

    """
    if not isinstance(H, DirectedHypergraph):
        raise TypeError("Algorithm only applicable to directed hypergraphs")

    sub_H = DirectedHypergraph()

    # If node weights are not provided, simply collect all the nodes that are
    # will be in the hypertree
    if node_weights is None:
        nodes = [node for node in Pv.keys() if Pv[node] is not None]
        nodes.append(source_node)
    # If node weights are provided, collect all the nodes that will be in the
    # tree and pair them with their corresponding weights
    else:
        nodes = [(node, {
            attr_name: node_weights[node]
        }) for node in Pv.keys() if Pv[node] is not None]
        nodes.append((source_node, {attr_name: node_weights[source_node]}))
    # Add the collected elements to the hypergraph
    sub_H.add_nodes(nodes)

    # Add all hyperedges, specified by Pv, to the hypergraph
    hyperedges = [(H.get_hyperedge_tail(hyperedge_id),
                   H.get_hyperedge_head(hyperedge_id),
                   H.get_hyperedge_attributes(hyperedge_id))
                  for hyperedge_id in Pv.values() if hyperedge_id is not None]
    sub_H.add_hyperedges(hyperedges)

    return sub_H
Ejemplo n.º 16
0
def test_hyperedge_cardinality_ratio_list():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    ratio_list = [0.5, 1.0, 1.0, 1.0, 2.0, 1.0, 1.5, 0.5]
    returned_list = directed_statistics.hyperedge_cardinality_ratio_list(H)

    assert sorted(ratio_list) == sorted(returned_list)
Ejemplo n.º 17
0
 def test_returns_hyperpath_containing_source_if_source_equals_destination(
         self):
     s = '1'
     T = {s: None}
     H = DirectedHypergraph()
     H.add_node(s)
     path = directed_paths.get_hyperpath_from_predecessors(H, T, s, s)
     self.assertTrue(path.has_node(s))
Ejemplo n.º 18
0
 def test_raises_exception_if_k_not_positive(self):
     H = DirectedHypergraph()
     source, destination = 1, 2
     H.add_nodes([source, destination])
     self.assertRaises(ValueError, ksh.k_shortest_hyperpaths, H, source,
                       destination, -4)
     self.assertRaises(ValueError, ksh.k_shortest_hyperpaths, H, source,
                       destination, 0)
Ejemplo n.º 19
0
def test_is_BF_hypergraph():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    assert not H.is_BF_hypergraph()

    H = DirectedHypergraph()
    H.add_hyperedge(['a', 'b'], ['c'])
    assert H.is_BF_hypergraph()

    H = DirectedHypergraph()
    H.add_hyperedge(['x'], ['y', 'z'])
    assert H.is_BF_hypergraph()

    H = DirectedHypergraph()
    H.add_hyperedge(['a', 'b'], ['c'])
    H.add_hyperedge(['x'], ['y', 'z'])
    assert H.is_BF_hypergraph()
Ejemplo n.º 20
0
 def test_raises_exception_if_all_nodes_have_predecessors(self):
     s1, s2, s3 = 1, 2, 3
     H = DirectedHypergraph()
     H.add_nodes([s1, s2, s3])
     e1 = H.add_hyperedge([s1], [s2])
     T = {s1: e1, s2: e1, s3: e1}
     self.assertRaises(ValueError,
                       directed_paths.get_hyperpath_from_predecessors, H, T,
                       s1, s2)
Ejemplo n.º 21
0
def test_get_symmetric_image():
    node_a = 'A'
    node_b = 'B'
    node_c = 'C'
    node_d = 'D'
    node_e = 'E'

    tail1 = set([node_a, node_b])
    head1 = set([node_c, node_d])
    frozen_tail1 = frozenset(tail1)
    frozen_head1 = frozenset(head1)

    tail2 = set([node_b, node_c])
    head2 = set([node_d, node_a])
    frozen_tail2 = frozenset(tail2)
    frozen_head2 = frozenset(head2)

    tail3 = set([node_d])
    head3 = set([node_e])
    frozen_tail3 = frozenset(tail3)
    frozen_head3 = frozenset(head3)

    hyperedges = [(tail1, head1), (tail2, head2), (tail3, head3)]

    H = DirectedHypergraph()
    hyperedge_names = H.add_hyperedges(hyperedges)

    sym_H = H.get_symmetric_image()

    sym_H._check_consistency()

    assert sym_H._node_attributes == H._node_attributes

    assert sym_H._hyperedge_attributes["e1"]["tail"] == head1
    assert sym_H._hyperedge_attributes["e1"]["head"] == tail1
    assert sym_H._hyperedge_attributes["e1"]["__frozen_tail"] == frozen_head1
    assert sym_H._hyperedge_attributes["e1"]["__frozen_head"] == frozen_tail1
    assert sym_H._hyperedge_attributes["e2"]["tail"] == head2
    assert sym_H._hyperedge_attributes["e2"]["head"] == tail2
    assert sym_H._hyperedge_attributes["e2"]["__frozen_tail"] == frozen_head2
    assert sym_H._hyperedge_attributes["e2"]["__frozen_head"] == frozen_tail2
    assert sym_H._hyperedge_attributes["e3"]["tail"] == head3
    assert sym_H._hyperedge_attributes["e3"]["head"] == tail3
    assert sym_H._hyperedge_attributes["e3"]["__frozen_tail"] == frozen_head3
    assert sym_H._hyperedge_attributes["e3"]["__frozen_head"] == frozen_tail3

    assert sym_H._forward_star[node_a] == set(["e2"])
    assert sym_H._forward_star[node_b] == set()
    assert sym_H._forward_star[node_c] == set(["e1"])
    assert sym_H._forward_star[node_d] == set(["e1", "e2"])
    assert sym_H._forward_star[node_e] == set(["e3"])

    assert sym_H._backward_star[node_a] == set(["e1"])
    assert sym_H._backward_star[node_b] == set(["e1", "e2"])
    assert sym_H._backward_star[node_c] == set(["e2"])
    assert sym_H._backward_star[node_d] == set(["e3"])
    assert sym_H._backward_star[node_e] == set()
Ejemplo n.º 22
0
 def test_returns_hyperpath_with_single_node_if_source_equals_destination(
         self):
     s = '1'
     T = {s: None}
     H = DirectedHypergraph()
     H.add_node(s)
     path = directed_paths.get_hyperpath_from_predecessors(H, T, s, s)
     self.assertEqual(len(path.get_node_set()), 1)
     self.assertEqual(len(path.get_hyperedge_id_set()), 0)
Ejemplo n.º 23
0
def test_hyperedge_head_cardinality_list():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    hyperedge_head_cardinality_list = \
        directed_statistics.hyperedge_head_cardinality_list(H)
    assert len(hyperedge_head_cardinality_list) == 8
    assert hyperedge_head_cardinality_list.count(1) == 5
    assert hyperedge_head_cardinality_list.count(2) == 3
Ejemplo n.º 24
0
def test_get_hypertree_from_predecessors():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    # Test with a weighting
    Pv, W, valid_ordering = \
        directed_paths.shortest_b_tree(
            H, 's', directed_paths.sum_function, True)

    sub_H = directed_paths.get_hypertree_from_predecessors(H, Pv, 's', W)

    sub_H._check_consistency()

    assert sub_H.get_node_set() == set(['s', 'x', 'y', 'z', 't', 'u'])

    assert sub_H.get_node_attribute('s', 'weight') == 0
    assert sub_H.get_node_attribute('x', 'weight') == 1
    assert sub_H.get_node_attribute('y', 'weight') == 2
    assert sub_H.get_node_attribute('z', 'weight') == 2
    assert sub_H.get_node_attribute('u', 'weight') == 8
    assert sub_H.get_node_attribute('t', 'weight') == 8

    assert Pv['s'] == None
    assert Pv['x'] == "e1"
    assert Pv['y'] == "e2"
    assert Pv['z'] == "e3"
    assert (Pv['u'], Pv['t']) == ("e4", "e4")
    assert (Pv['a'], Pv['b']) == (None, None)

    assert len(sub_H.get_hyperedge_id_set()) == 4
    assert sub_H.has_hyperedge(['s'], ['x'])
    assert sub_H.has_hyperedge(['s'], ['x', 'y'])
    assert sub_H.has_hyperedge(['s'], ['z'])
    assert sub_H.has_hyperedge(['x', 'y', 'z'], ['u', 't'])

    # Test without a weighting
    Pv, W = directed_paths.shortest_f_tree(H, 't', directed_paths.sum_function)

    sub_H = directed_paths.get_hypertree_from_predecessors(H, Pv, 't')

    sub_H._check_consistency()

    assert sub_H.get_node_set() == set(['t', 's', 'x'])

    assert len(sub_H.get_hyperedge_id_set()) == 2
    assert sub_H.has_hyperedge(['x'], ['s'])
    assert sub_H.has_hyperedge(['s'], ['t'])

    # Try an invalid hypergraph
    try:
        directed_paths.shortest_b_tree('s', 't')
        assert False
    except TypeError:
        pass
    except BaseException as e:
        assert False, e
Ejemplo n.º 25
0
def test_indegree_list():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    indegree_list = directed_statistics.indegree_list(H)
    assert len(indegree_list) == 8
    assert indegree_list.count(0) == 1
    assert indegree_list.count(1) == 4
    assert indegree_list.count(2) == 2
    assert indegree_list.count(3) == 1
Ejemplo n.º 26
0
 def test_raises_exception_if_values_of_function_are_not__in_hypergraph(
         self):
     s1, s2, s3 = 1, 2, 3
     H = DirectedHypergraph()
     H.add_nodes([s1, s2])
     e1 = H.add_hyperedge([s1], [s2])
     T = {s1: None, s2: 'e2'}
     self.assertRaises(KeyError,
                       directed_paths.get_hyperpath_from_predecessors, H, T,
                       s1, s2)
Ejemplo n.º 27
0
def test_outdegree_list():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    outdegree_list = directed_statistics.outdegree_list(H)
    assert len(outdegree_list) == 8
    assert outdegree_list.count(0) == 1
    assert outdegree_list.count(1) == 5
    assert outdegree_list.count(2) == 1
    assert outdegree_list.count(4) == 1
Ejemplo n.º 28
0
def test_remove_nodes():
    node_a = 'A'
    node_b = 'B'
    node_c = 'C'
    node_d = 'D'
    node_e = 'E'

    tail1 = set([node_a, node_b])
    head1 = set([node_c, node_d])
    frozen_tail1 = frozenset(tail1)
    frozen_head1 = frozenset(head1)

    tail2 = set([node_b, node_c])
    head2 = set([node_d, node_a])
    frozen_tail2 = frozenset(tail2)
    frozen_head2 = frozenset(head2)

    tail3 = set([node_d])
    head3 = set([node_e])
    frozen_tail3 = frozenset(tail3)
    frozen_head3 = frozenset(head3)

    tail4 = set([node_c])
    head4 = set([node_e])
    frozen_tail4 = frozenset(tail4)
    frozen_head4 = frozenset(head4)

    attrib = {'weight': 6, 'color': 'black'}
    common_attrib = {'sink': False}

    hyperedges = [(tail1, head1, attrib), (tail2, head2), (tail3, head3),
                  (tail4, head4)]

    H = DirectedHypergraph()
    hyperedge_names = \
        H.add_hyperedges(hyperedges, common_attrib, color='white')
    H.remove_nodes([node_a, node_d])

    # Test that everything that needed to be removed was removed
    assert node_a not in H._node_attributes
    assert node_a not in H._forward_star
    assert node_a not in H._backward_star
    assert "e1" not in H._hyperedge_attributes
    assert "e2" not in H._hyperedge_attributes
    assert frozen_tail1 not in H._successors
    assert frozen_head1 not in H._predecessors
    assert frozen_head2 not in H._predecessors
    assert frozen_tail2 not in H._successors

    assert node_d not in H._node_attributes
    assert node_d not in H._forward_star
    assert node_d not in H._backward_star
    assert "e3" not in H._hyperedge_attributes
    assert "e3" not in H._predecessors[frozen_head3]
    assert frozen_tail3 not in H._predecessors[frozen_head3]
Ejemplo n.º 29
0
def test_is_connected():
    H = DirectedHypergraph()
    H.read("tests/data/basic_directed_hypergraph.txt")

    assert directed_paths.is_connected(H, 's', 'x')
    assert directed_paths.is_connected(H, 's', 'y')
    assert directed_paths.is_connected(H, 's', 'z')
    assert directed_paths.is_connected(H, 's', 't')
    assert directed_paths.is_connected(H, 's', 'u')
    assert directed_paths.is_connected(H, 's', 'a')
    assert not directed_paths.is_connected(H, 's', 'b')
Ejemplo n.º 30
0
 def test_returns_disconnected_nodes_on_graph_with_two_nodes(self):
     H = DirectedHypergraph()
     s, t = 's', 't'
     H.add_node(s)
     H.add_node(t)
     e1 = H.add_hyperedge({s}, {t})
     predecessor = {s: None, t: e1}
     ordering = [s, t]
     branch = ksh._branching_step(H, predecessor, ordering)[0]
     self.assertEqual(branch.get_hyperedge_id_set(), set([]))
     self.assertEqual(branch.get_node_set(), {'s', 't'})