Example #1
0
    k = np.asarray([K[i]])  # Strike Price
    tau = np.asarray([T[i]])  # Time to Maturity
    r = np.asarray(1.02)  # CD91일물 금리 2020.5.21일 기준
    q = np.asarray(0.00)  # Dividend Rate
    cp = np.asarray(-1)  # Option Type
    P = np.asarray([S[i]])  # Market Price

    imp_vol = calcbsimpvol(dict(cp=cp, P=P, S=s, K=k, tau=tau, r=r, q=q))
    implied_volatility.append(imp_vol[0][0])
print(implied_volatility)

import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)

trace = go.Surface(x=TM, y=KP, z=imp_vol, colorscale='Jet', opacity=0.8)
data = [trace]
layout = go.Layout(title='Call Theta Surface',
                   scene={
                       'xaxis': {
                           'title': 'Maturity'
                       },
                       'yaxis': {
                           'title': 'Spot Price'
                       },
                       'zaxis': {
                           'title': 'Theta'
                       }
                   },
                   width=800,
                   height=800,
Example #2
0
def surface(x, y, z, opacity=1.0, colorscale=None):
    trace = go.Surface(x=x, y=y, z=z, opacity=opacity, colorscale=colorscale)
    return trace
Example #3
0
def plot_betti_surfaces(betti_curves,
                        samplings=None,
                        homology_dimensions=None):
    """Plots the Betti surfaces (Betti numbers against time and filtration
    parameter) by homology dimension.

    Parameters
    ----------
    betti_curves : ndarray of shape (n_samples, n_homology_dimensions, \
        n_values)
        ``n_samples`` collections of discretised Betti curves. There are
        ``n_homology_dimension`` curves in each collection. Index i along axis
        1 should yield all Betti curves in homology dimension i.

    homology_dimensions : list of int or None, default: ``None``
        Homology dimensions for which the Betti surfaces should be plotted.
        If ``None``, all available dimensions will be used.

    samplings : ndarray of shape (n_homology_dimension, n_values), \
        default: ``None``
        For each homology dimension, (filtration parameter) values to be used
        on the x-axis against the corresponding values in `betti_curves` on the
        y-axis. If ``None``, the samplings will start at 0 with step 1.

    """
    if homology_dimensions is None:
        homology_dimensions = np.arange(0, betti_curves.shape[1])
    if samplings is None:
        samplings = np.arange(0, betti_curves.shape[2])

    scene = {
        "xaxis": {
            "title": "Epsilon",
            "type": "linear",
            "showexponent": "all",
            "exponentformat": "e"
        },
        "yaxis": {
            "title": "Time",
            "type": "linear",
            "showexponent": "all",
            "exponentformat": "e"
        },
        "zaxis": {
            "title": "Betti number",
            "type": "linear",
            "showexponent": "all",
            "exponentformat": "e"
        }
    }
    if betti_curves.shape[0] == 1:
        plot_betti_curves(betti_curves[0], samplings, homology_dimensions)
    else:
        for i, dimension in enumerate(homology_dimensions):
            fig = gobj.Figure()
            fig.update_layout(scene=scene,
                              title="Betti surface for homology "
                              "dimension {}".format(int(dimension)))
            fig.add_trace(
                gobj.Surface(x=samplings,
                             y=np.arange(betti_curves.shape[0]),
                             z=betti_curves[:, i, :],
                             connectgaps=True,
                             hoverinfo='none'))

            fig.show()
Example #4
0
def interactive_3D_plot(post_equal_weights_file, trigdat_file, used_dets,
                        model, save_path):
    # Plot 10 degree grid
    trace_grid = []
    phi_l = np.arange(-180, 181, 10)  # file size!#
    theta_l = np.arange(-90, 91, 10)  # file size!#
    scale_factor_grid = 1.02
    b_side_angle = 45  # has to be <90
    for phi in phi_l:
        x, y, z = xyz(phi, theta_l)
        trace_grid.append(
            go.Scatter3d(
                x=scale_factor_grid * x,
                y=scale_factor_grid * y,
                z=scale_factor_grid * z,
                legendgroup="group",
                showlegend=False,
                mode="lines",
                line=dict(color="black", width=1, dash="dash"),
                hoverinfo=None,
            ))

    for theta in theta_l:
        theta_m = np.ones_like(phi_l) * theta
        x, y, z = xyz(phi_l, theta_m)
        trace_grid.append(
            go.Scatter3d(
                x=scale_factor_grid * x,
                y=scale_factor_grid * y,
                z=scale_factor_grid * z,
                legendgroup="group",
                showlegend=False,
                mode="lines",
                line=dict(color="black", width=1, dash="dash"),
                hoverinfo=None,
            ))
    # equator
    theta_m = np.ones_like(phi_l) * 0
    x, y, z = xyz(phi_l, theta_m)
    trace_grid.append(
        go.Scatter3d(
            x=np.array(scale_factor_grid * x),
            y=np.array(scale_factor_grid * y),
            z=np.array(scale_factor_grid * z),
            legendgroup="group",
            name="Spherical Grid (10 deg steps)",
            mode="lines",
            line=dict(color="black", width=3),
            hoverinfo=None,
        ))

    # PLOT B0 and B1 Side and Solar panel
    phi = np.concatenate([
        np.arange(0, b_side_angle - 1, (b_side_angle - 1) / 10),
        np.arange(b_side_angle - 1, b_side_angle + 1, 0.1),
        np.arange(b_side_angle + 1, 180 - (b_side_angle + 1),
                  2 * b_side_angle / 4),
        np.arange(180 - (b_side_angle + 1), 180 - (b_side_angle - 1), 0.1),
        np.arange(180 - (b_side_angle - 1), 181, (b_side_angle - 1.0) / 10.0),
    ])  # file size!#
    phi = np.concatenate([phi, -np.flip(phi[:-1], 0)])
    theta = np.arange(-90, 91, 5)  # file size!#
    # phi, theta = np.mgrid[-180:180:720j, -90:90:18j]
    phi, theta = np.meshgrid(phi, theta)
    x, y, z = xyz(phi, theta)
    points = np.array([x, y, z])

    b0_zen = 0
    b0_azi = 0
    b1_zen = 0
    b1_azi = 180
    b0_x, b0_y, b0_z = xyz(b0_azi, b0_zen)
    b1_x, b1_y, b1_z = xyz(b1_azi, b1_zen)

    idx_b0 = np.abs(phi) < b_side_angle
    idx_b1 = np.abs(phi) > 180 - b_side_angle
    xin_b0, yin_b0, zin_b0 = xyz(phi, theta)
    xin_b1, yin_b1, zin_b1 = xyz(phi, theta)
    xin_s, yin_s, zin_s = xyz(phi, theta)

    xin_b0[~idx_b0] = np.nan
    yin_b0[~idx_b0] = np.nan
    zin_b0[~idx_b0] = np.nan

    xin_b1[~idx_b1] = np.nan
    yin_b1[~idx_b1] = np.nan
    zin_b1[~idx_b1] = np.nan

    xin_s[idx_b1] = np.nan
    yin_s[idx_b1] = np.nan
    zin_s[idx_b1] = np.nan
    xin_s[idx_b0] = np.nan
    yin_s[idx_b0] = np.nan
    zin_s[idx_b0] = np.nan

    contours = go.surface.Contours(
        x=go.surface.contours.X(highlight=False),
        y=go.surface.contours.Y(highlight=False),
        z=go.surface.contours.Z(highlight=False),
    )

    theta = np.arcsin(z) * 180 / np.pi
    phi = np.arctan2(x, y) * 180 / np.pi
    my_text = []
    for i in range(len(phi)):
        te = []
        for j in range(len(phi[0])):
            te.append("phi:{}<br>theta:{}".format(phi[i, j], theta[i, j]))
        my_text.append(te)
    my_text = np.array(my_text)
    colorscale_b0 = [[0, "rgb(117,201,196)"], [1, "rgb(117,201,196)"]]
    trace_b0 = go.Surface(
        x=xin_b0,
        y=yin_b0,
        z=zin_b0,
        name="b0-side",
        showscale=False,
        colorscale=colorscale_b0,
        surfacecolor=np.ones_like(z),
        opacity=1,
        contours=contours,
        text=my_text,
        hoverinfo="text+name",
    )
    colorscale_b1 = [[0, "rgb(201,117,117)"], [1, "rgb(201,117,117)"]]
    trace_b1 = go.Surface(
        x=xin_b1,
        y=yin_b1,
        z=zin_b1,
        name="b1-side",
        showscale=False,
        colorscale=colorscale_b1,
        surfacecolor=np.ones_like(z),
        opacity=1,
        contours=contours,
        text=my_text,
        hoverinfo="text+name",
    )
    colorscale_s = [[0, "grey"], [1, "grey"]]
    trace_s = go.Surface(
        x=xin_s,
        y=yin_s,
        z=zin_s,
        name="solar_panel side",
        showscale=False,
        colorscale=colorscale_s,
        surfacecolor=np.ones_like(z),
        opacity=1,
        contours=contours,
        text=my_text,
        hoverinfo="text+name",
    )

    # PLOT DETS - dets in list used dets will be plotted solid all other dashed
    trace_dets = []
    color_dict = {
        "n0": "blue",
        "n1": "navy",
        "n2": "crimson",
        "n3": "lightgreen",
        "n4": "orchid",
        "n5": "brown",
        "n6": "firebrick",
        "n7": "plum",
        "n8": "darkgreen",
        "n9": "olive",
        "na": "aqua",
        "nb": "darkorange",
        "b0": "darkmagenta",
        "b1": "indigo",
    }
    det_pointing = {
        "n0": [45.9, 90 - 20.6],
        "n1": [45.1, 90 - 45.3],
        "n2": [58.4, 90 - 90.2],
        "n3": [314.9, 90 - 45.2],
        "n4": [303.2, 90 - 90.3],
        "n5": [3.4, 90 - 89.8],
        "n6": [224.9, 90 - 20.4],
        "n7": [224.6, 90 - 46.2],
        "n8": [236.6, 90 - 90],
        "n9": [135.2, 90 - 45.6],
        "na": [123.7, 90 - 90.4],
        "nb": [183.7, 90 - 90.3],
        "b0": [0.01, 90 - 90.01],
        "b1": [180.01, 90 - 90.01],
    }
    for keys in det_pointing:
        det_opening = 40  # in deg
        pointing = det_pointing[keys]
        ra_d = pointing[0] * np.pi / 180
        dec_d = pointing[1] * np.pi / 180
        scale_factor_d = 1.01
        theta_l = np.linspace(-np.pi / 2, np.pi / 2, 720)  # file size!#
        phi_res_0 = []
        phi_res_1 = []
        for theta in theta_l:
            phi_res_0.append(
                phi_0(theta, ra_d, dec_d, det_opening * np.pi / 180))
            phi_res_1.append(
                phi_1(theta, ra_d, dec_d, det_opening * np.pi / 180))

        phi_res_0 = np.array(phi_res_0)
        phi_res_1 = np.array(phi_res_1)
        theta_all = np.concatenate([theta_l, np.flip(theta_l, 0)])
        phi_all = np.concatenate([phi_res_0, np.flip(phi_res_1, 0)])
        mask = phi_all < 100
        theta_all = theta_all[mask]
        phi_all = phi_all[mask]
        theta_all = np.concatenate([theta_all, theta_all[0:1]])
        phi_all = np.concatenate([phi_all, phi_all[:1]])
        x = np.cos(theta_all) * np.cos(phi_all)
        y = np.cos(theta_all) * np.sin(phi_all)
        z = np.sin(theta_all)
        # plot earth
        name = str(keys)
        color = str(color_dict[keys])
        if name in used_dets:
            trace_dets.append(
                go.Scatter3d(
                    x=scale_factor_d * x,
                    y=scale_factor_d * y,
                    z=scale_factor_d * z,
                    name=name,
                    legendgroup="used detectors",
                    mode="lines",
                    line=dict(color=color, width=5, dash="solid"),
                    hoverinfo="name",
                ))
        else:
            trace_dets.append(
                go.Scatter3d(
                    x=scale_factor_d * x,
                    y=scale_factor_d * y,
                    z=scale_factor_d * z,
                    name=name,
                    mode="lines",
                    legendgroup="unused detectors",
                    line=dict(color=color, width=5, dash="dash"),
                    hoverinfo="name",
                ))

    with fits.open(trigdat_file) as f:
        quat = f["TRIGRATE"].data["SCATTITD"][0]
        sc_pos = f["TRIGRATE"].data["EIC"][0]
        times = f["TRIGRATE"].data["TIME"][0]

    # Plot Earth Shadow
    det = gbm_detector_list["n0"](quaternion=quat,
                                  sc_pos=sc_pos,
                                  time=astro_time.Time(utc(times)))
    earth_pos_sat = det.earth_position
    ra_earth_sat = earth_pos_sat.lon.deg
    dec_earth_sat = earth_pos_sat.lat.deg
    # earth_pos
    xe, ye, ze = xyz(ra_earth_sat, dec_earth_sat)
    earth_vec = np.array([xe, ye, ze])
    opening_angle = 67
    # points on sphere
    theta_l = np.concatenate([
        np.linspace(-np.pi / 2, -np.pi / 2 + 0.1, 30),
        np.linspace(-np.pi / 2 + 0.1, np.pi / 2 - 0.1, 400),
        np.linspace(np.pi / 2 - 0.1, np.pi / 2, 30),
    ])  # file size!#
    theta_final = []
    phi_final = []
    phi_l = np.arange(-np.pi, np.pi + 0.1, 0.1)
    for theta in theta_l:
        for phi in phi_l:
            x, y, z = xyz(phi * 180 / np.pi, theta * 180 / np.pi)
            angle = np.arccos(np.dot(np.array([x, y, z]), earth_vec))
            if angle < opening_angle * np.pi / 180:
                theta_final.append(theta)
                phi_final.append(phi)
    theta_final = np.array(theta_final)
    phi_final = np.array(phi_final)

    x = np.cos(theta_final) * np.cos(phi_final)
    y = np.cos(theta_final) * np.sin(phi_final)
    z = np.sin(theta_final)
    scale_factor_earth = 1.005
    colorscale = [[0, "navy"], [1, "navy"]]

    theta = np.arcsin(z) * 180 / np.pi
    phi = np.arctan2(x, y) * 180 / np.pi
    my_text = []
    for i in range(len(phi)):
        my_text.append("phi:{}<br>theta:{}".format(phi[i], theta[i]))
    my_text = np.array(my_text)
    trace_earth = go.Mesh3d(
        x=scale_factor_earth * x,
        y=scale_factor_earth * y,
        z=scale_factor_earth * z,
        showscale=False,
        name="earth",
        color="navy",
        alphahull=0,
        text=my_text,
        hoverinfo="text+name",
    )

    # Plot Balrog ERROR CONTOURS
    # Load data from chain with chain consumer
    chain = loadtxt2d(post_equal_weights_file)

    # Get parameter for model
    parameter = model_param_lookup[model]

    c1 = ChainConsumer()
    c1.add_chain(chain[:, :-1][:, :2],
                 parameters=parameter[:2]).configure(contour_labels="sigma",
                                                     colors="#cd5c5c",
                                                     label_font_size=20)
    # ra_contour, dec_contour, val_contour = c1.plotter.get_contours_list('ra', 'dec')  # ra, dec in deg here
    chains, parameters, truth, extents, blind, log_scales = c1.plotter._sanitise(
        None, None, None, None, color_p=True, blind=None)
    hist, ra_contour, dec_contour = c1.plotter._get_smoothed_histogram2d(
        chains[0], "ra (deg)", "dec (deg)")  # ra, dec in deg here
    hist[hist == 0] = 1e-16
    val_contour = c1.plotter._convert_to_stdev(hist.T)
    ra_con, dec_con = np.meshgrid(ra_contour, dec_contour)
    a = np.array([ra_con, dec_con]).T
    res = []
    q1, q2, q3, q4 = quat
    scx, scy, scz = sc_pos
    for a_inter in a:
        loc_icrs = SkyCoord(ra=a_inter[:, 0],
                            dec=a_inter[:, 1],
                            unit="deg",
                            frame="icrs")
        loc_sat = loc_icrs.transform_to(
            GBMFrame(
                quaternion_1=q1,
                quaternion_2=q2,
                quaternion_3=q3,
                quaternion_4=q4,
                sc_pos_X=scx,
                sc_pos_Y=scy,
                sc_pos_Z=scz,
            ))
        ra_sat = Angle(loc_sat.lon.deg * unit.degree).value
        dec_sat = Angle(loc_sat.lat.deg * unit.degree).value
        res.append(np.stack((ra_sat, dec_sat), axis=-1))
    res = np.array(res)
    scale_factor_con = 1.02
    x, y, z = xyz(res[:, :, 0], res[:, :, 1])
    x = scale_factor_con * x
    y = y * scale_factor_con
    z = z * scale_factor_con
    colorscale = [[0, "green"], [1.0 / 3.0, "orange"], [2.0 / 3.0, "red"],
                  [1, "grey"]]
    conf_levels = [0.68, 0.95, 0.99]
    trace_conf_l = []
    theta = np.arcsin(z) * 180 / np.pi
    phi = np.arctan2(x, y) * 180 / np.pi
    my_text = []
    for i in range(len(phi)):
        te = []
        for j in range(len(phi[0])):
            te.append("phi:{}<br>theta:{}".format(phi[i, j], theta[i, j]))
        my_text.append(te)
    my_text = np.array(my_text)
    for conf in conf_levels:
        x2n, y2n, z2n = (
            np.where(val_contour < conf, x, None),
            np.where(val_contour < conf, y, None),
            np.where(val_contour < conf, z, None),
        )
        trace_conf = go.Surface(
            x=x2n,
            y=y2n,
            z=z2n,
            cmin=0,
            cmax=3,
            showscale=False,
            colorscale=colorscale,
            surfacecolor=z2n,
            name="Balrog {} confidence level".format(conf),
            text=my_text,
            hoverinfo="text+name",
        )
        lx = len(trace_conf["z"])
        ly = len(trace_conf["z"][0])
        out = []
        x_sigma1 = []
        for i in range(lx):
            temp = []
            for j in range(ly):
                if val_contour[i, j] < 0.68:
                    temp.append(0)
                elif val_contour[i, j] < 0.95:
                    temp.append(1)
                elif val_contour[i, j] < 0.99:
                    temp.append(2)
                else:
                    temp.append(3)
            out.append(temp)
        # PLOT BESTFIT and SWIFT (if given)
        trace_conf["surfacecolor"] = out
        trace_conf_l.append(trace_conf)

    # TODO add swift position

    # add data together
    data = ([trace_b0, trace_b1, trace_s, trace_earth] + trace_grid +
            trace_dets + trace_conf_l)
    # change layout
    layout = go.Layout(
        dict(
            hovermode="closest",
            autosize=True,
            # width=1000,
            height=800,
            scene=dict(
                xaxis=dict(
                    title="",
                    autorange=True,
                    showgrid=False,
                    zeroline=False,
                    showline=False,
                    ticks="",
                    showticklabels=False,
                    showspikes=False,
                ),
                yaxis=dict(
                    title="",
                    autorange=True,
                    showgrid=False,
                    zeroline=False,
                    showline=False,
                    ticks="",
                    showticklabels=False,
                    showspikes=False,
                ),
                zaxis=dict(
                    title="",
                    autorange=True,
                    showgrid=False,
                    zeroline=False,
                    showline=False,
                    ticks="",
                    showticklabels=False,
                    showspikes=False,
                ),
            ),
        ))
    # create figure
    fig = go.Figure(data=data, layout=layout)

    output = plotly.offline.plot(fig,
                                 auto_open=False,
                                 output_type="div",
                                 include_plotlyjs=False,
                                 show_link=False)

    file_utils.if_dir_containing_file_not_existing_then_make(save_path)
    with open(save_path, "w") as text_file:
        text_file.write(output)
Example #5
0
def bandplot3d(bands, selector, indaxis=0, title='', fname='', **kwargs):
    """ Make 3D band structure (a number of electronic bands) surface plot.

    :Parameters:
        bands : 2D/3D matrix
            Electronic band structure ordered by band index.
        selector : iterable
            Index selector for the bands to visualize.
        indaxis : int | 0
            Axis of the band index.
        title : str | ''
            Title to appear on the plot.
        fname : str | ''
            User-defined filename for the plotted figure.
        **kwargs : keyword arguments
            Additional keyword arguments for `plotly.graph_objs.Layout()`.
            :width, height: numeric
                Width and height of the plotted figure.
            :plot_margin: dictionary
                Margins of the figure upon initialization, such as dict(l=65, r=50, b=65, t=90).
            :labelsize: int
                Size of the axes label.
            :aspect: list/tuple
                Aspect ratio of the x, y and z directions.
    """

    nb = bands.ndim

    if nb == 2:  # Amend an axis in case only one band is used as the input
        bands = bands[None, :, :]

    elif nb == 3:

        bands = np.moveaxis(bands, indaxis, 0)
        # Retrieve figure attributes
        plotmargin = kwargs.pop('plot_margin', dict(l=65, r=50, b=65, t=90))
        width = kwargs.pop('width', 600)
        height = kwargs.pop('height', 600)
        labelsize = kwargs.pop('labelsize', 30)
        asp = kwargs.pop('aspect', [1, 1, 1])

        data = [
            go.Surface(z=bands[i, :, :], showscale=False) for i in selector
        ]

        layout = go.Layout(scene=dict(
            xaxis=dict(ticks='',
                       showticklabels=False,
                       title='kx',
                       linewidth=3,
                       titlefont=dict(size=labelsize)),
            aspectratio=dict(x=asp[0], y=asp[1], z=asp[2]),
            yaxis=dict(ticks='',
                       showticklabels=False,
                       title='ky',
                       linewidth=3,
                       titlefont=dict(size=labelsize)),
            zaxis=dict(ticks='',
                       showticklabels=False,
                       title='Energy',
                       linewidth=3,
                       titlefont=dict(size=labelsize))),
                           title=title,
                           autosize=False,
                           width=width,
                           height=height,
                           margin=plotmargin,
                           **kwargs)

        f = go.Figure(data=data, layout=layout)
        plot = py.iplot(f, filename=fname)

        return plot
Example #6
0
    # ---------------------------------------------------------------------
    print("Graphing results for cap w/ R0 = ", R0[r])

    totCapSurf = go.Figure()
    # Graph GTotCap (GCap + GPore) surface
    print("Graphing total surface")
    totCapSurf.add_trace(
        go.Surface(
            #coloraxis=go.layout.Coloraxis(dict(
            #    title="Neg G", "coloraxis1")),
            colorbar=go.surface.ColorBar(title='Net G'),
            colorscale='matter',
            contours={
                "z": {
                    "show": True,
                    "start": np.max(GTotCap[r, :, :]) / 20,
                    "end": np.max(GTotCap[r, :, :]) * 0.95,
                    "size": np.max(GTotCap[r, :, :]) / 20
                }
            },
            name='Net G',
            x=rEffCap,
            y=rt,
            z=GTotCap[r, :, :],
            opacity=0.9))
    # Graph curve of min GTotCap for expanding rEffCap
    print("Graphing minimal G path")
    totCapSurf.add_trace(
        go.Scatter3d(marker=dict(color='blue', size=2),
                     mode='lines',
                     name='Min G path',
                     x=GMinPathCap[r, :, 0],
Example #7
0
        new_policy = policy_improvement(episode, player_policy, action_values)
        log.debug('Changes made to policy: {}'.format((new_policy != player_policy).sum()))
        player_policy = new_policy

    state_values = to_state_value(action_values)
    player_policy = to_policy(action_values)
    x = np.arange(0, state_values.shape[0]) + DEALER_MIN
    y = np.arange(0, state_values.shape[1]) + PLAYER_MIN
    label_dealer_sum = {'title': 'dealer sum', 'dtick': 1}
    label_player_sum = {'title': 'player sum', 'dtick': 1}
    kwargs = dict(x=x, y=y, hoverinfo="x+y+z")
    layout_surf = {'xaxis': label_dealer_sum, 'yaxis': label_player_sum, 'aspectratio': {'x': 1, 'y': 1, 'z': 0.5}}
    single_contour_config = {'show': True, 'highlight': False, 'project': {'z': True}}
    contours = {'x': single_contour_config, 'y': single_contour_config, 'z': {'highlight': False}}

    surface_no_ace = go.Surface(z=state_values[:, :, NO_ACE_LAYER].T, contours=contours, **kwargs)
    surface_ace = go.Surface(z=state_values[:, :, ACE_LAYER].T, contours=contours, **kwargs)
    heatmap_policy_no_ace = go.Heatmap(z=player_policy[:, :, NO_ACE_LAYER].T, **kwargs)
    heatmap_policy_ace = go.Heatmap(z=player_policy[:, :, ACE_LAYER].T, **kwargs)

    fig = tools.make_subplots(rows=2, cols=2, shared_xaxes=True,
                              specs=[[{'is_3d': True}, {'is_3d': True}],
                                     [{'is_3d': False}, {'is_3d': False}]],
                              subplot_titles=('No usable ace', 'Usable ace',
                                              'No usable ace', 'Usable ace'))
    fig.append_trace(surface_no_ace, 1, 1)
    fig.append_trace(surface_ace, 1, 2)
    fig.append_trace(heatmap_policy_no_ace, 2, 1)
    fig.append_trace(heatmap_policy_ace, 2, 2)

    fig['layout']['scene1'].update(layout_surf)
Example #8
0

plt.imshow(images[0])


import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

init_notebook_mode(connected=True)

iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])



data = [go.Surface(z=img[0])]

data

layout = go.Layout(
    title='Mt Bruno Elevation',
    autosize=False,
    width=500,
    height=500,
    margin=dict(
        l=65,
        r=50,
        b=65,
        t=90)
)
fig = go.Figure(data=data)
Example #9
0
 def update_figure(invar, invar_2, invar_3, outvar, invar1_log, invar2_log, invar3_log, outvar_log, param_slider,
                   graph_type, color_use, color_dd, error_use, error_dd, filter_active, fit_use, fit_dd, fit_num, fit_conf, add_noise_var, fit_color,
                   fit_opacity, fit_sampling, id_type, param_center, param_log):
     for i in range(len(param_slider)):
         if param_log[i] == ['log']:
             param_slider[i] = [10**val for val in param_slider[i]]
             param_center[i] = 10**param_center[i]
     if invar is None:
         return go.Figure()
     sel_y = np.full((len(outdata),), True)
     dds_value = []
     for iteration, values in enumerate(param_slider):
         dds_value.append(invars[id_type[iteration]['index']])
         # filter for minimum
         sel_y_min = np.array(indata[dds_value[iteration]] >= param_slider[iteration][0])
         # filter for maximum
         sel_y_max = np.array(indata[dds_value[iteration]] <= param_slider[iteration][1])
         # print('iter ', iteration, 'filer', filter_active[iteration][0])
         if filter_active != [[]]:
             if filter_active[iteration] == ['act']:
                 sel_y = sel_y_min & sel_y_max & sel_y
     if graph_type == '1D':
         fig = go.Figure(
             data=[go.Scatter(
                 x=indata[invar][sel_y],
                 y=outdata[outvar][sel_y],
                 mode='markers',
                 name='data',
                 error_y=dict(type='data', array=outdata[error_dd][sel_y], visible= error_use == ['true']),
                 # text=[(invar, outvar) for i in range(len(indata[invar][sel_y]))],
                 # hovertemplate=" %{text} <br> %{x} <br> %{y}",
             )],
             layout=go.Layout(xaxis=dict(title=invar, rangeslider=dict(visible=True)), yaxis=dict(title=outvar))
         )
         if fit_use == ['show']:
             mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                       param_center, [invar], [invar1_log],
                                                                       outvar, fit_sampling, add_noise_var)
             for i in range(len(fit_dd_values)):
                 fig.add_trace(go.Scatter(
                     x=mesh_in[i][invars.index(invar)],
                     y=mesh_out[i],
                     mode='lines',
                     name=f'fit: {fit_dd}={fit_dd_values[i]:.1e}',
                     line_color=colormap(indata[fit_dd].min(), indata[fit_dd].max(), fit_dd_values[i]),
                     marker_line=dict(coloraxis="coloraxis2"),
                 ))
                 fig.add_trace(go.Scatter(
                     x=np.hstack((mesh_in[i][invars.index(invar)], mesh_in[i][invars.index(invar)][::-1])),
                     y=np.hstack((mesh_out[i] + fit_conf * mesh_out_std[i], mesh_out[i][::-1] - fit_conf * mesh_out_std[i][::-1])),
                     showlegend=False,
                     fill='toself',
                     line_color=colormap(indata[fit_dd].min(), indata[fit_dd].max(), fit_dd_values[i]),
                     marker_line=dict(coloraxis="coloraxis2"),
                     opacity=fit_opacity,
                 ))
     elif graph_type == '2D':
         fig = go.Figure(
             data=[go.Scatter3d(
                 x=indata[invar][sel_y],
                 y=indata[invar_2][sel_y],
                 z=outdata[outvar][sel_y],
                 mode='markers',
                 name='Data',
                 error_z=dict(type='data', array=outdata[error_dd][sel_y], visible=error_use == ['true'], width= 10)
             )],
             layout=go.Layout(scene=dict(xaxis_title=invar, yaxis_title=invar_2, zaxis_title=outvar))
         )
         if fit_use == ['show'] and invar != invar_2:
             mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                       param_center, [invar, invar_2],
                                                                       [invar1_log, invar2_log], outvar,
                                                                       fit_sampling, add_noise_var)
             for i in range(len(fit_dd_values)):
                 fig.add_trace(go.Surface(
                     x=mesh_in[i][invars.index(invar)].reshape((fit_sampling, fit_sampling)),
                     y=mesh_in[i][invars.index(invar_2)].reshape((fit_sampling, fit_sampling)),
                     z=mesh_out[i].reshape((fit_sampling, fit_sampling)),
                     name=f'fit: {fit_dd}={fit_dd_values[i]:.2f}',
                     surfacecolor=fit_dd_values[i] * np.ones([fit_sampling, fit_sampling])
                         if fit_color == 'multi-fit' else
                         (mesh_in[i][invars.index(color_dd)].reshape((fit_sampling, fit_sampling))
                          if (fit_color == 'marker-color' and color_dd in invars) else
                          mesh_out[i].reshape((fit_sampling, fit_sampling))),
                     opacity=fit_opacity,
                     coloraxis="coloraxis2" if (fit_color == 'multi-fit' or
                         (fit_color == 'output' and (color_dd != outvar and color_dd != 'OUTPUT'))) else "coloraxis",
                     showlegend=True if len(invars) > 2 else False,
                 ))
                 if fit_conf > 0:
                     fig.add_trace(go.Surface(
                         x=mesh_in[i][invars.index(invar)].reshape((fit_sampling, fit_sampling)),
                         y=mesh_in[i][invars.index(invar_2)].reshape((fit_sampling, fit_sampling)),
                         z=mesh_out[i].reshape((fit_sampling, fit_sampling)) + fit_conf * mesh_out_std[i].reshape((fit_sampling, fit_sampling)),
                         showlegend=False,
                         name=f'fit+v: {fit_dd}={fit_dd_values[i]:.2f}',
                         surfacecolor=fit_dd_values[i] * np.ones([fit_sampling, fit_sampling])
                             if fit_color == 'multi-fit' else
                             (mesh_in[i][invars.index(color_dd)].reshape((fit_sampling, fit_sampling))
                              if (fit_color == 'marker-color' and color_dd in invars) else
                              mesh_out[i].reshape((fit_sampling, fit_sampling))),
                         opacity=fit_opacity,
                         coloraxis="coloraxis2" if (fit_color == 'multi-fit' or
                             (fit_color == 'output' and (color_dd != outvar and color_dd != 'OUTPUT')))
                             else "coloraxis",
                     ))
                     fig.add_trace(go.Surface(
                         x=mesh_in[i][invars.index(invar)].reshape((fit_sampling, fit_sampling)),
                         y=mesh_in[i][invars.index(invar_2)].reshape((fit_sampling, fit_sampling)),
                         z=mesh_out[i].reshape((fit_sampling, fit_sampling)) - fit_conf * mesh_out_std[i].reshape((fit_sampling, fit_sampling)),
                         showlegend=False,
                         name=f'fit-v: {fit_dd}={fit_dd_values[i]:.2f}',
                         surfacecolor=fit_dd_values[i] * np.ones([fit_sampling, fit_sampling])
                             if fit_color == 'multi-fit' else
                             (mesh_in[i][invars.index(color_dd)].reshape((fit_sampling, fit_sampling))
                              if (fit_color == 'marker-color' and color_dd in invars) else
                              mesh_out[i].reshape((fit_sampling, fit_sampling))),
                         opacity=fit_opacity,
                         coloraxis="coloraxis2" if (fit_color == 'multi-fit' or
                             (fit_color == 'output' and (color_dd != outvar and color_dd != 'OUTPUT')))
                             else "coloraxis",
                     ))
             fig.update_layout(coloraxis2=dict(
                 colorbar=dict(title=outvar if fit_color == 'output' else fit_dd),
                 cmin=min(fit_dd_values) if fit_color == 'multi-fit' else None,
                 cmax=max(fit_dd_values) if fit_color == 'multi-fit' else None,
             ))
     elif graph_type == '2D contour':
         mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                   param_center, [invar, invar_2],
                                                                   [invar1_log, invar2_log], outvar,
                                                                   fit_sampling, add_noise_var)
         data_x = mesh_in[0][invars.index(invar)]
         data_y = mesh_in[0][invars.index(invar_2)]
         fig = go.Figure()
         if min(data_x) != max(data_x):
             if min(data_y) != max(data_y):
                 fig.add_trace(go.Scatter(
                     x=indata[invar][sel_y],
                     y=indata[invar_2][sel_y],
                     mode='markers',
                     name='Data',
                 ))
                 fig.add_trace(go.Contour(
                     x=mesh_in[0][invars.index(invar)],
                     y=mesh_in[0][invars.index(invar_2)],
                     z=mesh_out[0],
                     contours_coloring='heatmap',
                     contours_showlabels=True,
                     coloraxis='coloraxis2',
                     name='fit',
                 ))
                 fig.update_xaxes(
                     range=[log10(min(fig.data[1]['x'])), log10(max(fig.data[1]['x']))] if invar1_log == ['log']
                     else [min(fig.data[1]['x']), max(fig.data[1]['x'])])
                 fig.update_yaxes(
                     range=[log10(min(fig.data[1]['y'])), log10(max(fig.data[1]['y']))] if invar2_log == ['log']
                     else [min(fig.data[1]['y']), max(fig.data[1]['y'])])
                 fig.update_layout(xaxis_title=invar,
                                   yaxis_title=invar_2,
                                   coloraxis2=dict(colorbar=dict(title=outvar),
                                                   colorscale='solar',
                                                   cmin=min(fig.data[1]['z']),
                                                   cmax=max(fig.data[1]['z'])))
             else:
                 fig.update_layout(title="y-data is constant, no contour-plot possible")
         else:
             fig.update_layout(title="x-data is constant, no contour-plot possible")
     elif graph_type == '3D':
         fig = go.Figure(
             data=go.Scatter3d(
                 x=indata[invar][sel_y],
                 y=indata[invar_2][sel_y],
                 z=indata[invar_3][sel_y],
                 mode='markers',
                 marker=dict(
                         color=outdata[outvar][sel_y],
                         coloraxis="coloraxis2",
                     ),
                 name='Data',
             ),
             layout=go.Layout(scene=dict(xaxis_title=invar, yaxis_title=invar_2, zaxis_title=invar_3)),
         )
         fig.update_layout(coloraxis2=dict(
             colorbar=dict(title=outvar),
         ))
         if fit_use == ['show'] and len({invar, invar_2, invar_3}) == 3:
             mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                       param_center, [invar, invar_2, invar_3],
                                                                       [invar1_log, invar2_log, invar3_log], outvar,
                                                                       fit_sampling, add_noise_var)
             for i in range(len(fit_dd_values)):
                 fig.add_trace(
                     go.Isosurface(
                         x=mesh_in[i][invars.index(invar)],
                         y=mesh_in[i][invars.index(invar_2)],
                         z=mesh_in[i][invars.index(invar_3)],
                         value=mesh_out[i],
                         surface_count=fit_num,
                         coloraxis="coloraxis2",
                         isomin=mesh_out[i].min() * 1.1,
                         isomax=mesh_out[i].max() * 0.9,
                         caps=dict(x_show=False, y_show=False, z_show=False),
                         opacity=fit_opacity,
                     ),
                 )
     else:
         fig = go.Figure()
     fig.update_layout(legend=dict(xanchor="left", x=0.01))
     # log scale
     log_dict = {'1D': (invar1_log, outvar_log),
                 '2D': (invar1_log, invar2_log, outvar_log),
                 '2D contour': (invar1_log, invar2_log),
                 '3D': (invar1_log, invar2_log, invar3_log),}
     log_list = ['linear' if log is None or len(log) == 0 else log[0] for log in log_dict[graph_type]]
     log_key = ['xaxis', 'yaxis', 'zaxis']
     comb_dict = dict(zip(log_key, [{'type': log} for log in log_list]))
     if len(log_list) < 3 :
         fig.update_layout(**comb_dict)
     else:
         fig.update_scenes(**comb_dict)
     # color
     if color_use == ['true']: # TODO: trigger-detection no new fig just update
         if fit_use == ['show'] and (graph_type=='2D' and (fit_color=='multi-fit' and color_dd==fit_dd)):
             fig.update_traces(
                 marker=dict(
                     coloraxis="coloraxis2",
                     color=indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y],
                 ),
                 selector=dict(mode='markers'),
             )
         elif graph_type == '3D':
             fig.update_traces(
                 marker=dict(
                     coloraxis="coloraxis2",
                     color=outdata[outvar][sel_y],
                 ),
                 selector=dict(mode='markers'),
             )
         elif graph_type=='1D':
             fig.update_traces(
                 marker=dict(
                     coloraxis="coloraxis2",
                     color=outdata[outvar][sel_y] if color_dd == 'OUTPUT' else
                     (indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y]),
                 ),
                 selector=dict(mode='markers'),
             )
             if color_dd==fit_dd:
                 fig.update_layout(coloraxis2=dict(colorscale='cividis', colorbar=dict(title=fit_dd)))
             elif color_dd == 'OUTPUT':
                 fig.update_layout(coloraxis2=dict(colorscale='plasma', colorbar=dict(title=outvar)))
             else:
                 fig.update_layout(coloraxis2=dict(colorscale='plasma', colorbar=dict(title=color_dd)))
         elif graph_type =='2D contour':
             fig.update_traces(
                 marker=dict(
                     coloraxis="coloraxis",
                     color=outdata[outvar][sel_y] if color_dd == 'OUTPUT' else
                     (indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y]),
                 ),
                 selector=dict(mode='markers'),
             )
             if color_dd == outvar or color_dd == 'OUTPUT':
                 fig.update_traces(marker_coloraxis="coloraxis2", selector=dict(mode='markers'))
             else:
                 fig.update_layout(coloraxis=dict(colorbar=dict(title=color_dd, x=1.1),
                                                  colorscale='ice'))
         else:
             fig.update_traces(
                 marker=dict(
                     coloraxis="coloraxis",
                     color=outdata[outvar][sel_y] if color_dd == 'OUTPUT' else
                     (indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y]),
                 ),
                 selector=dict(mode='markers'),
             )
             fig.update_layout(coloraxis=dict(
                 colorbar=dict(title=outvar if color_dd == 'OUTPUT' else color_dd, x=1.1),
                 colorscale='viridis',
             ))
     fig.update_layout(height=graph_height)
     return fig
