Skip to content

graph_based_clustering

connected_components(clusters)

Create connected components from iterable of known clusters.

Parameters:

Name Type Description Default
clusters Iterable[Collection[T]]

Known clusters

required

Returns:

Type Description
Generator[Set[T], None, None]

Generator of connected components

Source code in eche/graph_based_clustering.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def connected_components(
    clusters: Iterable[Collection[T]],
) -> Generator[Set[T], None, None]:
    """Create connected components from iterable of known clusters.

    Args:
        clusters: Known clusters

    Returns:
        Generator of connected components
    """
    # https://stackoverflow.com/a/4843408
    G = to_graph(clusters)
    return nx_con_com(G)

to_chain(elements)

Return elements as chain of edges.

Parameters:

Name Type Description Default
elements Collection[T]

Container with elements

required

Examples:

>>> list(to_chain(["a", "b", "c", "d"]))
[("a", "b"), ("a", "c"), ("a", "d")]
Source code in eche/graph_based_clustering.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def to_chain(elements: Collection[T]) -> Generator[Tuple[T, T], None, None]:
    """Return elements as chain of edges.

    Args:
        elements: Container with elements

    Examples:
        >>> list(to_chain(["a", "b", "c", "d"]))
        [("a", "b"), ("a", "c"), ("a", "d")]
    """
    try:
        it = iter(set(elements))
        last = next(it)
    except StopIteration:
        # return an empty generator https://stackoverflow.com/a/13243870
        return

    for current in it:
        yield last, current
        last = current

to_graph(elements)

Create chain graph from iterable of collections.

Parameters:

Name Type Description Default
elements Iterable[Collection]

Iterable of collections

required
Source code in eche/graph_based_clustering.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
def to_graph(elements: Iterable[Collection]) -> nx.Graph:
    """Create chain graph from iterable of collections.

    Args:
        elements: Iterable of collections
    """
    G = nx.Graph()
    for part in elements:
        # each sublist is a bunch of nodes
        G.add_nodes_from(part)
        # it also implies a chain of edges:
        G.add_edges_from(to_chain(part))
    return G