#                 mnet[p, layer_name][j, layer_name] = 1

# for p in node_set:
#     if p in home_set and p in school_set:
#         mnet[p, 'Households'][p, 'Schools'] = 1
#     if p in home_set and p in work_set:
#         mnet[p, 'Households'][p, 'Work'] = 1

# nn = mnet.iter_nodes('Households')
# for i in nn:
#     print(i)
# pos = nx.nx_pydot.graphviz_layout(G, prog='pydot')
# print(pos)

# print(A.layout())

import pydot

# P = nx.nx_pydot.to_pydot(G)
# print(P)
nx.nx_pydot.pydot_layout(G, prog='neato')

fig = pymnet.draw(
    mnet,
    defaultLayerAlpha=0.3,
    layout='circular',
    # nodeCoords = pos,
    nodeLabelRule={})
# fig.savefig('net.pdf')
fig.savefig('net_2.pdf')
Beispiel #2
0
def plot_complete_invariant_average_time_series(subnet_filename_list,
                                                title,
                                                xlabel,
                                                ylabel,
                                                savename=None,
                                                examples_filename=None,
                                                map_ni_to_nli=False,
                                                yscale='log',
                                                colormap=plt.cm.jet,
                                                **kwargs):
    compinv_timeseries_dict_list = []
    layersets = set()
    invariants = set()
    for filename in subnet_filename_list:
        f = open(filename, 'r')
        complete_invariant_timeseries_dict = pickle.load(f)
        f.close()
        for key in complete_invariant_timeseries_dict:
            invariants.add(key)
            layersets.update(
                [key2 for key2 in complete_invariant_timeseries_dict[key]])
        compinv_timeseries_dict_list.append(complete_invariant_timeseries_dict)

    if examples_filename is not None:
        invdicts = complete_invariant_dicts.load_example_nets_file(
            examples_filename)
    else:
        nnodes = int(subnet_filename_list[0].split('/')[-1].strip()[0])
        nlayers = int(subnet_filename_list[0].split('/')[-1].strip()[2])
        example_nets_filename = 'example_nets/' + str(nnodes) + '_' + str(
            nlayers) + '.pickle'
        invdicts = complete_invariant_dicts.load_example_nets_file(
            example_nets_filename)

    layersets = list(layersets)
    layersets.sort()
    full_range = zip(*(range(layersets[0][0], layersets[-1][-1] + 1)[ii:]
                       for ii in range(len(layersets[0]))))
    if layersets != full_range:
        layersets = full_range
    x_axis = list(range(layersets[0][0], layersets[-1][1]))

    if map_ni_to_nli:
        invariants = set()
        mapped_invdicts = dict()
        mapped_compinv_timeseries_dict_list = []
        for complete_invariant_timeseries_dict in compinv_timeseries_dict_list:
            mapped_complete_invariant_timeseries_dict = dict()
            for complete_invariant in complete_invariant_timeseries_dict:
                nl_complete_invariant = pn.get_complete_invariant(
                    invdicts[complete_invariant])
                if nl_complete_invariant not in mapped_invdicts:
                    mapped_invdicts[nl_complete_invariant] = invdicts[
                        complete_invariant]
                invariants.add(nl_complete_invariant)
                mapped_complete_invariant_timeseries_dict[
                    nl_complete_invariant] = mapped_complete_invariant_timeseries_dict.get(
                        nl_complete_invariant, dict())
                for tw in complete_invariant_timeseries_dict[
                        complete_invariant]:
                    mapped_complete_invariant_timeseries_dict[
                        nl_complete_invariant][
                            tw] = mapped_complete_invariant_timeseries_dict[
                                nl_complete_invariant].get(
                                    tw,
                                    0) + complete_invariant_timeseries_dict[
                                        complete_invariant][tw]
            mapped_compinv_timeseries_dict_list.append(
                mapped_complete_invariant_timeseries_dict)
        compinv_timeseries_dict_list = mapped_compinv_timeseries_dict_list
        invdicts = mapped_invdicts

    number_of_invariants = len(invariants)
    grid_side_length = 0
    while grid_side_length**2 < number_of_invariants:
        grid_side_length = grid_side_length + 1
    ax_locs = list(
        itertools.product(range(grid_side_length),
                          range(grid_side_length, 2 * grid_side_length)))

    fig = plt.figure(figsize=(12, 6))
    main_ax = plt.subplot2grid((grid_side_length, 2 * grid_side_length),
                               (0, 0),
                               rowspan=grid_side_length,
                               colspan=grid_side_length)
    colorcycler = plt.cycler('color',
                             colormap(np.linspace(0, 1, number_of_invariants)))
    main_ax.set_prop_cycle(colorcycler)

    for ii, compinv in enumerate(sorted(invariants)):
        y_values = []
        std_values = []
        for layerset in layersets:
            temp_layerset_vals = []
            for compinv_timeseries_dict in compinv_timeseries_dict_list:
                if compinv in compinv_timeseries_dict:
                    temp_layerset_vals.append(
                        compinv_timeseries_dict[compinv].get(layerset, 0))
                else:
                    temp_layerset_vals.append(0)
            y_values.append(np.mean(temp_layerset_vals))
            std_values.append(np.std(temp_layerset_vals))

        line = main_ax.plot(x_axis, y_values, label=str(ii))
        main_ax.fill_between(x_axis,
                             np.subtract(y_values, std_values),
                             np.add(y_values, std_values),
                             facecolor=line[0].get_color(),
                             alpha=0.2)
        compinv_ax = plt.subplot2grid((grid_side_length, 2 * grid_side_length),
                                      ax_locs[ii],
                                      projection='3d')
        M = invdicts[compinv]
        pn.draw(M,
                layout='shell',
                alignedNodes=True,
                ax=compinv_ax,
                layerLabelRule={},
                nodeLabelRule={})
        if grid_side_length < 3:
            legend_loc = 'lower left'
        else:
            legend_loc = (0, 0)
        leg = compinv_ax.legend(labels=[''],
                                loc=legend_loc,
                                handles=line,
                                frameon=False)
        plt.setp(leg.get_lines(), linewidth=4)

    main_ax.set_xticks(x_axis)
    main_ax.set_xticklabels(layersets, rotation=90, fontsize='small')
    main_ax.set_yscale(yscale)
    main_ax.set_xlabel(xlabel)
    main_ax.set_ylabel(ylabel)
    main_ax.set_title(title)
    main_ax.margins(y=0.2)
    main_ax.set_xlim([x_axis[0], x_axis[-1]])
    plt.tight_layout()

    if savename == None:
        plt.show()
    else:
        plt.savefig(savename, format='pdf')