Example #10
0
import plotly.graph_objs as go
import numpy as np

r = np.linspace(0, 10, 100)
t = np.linspace(0, 2 * np.pi, 240)

rGrid, tGrid = np.meshgrid(r, t)

x = rGrid * np.cos(tGrid)
y = rGrid * np.sin(tGrid)
z1 = np.maximum(1 - rGrid / 5, rGrid * 0)
z2 = np.maximum(1 - rGrid / 3, rGrid * 0)

surface1 = go.Surface(x=x,
                      y=y,
                      z=z1,
                      opacity=0.7,
                      colorscale='Viridis',
                      colorbar=dict(showticklabels=False))
surface2 = go.Surface(x=x, y=y, z=z2, opacity=1, colorscale='Viridis')
data = [surface1, surface2]

layout = go.Layout(title='2D IT2 Fuzzy FMF',
                   scene=dict(xaxis=dict(
                       title='y₁',
                       gridcolor='rgb(255, 255, 255)',
                       zerolinecolor='rgb(255, 255, 255)',
                       showbackground=True,
                       backgroundcolor='rgb(230, 230,230)',
                       range=[-5, 5],
                   ),
                              yaxis=dict(
Example #11
0
def get_fit_trace(result,
                  x,
                  n_points=None,
                  log_x=False,
                  flip_xy=False,
                  showlegend=False,
                  fit_x_range=None):
    if isinstance(result, np.ndarray):
        fit_type = result["fit_type"]
        # params = result["params"]
        x_range = result["x_range"]
        y_range = result["y_range"]
        is_multivariate = result["is_multivariate"]
    else:
        fit_type, params, _, _, _, x_range, y_range, *_, is_multivariate = result

    x = np.asarray(x)
    if x.ndim == 1:
        x = x[np.isfinite(x)]
    elif x.ndim == 2:
        x = x[np.isfinite(x).any(axis=-1)]
    else:
        raise NotImplementedError

    if is_multivariate:
        if n_points is None:
            n_points = int(np.power(len(x) * 20, 1.5))

        assert log_x is False
        n_variables = x.shape[1]
        if 2 < n_variables:
            raise NotImplementedError("2 < n_variables")

        # x_margin = 0.1 * (x.max(axis=0) - x.min(axis=0))
        # print(x_margin)
        x_margin = [0, 0]
        if fit_x_range is None:
            fit_x_range = [(max(x_range[0][0], x[:, 0].min() - x_margin[0]),
                            min(x_range[0][1], x[:, 0].max() + x_margin[0])),
                           (max(x_range[1][0], x[:, 1].min() - x_margin[1]),
                            min(x_range[1][1], x[:, 1].max() + x_margin[1]))]

        # fit_x = np.stack([
        #     e.flatten()
        #     for e in np.meshgrid(
        #         np.linspace(fit_x_range[0][0], fit_x_range[0][1], int(np.sqrt(n_points))),
        #         np.linspace(fit_x_range[1][0], fit_x_range[1][1], int(np.sqrt(n_points)))
        #     )
        # ], axis=-1)
        fit_x = (np.linspace(fit_x_range[0][0], fit_x_range[0][1],
                             int(np.sqrt(n_points))),
                 np.linspace(fit_x_range[1][0], fit_x_range[1][1],
                             int(np.sqrt(n_points))))
    else:
        if n_points is None:
            n_points = min(len(x) * 20, 300_000)

        if log_x is True:
            x_margin = 0.1 * (np.log10(np.max(x)) - np.log10(np.min(x)))
            if fit_x_range is None:
                fit_x_range = (max(x_range[0],
                                   10**(np.log10(np.min(x)) - x_margin)),
                               min(x_range[1],
                                   10**(np.log10(np.max(x)) + x_margin)))
            fit_x = np.logspace(*np.log10(fit_x_range), n_points)
        else:
            x_margin = 0.1 * (np.max(x) - np.min(x))
            if fit_x_range is None:
                fit_x_range = (max(x_range[0],
                                   np.min(x) - x_margin),
                               min(x_range[1],
                                   np.max(x) + x_margin))
            fit_x = np.linspace(*fit_x_range, n_points)

    if is_multivariate:
        fit_y = regression.eval(
            np.stack([e.flatten() for e in np.meshgrid(fit_x[0], fit_x[1])],
                     axis=-1), result)
    else:
        fit_y = regression.eval(fit_x, result)
    matched_on_y = (y_range[0] <= fit_y) & (fit_y <= y_range[1])
    fit_y[~matched_on_y] = np.nan
    # if is_multivariate:
    #     fit_x[0][~matched_on_y] = fit_x[1][~matched_on_y] = np.nan
    # else:
    #     fit_x[~matched_on_y] = np.nan

    plot_kwargs = dict(name=f"{fit_type} fit", showlegend=showlegend)

    if is_multivariate:
        assert flip_xy is False

        import plotly.express as px
        # plot_kwargs.update(color="#EF553B", opacity=0.3)
        # return go.Mesh3d(x=fit_x[:, 0], y=fit_x[:, 1], z=fit_y, **plot_kwargs)
        # plot_kwargs.update(colorscale=px.colors.sequential.Reds[2:], opacity=0.5, showscale=False)
        plot_kwargs.update(colorscale=["#EF553B"] * 2,
                           opacity=0.3,
                           showscale=False)
        return go.Surface(
            # x=np.linspace(x[:, 0].min(), x[:, 0].max(), int(np.sqrt(n_points))),
            # y=np.linspace(x[:, 1].min(), x[:, 1].max(), int(np.sqrt(n_points))),
            x=fit_x[0],
            y=fit_x[1],
            z=fit_y.reshape((int(np.sqrt(n_points))), int(np.sqrt(n_points))),
            **plot_kwargs)
    else:
        if flip_xy:
            fit_x, fit_y = fit_y, fit_x

        plot_kwargs.update(line=dict(color="red"))
        return go.Scattergl(mode="lines", x=fit_x, y=fit_y, **plot_kwargs)
Example #12
0
 def __init__(self, z, **kwargs):
     super().__init__(data=go.Surface(z=z, **kwargs))
Example #13
0
            distance = math.sqrt(math.pow(i-charge[0],2.0)+math.pow(j-charge[1],2.0))
            
            if distance != 0:
                total +=charge[2] / distance
            else:
                total += charge[2]/0.8
        
        zlist.append(total)
    masterlist.append(zlist)

## y value is index of z
## x value is index of inner list
## z value is number at that point
## indexing list z [y][x]
data = [
    go.Surface(
        z = masterlist)
    ]

layout = go.Layout(
    title='Electric Potential',
    autosize=True,
    width=500,
    height=500,
    margin=dict(
        l=65,
        r=50,
        b=65,
        t=90
    )
)
fig = go.Figure(data=data, layout=layout)
Example #14
0
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from joblib import load
import pandas as pd
import plotly.graph_objs as go

# Imports from this application
from app import app

pdp = load('assets/pdp.joblib')
pdp2 = load('assets/pdp2.joblib')
pdp3 = load('assets/pdp3.joblib')

surface = go.Surface(x=pdp.columns, y=pdp.index, z=pdp.values)

fig = go.Figure(surface)

fig.update_layout(scene=dict(
    xaxis_title='Spore Print Color',
    yaxis_title='Ring Type',
    zaxis_title='Predicted Probability of Poisonous Mushroom'),
                  width=700,
                  margin=dict(r=20, b=10, l=10, t=10))

surface2 = go.Surface(x=pdp2.columns, y=pdp2.index, z=pdp2.values)

fig2 = go.Figure(surface2)

fig2.update_layout(scene=dict(
Example #15
0
                                   'title': 'Hit = f(X,Y)',
                               }
                           }))
          ]),
 html.H3('Eit visualization'),
 html.Hr(),
 html.Div(className='row',
          children=[
              html.Div(className='col-6',
                       children=dcc.Graph(
                           id='map3d-graph',
                           figure={
                               'data': [
                                   go.Surface(
                                       z=Z_Eit,
                                       x=xi,
                                       y=yi,
                                       colorscale='Viridis',
                                   )
                               ],
                               'layout': {
                                   'title': 'Eit = f(X,Y)',
                               }
                           })),
              html.Div(className='col-5',
                       children=dcc.Graph(
                           id='map2-graph',
                           figure={
                               'data': [
                                   go.Scatter(
                                       x=X_list,
                                       y=Y_list,
Example #16
0
plt.tight_layout()

mfcc = librosa.feature.mfcc(S=log_S, n_mfcc=13)

# Let's pad on the first and second deltas while we're at it
delta2_mfcc = librosa.feature.delta(mfcc, order=2)

plt.figure(figsize=(12, 4))
librosa.display.specshow(delta2_mfcc)
plt.ylabel('MFCC coeffs')
plt.xlabel('Time')
plt.title('MFCC')
plt.colorbar()
plt.tight_layout()

data = [go.Surface(z=spectrogram.T)]
layout = go.Layout(
    title='Specgtrogram of "yes" in 3d',
    scene=dict(
        yaxis=dict(title='Frequencies', range=freqs),
        xaxis=dict(title='Time', range=times),
        zaxis=dict(title='Log amplitude'),
    ),
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig)

#%matplotlib inline
ipd.Audio(samples, rate=sample_rate)

import IPython
import plotly
import plotly.graph_objs as go
import numpy as np

df = 'data/mt_bruno_elevation.csv'
Z = np.loadtxt(df, delimiter=',', skiprows=1, usecols=range(1, 25))
data = [go.Surface(z=Z)]
fig = go.Figure(data=data)
plotly.offline.plot(fig, filename='../templates/mt-3d-surface.html')
Example #18
0
            width=0.5
        ),
        opacity=0.8
    )
)

data = [trace1]
layout = go.Layout(
    margin=dict(
        l=0,
        r=0,
        b=0,
        t=0
    )
)
fig = go.Figure(data=data, layout=layout)
"""

data = [go.Surface(z=A)]
layout = go.Layout(
    title='CNN Output/Input Sizes',
    autosize=True,  # we want this to fill the screen
    #    width=500,
    #    height=500,
    margin=dict(l=65, r=50, b=65, t=90),
    xaxis=dict(title='Filter Size'),
    yaxis=dict(title='Stride Length'))
fig = go.Figure(data=data, layout=layout)

plot(fig)
Example #19
0
def PyPlot3D(title,
             z_csv,
             x_csv,
             y_csv,
             t_coeff=1,
             online=True,
             path=".",
             filename="wt2",
             xaxis="states",
             yaxis="time",
             to_file="",
             y_scale=1):
    print("Making plot...")
    # Z----------------------------------------------
    z_data = pd.read_csv(z_csv, header=None)
    # Z----------------------------------------------

    # X----------------------------------------------
    x = pd.read_csv(x_csv, keep_default_na=False)
    x.replace(r'\[(.+)\]', r'≺\1≻', regex=True, inplace=True)

    x_header = list(x)[0]
    x["x"] = list(x["x"])
    print(x["x"])
    print(x["vals"])
    # x_ticktext = list(x["x"])
    x_tickvals = np.linspace(list(x["x"])[0], list(x["x"])[-1], 10)
    # x_ticktext = np.linspace(0, len(x["x"]), 5)
    x_ticktext = np.linspace(list(x["vals"])[0], list(x["vals"])[-1], 10)
    x_ticktext /= 100
    x_ticktext = np.round(x_ticktext, 4)
    # print(list(x["x"])[-1])
    # for i in range(len(x_ticktext)):
    # x_ticktext[i] = x_ticktext[i]
    # x_ticktext[i] = str(x_ticktext[i])
    print(x["x"])
    print('x_ticktext:', x_ticktext)
    print('x_tickvals:', x_tickvals)
    # exit(0)
    # X----------------------------------------------

    # Y----------------------------------------------
    y = pd.read_csv(y_csv, keep_default_na=False)
    y_header = list(y)[0]

    # print(list(y["y"]))
    # exit(0)
    y_y = list(y["y"])
    y_v = list(y["vals"])
    y["vals"] = list(y["vals"])
    y_tickvals = list(np.arange(0, y_y[-1] + 1, 2))
    # y_tickvals = y_y
    # y_tickvals = list(np.arange(0, y_v[-1] + 1, 10))
    y_ticktext = list(np.arange(y_v[0], y_v[-1] + 1, 10))
    # y_tickvals = np.linspace(
    #     list(y["y"])[0], list(y["y"])[-1], 5)
    # y_ticktext = np.linspace(
    #     list(y["vals"])[0], list(y["vals"])[-1], 5)
    # y_ticktext = np.round(y_ticktext, 2)
    # y_ticktext = list(y["y"])
    # y_tickvals = list(y["vals"])
    # y_tickvals = np.array(y_tickvals) / t_coeff
    print('y_ticktext:', y_ticktext)
    print('y_tickvals:', y_tickvals)
    # Y----------------------------------------------

    data = [
        go.Surface(
            showlegend=False,
            showscale=False,
            lighting=dict(diffuse=0.5, specular=.2, fresnel=0.2),
            z=z_data.as_matrix(),
            colorscale="Portland",
        )
    ]

    scale = int(y_ticktext[-1])

    layout = go.Layout(
        # plot_bgcolor="#000000",
        # pap_bgcolor="#000000",
        title=title,
        titlefont=dict(
            # family="Courier New, monospace",
            # family='Open Sans, sans-serif',
            family='Lato',
            size=20,
            color="#222"),
        margin=go.Margin(
            l=0,
            r=0,
            b=0,
            t=35,
            pad=50,
        ),
        xaxis=dict(
            # linecolor="black",
            # linewidth=2,
            autotick=False,
            # dtick=1,
            ticks='outside',
            tickfont=dict(
                # size=20,
                size=200, ),
        ),
        yaxis=dict(
            # tickangle=45,
            title="y Axis",
            titlefont=dict(
                family="Courier New, monospace",
                # family='Old Standard TT, serif',
                size=40,
                # size=14,
                color="#FFFFFF"),
            autotick=False,
            # dtick=1,
            ticks='outside',
            tickfont=dict(
                # size=20,
                size=200, ),
        ),
        # zaxis=dict(
        #     tickangle=90
        # ),
        autosize=False,
        # autosize=True,
        width=1200,
        height=650,
        plot_bgcolor="#AAA",
        # paper_bgcolor="#AAA",
        scene=go.Scene(
            camera=dict(up=dict(x=0, y=0, z=1),
                        center=dict(x=0, y=0, z=0.2),
                        eye=dict(x=3.75, y=3.75, z=3.75)),
            # aspectratio={"x": 1, "y": 1, "z": 1},
            aspectratio={
                "x": 2,
                "y": 2,
                "z": 1
            },
            xaxis={
                "title": xaxis,
                "showgrid": False,
                "showline": False,
                # "showline":True,
                # "ticks": "outside",
                # "showticklabels": True,
                # "linewidth": 1,
                # "tickvals": list(range(len(x_tickvals))),
                # "ticktext": list(range(len(x_tickvals))),
                "tickvals": x_tickvals,
                "ticktext": x_ticktext,
                'titlefont': dict(size=18, ),
                'tickfont': dict(size=14, ),
                'autorange': True,

                # "tickangle": 45,
                # "linecolor": "black",
                # "linewidth": 2,
            },
            yaxis={
                'autorange': True,
                "title": yaxis + "\t\t\t\t.",
                "ticktext": y_ticktext,
                "tickvals": y_tickvals,
                # "linecolor": "black",
                "linewidth": 1,
                'titlefont': dict(size=18, ),
                'tickfont': dict(size=14, )
            },
            zaxis={
                'autorange': True,
                "range": [0, 1],
                "title": "",
                # "title": "prob.\t\t\t\t\t\t.",
                "title": "T, ns          .",
                'nticks': 5,
                # "title": "max(hp) / max(p(t))                                             .",
                # 'dtick': -20,
                # "tickangle": 45,
                # "linecolor": "black",
                # "ticktext": y_ticktext,
                # "tickvals": y_tickvals,
                "linewidth": 1,
                'titlefont': dict(size=18, ),
                'tickfont': dict(size=14, )
                # "transform": {"rotate": '0'}
            },
        ),
        showlegend=False)

    fig = go.Figure(data=data, layout=layout)

    if to_file:
        py.image.save_as(fig, filename=to_file)
        return
# fig["layout"].update(scene=dict(aspectmode="data"))
# online=False
    if online:
        py.plot(fig, filename=filename)
        # plotly.offline.init_notebook_mode()
        # plotly.offline.iplot(fig, filename="wt.html")

        # plotly.
        # py.offline.iplot(fig, filename="wt")
    else:
        # plotly.offline.init_notebook_mode()
        plotly.offline.plot(fig, filename=path + filename + ".html")

    return
Example #20
0
else:
    effective_order = h_order

if effective_order < 3:
    rE_min = 0.5
else:
    rE_min = 0.7

rE_plot = go.Surface(
    name='Energy Model Localization Vector (r<sub>E</sub>)',
    x=0.9 * np.min(spkr_rr) * np.reshape(xyz[0, :], T.shape),
    y=0.9 * np.min(spkr_rr) * np.reshape(xyz[1, :], T.shape),
    z=0.9 * np.min(spkr_rr) * np.reshape(xyz[2, :], T.shape),
    cmin=rE_min,
    cmax=np.ceil(np.max(rEr) * 10) / 10,
    surfacecolor=c,
    colorscale='Portland',
    hoverinfo='text',
    visible=False,
    opacity=1.0,
    text=np.vectorize(lambda u, v, c: "rE: %.2f<br>a: %.1f<br>e: %.1f" %
                      (c, u, v))(T.az * 180 / pi, T.el * 180 / pi,
                                 np.reshape(r, T.shape)),
    contours=dict(z=dict(show=True), y=dict(show=True), x=dict(show=True)))

#  https://plot.ly/python/reference/#scatter3d
spkr_locs = go.Scatter3d(
    name='Loudspeakers',
    x=spkr_x,
    y=spkr_y,
    z=spkr_z,
    mode='markers',
Example #21
0
    def prepare(self):
        # ---------------------
        print("Making plot...")
        # ---------------------
        # -------------------------------------------
        x_data = self.x_data
        y_data = self.y_data
        z_data = self.z_data
        # -------------------------------------------

        # ------------------------------------------------
        # x_ticktext = x_data
        # x_tickvals = x_data
        # x_tickvals = list(range(len(x_data)))

        # x_ticktext = [str(i) for i in x_ticktext]

        # x_ticktext = x_ticktext[::50]
        # x_tickvals = x_tickvals[::50]
        # ------------------------------
        # print('x_tickvals:', x_tickvals)
        # print('x_ticktext:', x_ticktext)
        # ------------------------------------------------

        # ------------------------------------------------
        # y_ticktext = y_data
        # y_ticktext = [str(i) for i in y_ticktext]

        # y_tickvals = list(range(len(y_data)))
        # y_tickvals = y_data
        # y_tickvals = np.array(y_tickvals) / self.t_coeff

        # y_ticktext = y_ticktext[::50]
        # y_tickvals = y_tickvals[::50]

        # y_tickvals = y_tickvals[::50]
        # ------------------------------
        # print('y_tickvals:', y_tickvals)
        # print('y_ticktext:', y_ticktext)
        # ------------------------------------------------

        data = [
            # go.Surface(
            #     showlegend=False,
            #     showscale=False,
            #     lighting=dict(diffuse=0.5, specular=.2, fresnel=0.2),
            #     z=z_data,
            #     # colorscale="Portland",
            #     # colorscale='Viridis',
            # )
            go.Surface(
                z=z_data,
                colorscale="Portland",
                contours=go.surface.Contours(z=go.surface.contours.Z(
                    show=True,
                    usecolormap=True,
                    # highlightcolor="#42f462",
                    project=dict(z=True),
                    # colorscale="Portland",
                )))
        ]

        scale = 1
        # scale = int(y_ticktext[-1])

        layout = go.Layout(
            # needed
            # ---------------
            title='<b>' + self.title + '</b>',
            # ---------------

            # -----------------
            width=self.width,
            height=self.height,
            # -----------------
            titlefont=dict(
                family='Lato',
                color="#222",
                size=20,
            ),
            xaxis=dict(title=r'$\sqrt{(n_\text{c}(t|{T_\text{early}}))}$'),
            # margin=go.Margin(
            #     l=0,
            #     r=0,
            #     b=0,
            #     t=35,
            #     pad=50,
            # ),

            # zaxis=dict(
            #     tickangle=90
            # ),

            # --------------
            # autosize=False,
            autosize=True,
            # --------------
            plot_bgcolor="#AAA",
            # paper_bgcolor="#AAA",
            scene=go.Scene(
                camera=dict(up=dict(x=0, y=0, z=1),
                            center=dict(x=0, y=0, z=0.2),
                            eye=dict(x=3.75, y=3.75, z=3.75)),
                xaxis={
                    # --------------------
                    "title":
                    self.x_title,
                    # --------------------

                    # ---------------------
                    # ---------------------
                    "linewidth":
                    2,
                    "showgrid":
                    False,
                    "showline":
                    False,

                    # -----------------------------------
                    'titlefont':
                    dict(
                        family=self.ticks['family'],
                        color=self.ticks['color'],
                        size=self.ticks['title']['size'],
                    ),
                    'tickfont':
                    dict(
                        family=self.ticks['family'],
                        color=self.ticks['color'],
                        size=self.ticks['size'],
                    ),
                    # -----------------------------------
                    # 'nticks': 5,
                    'tickangle':
                    0,
                    # 'orientation': 'h',

                    # 'autorange': True,
                    # "ticktext": self.x_tickvals,
                    "tickvals":
                    self.x_tickvals,
                    "ticktext":
                    self.x_ticktext,

                    # "showline":True,
                    # "ticks": "outside",
                    # "showticklabels": True,
                    # "tickvals": list(range(len(x_tickvals))),
                    # "ticktext": list(range(len(x_tickvals))),
                    # "tickangle": 45,
                    # "linecolor": "black",
                    # "linewidth": 2,
                },
                yaxis={
                    # --------------------------------
                    "title":
                    self.y_title,
                    # "title": self.y_title+"\t\t\t\t.",
                    # --------------------------------

                    # ---------------------
                    # "ticktext": self.y_tickvals,
                    "tickvals":
                    self.y_tickvals,
                    "ticktext":
                    self.y_ticktext,
                    # ---------------------
                    "linewidth":
                    2,
                    # 'nticks': 5,
                    # 'autotick': False,
                    # 'tick0': 0.001,
                    # 'dtick': 0.5,
                    # -----------------------------------
                    'titlefont':
                    dict(
                        family=self.ticks['family'],
                        color=self.ticks['color'],
                        size=self.ticks['title']['size'],
                    ),
                    'tickfont':
                    dict(
                        family=self.ticks['family'],
                        color=self.ticks['color'],
                        size=self.ticks['size'],
                    ),
                    # -----------------------------------
                    'tickangle':
                    0,

                    # 'autorange': True,

                    # "linecolor": "black",
                },
                zaxis={
                    # --------------------
                    "title":
                    self.z_title,
                    # --------------------
                    "linewidth":
                    2,
                    # 'nticks': 5,

                    # -----------------------------------
                    'titlefont':
                    dict(
                        family=self.ticks['family'],
                        color=self.ticks['color'],
                        size=self.ticks['title']['size'],
                    ),
                    'tickfont':
                    dict(
                        family=self.ticks['family'],
                        color=self.ticks['color'],
                        size=self.ticks['size'],
                    ),
                    # -----------------------------------
                    'tickangle':
                    0,
                    'autorange':
                    True,

                    # 'usecolormap': True,
                    # 'highlightcolor': "#42f462",
                    # 'dtick': -20,
                    # "tickangle": 45,
                    # "linecolor": "black",
                    # "range": self.z_range,
                    # "transform": {"rotate": '0'}
                },
                aspectratio={
                    "x": self.scale['x'],
                    "y": self.scale['y'],
                    "z": self.scale['z'],
                },
            ),
            # showlegend=False
        )

        self.fig = go.Figure(data=data, layout=layout)

        if self.to_file:
            py.image.save_as(self.fig, filename=self.to_file)
            return

        return
Example #22
0
                                     x=list(corrs.columns),
                                     y=list(corrs.index),
                                     annotation_text=corrs.round(2).values,
                                     showscale=True)
py.iplot(figure, filename='heatmap')

df1 = dataset.drop(axis=1,
                   columns=["Axial load(kN)", "Tensile elongation (%)"])
df2 = dataset.drop(
    axis=1, columns=["Axial load(kN)", "ultimate tensile strength(MPa)"])

#3D surface plots
#1
data = [
    go.Surface(x=dataset['Rotational speed(RPM)'],
               y=dataset['Weilding speed(mm/min)'],
               z=df1.values.tolist(),
               colorscale='Viridis')
]

layout = go.Layout(width=800,
                   height=700,
                   autosize=False,
                   title='Friction Stir Weilding dataset',
                   scene=dict(xaxis=dict(gridcolor='rgb(255, 255, 255)',
                                         zerolinecolor='rgb(255, 255, 255)',
                                         showbackground=True,
                                         backgroundcolor='rgb(230, 230,230)'),
                              yaxis=dict(gridcolor='rgb(255, 255, 255)',
                                         zerolinecolor='rgb(255, 255, 255)',
                                         showbackground=True,
                                         backgroundcolor='rgb(230, 230,230)'),
Example #23
0
def data_graph(
    df,
    filename,
    chart_type,
    xaxis_type,
    yaxis_type,
):
    """アップロードされたデータのグラフを描画"""

    basename = os.path.splitext(filename)[0]
    # ファイル名の1つ目の'_'で区切って、グラフタイトルとY軸名に分ける
    if '_' in basename:
        title, yaxis_name = basename.split('_', 1)
    # ファイル名に'_'がなければグラフタイトル、Y軸名ともにファイル名
    else:
        title, yaxis_name = basename, basename

    def args(i):
        """graph_objs helper func"""
        return {'x': df.index, 'y': df[i], 'name': i}

    # チャートの種類をディクショナリで分岐
    # 内包表記でdfの列の数だけトレース
    data = {
        'Line': [go.Scatter(args(i)) for i in df.columns],
        'Bar': [go.Bar(args(i)) for i in df.columns],
        'Histogram':
        [go.Histogram(x=df[i], name=i, opacity=.5) for i in df.columns],
        'Pie': [
            go.Pie(labels=df.index,
                   values=df[i],
                   name=i,
                   domain={'column': list(df.columns).index(i)})
            for i in df.columns
        ],
        'Polar': [
            go.Scatterpolar(
                r=df[i],
                theta=df.index,
                name=i,
            ) for i in df.columns
        ],
        'Heatmap': [go.Heatmap(x=df.index, y=df.columns, z=df.values)],
        'Box': [go.Box(y=df[i], name=i) for i in df.columns],
        # 'Contour': [go.Contour(x=df.index, y=df.columns, z=df.values)]
        '3D Scatter': [
            go.Scatter3d(x=df.index, y=df.columns, z=df[i], name=i)
            for i in df.columns
        ],
        '3D Surface': [
            go.Surface(x=df.index,
                       y=df.columns,
                       z=df.values,
                       name=yaxis_name,
                       contours=go.surface.Contours(
                           z=go.surface.contours.Z(show=True,
                                                   usecolormap=True,
                                                   highlightcolor="#42f462",
                                                   project=dict(z=True)))),
        ],
        '2D Histogram': [go.Histogram2d(x=df.iloc[:, 0], y=df.iloc[:, 1])]
    }

    # チャートの種類でレイアウトを分岐
    # 分岐にはdefaultdictを使い、デフォルトはlambda式で返す
    layout = defaultdict(
        # default layout
        lambda: go.Layout(title=go.layout.Title(text=title),
                          xaxis={
                              'type': xaxis_type,
                              'title': df.index.name,
                              'rangeslider': dict(visible=False),
                          },
                          yaxis={
                              'type': yaxis_type,
                              'title': yaxis_name,
                          },
                          margin={
                              'l': 60,
                              'b': 50
                          },
                          hovermode='closest'),
        # other layout
        {
            'Histogram':
            go.Layout(title=title,
                      xaxis={'title': 'Value'},
                      yaxis={'title': 'Count'},
                      barmode='overlay',
                      hovermode='closest'),
            'Pie':
            go.Layout(title=go.layout.Title(text=title),
                      grid={
                          'columns': len(df.columns) - 1,
                          'rows': 1
                      },
                      hovermode='closest')
        })
    return dcc.Graph(id='the_graph',
                     figure={
                         'data': data[chart_type],
                         'layout': layout[chart_type]
                     })
Example #24
0
# HiMCM 2017 Model Calculation
# Team # 7680

import plotly.plotly as py
import plotly.graph_objs as go

import pandas as pd

# Read data from a csv
z_data = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv'
)

data = [go.Surface(z=z_data.as_matrix())]
layout = go.Layout(title='Mt Bruno Elevation',
                   autosize=False,
                   width=500,
                   height=500,
                   margin=dict(l=65, r=50, b=65, t=90))
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='elevations-3d-surface')
Example #25
0
init_notebook_mode(connected=True)

np.random.seed(1)

x = (np.random.rand(1000) - .5) * 10
y = -2 * x + np.random.normal(0, 2, x.shape) + 5


def cost(w, b):
    y_hat = w * x + b
    return np.mean((y - y_hat)**2)


cost = np.vectorize(cost)

w = np.linspace(-5, 1, 100)
b = np.linspace(2, 8, 100)

W, B = np.meshgrid(w, b)
Z = cost(W, B)

surface = go.Surface(x=W, y=B, z=Z, colorscale='Viridis')

layout = go.Layout(scene=dict(
    xaxis=dict(title='w'),
    yaxis=dict(title='b'),
    zaxis=dict(title='cost'),
))

figure = go.Figure(data=[surface], layout=layout)
iplot(figure)
Example #26
0
    def __init__(self, layout, input_data, axes, value_name, cb,
                 show_variances, volume, volume_sampling):

        super().__init__(input_data,
                         axes,
                         value_name,
                         cb,
                         show_variances,
                         button_options=['X', 'Y', 'Z'],
                         volume=volume)

        self.cube = None
        self.volume = volume

        # Initialise Figure and VBox objects
        self.fig = None
        params = {
            "values": {
                "cbmin": "min",
                "cbmax": "max"
            },
            "variances": None
        }
        if self.show_variances:
            params["variances"] = {"cbmin": "min_var", "cbmax": "max_var"}

        # Set colorbar limits once to keep them constant for slicer
        # TODO: should there be auto scaling as slider value is changed?
        for i, (key, val) in enumerate(sorted(params.items())):
            if val is not None:
                arr = getattr(self.input_data, key)
                if self.cb[val["cbmin"]] is not None:
                    val["cmin"] = self.cb[val["cbmin"]]
                else:
                    val["cmin"] = np.amin(arr[np.where(np.isfinite(arr))])
                if self.cb[val["cbmax"]] is not None:
                    val["cmax"] = self.cb[val["cbmax"]]
                else:
                    val["cmax"] = np.amax(arr[np.where(np.isfinite(arr))])

        colorbars = [{
            "x": 1.0,
            "title": value_name,
            "thicknessmode": 'fraction',
            "thickness": 0.02
        }]

        # Store min/max for each dimension for invisible scatter
        self.xminmax = dict()
        for key, var in self.slider_x.items():
            self.xminmax[key] = [var.values[0], var.values[-1]]
        scatter_x, scatter_y, scatter_z = self.get_outline_as_scatter()

        # Make a generic volume trace
        if self.volume:
            vol_trace = go.Volume(x=[0],
                                  y=[0],
                                  z=[0],
                                  value=[0],
                                  opacity=0.1,
                                  surface_count=volume_sampling,
                                  colorscale=self.cb["name"],
                                  showscale=True)

        xyz = "xyz"
        if self.show_variances:
            self.fig = go.FigureWidget(
                make_subplots(rows=1,
                              cols=2,
                              horizontal_spacing=0.16,
                              specs=[[{
                                  "type": "scene"
                              }, {
                                  "type": "scene"
                              }]]))

            colorbars.append({
                "x": 1.0,
                "title": "Variances",
                "thicknessmode": 'fraction',
                "thickness": 0.02
            })
            colorbars[0]["x"] = -0.1

            for i, (key, val) in enumerate(sorted(params.items())):
                if self.volume:
                    vol_trace["isomin"] = val["cmin"]
                    vol_trace["isomax"] = val["cmax"]
                    vol_trace["meta"] = key
                    vol_trace["colorbar"] = colorbars[i]
                    self.fig.add_trace(vol_trace, row=1, col=i + 1)
                else:
                    for j in range(3):
                        self.fig.add_trace(go.Surface(
                            cmin=val["cmin"],
                            cmax=val["cmax"],
                            showscale=False,
                            colorscale=self.cb["name"],
                            colorbar=colorbars[i],
                            meta=key,
                            name="slice_{}".format(xyz[j])),
                                           row=1,
                                           col=i + 1)
                    self.fig.add_trace(go.Scatter3d(
                        x=scatter_x,
                        y=scatter_y,
                        z=scatter_z,
                        marker=dict(cmin=val["cmin"],
                                    cmax=val["cmax"],
                                    color=np.linspace(val["cmin"], val["cmax"],
                                                      8),
                                    colorbar=colorbars[i],
                                    colorscale=self.cb["name"],
                                    showscale=True,
                                    opacity=1.0e-6),
                        mode="markers",
                        hoverinfo="none",
                        meta=key,
                        name="scatter"),
                                       row=1,
                                       col=i + 1)
            self.fig.update_layout(**layout)
        else:
            if self.volume:
                vol_trace["isomin"] = params["values"]["cmin"]
                vol_trace["isomax"] = params["values"]["cmax"]
                vol_trace["meta"] = "values"
                vol_trace["colorbar"] = colorbars[0]
                data = [vol_trace]
            else:
                data = [
                    go.Surface(cmin=params["values"]["cmin"],
                               cmax=params["values"]["cmax"],
                               colorscale=self.cb["name"],
                               colorbar=colorbars[0],
                               showscale=False,
                               meta="values",
                               name="slice_{}".format(xyz[j]))
                    for j in range(3)
                ]

                data += [
                    go.Scatter3d(x=scatter_x,
                                 y=scatter_y,
                                 z=scatter_z,
                                 marker=dict(cmin=params["values"]["cmin"],
                                             cmax=params["values"]["cmax"],
                                             color=np.linspace(
                                                 params["values"]["cmin"],
                                                 params["values"]["cmax"], 8),
                                             colorbar=colorbars[0],
                                             colorscale=self.cb["name"],
                                             showscale=True,
                                             opacity=1.0e-6),
                                 mode="markers",
                                 hoverinfo="none",
                                 meta="values",
                                 name="scatter")
                ]
            self.fig = go.FigureWidget(data=data, layout=layout)

        # Call update_slice once to make the initial image
        self.update_axes()
        self.vbox = [self.fig] + self.vbox
        self.vbox = widgets.VBox(self.vbox)
        self.vbox.layout.align_items = 'center'

        return
Example #27
0
def update1(value1, value2, value3):
    print('----------------------------------------')
    print(volume.shape)
    print(value1, value2, value3)
    print(dim)
    xx = np.array(range(dim[0]))
    yy = np.array(range(dim[1]))
    zz = np.array(range(dim[2]))

    # trace X
    z, y = np.meshgrid(zz, yy)
    x = z * 0 + value1
    surf = volume[value1, :, :]
    tracex = go.Surface(
        x=x,
        y=y,
        z=z,
        surfacecolor=surf,
        colorscale='Gray'
    )

    # trace Y
    z, x = np.meshgrid(zz, xx)
    y = x * 0 + value2
    surf = volume[:, value2, :]
    tracey = go.Surface(
        x=x,
        y=y,
        z=z,
        surfacecolor=surf,
        colorscale='Gray'
    )

    # trace Z
    y, x = np.meshgrid(yy, xx)
    z = y * 0 + value3
    surf = volume[:, :, value3]
    print(z.shape, surf.shape)
    tracez = go.Surface(
        x=x,
        y=y,
        z=z,
        surfacecolor=surf,
        colorscale='Gray'
    )

    data = [
        tracex,
        tracey,
        tracez,
    ]
    fig = go.Figure(data=data)

    m = max(dim)
    fig.update_layout(
        title='Volume',
        scene=dict(
            xaxis={'range': [-1, dim[0]]},
            yaxis={'range': [-1, dim[1]]},
            zaxis={'range': [-1, dim[2]]},
            aspectratio=dict(x=dim[0]/m,
                             y=dim[1]/m,
                             z=dim[2]/m),
        )
    )

    return fig
Example #28
0
data6000 = nouvellesdonnees[:6000, :]
print(data6000.shape)
for pays in np.unique(pays_index):
    pays_sbvts[pays] = data6000[data6000[:, 2] == pays,
                                -2].astype(np.float).sum()

##########################################
# trace1 = go.Pie(labels=list(pays_sbvts.keys()), values=list(pays_sbvts.values()))
# plot([trace1], filename="PieChartSubv1.html")
#
# randomdata2 = np.random.randn(500)
# trace2 = go.Histogram(x=randomdata2)
# plot([trace2], filename="HistoSubv1.html")

size3 = 100000
# randomdata3 = np.zeros(3 * size3)
# randomdata3[0::3] = (np.random.rand(size3) * 2) - float(size3)
# randomdata3[1::3] = (np.random.rand(size3) * 2) - float(size3)
# randomdata3[2::3] = np.multiply((np.square(randomdata3[0::3]) + np.square(randomdata3[1::3])),
#                                 (np.exp(1 / (randomdata3[0::3] + randomdata3[1::3]))))
# randomdata3 = np.array(list(zip(randomdata3[0::3], randomdata3[1::3], randomdata3[2::3])))
x3 = ((np.random.rand(size3) * 2) - 1) * 30
y3 = ((np.random.rand(size3) * 2) - 1) * 30
z3 = np.multiply((np.square(x3) + np.square(y3)),
                 (np.log2(np.abs(1 / (x3 + y3)))))
# randomdata3 = np.array(list(zip(randomdata3[0::3], randomdata3[1::3], randomdata3[2::3])))
trace3 = go.Surface(x=x3, y=y3, z=z3)
layout3 = go.Layout(title='Test surface', autosize=True)
# fig3 = go.Figure(data=trace3, layout=layout3)
plot([trace3], filename="Surface1.html")
Example #29
0
# In[5]:

# Input value
x = lon_topo
y = lat_topo
z = topo

# Import color scale
reload(Pcode)
name = "topo"
Ctopo = Pcode.Colorscale_Plotly(name)
cmin = -8000
cmax = 8000

topo3D = go.Surface(x=x, y=y, z=z, colorscale=Ctopo, cmin=cmin, cmax=cmax)

# The position of z-axis
z_offset = depmax * np.ones(z.shape)  # Plot at the bottom
#z_offset=0*np.ones(z.shape)  # Plot at 0 level

topo_surf = go.Surface(z=z_offset,
                       x=x,
                       y=y,
                       colorscale=Ctopo,
                       cmin=cmin,
                       cmax=cmax,
                       showlegend=False,
                       showscale=False,
                       surfacecolor=topo,
                       hoverinfo='text')
Example #30
0
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np

import pandas as pd

sparse_matrix = np.load(
    r"C:\Users\Isaiah Nields\Documents\GitHub\brown_datathon_v2\tripadvisor\topo_map.npz"
)['sparse_matrix']
data = [go.Surface(z=sparse_matrix[:1000, :])]
layout = go.Layout(
    title='Sparse Matrix Topography',
    autosize=True
    # margin=dict(
    #     l=65,
    #     r=50,
    #     b=65,
    #     t=90
    # )
)
fig = go.Figure(data=data, layout=layout)