def test_append_scatter3d():
    expected = Figure(
        data=Data([
            Scatter3d(
                x=[1, 2, 3],
                y=[2, 3, 4],
                z=[1, 2, 3],
                scene='scene2'
            ),
            Scatter3d(
                x=[1, 2, 3],
                y=[2, 3, 4],
                z=[1, 2, 3],
                scene='scene2'
            )
        ]),
        layout=Layout(
            scene1=Scene(
                domain={'y': [0.575, 1.0], 'x': [0.0, 1.0]}
            ),
            scene2=Scene(
                domain={'y': [0.0, 0.425], 'x': [0.0, 1.0]}
            )
        )
    )

    fig = tls.make_subplots(rows=2, cols=1,
                            specs=[[{'is_3d': True}], 
                                   [{'is_3d': True}]])
    trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3])
    fig.append_trace(trace, 1, 1)
    fig.append_trace(trace, 2, 1)
    assert fig == expected
Beispiel #2
0
def test_append_scatter3d():
    expected = Figure(data=Data([
        Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene='scene1'),
        Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene='scene2')
    ]),
                      layout=Layout(scene1=Scene(domain={
                          'y': [0.575, 1.0],
                          'x': [0.0, 1.0]
                      }),
                                    scene2=Scene(domain={
                                        'y': [0.0, 0.425],
                                        'x': [0.0, 1.0]
                                    })))

    fig = tls.make_subplots(rows=2,
                            cols=1,
                            specs=[[{
                                'is_3d': True
                            }], [{
                                'is_3d': True
                            }]])
    trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3])
    fig.append_trace(trace, 1, 1)
    fig.append_trace(trace, 2, 1)

    d1, d2 = strip_dict_params(fig['data'][0], expected['data'][0])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig['data'][1], expected['data'][1])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig['layout'], expected['layout'])
    assert d1 == d2
Beispiel #3
0
    def init_layout(self, key, element, ranges):
        l, b, zmin, r, t, zmax = self.get_extents(element, ranges)

        xd, yd, zd = (element.get_dimension(i) for i in range(3))
        xaxis = dict(range=[l, r], title=str(xd))
        if self.logx:
            xaxis['type'] = 'log'

        yaxis = dict(range=[b, t], title=str(yd))
        if self.logy:
            yaxis['type'] = 'log'

        zaxis = dict(range=[zmin, zmax], title=str(zd))
        if self.logz:
            zaxis['type'] = 'log'

        opts = {}
        if self.aspect == 'cube':
            opts['aspectmode'] = 'cube'
        else:
            opts['aspectmode'] = 'manual'
            opts['aspectratio'] = self.aspect
        scene = Scene(xaxis=XAxis(xaxis),
                      yaxis=YAxis(yaxis),
                      zaxis=ZAxis(zaxis),
                      **opts)

        return dict(width=self.width,
                    height=self.height,
                    title=self._format_title(key, separator=' '),
                    plot_bgcolor=self.bgcolor,
                    scene=scene)
def Kmeans_3D(XT, plt_title, k):
    kmeans = KMeans(n_clusters=k)
    # Compute cluster centers and predict cluster indices
    X_clustered = kmeans.fit_predict(XT)

    fig = go.Figure(data=[
        go.Scatter3d(x=XT[:, 0],
                     y=XT[:, 1],
                     z=XT[:, 2],
                     mode="markers",
                     showlegend=False,
                     text=adata.var_names,
                     marker=dict(size=8,
                                 color=X_clustered,
                                 colorscale='Portland',
                                 showscale=False,
                                 line=dict(width=2,
                                           color='rgb(255, 255, 255)')))
    ])

    layout = fig.update_layout(title=plt_title,
                               hovermode='closest',
                               scene=Scene(bgcolor='rgba(255,255,255,255)',
                                           xaxis={
                                               'showgrid': False,
                                               'backgroundcolor':
                                               'rgba(255,255,255,255)',
                                               'showline': False,
                                               'zeroline': False,
                                               'color': "rgb(255,255,255)"
                                           },
                                           yaxis={
                                               'showgrid': False,
                                               'showline': False,
                                               'zeroline': False,
                                               'backgroundcolor':
                                               'rgba(255,255,255,255)',
                                               'color': "rgb(255,255,255)"
                                           },
                                           zaxis={
                                               'showgrid': False,
                                               'showline': False,
                                               'zeroline': False,
                                               'backgroundcolor':
                                               'rgba(255,255,255,255)',
                                               'color': "rgb(255,255,255)"
                                           }),
                               showlegend=False)

    data = fig
    fig1 = dict(data=data, layout=layout)
    py.plot(fig1, filename=plt_title)
    print('Clustering Score', silhouette_score(XT, X_clustered))