Beispiel #3
0
fig = pymnet.draw(
    net,
    show=False,
    azim=-60,
    elev=25,
    layergap=0.75,
    layout='shell',
    #						layershape='circle',
    autoscale=True,
    defaultNodeLabelAlpha=0.75,
    defaultLayerAlpha=0.25,

    # color
    nodeColorDict=nodeColorDict0,
    nodeLabelColorDict=nodeColorDict0,
    edgeColorDict=edgeColorDict0,

    # size
    nodeSizeDict=nodeSizeDict0,
    nodeSizeRule={
        'scalecoeff': 0.2,
        'rule': 'scaled'
    },
    nodeLabelSizeDict=nodeLabelSizeDict0,

    # width
    edgeWidthDict=edgeWidthDict0,
    defaultEdgeAlpha=1,

    # coords
    nodeCoords=nodeCoords0,
    nodelayerCoords=nodeCoords0,
    layerColorDict={
        'Gene': '#DAA520',
        'Protein': '#FF0000'
    },
    layerOrderDict={
        'SNP': 4,
        'Gene': 3,
        'miRNA': 2,
        'Protein': 1
    },
    # node label style
    defaultNodeLabelStyle='oblique',  # normal, italic or oblique
    layerPadding=0.25)
Beispiel #4
0
def plot_complete_invariant_time_series(subnet_filename,
                                        title,
                                        xlabel,
                                        ylabel,
                                        savename=None,
                                        examples_filename=None,
                                        map_ni_to_nli=False,
                                        colormap=plt.cm.jet,
                                        **kwargs):

    M = pn.MultilayerNetwork(aspects=1, fullyInterconnected=False)
    M['a', 'b', 0, 0] = 1
    M['a', 'a', 0, 1] = 1

    #layersetwise_complete_invariants = dict()
    complete_invariant_timeseries_dict = dict()
    layersets = set()
    invariants = set()

    if subnet_filename.strip()[-10:] == 'agg.pickle':
        f = open(subnet_filename, 'r')
        complete_invariant_timeseries_dict = pickle.load(f)
        f.close()
        for key in complete_invariant_timeseries_dict:
            invariants.add(key)
            layersets.update(
                [key2 for key2 in complete_invariant_timeseries_dict[key]])

    else:
        for subnet_data in subgraph_classification.yield_subnet_with_complete_invariant(
                subnet_filename):
            nodes = tuple(subnet_data[0])
            layers = tuple(sorted(subnet_data[1]))
            complete_invariant = subnet_data[2]
            layersets.add(layers)
            invariants.add(complete_invariant)
            #layersetwise_complete_invariants[layers] = layersetwise_complete_invariants.get(layers,dict())
            #layersetwise_complete_invariants[layers][complete_invariant] = layersetwise_complete_invariants[layers].get(complete_invariant,0) + 1
            complete_invariant_timeseries_dict[
                complete_invariant] = complete_invariant_timeseries_dict.get(
                    complete_invariant, dict())
            complete_invariant_timeseries_dict[complete_invariant][
                layers] = complete_invariant_timeseries_dict[
                    complete_invariant].get(layers, 0) + 1

    layersets = list(layersets)
    layersets.sort()
    full_range = zip(*(range(layersets[0][0], layersets[-1][-1] + 1)[ii:]
                       for ii in range(len(layersets[0]))))
    if layersets != full_range:
        layersets = full_range
    x_axis = list(range(layersets[0][0], layersets[-1][1]))

    # load example networks
    if examples_filename is not None:
        f = open(examples_filename, 'r')
        invdicts = pickle.load(f)
        f.close()
    else:
        nnodes = int(subnet_filename.split('/')[-1].strip()[0])
        nlayers = int(subnet_filename.split('/')[-1].strip()[2])
        example_nets_filename = 'example_nets/' + str(nnodes) + '_' + str(
            nlayers) + '.pickle'
        invdicts = complete_invariant_dicts.load_example_nets_file(
            example_nets_filename)

    # map node isomorphisms to nodelayer isomorphisms:
    if map_ni_to_nli:
        invariants = set()
        mapped_invdicts = dict()
        mapped_complete_invariant_timeseries_dict = dict()
        for complete_invariant in complete_invariant_timeseries_dict:
            nl_complete_invariant = pn.get_complete_invariant(
                invdicts[complete_invariant])
            if nl_complete_invariant not in mapped_invdicts:
                mapped_invdicts[nl_complete_invariant] = invdicts[
                    complete_invariant]
            invariants.add(nl_complete_invariant)
            mapped_complete_invariant_timeseries_dict[
                nl_complete_invariant] = mapped_complete_invariant_timeseries_dict.get(
                    nl_complete_invariant, dict())
            for tw in complete_invariant_timeseries_dict[complete_invariant]:
                mapped_complete_invariant_timeseries_dict[
                    nl_complete_invariant][
                        tw] = mapped_complete_invariant_timeseries_dict[
                            nl_complete_invariant].get(
                                tw, 0) + complete_invariant_timeseries_dict[
                                    complete_invariant][tw]
        complete_invariant_timeseries_dict = mapped_complete_invariant_timeseries_dict
        invdicts = mapped_invdicts

    # needed numbers of example figures
    number_of_invariants = len(invariants)
    grid_side_length = 0
    while grid_side_length**2 < number_of_invariants:
        grid_side_length = grid_side_length + 1
    ax_locs = list(
        itertools.product(range(grid_side_length),
                          range(grid_side_length, 2 * grid_side_length)))

    # figure
    fig = plt.figure(figsize=(12, 6))
    main_ax = plt.subplot2grid((grid_side_length, 2 * grid_side_length),
                               (0, 0),
                               rowspan=grid_side_length,
                               colspan=grid_side_length)
    colorcycler = plt.cycler('color',
                             colormap(np.linspace(0, 1, number_of_invariants)))
    main_ax.set_prop_cycle(colorcycler)
    #    side_ax = plt.subplot2grid((2,4),(0,2),projection='3d')
    #    side_ax2 = plt.subplot2grid((2,4),(0,3),projection='3d')
    #plt.hold(True)

    # identifiers for legend
    ids = range(len(invariants))

    for ii, compinv in enumerate(
            sorted(complete_invariant_timeseries_dict.iterkeys())):
        y_values = []
        for layerset in layersets:
            y_values.append(complete_invariant_timeseries_dict[compinv].get(
                layerset, 0))
        #main_ax = plt.subplot2grid((2,4),(0,0),rowspan=2,colspan=2)
        #main_ax.plot(x_axis,y_values,label=str(compinv))
        line = main_ax.plot(x_axis, y_values, label=str(ii))
        compinv_ax = plt.subplot2grid((grid_side_length, 2 * grid_side_length),
                                      ax_locs[ii],
                                      projection='3d')
        #example_ax = plt.gcf().add_axes((1.1,0,0.5,0.5),projection='3d')
        M = invdicts[compinv]
        pn.draw(M,
                layout='shell',
                alignedNodes=True,
                ax=compinv_ax,
                layerLabelRule={},
                nodeLabelRule={})
        #compinv_ax.text2D(0,0,str(ii),None,False,transform=compinv_ax.transAxes)
        if grid_side_length < 3:
            legend_loc = 'lower left'
        else:
            legend_loc = (0, 0)
        leg = compinv_ax.legend(labels=[''],
                                loc=legend_loc,
                                handles=line,
                                frameon=False)
        plt.setp(leg.get_lines(), linewidth=4)


