def visualize_clusters(self, clusters):
     """
     Visualization of point cloud data
     :param clusters: identified clusters
     :return:
     """
     trace_1 = go.Scatter3d(x=self.pcd_data.X,
                            y=self.pcd_data.Y,
                            z=self.pcd_data.Z,
                            mode='markers')
     # extract points from clusters
     cluster_points = pd.DataFrame(columns={"Cluster_id", "X", "Y", "Z"})
     for key in clusters:
         # Get all the indexes related to the cluster id = key
         cluster_point_indexes = clusters[key]
         for point_index in cluster_point_indexes:
             point = self.get_point(point_index)
             cluster_points = cluster_points.append(
                 {
                     "Cluster_id": key,
                     "X": point[0],
                     "Y": point[1],
                     "Z": point[2]
                 },
                 ignore_index=True)
     unique_clusters = []
     for cluster_id in cluster_points.Cluster_id.unique():
         cluster_traces = [
             go.Scatter3d(x=cluster_points[cluster_points["Cluster_id"] ==
                                           cluster_id].X,
                          y=cluster_points[cluster_points["Cluster_id"] ==
                                           cluster_id].Y,
                          z=cluster_points[cluster_points["Cluster_id"] ==
                                           cluster_id].Z,
                          mode='markers')
         ]
         unique_clusters.extend(cluster_traces)
     data = [trace_1]
     data.extend(unique_clusters)
     fig = go.Figure(data)
     fig.show()
Example #2
0
def test_scatter(X, Y, Z, x_test, y_test, Z_validate, surface_name='MADGE Interpolate Surface', filename='test.html'):
    """
    Generates a plot of the interpolated data overlayed with the general data
    :param X: 
    :return: None
    """
    trace_surface = go.Surface(x=X, y=Y, z=Z, name=surface_name)
    test_scatter = go.Scatter3d(x=x_test, y=y_test, z=Z_validate, mode='markers',
                                         name='Interpolated Values')
    data = [trace_surface, test_scatter]
    fig = go.Figure(data=data)
    py.offline.plot(fig, filename=filename)
def pcshow(xs, ys, zs):
    data = [go.Scatter3d(x=xs, y=ys, z=zs, mode='markers')]
    fig = visualize_rotate(data)
    fig.update_traces(marker=dict(size=2,
                                  line=dict(width=2, color='DarkSlateGrey')),
                      selector=dict(mode='markers'))
    fig.show()
    # 文件导出需要用到plotly-orca
    # 安装方法: conda install -c plotly plotly-orca
    if not os.path.exists("images"):
        os.mkdir("images")
    fig.write_image("images/fig1.svg")
def add_t(x, y, z, fig, size=.1, color='white'):
    fig.add_trace(
        go.Scatter3d(
            x=x,
            y=y,
            z=z,
            opacity=1,
            marker=dict(
                size=size,
                color=color,
            ),
        ))
Example #5
0
def _add_camera_trace(
    fig: go.Figure,
    cameras: CamerasBase,
    trace_name: str,
    subplot_idx: int,
    ncols: int,
    camera_scale: float,
):  # pragma: no cover
    """
    Adds a trace rendering a Cameras object to the passed in figure, with
    a given name and in a specific subplot.

    Args:
        fig: plotly figure to add the trace within.
        cameras: the Cameras object to render. It can be batched.
        trace_name: name to label the trace with.
        subplot_idx: identifies the subplot, with 0 being the top left.
        ncols: the number of subplots per row.
        camera_scale: the size of the wireframe used to render the Cameras object.
    """
    cam_wires = get_camera_wireframe(camera_scale).to(cameras.device)
    cam_trans = cameras.get_world_to_view_transform().inverse()
    cam_wires_trans = cam_trans.transform_points(cam_wires).detach().cpu()
    # if batch size is 1, unsqueeze to add dimension
    if len(cam_wires_trans.shape) < 3:
        cam_wires_trans = cam_wires_trans.unsqueeze(0)

    nan_tensor = torch.Tensor([[float("NaN")] * 3])
    all_cam_wires = cam_wires_trans[0]
    for wire in cam_wires_trans[1:]:
        # We combine camera points into a single tensor to plot them in a
        # single trace. The NaNs are inserted between sets of camera
        # points so that the lines drawn by Plotly are not drawn between
        # points that belong to different cameras.
        all_cam_wires = torch.cat((all_cam_wires, nan_tensor, wire))
    x, y, z = all_cam_wires.detach().cpu().numpy().T.astype(float)

    row, col = subplot_idx // ncols + 1, subplot_idx % ncols + 1
    fig.add_trace(
        go.Scatter3d(x=x, y=y, z=z, marker={"size": 1}, name=trace_name),
        row=row,
        col=col,
    )

    # Access the current subplot's scene configuration
    plot_scene = "scene" + str(subplot_idx + 1)
    current_layout = fig["layout"][plot_scene]

    # flatten for bounds calculations
    flattened_wires = cam_wires_trans.flatten(0, 1)
    verts_center = flattened_wires.mean(0)
    max_expand = (flattened_wires.max(0)[0] - flattened_wires.min(0)[0]).max()
    _update_axes_bounds(verts_center, max_expand, current_layout)
