Beispiel #1
0
def plot(model, pos=None, scale=1, figsize=(15,8), verbose=3):
    """Plot the learned stucture.

    Parameters
    ----------
    model : dict
        Learned model from the .fit() function..
    pos : graph, optional
        Coordinates of the network. If there are provided, the same structure will be used to plot the network.. The default is None.
    scale : int, optional
        Scaling parameter for the network. A larger number will linearily increase the network.. The default is 1.
    figsize : tuple, optional
        Figure size. The default is (15,8).
    verbose : int, optional
        Print progress to screen. The default is 3.
        0: None, 1: ERROR, 2: WARN, 3: INFO (default), 4: DEBUG, 5: TRACE

    Returns
    -------
    dict containing pos and G
        pos : list
            Positions of the nodes.
        G : Graph
            Graph model

    """
    out = {}
    G = nx.DiGraph()  # Directed graph
    layout='fruchterman_reingold'

    # Extract model if in dict
    if 'dict' in str(type(model)):
        model = model.get('model', None)

    # Bayesian model
    if 'BayesianModel' in str(type(model)) or 'pgmpy' in str(type(model)):
        if verbose>=3: print('[BNLEARN][plot] Making plot based on BayesianModel')
        # positions for all nodes
        pos = network.graphlayout(model, pos=pos, scale=scale, layout=layout)
        # Add directed edge with weigth
        # edges=model.edges()
        edges=[*model.edges()]
        for i in range(len(edges)):
            G.add_edge(edges[i][0], edges[i][1], weight=1, color='k')
    elif 'networkx' in str(type(model)):
        if verbose>=3: print('[BNLEARN][plot] Making plot based on networkx model')
        G = model
        pos = network.graphlayout(G, pos=pos, scale=scale, layout=layout)
    else:
        if verbose>=3: print('[BNLEARN][plot] Making plot based on adjacency matrix')
        G = network.adjmat2graph(model)
        # Convert adjmat to source target
        # df_edges=model.stack().reset_index()
        # df_edges.columns=['source', 'target', 'weight']
        # df_edges['weight']=df_edges['weight'].astype(float)

        # # Add directed edge with weigth
        # for i in range(df_edges.shape[0]):
        #     if df_edges['weight'].iloc[i]!=0:
        #         color='k' if df_edges['weight'].iloc[i]>0 else 'r'
        #         G.add_edge(df_edges['source'].iloc[i], df_edges['target'].iloc[i], weight=np.abs(df_edges['weight'].iloc[i]), color=color)
        # Get positions
        pos = network.graphlayout(G, pos=pos, scale=scale, layout=layout)

    # Bootup figure
    plt.figure(figsize=figsize)
    # nodes
    nx.draw_networkx_nodes(G, pos, node_size=500, with_labels=True, alpha=0.85)
    # edges
    colors = [G[u][v].get('color','k') for u,v in G.edges()]
    weights = [G[u][v].get('weight',1) for u,v in G.edges()]
    nx.draw_networkx_edges(G, pos, arrowstyle='->', edge_color=colors, width=weights)
    # Labels
    nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')
    # Get labels of weights
    # labels = nx.get_edge_attributes(G,'weight')
    # Plot weights
    nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes(G,'weight'))
    # Making figure nice
    ax = plt.gca()
    ax.set_axis_off()
    plt.show()

    # Store
    out['pos']=pos
    out['G']=G
    return(out)
Beispiel #2
0
def plot(model, pos=None, scale=1, width=15, height=8, verbose=3):
    out = dict()
    G = nx.DiGraph()  # Directed graph
    layout = 'fruchterman_reingold'

    # Extract model if in dict
    if 'dict' in str(type(model)):
        model = model.get('model', None)

    # Bayesian model
    if 'BayesianModel' in str(type(model)) or 'pgmpy' in str(type(model)):
        if verbose >= 3:
            print('[BNLEARN.plot] Making plot based on BayesianModel')
        # positions for all nodes
        pos = network.graphlayout(model, pos=pos, scale=scale, layout=layout)
        # Add directed edge with weigth
        # edges=model.edges()
        edges = [*model.edges()]
        for i in range(len(edges)):
            G.add_edge(edges[i][0], edges[i][1], weight=1, color='k')
    elif 'networkx' in str(type(model)):
        if verbose >= 3:
            print('[BNLEARN.plot] Making plot based on networkx model')
        G = model
        pos = network.graphlayout(G, pos=pos, scale=scale, layout=layout)
    else:
        if verbose >= 3:
            print('[BNLEARN.plot] Making plot based on adjacency matrix')
        G = network.adjmat2graph(model)
        # Convert adjmat to source target
        #        df_edges=model.stack().reset_index()
        #        df_edges.columns=['source', 'target', 'weight']
        #        df_edges['weight']=df_edges['weight'].astype(float)
        #
        #        # Add directed edge with weigth
        #        for i in range(df_edges.shape[0]):
        #            if df_edges['weight'].iloc[i]!=0:
        #                color='k' if df_edges['weight'].iloc[i]>0 else 'r'
        #                G.add_edge(df_edges['source'].iloc[i], df_edges['target'].iloc[i], weight=np.abs(df_edges['weight'].iloc[i]), color=color)
        # Get positions
        pos = network.graphlayout(G, pos=pos, scale=scale, layout=layout)

    # Bootup figure
    plt.figure(figsize=(width, height))
    # nodes
    nx.draw_networkx_nodes(G, pos, node_size=500, with_labels=True, alpha=0.85)
    # edges
    colors = [G[u][v].get('color', 'k') for u, v in G.edges()]
    weights = [G[u][v].get('weight', 1) for u, v in G.edges()]
    nx.draw_networkx_edges(G,
                           pos,
                           arrowstyle='->',
                           edge_color=colors,
                           width=weights)
    # Labels
    nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')
    # Get labels of weights
    #labels = nx.get_edge_attributes(G,'weight')
    # Plot weights
    nx.draw_networkx_edge_labels(G,
                                 pos,
                                 edge_labels=nx.get_edge_attributes(
                                     G, 'weight'))
    # Making figure nice
    ax = plt.gca()
    ax.set_axis_off()
    plt.show()

    # Store
    out['pos'] = pos
    out['G'] = G
    return (out)