#        if ii==0:
#            pn.draw(M,ax=side_ax)
#        else:
#            pn.draw(M,ax=side_ax2)
#plt.sca(fig.gca())

#    plt.xticks(x_axis,layersets,rotation=90,fontsize='small')
#    plt.xlabel(xlabel)
#    plt.ylabel(ylabel)
#    plt.title(title)
#    plt.legend(bbox_to_anchor=(1.05,1.),loc=0,fontsize='xx-small')
#    plt.yscale('log')
#    plt.margins(y=0.2)
#    plt.xlim([x_axis[0],x_axis[-1]])
#    plt.tight_layout()
#    plt.show()
    main_ax.set_xticks(x_axis)
    main_ax.set_xticklabels(layersets, rotation=90, fontsize='small')
    main_ax.set_yscale('log')
    main_ax.set_xlabel(xlabel)
    main_ax.set_ylabel(ylabel)
    main_ax.set_title(title)
    #main_ax.legend(bbox_to_anchor=(1.05,0),loc='upper left',ncol=number_of_invariants,fontsize='small')
    #main_ax.yscale('log')
    main_ax.margins(y=0.2)
    main_ax.set_xlim([x_axis[0], x_axis[-1]])
    plt.tight_layout()

    if savename == None:
        plt.show()
    else:
        plt.savefig(savename, format='pdf')