Example #6
0
def add_line(measurement, p1, p2, line_width, line_color, figure):

    midpoint = (p1 + p2) / 2

    line = go.Scatter3d(x=[p1[0], p2[0]],
                        y=[p1[1], p2[1]],
                        z=[p1[2], p2[2]],
                        mode="lines",
                        line={
                            "width": line_width,
                            "color": line_color,
                            "dash": "dot"
                        })
    label = go.Scatter3d(x=[midpoint[0]],
                         y=[midpoint[1]],
                         z=[midpoint[2]],
                         mode="text",
                         text=measurement,
                         textposition="middle center")
    figure.add_trace(line)
    figure.add_trace(label)
Example #7
0
    def plot_d(dataset, name, htext):
        x = [x[0] for x in dataset]
        y = [x[1] for x in dataset]
        z = [x[2] for x in dataset]

        fig.add_trace(go.Scatter3d(
            x=x, y=y, z=z,
            hovertext=htext, name=name, mode='markers',  # hoverinfo='text',
            marker=dict(size=8, color=rrgb(), opacity=0.9,
                        line=dict(width=1, color='black'))
        ))
        return
Example #8
0
    def production_envelope_3d(self,
                               dataframe,
                               grid=None,
                               width=None,
                               height=None,
                               title=None,
                               points=None,
                               points_colors=None,
                               palette=None,
                               x_axis_label=None,
                               y_axis_label=None,
                               z_axis_label=None):

        variables = dataframe["strain"].unique()
        palette = self.get_option('palette') if palette is None else palette
        width = self.get_option('width') if width is None else width

        width, height = self.golden_ratio(width, height)
        data = []
        palette = self._palette(palette, len(variables))
        for variable, color in zip_repeat(variables, palette):
            _dataframe = dataframe[dataframe["strain"] == variable]
            surface = self._make_production_envelope_3d(_dataframe,
                                                        variable,
                                                        color=color)
            data.append(surface)

        if points is not None:
            x, y, z = zip(*points)
            scatter = go.Scatter3d(
                x=x,
                y=y,
                z=z,
                mode="markers",
                name="Data Points",
                marker=dict(
                    color="green" if points_colors is None else points_colors))
            data.append(scatter)

        layout = go.Layout(title=title,
                           scene=go.Scene(xaxis=dict(title=x_axis_label),
                                          yaxis=dict(title=y_axis_label),
                                          zaxis=dict(title=z_axis_label)),
                           width=width,
                           height=height)

        if grid is not None:
            plot = self.Figure(data=data, layout=layout)
            grid.append(plot)
            return grid
        else:
            plot = go.Figure(data=data, layout=layout)
        return plot