def test_append_scatter3d():
    expected = Figure(
        data=Data([
            Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene="scene1"),
            Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3], scene="scene2"),
        ]),
        layout=Layout(
            scene1=Scene(domain={
                "y": [0.575, 1.0],
                "x": [0.0, 1.0]
            }),
            scene2=Scene(domain={
                "y": [0.0, 0.425],
                "x": [0.0, 1.0]
            }),
        ),
    )

    fig = tls.make_subplots(rows=2,
                            cols=1,
                            specs=[[{
                                "is_3d": True
                            }], [{
                                "is_3d": True
                            }]])
    trace = Scatter3d(x=[1, 2, 3], y=[2, 3, 4], z=[1, 2, 3])
    fig.append_trace(trace, 1, 1)
    fig.append_trace(trace, 2, 1)

    d1, d2 = strip_dict_params(fig["data"][0], expected["data"][0])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig["data"][1], expected["data"][1])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig["layout"], expected["layout"])
    assert d1 == d2
Beispiel #6
0
def make_plot(args):
    """This function will generate a 3D surface plot."""
    raw_data = pd.read_csv(args.outprefix + '_matrix.tsv',
                           sep="\t",
                           dtype=float,
                           names=['length_pseudo', 'shared_hits', 'vals'],
                           header=0)
    matrix = raw_data.pivot(index='length_pseudo',
                            columns='shared_hits',
                            values='vals')

    data = [Surface(x=matrix.columns, y=matrix.index, z=matrix.values)]

    layout = Layout(
        scene=Scene(xaxis=dict(title='shared_hits', autorange=True),
                    yaxis=dict(title='length_pseudo', autorange=True),
                    zaxis=dict(title=args.title, autorange=True)))

    fig = Figure(data=data, layout=layout)
    plot(fig, filename=args.outprefix + ".html", auto_open=False)
    print("%s\tFigure plotted: %s.html" % (current_time(), args.outprefix))
Beispiel #7
0
def plot_opti_lambdas(path):
    costs = deserialize_costs(path)
    print("Loaded {} cached hyperparameters combinations".format(len(costs)))
    ucosts, icosts = list(zip(*costs))
    z = list(costs.values())
    (
        min_ulambda,
        min_ilambda,
    ), min_cost = min(costs.items(), key=lambda x: x[1])
    fig = go.Figure(
        data=[
            go.Scatter3d(
                x=ucosts,
                y=icosts,
                z=z,
                mode='markers',
                marker=dict(
                    size=8,
                    color=z,  # set color to an array/list of desired values
                    colorscale='Viridis',  # choose a colorscale
                    opacity=0.8,
                ),
                name="Sample"),
            go.Scatter3d(x=[min_ulambda],
                         y=[min_ilambda],
                         z=[min_cost],
                         mode="markers",
                         ids=["Minimum"],
                         marker=dict(
                             size=8,
                             color="red",
                             opacity=0.8,
                         ),
                         name="Minimum")
        ],
        layout=Layout(scene=Scene(xaxis=XAxis(title='User lambda'),
                                  yaxis=YAxis(title='Item lambda'),
                                  zaxis=ZAxis(title='Cost'))))
    fig.show()
