math.materializers.materialize()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 37
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 37
rs 8.6166
c 0
b 0
f 0
cc 6
nop 6
1
import functools
2
import json
3
from collections.abc import Callable, Mapping
4
from enum import Enum
5
6
from graphinate import GraphModel, GraphType, builders, graphql, matplotlib
7
8
9
class Materializers(Enum):
10
    """Materializers Enum
11
12
    Attributes:
13
        D3Graph: create a D3 Graph and print it to stdout
14
        GraphQL: create a GraphQL Schema and serve it in a web server
15
        NetworkX: create a NetworkX Graph and plot+show it with matplotlib
16
        NetworkX_with_edge_labels: create a NetworkX Graph and plot+show it with matplotlib
17
    """
18
    D3Graph: tuple = (builders.D3Builder, lambda d: print(json.dumps(d, indent=2, default=str)))
19
    GraphQL: tuple = (builders.GraphQLBuilder, graphql.server)
20
    NetworkX: tuple = (builders.NetworkxBuilder, matplotlib.plot)
21
    NetworkX_with_edge_labels: tuple = (builders.NetworkxBuilder,
22
                                        functools.partial(matplotlib.plot, with_edge_labels=True))
23
    Mermaid: tuple = (builders.MermaidBuilder, print)
24
25
26
def materialize(model: GraphModel,
27
                graph_type: GraphType = GraphType.Graph,
28
                default_node_attributes: Mapping | None = None,
29
                builder: type[builders.Builder] | None = None,
30
                builder_output_handler: Callable | None = None,
31
                **kwargs):
32
    """
33
    Materialize a GraphModel using a Builder and an Actualizer
34
35
    Args:
36
        model: GraphModel - the model to be materialized
37
        graph_type: GraphType - the type of graph to be built.
38
                                Default is Graph.
39
        default_node_attributes: Mapping - A Mapping containing attributes that are added to all nodes.
40
        builder: Builder - the builder to be used to build the graph.
41
        builder_output_handler: function that will consume the resulting built graph and
42
                    outputs it (e.g., display, serve, print, etc.).
43
        **kwargs:
44
45
46
    Returns:
47
        None
48
    """
49
    if builder is None and builder_output_handler is None:
50
        raise ValueError("Missing: builder, builder_output_handler")
51
52
    if builder:
53
        graph = builders.build(builder,
54
                               model,
55
                               graph_type,
56
                               default_node_attributes=default_node_attributes,
57
                               **kwargs)
58
59
        if builder_output_handler and callable(builder_output_handler):
60
            builder_output_handler(graph, **kwargs)
61
        else:
62
            print(graph)
63