Example #9
0
    def line_3d_tests(self, env, result):
        """
        Example from https://plotly.com/python/3d-line-plots/
        """
        rs = np.random.RandomState()
        rs.seed(0)

        def brownian_motion(T=1, N=100, mu=0.1, sigma=0.01, S0=20):
            dt = float(T) / N
            t = np.linspace(0, T, N)
            W = rs.standard_normal(size=N)
            W = np.cumsum(W) * np.sqrt(dt)  # standard brownian motion
            X = (mu - 0.5 * sigma**2) * t + sigma * W
            S = S0 * np.exp(X)  # geometric brownian motion
            return S

        dates = pd.date_range("2012-01-01", "2013-02-22")
        T = (dates.max() - dates.min()).days / 365
        N = dates.size
        start_price = 100
        y = brownian_motion(T, N, sigma=0.1, S0=start_price)
        z = brownian_motion(T, N, sigma=0.1, S0=start_price)

        fig = go.Figure(data=go.Scatter3d(
            x=dates,
            y=y,
            z=z,
            marker=dict(
                size=4,
                color=z,
                colorscale="Viridis",
            ),
            line=dict(color="darkblue", width=2),
        ))

        fig.update_layout(
            width=800,
            height=700,
            autosize=False,
            scene=dict(
                camera=dict(
                    up=dict(x=0, y=0, z=1),
                    eye=dict(
                        x=0,
                        y=1.0707,
                        z=1,
                    ),
                ),
                aspectratio=dict(x=1, y=1, z=0.7),
                aspectmode="manual",
            ),
        )
        result.plotly(fig, description="Brownian Motion")
Example #10
0
def coordinate(go):
    traces = {}
    traces["coordinate_x"] = go.Scatter3d(x=[0, 1],
                                          y=[0, 0],
                                          z=[0, 0],
                                          showlegend=False,
                                          mode='lines',
                                          line=dict(color="green", width=5))
    traces["coordinate_y"] = go.Scatter3d(x=[0, 0],
                                          y=[0, 1],
                                          z=[0, 0],
                                          showlegend=False,
                                          mode='lines',
                                          line=dict(color="red", width=5))
    traces["coordinate_z"] = go.Scatter3d(x=[0, 0],
                                          y=[0, 0],
                                          z=[0, 1],
                                          showlegend=False,
                                          mode='lines',
                                          line=dict(color="blue", width=5))
    return traces
Example #11
0
 def _draw_point(self, _name, _point, _size, _color):
     self.fig.add_trace(
         go.Scatter3d(name=_name,
                      x=[_point.x],
                      y=[_point.y],
                      z=[_point.z],
                      mode='markers',
                      marker={
                          'size': _size,
                          'color': _color,
                          'opacity': 1.0
                      }))