Beispiel #8
0
def draw3Dnx(graph=None,
             out_path=None,
             perc_threshold=None,
             positions_array=None,
             positions_dict=None,
             plot_title='',
             plot_description='',
             colorscale='Set3',
             notebook_mode=True,
             auto_open=False):
    """Draws a given graph in 3D"""

    if graph is None or nx.is_empty(graph):
        raise ValueError('input graph can not be empty!')
        # graph = nx.random_geometric_graph(200, 0.05)

    if notebook_mode:
        init_notebook_mode()

    marker_size = 7
    marker_edge_width = 2
    link_width = 2
    colorbar_title = 'Node Connections'
    hover_description = '# connections: '

    position_attr = ['x', 'y', 'z']
    if positions_array is not None:
        for node in graph.nodes():
            for ix, attr in enumerate(position_attr):
                graph.nodes[node][attr] = positions_array[node][ix]
    elif positions_dict is not None:
        for node in graph.nodes():
            for attr in position_attr:
                graph.nodes[node][attr] = positions_array[node][attr]

    for attr in position_attr:
        if not nx.get_node_attributes(graph, attr):
            raise ValueError(
                'Position attribute {} missing. '
                'Add it to graph or supply with one of the position inputs'.
                format(attr))

    edge_threshold = -np.Inf
    if perc_threshold is not None:
        eval_distr = np.array(
            list(nx.get_edge_attributes(graph, 'weight').values()))
        try:
            edge_threshold = np.percentile(eval_distr, perc_threshold)
        except:
            print('threshold to prune edges can not be determined.')
            traceback.print_exc()
            return

    edge_trace = Scatter3d(
        x=[],
        y=[],
        z=[],
        mode='lines',
        line=Line(width=marker_edge_width, color='#888'),
        hoverinfo='none',
    )

    def get_position(gnode):
        """Helper to retun the x, y, z coords of a node"""
        return gnode['x'], gnode['y'], gnode['z']

    for src, dest in graph.edges():
        # adding only the strongest edges
        if perc_threshold is None or graph.get_edge_data(
                src, dest)['weight'] > edge_threshold:
            x0, y0, z0 = get_position(graph.nodes[src])  # ['position']
            x1, y1, z1 = get_position(graph.nodes[dest])  # ['position']
            edge_trace['x'].extend([x0, x1, None])
            edge_trace['y'].extend([y0, y1, None])
            edge_trace['z'].extend([z0, z1, None])

    # empty lists here will be appended with data to be plotted
    node_trace = Scatter3d(x=[],
                           y=[],
                           z=[],
                           text=[],
                           mode='markers',
                           hoverinfo='text',
                           marker=Marker(
                               symbol='dot',
                               showscale=True,
                               colorscale=colorscale,
                               reversescale=True,
                               color=[],
                               size=marker_size,
                               colorbar=dict(thickness=15,
                                             title=colorbar_title,
                                             xanchor='left',
                                             titleside='right'),
                           ))

    # setting nodal positions and info
    for ix, node in enumerate(graph.nodes()):
        x, y, z = get_position(graph.nodes[node])
        node_trace['x'].append(x)
        node_trace['y'].append(y)
        node_trace['z'].append(z)
        node_trace['text'].append(node)
        node_trace['marker']['color'].append(ix)

    axis = dict(showbackground=False,
                showline=False,
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                title='')

    scene = Scene(xaxis=XAxis(axis), yaxis=YAxis(axis), zaxis=ZAxis(axis))

    annotations = Annotations([
        Annotation(
            showarrow=False,
            text=plot_description,
            xref='paper',
            yref='paper',
            x=0,
            y=0.1,  # z=0.05,
            xanchor='left',
            yanchor='bottom',  # zanchor='bottom',
            font=Font(size=14))
    ])

    layout = Layout(
        title=plot_title,
        titlefont=dict(size=16),
        # width=1000,
        # height=1000,
        showlegend=False,
        hovermode='closest',
        scene=scene,
        margin=Margin(t=100),
        # margin=dict(b=20,l=5,r=5,t=40),
        annotations=annotations,
    )

    fig_data = Data([edge_trace, node_trace])

    fig = Figure(data=fig_data, layout=layout)

    if out_path is None and auto_open is False:
        auto_open = True

    if notebook_mode:
        iplot(fig, filename=out_path)
    else:
        plot(fig, filename=out_path, auto_open=auto_open)

    return fig
Beispiel #9
0
axis=dict(showbackground=False,
          showline=False,
          zeroline=False,
          showgrid=False,
          showticklabels=False,
          title=''
          )