def orbit_counts_all(net,
                     n,
                     nets,
                     invs,
                     auts,
                     orbit_list,
                     allowed_aspects='all'):
    '''
    Computes the orbit counts for all the nodes in net
    
    Parameters
    ----------
    net : network
    n : int
        max number of nodes
    nets : dict (key: n_nodes, value: list of networks)
        Graphlets, as produced by graphlets
    invs : dict (key: str(complete invariant), value: tuple(n_nodes, net_index in nets))
        complete invariants of the graphlets, as produced by graphlet
    auts : dd (key: (n_nodes, net_index, node), value: node)
        automorphisms, as produced by automorphism_orbits
    orbit_list : list of orbits
        as returned by ordered_orbit_list
    allowed_aspects : list, string
        the aspects that can be permutated when computing isomorphisms
        
    Returns
    -------
    orbits : dd (key: (node, orbit), value: count)
        Orbit counts for all the nodes
    
    Notes
    -----
    Should be faster than orbit_counts if the counts are computed for all 
    (/ most of) the nodes
    '''

    nodes = net.slices[0]
    layers = net.slices[1]

    orbits = dd()

    for node in nodes:
        for orbit in orbit_list:
            orbits[node, orbit] = 0

    processed = set()

    for node0 in nodes:
        node_sets = set()
        set_p = set([frozenset([node0])])
        for _ in range(n - 1):
            set_c = set()
            for p in set_p:
                for node_p in p:
                    for layer in layers:
                        node_o = net.__getitem__((node_p, layer))
                        for neighbor in node_o.iter_total():
                            if not (neighbor[0] in p
                                    or neighbor[0] in processed):
                                set_n = frozenset(p | set([neighbor[0]]))
                                set_c.add(set_n)

            node_sets = node_sets.union(set_c)
            set_p = set_c.copy()

        processed.add(node0)
        for node_comb in node_sets:
            sub_net = pymnet.subnet(net, node_comb, layers)
            ci_sub = str(
                pymnet.get_complete_invariant(sub_net,
                                              allowed_aspects=allowed_aspects))
            if ci_sub not in invs:
                pymnet.draw(sub_net)
                print(len(invs))
            i = invs[ci_sub][0]
            j = invs[ci_sub][1]
            nw = nets[i][j]
            iso = pymnet.get_isomorphism(sub_net,
                                         nw,
                                         allowed_aspects=allowed_aspects)
            for node in node_comb:
                if node in iso[0]:
                    orbits[node, (i, j, auts[i, j, iso[0][node]])] += 1
                else:
                    orbits[node, (i, j, auts[i, j, node])] += 1

        for layer in layers:
            nls = list(net[node0, :, layer])
            for node1 in nls:
                net[node0, node1[0], layer] = 0  #remove edges

    return orbits