Example #12
0
def generateCombinePlot3(fileAbsOrig, fileAbsNew):
    current = Path.cwd()
    fileOrig = current.joinpath(fileAbsOrig)
    fileNew = current.joinpath(fileAbsNew)

    xValOrig = list()
    yValOrig = list()
    zValOrig = list()

    xValNew = list()
    yValNew = list()
    zValNew = list()

    with open(fileOrig, 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.rstrip()
            splits = line.split(',')
            if len(splits) == 3:
                xValOrig.append(float(splits[0]))
                yValOrig.append(float(splits[1]))
                zValOrig.append(float(splits[2]))

    with open(fileNew, 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.rstrip()
            splits = line.split(',')
            if len(splits) == 3:
                xValNew.append(float(splits[0]))
                yValNew.append(float(splits[1]))
                zValNew.append(float(splits[2]))

    fig = go.Figure()
    fig.add_trace(
        go.Scatter3d(x=xValOrig, y=yValOrig, z=zValOrig, mode='markers'))
    fig.add_trace(go.Scatter3d(x=xValNew, y=yValNew, z=zValNew,
                               mode='markers'))
    fig.show()
    fig.write_image(str(Path.joinpath(fileNew.parent, fileNew.stem + ".PNG")))
Example #13
0
    def draw_pos(self):
        if self.pos is None:
            self.find_pos()

        z_zeros = np.zeros(self.pos.shape[0])
        fig = go.Figure(data=[
            go.Scatter3d(x=self.pos[:, 0],
                         y=self.pos[:, 1],
                         z=self.pos[:, 2],
                         opacity=0.5,
                         name='Gesture'),
            go.Scatter3d(x=self.pos_proj_3d[:, 0],
                         y=self.pos_proj_3d[:, 1],
                         z=self.pos_proj_3d[:, 2],
                         opacity=0.5,
                         name='Gesture proj 3d'),
            go.Scatter3d(x=self.pos_proj_2d[:, 0],
                         y=self.pos_proj_2d[:, 1],
                         z=z_zeros,
                         opacity=0.5,
                         name='Gesture proj 2d')
        ])
        size_of_cube = 0.5
        fig.update_layout(scene=dict(
            xaxis=dict(
                nticks=4,
                range=[-size_of_cube, size_of_cube],
            ),
            yaxis=dict(
                nticks=4,
                range=[-size_of_cube, size_of_cube],
            ),
            zaxis=dict(
                nticks=4,
                range=[-size_of_cube, size_of_cube],
            ),
        ),
                          width=700,
                          margin=dict(r=20, l=10, b=10, t=10))
        fig.show()
Example #14
0
    def add_line(self,point_start,point_end,row=1,column=1,color='red'):
        """
        Definition to add a ray to the figure.

        Parameters
        ----------
        point_start    : ndarray
                         Starting point(s).
        point_end      : ndarray
                         Ending point(s).
        row            : int
                         Row number of the figure.
        column         : int
                         Column number of the figure.
        color          : str
                         Color of the lune to be drawn.
        """
        if np.__name__ == 'cupy':
            point_start = np.asnumpy(point_start)
            point_end   = np.asnumpy(point_end)
        if len(point_start.shape) == 1:
            point_start = point_start.reshape((1,3))
        if len(point_end.shape) == 1:
            point_end   = point_end.reshape((1,3))
        if point_start.shape != point_end.shape:
            print('Size mismatch in line plot. Sizes are {} and {}.'.format(point_start.shape,point_end.shape))
            sys.exit()
        for point_id in range(0,point_start.shape[0]):
            points = np.array(
                              [
                               point_start[point_id],
                               point_end[point_id]
                              ]
                             )
            points = points.reshape((2,3))
            if np.__name__ == 'cupy':
                points = np.asnumpy(points)
            self.fig.add_trace(
                               go.Scatter3d(
                                            x=points[:,0],
                                            y=points[:,1],
                                            z=points[:,2],
                                            mode='lines',
                                            line=dict(
                                                      width=self.settings["line width"],
                                                      color=color,
                                                     ),
                                            opacity=self.settings["opacity"]
                                           ),
                               row=row,
                               col=column
                              )
Example #15
0
def make_3d_time_map(
        times, times_tot_mins, sep_array, Ncolors,
        title):  # plot standard, scatter-plot time map. Nothing is returned

    # import plotly.express as px
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots

    print("rendering 3D time map ...")
    np.save("sep_array", sep_array)
    np.save("times_tot_mins", times_tot_mins)
    np.save("times", times)
    import sys
    sys.exit()
    df = pandas.DataFrame()
    Xs = sep_array[:, 0]
    Ys = sep_array[:, 1]
    # Zs = times[1:-1]
    Zs = times_tot_mins[1:-1]

    df["before"] = Xs
    df["after"] = Ys
    df["time"] = Zs
    df["colors"] = times[1:-1]
    # df["colors"] = times_tot_mins[1:-1]

    print("plotting")
    # fig = make_subplots(
    #     rows=1, cols=2, specs=[[dict(is_3d=False, type="scatter3d"), dict(is_3d=True, type="scatter3d"),],]
    # )
    fig = make_subplots(rows=1,
                        cols=2,
                        specs=[[{
                            'type': 'surface'
                        }, {
                            'type': 'surface'
                        }]])
    scatter = go.Scatter(
        x=Xs,
        y=Ys,
        # colors=Zs,
        mode="markers",
    )
    scatter3d = go.Scatter3d(
        x=Xs,
        y=Ys,
        z=Zs,
        mode="markers",
    )
    fig.add_trace(scatter3d, row=1, col=1)
    fig.add_trace(scatter3d, row=1, col=2)
    fig.show()
Example #16
0
def Compare_Keywords_with_Assocated_Texts(username, prname, ):
    import plotly.graph_objects as go
    import plotly.express as px
    import numpy as np
    from .utils import Read_Arg_, import_dataframe, option_finder
    import os

    _, input_, output_ = Read_Arg_("3DPlot_for_Pairs(Fit_by_Importance)")
    min_freq, max_freq = option_finder("3DPlot_for_Pairs(Fit_by_Importance)")["option_1", "option_2"]
    if (username is None) or (prname is None):
        cooc = import_dataframe(os.path.join(input_))
    else:
        input_directory = "/".join(username, prname)
        cooc = import_dataframe(os.path.join(input_directory, input_))

    cooc = cooc[
            (cooc["cooccurrence_count"] >= min_freq*cooc["cooccurrence_count"].max())&
            (cooc["cooccurrence_count"] <= max_freq*cooc["cooccurrence_count"].max())
            ]
    # x = cooc[["W_1^%","W_2^%"]].max(axis=1)
    # y = cooc["W_1^%"]*cooc["W_2^%"]
    z = np.log(cooc["Fit(1|2)"])

    fig = px.scatter_3d(cooc,
                        x="W_1^%",
                        y="W_2^%",
                        z=z,
                        text=cooc["pair"],
                        opacity=.7,
                        title="fitplot 3D",
                        height=1000,
                        width=1000)

    xaxis_min = cooc["W_1^%"].min()
    xaxis_max = cooc["W_1^%"].max()
    yaxis_min = cooc["W_2^%"].min()
    yaxis_max = cooc["W_2^%"].max()
    dict_z = {"x": [xaxis_min, xaxis_max, xaxis_max, xaxis_max, xaxis_max, xaxis_min, xaxis_min, xaxis_min],
              "y": [yaxis_min, yaxis_min, yaxis_min, yaxis_max, yaxis_max, yaxis_max, yaxis_max, yaxis_min],
              "z": [0] * 8}

    fig.add_trace(go.Scatter3d(x=dict_z["x"],
                               y=dict_z["y"],
                               z=dict_z["z"],
                               mode="lines",
                               line=dict(width=10,
                                         color="rgb(000, 000, 000)"),
                               surfaceaxis=2,
                               surfacecolor="rgb(204, 204, 153)",
                               opacity=.5))
    fig.write_html(f"{output_}")
    fig.show()
Example #17
0
def data_plot_clf_3d(h, y_pred_history):
    if h.X_raw.shape[1] != 3:
        return

    y = list(map(lambda x: x[0], h.y))

    x_min, x_max = h.X_raw[:, 1].min() - 1, h.X_raw[:, 1].max() + 1
    y_min, y_max = h.X_raw[:, 2].min() - 1, h.X_raw[:, 2].max() + 1
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 201),
                         np.linspace(y_min, y_max, 201))

    t = np.c_[xx.ravel(), yy.ravel()]
    t = Polynomial(t, h.y, degree=h.degree)
    Z = h.hypothesis(X=t.X)
    Z = Z.reshape(xx.shape)
    Z = -np.log((1 / Z) - 1)

    del xx, yy, t
    gc.collect()

    fig = go.Figure()

    fig.add_trace(
        go.Scatter3d(
            x=h.X_raw[:, 1],
            y=h.X_raw[:, 2],
            z=y,
            mode='markers',
            marker=dict(
                size=3,
                color=y,  # set color to an array/list of desired values
                colorscale=[[0, "rgb(166,206,227)"], [0.25, "rgb(31,120,180)"],
                            [0.45,
                             "rgb(178,223,138)"], [0.65, "rgb(51,160,44)"],
                            [0.85, "rgb(251,154,153)"],
                            [1, "rgb(227,26,28)"]],  # choose a colorscale
                opacity=0.8)))

    fig.add_trace(
        go.Surface(
            z=Z,
            x=np.linspace(x_min, x_max, 201),
            y=np.linspace(y_min, y_max, 201),
            showscale=False,
        ))

    fig.update_layout(title='Data scatter plot and Decision boundary',
                      autosize=False,
                      width=900,
                      height=600)

    st.plotly_chart(fig)