layout = Layout(
         title="Link Structure for Delhi University - Academics",
         width=1000,
         height=1000,
         showlegend=False,
         scene=Scene(
         xaxis=XAxis(axis),
         yaxis=YAxis(axis),
         zaxis=ZAxis(axis),
        ),
     margin=Margin(
        t=100
    ),
    hovermode='closest',
    annotations=Annotations([
           Annotation(
           showarrow=False,
            text="",
            xref='paper',
            yref='paper',
            x=0,
            y=0.1,
            xanchor='left',
                    y=y,
                    z=z,
                    mode='markers',
                    marker=dict(
                        size=6,
                        #             line=dict(
                        #                 color='rgba(217, 217, 217, 0.14)',
                        #                 width=0.2
                        #             ),
                        opacity=0.5),
                    name='cluster ' + str(i),
                    text=names[cur_km.labels_ == i]))

        layout = Layout(title='3 KMeans clusters of strains by effects',
                        scene=Scene(xaxis=XAxis(title='PCA Dimension 1'),
                                    yaxis=YAxis(title='PCA Dimension 2'),
                                    zaxis=ZAxis(title='PCA Dimension 3')))

        fig = go.Figure(data=traces, layout=layout)
        py.plot(fig,
                filename='3 KMeans clusters of strains by effects',
                world_readable=True)

        # look at means of chemicals in different groups
        groups = []
        for i in range(3):
            groups.append(product_chem_df[cur_km.labels_ == i])
            print(groups[i].mean())

        pk.dump(groups, open('analytical360/3_kmeans_chem_groups_pd.pk', 'w'),
                2)
Beispiel #11
0
def visualize(depo_nodes, customer_nodes, edges):
    customers_count = len(customer_nodes)
    depo_count = len(depo_nodes)

    print(edges)

    customer_labels = []
    customer_group = []
    for node in customer_nodes:
        customer_labels.append(node['name'])
        customer_group.append(node['group'])

    depo_labels = []
    depo_group = []
    for node in depo_nodes:
        depo_labels.append(node['name'])
        depo_group.append(node['group'])

    customer_x = [
        customer_nodes[k]["coords"][0] for k in range(customers_count)
    ]  # x-coordinates of nodes
    customer_y = [
        customer_nodes[k]["coords"][1] for k in range(customers_count)
    ]  # y-coordinates
    customer_z = [
        customer_nodes[k]["coords"][2] for k in range(customers_count)
    ]  # z-coordinates

    depo_x = [depo_nodes[k]["coords"][0]
              for k in range(depo_count)]  # x-coordinates of nodes
    depo_y = [depo_nodes[k]["coords"][1]
              for k in range(depo_count)]  # y-coordinates
    depo_z = [depo_nodes[k]["coords"][2]
              for k in range(depo_count)]  # z-coordinates

    xe = []
    ye = []
    ze = []
    for e in edges:
        xe += [e["source"][0], e["target"][0],
               None]  # x-coordinates of edge ends
        ye += [e["source"][1], e["target"][1], None]
        ze += [e["source"][2], e["target"][2], None]

    trace1 = Scatter3d(x=xe,
                       y=ye,
                       z=ze,
                       mode='lines',
                       line=Line(color='rgb(125,0,125)', width=5),
                       hoverinfo='text')
    trace2 = Scatter3d(x=customer_x,
                       y=customer_y,
                       z=customer_z,
                       mode='markers',
                       name='customers',
                       marker=Marker(symbol='dot',
                                     size=6,
                                     color=[2, 0],
                                     colorscale='Viridis',
                                     line=Line(color='rgb(50,50,50)',
                                               width=0.5)),
                       text=customer_labels,
                       hoverinfo='text')

    trace3 = Scatter3d(x=depo_x,
                       y=depo_y,
                       z=depo_z,
                       mode='markers',
                       name='depos',
                       marker=Marker(symbol='dot',
                                     size=12,
                                     color=[0, 1, 2],
                                     colorscale='Viridis',
                                     line=Line(color='rgb(50,50,50)',
                                               width=0.5)),
                       text=depo_labels,
                       hoverinfo='text')
    axis = dict(showbackground=True,
                showline=True,
                zeroline=False,
                showgrid=True,
                showticklabels=True,
                title='')

    layout = Layout(title="Network of ...",
                    width=1200,
                    height=800,
                    showlegend=True,
                    scene=Scene(
                        xaxis=XAxis(axis),
                        yaxis=YAxis(axis),
                        zaxis=ZAxis(axis),
                    ),
                    margin=Margin(t=100),
                    hovermode='closest')

    plotly.offline.plot({"data": [trace1, trace2, trace3], "layout": layout})
Beispiel #12
0
def experimental_antibug_visualize(depo_nodes, customer_nodes, edges):
    traces = []
    for i in range(len(depo_nodes)):
        traces.append(
            Scatter3d(x=[depo_nodes[i]["coords"][0]],
                      y=[depo_nodes[i]["coords"][1]],
                      z=[depo_nodes[i]["coords"][2]],
                      mode='markers',
                      name='depos',
                      marker=Marker(symbol='dot',
                                    size=12,
                                    color=my_scale[depo_nodes[i]["group"]],
                                    line=Line(color='rgb(50,50,50)',
                                              width=0.5)),
                      text=depo_nodes[i]["name"],
                      hoverinfo='text'))

    for i in range(len(customer_nodes)):
        traces.append(
            Scatter3d(x=[customer_nodes[i]["coords"][0]],
                      y=[customer_nodes[i]["coords"][1]],
                      z=[customer_nodes[i]["coords"][2]],
                      mode='markers',
                      name='customers',
                      marker=Marker(symbol='dot',
                                    size=6,
                                    color=my_scale[customer_nodes[i]["group"]],
                                    line=Line(color='rgb(50,50,50)',
                                              width=0.5)),
                      text=customer_nodes[i]["name"],
                      hoverinfo='text'))

    xe = []
    ye = []
    ze = []
    for e in edges:
        xe += [e["source"][0], e["target"][0],
               None]  # x-coordinates of edge ends
        ye += [e["source"][1], e["target"][1], None]
        ze += [e["source"][2], e["target"][2], None]

    traces.append(
        Scatter3d(x=xe,
                  y=ye,
                  z=ze,
                  mode='lines',
                  line=Line(color='rgb(125,0,125)', width=5),
                  hoverinfo='text'))

    axis = dict(showbackground=True,
                showline=True,
                zeroline=False,
                showgrid=True,
                showticklabels=True,
                title='')

    layout = Layout(title="Network of ...",
                    width=1200,
                    height=800,
                    showlegend=False,
                    scene=Scene(
                        xaxis=XAxis(axis),
                        yaxis=YAxis(axis),
                        zaxis=ZAxis(axis),
                    ),
                    margin=Margin(t=100),
                    hovermode='closest')

    plotly.offline.plot({"data": traces, "layout": layout})
Beispiel #13
0
    def GeneRegulationNetwork(self, netthreshold, config, netconfig):

        # Transpose the dataframe to get correct format to create the network
        dfT = self.dfz.transpose()

        # Get all the TF Gene names
        tf_names = list(dfT)

        # Create a Dask Client, just in case we want parellalize the algorithm
        client = Client(processes=False)

        # create dataframe network with columns --> TF, target Gene, Importance
        if netconfig == 1:
            network = grnboost2(expression_data=dfT,
                                tf_names=tf_names,
                                client_or_address=client)
            print("grnboost2")
        else:
            network = genie3(expression_data=dfT,
                             tf_names=tf_names,
                             client_or_address=client)

        # We put a threshold because we have a lot of conections and we want to obtain a clear graph with the most representatives conected genes
        limit = network.index.size * netthreshold

        G = nx.from_pandas_edgelist(network.head(int(limit)),
                                    'TF',
                                    'target', ['importance'],
                                    create_using=nx.Graph(directed=False))

        N = len(list(G.node()))  # number of genes nodes
        V = list(G.node())  # list of genes nodes

        Edges = list(G.edges())

        layt = {
            1: nx.fruchterman_reingold_layout(G, dim=3),
            2: nx.circular_layout(G, dim=3)
        }.get(config, nx.circular_layout(G, dim=3))

        laytN = list(layt.values())

        Xn = [laytN[k][0] for k in range(N)]  # x-coordinates of nodes
        Yn = [laytN[k][1] for k in range(N)]  # y-coordinates
        Zn = [laytN[k][2] for k in range(N)]  # z-coordinates
        Xe = []
        Ye = []
        Ze = []
        for e in Edges:
            Xe += [layt[e[0]][0], layt[e[1]][0],
                   None]  # x-coordinates of edge ends
            Ye += [layt[e[0]][1], layt[e[1]][1], None]
            Ze += [layt[e[0]][2], layt[e[1]][2], None]

        trace1 = Scatter3d(x=Xe,
                           y=Ye,
                           z=Ze,
                           mode='lines',
                           line=Line(color='rgb(125,125,125)', width=1),
                           hoverinfo='none')

        trace2 = Scatter3d(x=Xn,
                           y=Yn,
                           z=Zn,
                           mode='markers+text',
                           textposition='top center',
                           name='genes',
                           marker=Marker(symbol='circle',
                                         size=3,
                                         color='#6959CD',
                                         colorscale='Viridis',
                                         line=Line(color='rgb(50,50,50)',
                                                   width=1)),
                           text=V,
                           hoverinfo='text')

        axis = dict(showbackground=False,
                    showline=False,
                    zeroline=False,
                    showgrid=False,
                    showticklabels=False,
                    title='')

        fig = Figure(data=Data([trace1, trace2]),
                     layout=Layout(
                         title="Gene Regulatory Network",
                         width=1000,
                         height=1000,
                         showlegend=False,
                         scene=Scene(
                             xaxis=XAxis(axis),
                             yaxis=YAxis(axis),
                             zaxis=ZAxis(axis),
                         ),
                         margin=Margin(t=100),
                         hovermode='closest',
                         annotations=Annotations([
                             Annotation(showarrow=False,
                                        text="Khaos Research Group",
                                        xref='paper',
                                        yref='paper',
                                        x=0,
                                        y=0.1,
                                        xanchor='left',
                                        yanchor='bottom',
                                        font=Font(size=20))
                         ]),
                     ))

        plotly.offline.plot(fig, filename='3DNetworkx_.html', auto_open=True)
        script = plot(fig,
                      output_type='div',
                      include_plotlyjs=False,
                      show_link=True)
        #print(script)
        return script
Beispiel #14
0
    def draw_igraph(self, title, colors=None):
        (Xn, Yn, Zn), (Xe, Ye, Ze) = self.get_3d_position()

        trace1 = Scatter3d(x=Xe,
                           y=Ye,
                           z=Ze,
                           mode='lines',
                           line=Line(color='rgb(125,125,125)',
                                     width=1,
                                     dash=True),
                           hoverinfo='none')

        trace2 = Scatter3d(
            x=Xn,
            y=Yn,
            z=Zn,
            mode='markers',
            name='callers',
            marker=Marker(
                symbol='dot',
                size=[100 * x + 5 for x in list(self.betweenness.values())],
                color=self.colors,
                colorscale='Rainbow',
                opacity=0.5),
            text=self.nodes,
            hoverinfo='text')

        axis = dict(showbackground=False,
                    showline=False,
                    zeroline=False,
                    showgrid=False,
                    showticklabels=False,
                    title='')
        layout = Layout(
            title=title,
            width=1000,
            height=1000,
            showlegend=False,
            scene=Scene(
                xaxis=XAxis(axis),
                yaxis=YAxis(axis),
                zaxis=ZAxis(axis),
            ),
            margin=Margin(t=100),
            hovermode='closest',
            annotations=Annotations([
                Annotation(showarrow=False,
                           text="Data source: ???",
                           xref='paper',
                           yref='paper',
                           x=0,
                           y=0.1,
                           xanchor='left',
                           yanchor='bottom',
                           font=Font(size=14))
            ]),
        )

        data = Data([trace1, trace2])
        fig = Figure(data=data, layout=layout)

        iplot(fig, filename='Call Network')
Beispiel #15
0
def Generate_3DModel(idList, labelList, percentage):

    network = pd.read_csv("network.csv")
    L = len(network['TF'])

    #Values=[network['importance'][k] for k in range(L)]

    #G=ig.Graph(Edges, directed=False)
    #layt=G.layout('kk', dim=3)

    G = Create_Graph(idList, labelList, percentage, netthreshold)
    N = len(list(G.node()))  #--> Numero de nodos
    V = list(G.node())  # lista con todos los nodos

    #Edges=[(network['TF'][k], network['target'][k]) for k in range(L)]
    Edges = list(G.edges())

    #layt=nx.spectral_layout(G,dim=3)

    #layt=nx.spring_layout(G, dim=3)
    #layt=nx.fruchterman_reingold_layout(G,dim=3)
    #layt=laytdict.values()

    #g=nx.Graph()
    #g.add_nodes_from(V)
    #g.add_edges_from(Edges)

    layt = nx.fruchterman_reingold_layout(G, dim=3)
    #layt = nx.circular_layout(G,scale=10,dim=3)
    #layt=nx.spring_layout(G,dim=3)
    laytN = list(layt.values())

    Xn = [laytN[k][0] for k in range(N)]  # x-coordinates of nodes
    Yn = [laytN[k][1] for k in range(N)]  # y-coordinates
    Zn = [laytN[k][2] for k in range(N)]  # z-coordinates
    Xe = []
    Ye = []
    Ze = []
    for e in Edges:
        Xe += [layt[e[0]][0], layt[e[1]][0],
               None]  # x-coordinates of edge ends
        Ye += [layt[e[0]][1], layt[e[1]][1], None]
        Ze += [layt[e[0]][2], layt[e[1]][2], None]

    trace1 = Scatter3d(x=Xe,
                       y=Ye,
                       z=Ze,
                       mode='lines',
                       line=Line(color='rgb(125,125,125)', width=1),
                       hoverinfo='none')
    trace2 = Scatter3d(x=Xn,
                       y=Yn,
                       z=Zn,
                       mode='markers+text',
                       textposition='top',
                       name='genes',
                       marker=Marker(symbol='dot',
                                     size=6,
                                     color='#6959CD',
                                     colorscale='Viridis',
                                     line=Line(color='rgb(50,50,50)',
                                               width=1)),
                       text=V,
                       hoverinfo='text')

    #for node, adjacencies in enumerate(G.adjacency()):
    #trace2['marker']['color'].append(len(adjacencies))
    #node_info = 'Number of connections: '+str(len(adjacencies))
    #trace2['text'].append(node_info)

    axis = dict(showbackground=False,
                showline=False,
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                title='')

    fig = Figure(data=Data([trace1, trace2]),
                 layout=Layout(
                     title="Network (3D visualization)",
                     width=1000,
                     height=1000,
                     showlegend=False,
                     scene=Scene(
                         xaxis=XAxis(axis),
                         yaxis=YAxis(axis),
                         zaxis=ZAxis(axis),
                     ),
                     margin=Margin(t=100),
                     hovermode='closest',
                     annotations=Annotations([
                         Annotation(showarrow=False,
                                    text="",
                                    xref='paper',
                                    yref='paper',
                                    x=0,
                                    y=0.1,
                                    xanchor='left',
                                    yanchor='bottom',
                                    font=Font(size=14))
                     ]),
                 ))

    py.iplot(fig, filename='networkx3D')
Beispiel #16
0
    def plot(self, engine='pyplot', iterations=None):
        """Plots the system using a specified render engine.
        Needs compute_3d_vectrices() to be called before.
        - engine: String for the render engine. Can be 'pyplot', 'plotly' or 'visvis'.
        pyplot is the nicest because it supports antialiasing on translucent objects.
        plotly is a way faster alternative that uses your web browser's render engine.
        visvis is faster but a bit rough.
        - iterations: Limits the plotting to this number of iterations.
        If None, the whole system states will be plotted."""
        engine = engine.lower()
        if iterations is None:
            iterations = self.iterations
        elif iterations > self.iterations:
            raise ValueError("Unable to plot %s out of %s iterations"
                % (iterations, self.iterations))

        if engine == 'visvis':
            try:
                import visvis as vv
            except ImportError:
                raise ImportError("visvis must be installed in order to use it."
                "Try to 'pip install visvis' in a command line.")
            app = vv.use()
            fig = vv.clf()
            ax  = vv.cla()

        elif engine == 'pyplot':
            try:
                import matplotlib.pyplot as plt
                from mpl_toolkits.mplot3d import Axes3D
            except ImportError:
                raise ImportError("pyplot must be installed in order to use it."
                "Try to 'pip install matplotlib' in a command line.")
            fig = plt.figure(figsize=(32, 18), dpi=100)
            ax = fig.gca(projection='3d')
            ax.set_axis_off()

        elif engine == 'plotly':
            try:
                import plotly as pl
                from plotly.graph_objs import Scatter3d, Layout, Scene, Figure
            except ImportError:
                raise ImportError("plotly must be installed in order to use it."
                "Try to 'pip install plotly' in a command line.")
            data = []
            layout = Layout(
                scene = Scene(
                    xaxis=dict(
                        visible = False,
                        autorange = True,
                    ),
                    yaxis=dict(
                        visible = False,
                        autorange = True,
                    ),
                    zaxis=dict(
                        visible = False,
                        autorange = True,
                    )
                ),
                margin=dict(
                    r=0, l=0,
                    b=0, t=0
                ),
                showlegend = False,
                hovermode = False
            )

        else:
            raise ValueError("%s is not a supported render engine." % engine)


        rings  = self.rings[:iterations]
        for i, ring in enumerate(rings):
            color = self.cmap(i, 0, len(self.rings) / 2, 1)
            if engine == 'visvis':
                vv.plot(*ring, lc=color, mw=0, alpha=.2)
            elif engine == 'pyplot':
                ax.plot(*ring, c=color+(.4,)) # Adding alpha as (r, g, b, a)
            else:
                data.append(Scatter3d(
                    x = ring[0],
                    y = ring[1],
                    z = ring[2],
                    mode = 'lines',
                    opacity = .3,
                    line = dict(
                        color = ("rgb(%s,%s,%s)" % tuple([int(x*255) for x in color])),
                        width = 3)
                ))

        curves = [curve[:iterations] for curve in self.curves]
        for curve in curves:
            if engine == 'visvis':
                vv.plot(*curve, lc='k', mw=0, lw=2)
            elif engine == 'pyplot':
                ax.plot(*curve, c=(0, 0, 0, .8))
            else:
                data.append(Scatter3d(
                x = curve[0],
                y = curve[1],
                z = curve[2],
                mode = 'lines',
                line = dict(
                    color = ("rgb(0, 0, 0)"),
                    width = 4)
                ))

        if engine == 'visvis':
            ax = vv.gca()
            app.Run()

        elif engine == 'pyplot':
            fig.tight_layout()
            # plt.draw()
            mng = plt.get_current_fig_manager()
            mng.full_screen_toggle()
            plt.show()

        else:
            fig = Figure(data=data, layout=layout)
            # pl.plot(fig, filename='3d-scatter-with-axes-titles')
            pl.offline.plot(fig)

        return
Beispiel #17
0
def visualize_graph_3d(G, filename, node_labels=[], node_sizes=[], title="3d"):
    edge_trace = Scatter3d(x=[],
                           y=[],
                           z=[],
                           mode='lines',
                           line=Line(color='rgba(136, 136, 136, .8)', width=1),
                           hoverinfo='none')

    node_trace = Scatter3d(
        x=[],
        y=[],
        z=[],
        mode='markers',
        #name='actors',
        marker=Marker(
            symbol='circle',
            size=[],
            color=[],
            colorscale='Jet',  #'Viridis',
            colorbar=dict(thickness=15,
                          title='Node Connections',
                          xanchor='left',
                          titleside='right'),
            line=Line(color='rgb(50,50,50)', width=0.5)),
        text=[],
        hoverinfo='text')

    positions = nx.fruchterman_reingold_layout(G,
                                               dim=3,
                                               k=0.5,
                                               iterations=1000)

    for edge in G.edges():
        x0, y0, z0 = positions[edge[0]]
        x1, y1, z1 = positions[edge[1]]
        edge_trace['x'] += (x0, x1, None)
        edge_trace['y'] += (y0, y1, None)
        edge_trace['z'] += (z0, z1, None)

    for node in G.nodes():
        x, y, z = positions[node]
        node_trace['x'] += (x, )
        node_trace['y'] += (y, )
        node_trace['z'] += (z, )

    for adjacencies in G.adjacency_list():
        node_trace['marker']['color'].append(len(adjacencies))

    if node_sizes:
        for size in node_sizes:
            node_trace['marker']['size'].append(size)
    else:
        node_trace['marker']['size'] = [1] * len(G.nodes())

    if not node_labels:
        node_labels = G.nodes()

    for node in node_labels:
        node_trace['text'].append(node)

    axis = dict(showbackground=False,
                showline=False,
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                title='')

    layout = Layout(
        title=title,
        width=1000,
        height=1000,
        showlegend=False,
        scene=Scene(
            xaxis=XAxis(axis),
            yaxis=YAxis(axis),
            zaxis=ZAxis(axis),
        ),
        margin=Margin(t=100),
        hovermode='closest',
        annotations=Annotations([
            Annotation(showarrow=False,
                       text="",
                       xref='paper',
                       yref='paper',
                       x=0,
                       y=0.1,
                       xanchor='left',
                       yanchor='bottom',
                       font=Font(size=14))
        ]),
    )

    data = Data([node_trace, edge_trace])
    fig = Figure(data=data, layout=layout)

    offpy(fig, filename=filename, auto_open=True, show_link=False)