Example #18
0
def cost_function_plot_3d(h, properties, weights_history, loss_history):
    if h.weight.shape[0] != 2 and len(weights_history) > 2:
        return

    y = list(map(lambda x: x[0], h.y))

    theta = [np.array([i[0][0], i[1][0]]) for i in weights_history]

    theta0 = np.array([i[0][0] for i in weights_history])
    theta1 = np.array([i[1][0] for i in weights_history])

    thetha0_min = np.min(theta0) - 3 * np.std(theta0)
    thetha0_max = np.max(theta0) + 3 * np.std(theta0)

    thetha1_min = np.min(theta1) - 3 * np.std(theta1)
    thetha1_max = np.max(theta1) + 3 * np.std(theta1)

    theta0_grid = np.linspace(thetha0_min, thetha0_max, 101)
    theta1_grid = np.linspace(thetha1_min, thetha1_max, 101)

    J_grid = compute_j_grid(h,
                            theta0_grid,
                            theta1_grid,
                            properties.cost_function,
                            C=properties.reg_coef,
                            regularization=properties.regularization)

    X, Y = np.meshgrid(theta0_grid, theta1_grid)

    fig = go.Figure()

    fig.add_trace(go.Surface(x=X, y=Y, z=J_grid, showscale=False))

    fig.add_trace(
        go.Scatter3d(
            x=theta0[1:],
            y=theta1[1:],
            z=loss_history[1:],
            mode='lines+markers',
            marker=dict(
                size=3,
                color='red',
                #color=y,                # set color to an array/list of desired values
                # colorscale='greens',   # choose a colorscale
                opacity=0.8)))

    fig.update_layout(title='Cost function surface plot',
                      autosize=False,
                      width=900,
                      height=600)

    st.plotly_chart(fig)
Example #19
0
    def drawParticles(self, label, colortype):
        print("Drawing particles", label)
        if not self.particles or "particles" not in self.data or not label in self.data["particles"]:
            return []
        df = self.data["particles"][label]
        mom = self.momentumVectors(label)
        vtx = self.makeVertices(label)
        charge = self.data["particles"][label][label+"_charge"]
        ids = df[label+"_pdgId"] if label+"_pdgId" in df else np.zeros_like(charge)
        if colortype == "PFTruthPartIdx":
            ids = df[label+"_PFTruthPartIdx"]
        end = self.trajectoryEndPoint(label)
        # Should make this array based
        ptEtaPhi = self.PtEtaPhiVectors(label)
        traces = []
        isPU = np.zeros(len(charge), dtype=int)
        if label in ["Track", "TrackDisp"] and all([x in self.data["particles"] for x in ["TrackMatch", "TrackingPart"]]):
            tpdf = self.data["particles"]["TrackingPart"]
            tpisPU = (tpdf["TrackingPart_eventId"] != 0) | (tpdf["TrackingPart_bunchCrossing"] != 0)
            tpid = tpdf["TrackingPart_pdgId"]
            bestmatch = np.cumsum(df["Track_TrackingPartNumMatch"])-df["Track_TrackingPartNumMatch"][0]
            matchdf = self.data["particles"]["TrackMatch"]
            if "Track_TrackingPart_MatchIdx" in matchdf:
                tpidx = np.where(bestmatch >= 0, matchdf["Track_TrackingPart_MatchIdx"][bestmatch], -1)
                ids = np.where(tpidx >= 0, tpid[tpidx], -1)
                isPU = np.where(tpidx >= 0, tpisPU[tpidx], -1)
        elif label == "CaloPart":
            isPU = (df["CaloPart_eventId"] != 0) | (df["CaloPart_bunchCrossing"] != 0)

        for i, (v,m,e,q) in enumerate(zip(vtx, mom, end, charge)):
            pt,eta,phi = ptEtaPhi[i]
            if pt < self.trackPtCut:
                continue
            pid = ids[i] 
            points = self.trajectory(v, m, e, q) 
            #lightenPileup = self.removePU and isPU[i]
            #color = self.mapColor(i if colortype == "Index" else pid, 0.25 if lightenPileup else 1.0)
            color = self.mapColor(i if colortype == "Index" else pid)
            if self.removePU and isPU[i]:
               color = self.mapColor(-2, 1.)

            idtext = 'pdgId' if colortype != 'PFTruthPartIdx' else "PFTruthPartIdx"
            text = [f'{idtext}: {pid}<br>isPU: {isPU[i]}<br>p<sub>T</sub>, η, phi:  ({pt:0.2f} GeV, {eta:0.2f}, {phi:0.2f})' 
                            for p in points]
            traces.append(go.Scatter3d(x=points[:,2], y=points[:,0], z=points[:,1],
                    mode='lines', name=f"{label}Idx{i} (pdgId={pid})", 
                    hovertemplate="x: %{y}<br>y: %{z}<br>z: %{x}<br>%{text}<br>",
                    text=text,
                    line=dict(color=color)
                )
            )
        return traces
Example #20
0
def plotPointCloud(object, model=None):
    """
    Retrieve 4 random point clouds and plot interactive graphs  
    """

    # Layout for plot
    fig = make_subplots(rows=2,
                        cols=2,
                        vertical_spacing=0.05,
                        horizontal_spacing=0.05,
                        specs=[[{
                            'type': 'scatter3d'
                        }, {
                            'type': 'scatter3d'
                        }], [{
                            'type': 'scatter3d'
                        }, {
                            'type': 'scatter3d'
                        }]])

    objlst = Data(object)

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    for i in range(4):
        point_cloud = objlst[np.random.randint(len(objlst))]

        if model is not None and 'Autoencoder' in model.name:
            point_cloud = model(point_cloud[None, :].to(device))
            point_cloud = torch.squeeze(point_cloud, 0)

        if model is not None and 'Generator' in model.name:
            noise = noiseFunc(0, 0.2, 1, device)
            point_cloud = model(noise)
            point_cloud = torch.squeeze(point_cloud, 0)

        np_point_cloud = point_cloud.detach().cpu().numpy()

        fig.add_trace(go.Scatter3d(x=np_point_cloud[:, 0],
                                   y=np_point_cloud[:, 1],
                                   z=np_point_cloud[:, 2],
                                   mode='markers',
                                   marker=dict(size=1,
                                               color=np_point_cloud[:, 2],
                                               colorscale='Viridis',
                                               opacity=0.8)),
                      row=i // 2 + 1,
                      col=i % 2 + 1)

    fig.update_layout(showlegend=False, height=800, width=1500)

    fig.show()
Example #21
0
def scatter_plot_3d(input_data,
                    hover_info=[],
                    marker_size=6,
                    title="",
                    plot_save_path=""):
    """Generate and open an interactive 3D scatter plot as html.

    Args:
        input_data (dict): Dictionary of (user: feature_vector).
        hover_info (list): List of labels/info to display for each 
            user in input_data in 3D scatter plot.
            May be Hastags or Mentions.
        marker_size (int, optional): Point size in plot. Defaults to 6.
        title (str, optional): Title of the plot. Defaults to "".
        plot_save_path (str, optional): Save path for plot html file. Defaults to "".
    
    TODO:
        Add marker labels.
    """

    # Get data to plot from input_data dict
    feature_vectors, labels = zip(*list(input_data.values()))
    x, y, z = zip(*[tuple(x) for x in feature_vectors])

    trace = [
        go.Scatter3d(x=x,
                     y=y,
                     z=z,
                     mode='markers',
                     hovertemplate='%{text}',
                     text=[" ".join(x for x in item) for item in hover_info],
                     marker=dict(size=marker_size,
                                 color=labels,
                                 colorscale='Viridis',
                                 opacity=0.8))
    ]
    fig = go.Figure(data=trace)

    title += INFO.LOAD_PARAMS_USED + INFO.DIM_RED_USED + INFO.CLUSTERING_USED
    fig.update_layout(title=title,
                      xaxis_title="",
                      yaxis_title="",
                      legend_title="")

    if plot_save_path:
        extra_info = INFO.LOAD_PARAMS_USED + INFO.DIM_RED_USED + INFO.CLUSTERING_USED
        plot_save_path = unique_filename(plot_save_path, extra_info)
        fig.write_html(plot_save_path)

    fig.show()

    return
 def drawCSCME1(self):
     x, y, z = boundary_circle(275, 580)
     return [
         go.Scatter3d(x=z,
                      y=x,
                      z=y,
                      mode='lines',
                      surfaceaxis=0,
                      line=dict(color='#f5ebd7'),
                      opacity=0.25,
                      hoverinfo='skip',
                      name='CSC ME1/1'),
         go.Scatter3d(x=-1 * z,
                      y=x,
                      z=y,
                      mode='lines',
                      surfaceaxis=0,
                      line=dict(color='#f5ebd7'),
                      opacity=0.25,
                      hoverinfo='skip',
                      name='CSC ME-1/1'),
     ]
Example #23
0
def manoeuvretraces(seq):
    traces = []
    for name, manoeuvre in seq.split_manoeuvres().items():
        traces.append(
            go.Scatter3d(x=manoeuvre.x,
                         y=manoeuvre.y,
                         z=manoeuvre.z,
                         mode='lines',
                         text=manoeuvre.element,
                         hoverinfo="text",
                         name=name))

    return traces
Example #24
0
def plot(pc):
    '''
    plots the Nx6 point cloud pc in 3D
    assumes (1,0,0), (0,1,0), (0,0,-1) as basis
    '''
    fig = go.Figure(data=[
        go.Scatter3d(x=pc[:, 0],
                     y=pc[:, 1],
                     z=-pc[:, 2],
                     mode='markers',
                     marker=dict(size=2, color=pc[:, 3:], opacity=1))
    ])
    fig.show()
def create_ellipse(a, b, R, x_c=0, y_c=0, z_c=0, N=100):
    y_c -= a - b
    t = np.linspace(0, 2 * pi, N)
    xs = a * cos(t) + x_c
    ys = b * sin(t) + y_c
    zs = np.zeros(N) + z_c
    # coordinate of the  ellipse points with respect to the system of axes [1, 0], [0,1] with origin (0,0)
    xp, yp, zp = np.dot(R, [xs, ys, zs])
    x = [x for x in np.array(xp).flat]
    y = [y for y in np.array(yp).flat]
    z = [z for z in np.array(zp).flat]
    trace = go.Scatter3d(x=x, y=y, z=z, mode='lines')
    return trace
Example #26
0
def elementtraces(seq):
    traces = []
    for name, element in seq.split_elements().items():
        traces.append(
            go.Scatter3d(x=element.x,
                         y=element.y,
                         z=element.z,
                         mode='lines',
                         text=element.manoeuvre,
                         hoverinfo="text",
                         name=name))

    return traces
Example #27
0
def graph_reflections(v_set):
    vx = np.array([])
    vy = np.array([])
    vz = np.array([])

    for v in v_set:
        vx = np.append(vx, v[0])
        vy = np.append(vy, v[1])
        vz = np.append(vz, v[2])


    fig = go.Figure(data=[go.Scatter3d(x=vx, y=vy, z=vz, mode='markers')])
    fig.write_html('first_figure.html', auto_open=True)
Example #28
0
    def make_scatter(cls,
                     points: Union[np.ndarray, Sequence[Vec3f]],
                     offset: Optional[Vec3f] = None,
                     **kwargs):
        kwargs.setdefault("marker", {})
        kwargs["marker"].setdefault("size", 0.1)
        kwargs.setdefault("mode", "markers")

        pts = np.asarray(points)
        if offset is not None:
            pts += offset
        x, y, z = pts.T
        return go.Scatter3d(x=x, y=y, z=z, **kwargs)
Example #29
0
def plot_data(coord, label):
    subfig = go.Scatter3d(x=coord[:, 0],
                          y=coord[:, 1],
                          z=coord[:, 2],
                          mode='markers',
                          marker=dict(size=2,
                                      color=label,
                                      colorscale='Viridis',
                                      opacity=0.8))
    fig = make_subplots(rows=1, cols=1, specs=[[{'type': 'surface'}]])
    fig.add_trace(subfig)
    fig.update_layout(scene_aspectmode='data', )
    fig.show()
Example #30
0
def plotly_block_edges(origin, sizes):
    x = origin[0] + np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0
                              ]) * sizes[0]
    y = origin[1] + np.array([0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1
                              ]) * sizes[1]
    z = origin[2] + np.array([0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0
                              ]) * sizes[2]
    return go.Scatter3d(x=x,
                        y=z,
                        z=y,
                        mode="lines",
                        line=dict(width=1.0, color="black"),
                        showlegend=False)