Esempio n. 1
0
def animate_real_imag():
    """ Animate the time evolution of real and imag part of the wave function """
    data = np.load("npz/p8.npz")
    m = int(np.sqrt(data.shape[1] - 1))
    t = data[:, 0]

    real = np.load("npz/p8_real.npz").reshape(len(t), m, m)
    imag = np.load("npz/p8_imag.npz").reshape(len(t), m, m)

    axes = np.linspace(0, 1, m + 2)[1:-1]

    real_ = go.Contour(x=axes, y=axes, z=real[0])
    imag_ = go.Contour(x=axes, y=axes, z=imag[0])

    real_frames = [
        go.Frame(data=[go.Contour(x=axes, y=axes, z=real[i])])
        for i in range(1, len(t))
    ]
    imag_frames = [
        go.Frame(data=[go.Contour(x=axes, y=axes, z=imag[i])])
        for i in range(1, len(t))
    ]

    layout = go.Layout(updatemenus=[
        dict(type="buttons",
             buttons=[dict(label="Play", method="animate", args=[None])])
    ])

    rf = go.Figure(data=real_, layout=layout, frames=real_frames)
    imf = go.Figure(data=imag_, layout=layout, frames=imag_frames)
    rf.show()
    imf.show()
Esempio n. 2
0
def animate(file="p9_3_slit.npz", h=0.005):
    """ Animate time evolution of a simulation """
    data = np.load("npz/" + file)
    m = int(np.sqrt(data.shape[1] - 1))
    t = data[:, 0]
    Z = data[:, 2:].reshape(len(t), m, m)
    axes = np.linspace(h, 1 - h, m)

    data = go.Contour(
        x=axes,
        y=axes,
        z=Z[0],
    )

    frames = [
        go.Frame(data=[go.Contour(x=axes, y=axes, z=Z[i].reshape(m, m))])
        for i in range(1, len(t))
    ]

    layout = go.Layout(updatemenus=[
        dict(type="buttons",
             buttons=[dict(label="Play", method="animate", args=[None])])
    ])

    fig = go.Figure(data=data, layout=layout, frames=frames)
    fig.show()
Esempio n. 3
0
def gr_membership_contour(estimated_membership, fig):
    print(estimated_membership([(1, 1)]))
    x = np.linspace(2, 8, 100)
    y = np.linspace(-.5, 3, 100)
    X, Y = np.meshgrid(x, y)
    # zs = np.array([estimated_membership((x, y))
    #                for x, y in zip(np.ravel(X), np.ravel(Y))])
    zs = estimated_membership(np.array((np.ravel(X), np.ravel(Y))).T)
    Z = zs.reshape(X.shape)

    fig.add_trace(
        go.Contour(x=x,
                   y=y,
                   z=Z,
                   colorscale='Blues',
                   line_smoothing=0.85,
                   contours={
                       "start": 0,
                       "end": 1,
                       "size": .2,
                       "showlabels": True,
                       "labelfont": {
                           "size": 12,
                           "color": "white"
                       }
                   }))
Esempio n. 4
0
def vizualize(df_train, df_test, model):
    fig = go.Figure([
        go.Scatter(
            x=df_train.x0,
            y=df_train.x1,
            marker=go.scatter.Marker(
                color=df_train.y,
                size=8,
                line_width=2,
                line_color="DarkSlateGrey",
            ),
            mode="markers",
            name="train",
        ),
        go.Scatter(
            x=df_test.x0,
            y=df_test.x1,
            marker=go.scatter.Marker(
                color=df_test.y,
                size=12,
                line_width=2,
                line_color="DarkSlateGrey",
            ),
            mode="markers",
            name="test",
        ),
    ])
    fig.update_layout(template="simple_white")
    xx, yy, zz = decision_boundaries(df_train[["x0", "x1"]].to_numpy(), model)
    xx = xx[0]
    yy = yy[:, 0]
    fig.add_trace(go.Contour(x=xx, y=yy, z=zz, opacity=0.5))
    fig.show()
Esempio n. 5
0
def plot_f1_score():
    N = 100
    X, Y = np.linspace(0.1, 1, N), np.linspace(0.1, 1, N)
    Z = [[(2 * x * y) / (x + y) for x in X] for y in Y]

    fig = go.Figure(
        data=[
            go.Contour(
                z=Z,
                x=X,
                y=Y,
                contours=dict(
                    coloring="heatmap",
                    showlabels=True,  # show labels on contours
                    labelfont=dict(size=12, color="white",),  # label font properties
                ),
            )
        ],
    )

    fig.update_layout(
        title=dict(text="Contours of F1 score based on precision and recall", x=0.5),
        font=dict(family="IBM Plex Sans", color="black"),
        autosize=False,
        width=300,
        height=300,
        xaxis_title="Precision",
        yaxis_title="Recall",
    )
    st.plotly_chart(fig)
Esempio n. 6
0
    def plot(self, region, sample, law=None):
        if law is None:
            law = self.law

        x, y = np.logspace(-2, 0, 50), np.logspace(-2, 0, 50)
        z = np.zeros((len(y), len(x)))
        for i in range(len(y)):
            for j in range(len(x)):
                dynamic = SIR(x[j], y[i])
                epidemic = dynamic.estimate(region, sample.t[-1])
                z[i, j] = loglikely(epidemic, sample, law)

        fig = go.Figure(data=go.Contour(z=np.log(np.max(z) - z + 1),
                                        x=x,
                                        y=y,
                                        showscale=False,
                                        name='log(-loglikely)'))
        fig.update_layout(showlegend=False,
                          margin=dict(b=0, l=0, r=0, t=25),
                          xaxis=dict(scaleanchor="y",
                                     scaleratio=1,
                                     constrain="domain",
                                     range=(-2, 0)))
        fig.update_xaxes(type="log")
        fig.update_yaxes(type="log")
        return fig
Esempio n. 7
0
    def decision_boundary(self, x: np.ndarray, y: np.ndarray,
                          model: BaseEstimator):
        x0 = x[:, 0]
        x1 = x[:, 1]

        x_min, x_max = x0.min() - 1, x0.max() + 1
        y_min, y_max = x1.min() - 1, x1.max() + 1

        xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
                             np.arange(y_min, y_max, 0.1))

        z = model.predict(np.c_[xx.ravel(), yy.ravel()])
        z = z.reshape(xx.shape)
        z = z.astype(np.str)

        y = [str(label) for label in y]

        fig = px.scatter(x=x0, y=x1, color=y)

        # fig = go.Figure()

        contour = go.Contour(z=z,
                             x=np.arange(x_min, x_max, 0.1),
                             y=np.arange(y_min, y_max, 0.1),
                             line_width=0,
                             colorscale=[[0, '#ff9900'], [1, '#6666ff']],
                             opacity=0.4,
                             showscale=False)

        fig.add_trace(contour)

        fig.update_layout(title='Decision boundary', legend_title='Label')

        pyo.iplot(fig)
Esempio n. 8
0
def plotly_contour_lines(gray, colorname):
    terrain_cmap = plt.cm.get_cmap(colorname)

    terrain = matplotlib_to_plotly(terrain_cmap, 255)

    layout = go.Layout(xaxis=dict(showgrid=False,
                                  visible=False,
                                  constrain="domain"),
                       yaxis=dict(showgrid=False,
                                  visible=False,
                                  scaleanchor="x",
                                  scaleratio=1))

    fig = go.Figure(
        data=go.Contour(
            z=gray,
            colorscale=terrain,
            showscale=False,
            # contours=dict(start=0,end=1,size=0.1,),
        ),
        layout=layout)

    fig.update_yaxes(autorange="reversed")

    return fig
Esempio n. 9
0
def _plotly_contour2(x, y, z, **kwargs):
    colorscale = kwargs.pop("colorscale", "viridis")
    cmin = kwargs.pop("cmin", 0.0)
    cmax = kwargs.pop("cmax", round(z.mean() * 2, 1))
    cstep = kwargs.pop("cstep", 0.1)

    plot_object = [
        _go.Contour(
            z=z,
            x=x,  # horizontal axis
            y=y,  # vertical axis
            colorscale=colorscale,
            connectgaps=True,
            line_smoothing=0.85,
            zmin=cmin,
            zmax=cmax,
            contours=dict(
                # coloring="heatmap",
                showlabels=True,  # show labels on contours
                start=cmin,
                end=cmax,
                size=cstep,
                labelfont=dict(  # label font properties
                    size=12,
                    color="white",
                ),
            ),
            colorbar=dict(
                title="|B| (T)",
                titleside="right",
                titlefont=dict(size=14, family="Arial, sans-serif"),
            ),
        )
    ]
    return plot_object
Esempio n. 10
0
  def step_stage_final(self):
    temp_bider = np.where(self.bid_store == 1,1,None)
    self.frames.append(go.Frame(data = [go.Heatmap(z=temp_bider,colorscale=self.colorscale,showscale = False,opacity = 1),
      go.Contour(z=self.matrix,colorscale='Greys',opacity = 0.65,autocolorscale=False)]))
    #self.frames.append(go.Frame(data = [go.Contour(z=self.matrix,colorscale='Greys',opacity = 1,visible = True),
      #go.Scatter(x = np.where(self.bid_store == 1)[1],
      #y =np.where(self.bid_store == 1)[0],mode='markers',marker = dict(size = 5,line=dict(width=1,color='DarkSlateGrey')))]))

    tot_view = len(np.where(self.explored == 1)[1])
    num_wining_bids = len(np.where(self.bid_store == 1)[1])
    self.num_wining_bids.append(num_wining_bids)
    self.explored_rate.append(tot_view)
    to_plot = self.model.to_plot
    if self.model.timestep % int(self.model.plot_interval) == 0 and to_plot:

      plt.figure(figsize=(15,15))
      plt.suptitle(str(self.unique_id+'('+str(tot_view)+'/'+str(self.size**2)+')____'+str(num_wining_bids)))

      plt.subplot(121)
      plt.imshow(self.explored)
      plt.contour(self.matrix,alpha = 0.75)
      

      plt.subplot(122)
      plt.contour(self.matrix,alpha = 0.75)
      plt.imshow(self.bid_store)
      plt.show()
Esempio n. 11
0
def get_contour_h_prod_rate(simulation, title, nbInterval=10):
    oxygen, glucose, data = simulate_at_different_extra_concentration(simulation, nbInterval)
    fig = go.Figure(
        data = go.Contour(
            x = oxygen,
            y = glucose,
            z = data,
            zmin = 0.0,
            zmax = data.max(),
            colorbar = {
                "exponentformat" : "e",
                "showexponent" : "all",
                "title" : "Protons Rate (mmol/L/min)"   
            },
             contours=dict(
                start=0,
                end=0.001,
                size=1e-4
            )
        )
    )
    fig.update_layout(
        title = title,
        xaxis = {
            "title" : "Oxygen concentration (mmol/L)"
        },
        yaxis = {
            "title" : "Glucose concentration (mmol/L)"
        }
    )
    return fig
def plot_anomaly(X_train, xx, yy, Z, dash=True):

    back = go.Contour(x=xx,
                      y=yy,
                      z=Z,
                      colorscale=matplotlib_to_plotly(plt.cm.Blues_r, len(Z)),
                      showscale=False,
                      line=dict(width=0))

    b1 = go.Scatter(x=X_train[:, 0],
                    y=X_train[:, 1],
                    name="training observations",
                    mode='markers',
                    marker=dict(color='white',
                                size=7,
                                line=dict(color='black', width=1)))

    layout = go.Layout(title="IsolationForest", hovermode='closest')
    data = [back, b1]

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

    if dash:
        return apply_layout(fig, title="", height=800, width=1000)
    else:
        fig.show()
    def visualisation(self):
        mesh_size = .02
        margin = 0.25

        X = self.data_train.iloc[:, [0, 1]].values
        y = self.data_train.iloc[:, [2]].astype(int).values.ravel()
        # Load and split data
        X_train = self.data_train.iloc[:, :-1].values
        X_test = self.data_test.iloc[:, :-1].values
        y_train_float = self.data_train.iloc[:, -1:].values
        y_test_float = self.data_test.iloc[:, -1:].values

        a = y_train_float.astype(int)
        y_train = a.astype('str').ravel()
        b = y_test_float.astype(int)
        y_test = b.astype('str').ravel()

        # Create a mesh grid on which we will run our model
        x_min, x_max = X[:, 0].min() - margin, X[:, 0].max() + margin
        y_min, y_max = X[:, 1].min() - margin, X[:, 1].max() + margin
        xrange = np.arange(x_min, x_max, mesh_size)
        yrange = np.arange(y_min, y_max, mesh_size)
        xx, yy = np.meshgrid(xrange, yrange)

        # Create classifier, run predictions on grid
        clf = KNeighborsClassifier(self.k, weights='uniform')
        clf.fit(X_train, y_train)
        Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
        Z = Z.reshape(xx.shape)

        trace_specs = [[X_train, y_train, '0', 'Train', 'square'],
                       [X_train, y_train, '1', 'Train', 'circle'],
                       [X_test, y_test, '0', 'Test', 'square-dot'],
                       [X_test, y_test, '1', 'Test', 'circle-dot']]

        fig = go.Figure(data=[
            go.Scatter(x=X[y == label, 0],
                       y=X[y == label, 1],
                       name=f'{split} Split, Label {label}',
                       mode='markers',
                       marker_symbol=marker)
            for X, y, label, split, marker in trace_specs
        ])
        fig.update_traces(
            marker_size=12,
            marker_line_width=1.5,
            # marker_color="lightyellow"
        )

        fig.add_trace(
            go.Contour(x=xrange,
                       y=yrange,
                       z=Z,
                       showscale=False,
                       colorscale='RdBu',
                       opacity=0.8,
                       name='Score',
                       hoverinfo='skip'))
        name = f'knn, k=' + str(self.k)
        webview.create_window(name, html=fig.to_html())
Esempio n. 14
0
def plot_potential(slits, h=0.005):
    """ Plot the potential in unit space """
    V = np.load(f"npz/potential_{slits}_slits.npz")
    m = V.shape[0]
    x = np.linspace(h, 1 - h, m)
    fig = go.Figure(go.Contour(x=x, y=x, z=V))
    fig.show()
def main():
    print("What directory would you like to explore?")
    dir = input("Directory name: ")
    grid_df = plot_grid(dir=dir)
    run_df = plot_run(dir=dir)

    fig = go.Figure(data=go.Contour(z=grid_df))
    columns = list(run_df)
    x = []
    y = []
    for i in columns:
        l = run_df[i].tolist()
        for j in l:
            if str(j) == 'nan':
                break
            else:
                j = ast.literal_eval(j)
                x.append(j[0])
                y.append(j[1])

        run = go.Scatter(x=x, y=y)
        fig.add_trace(run)
        x.clear()
        y.clear()

    fig.show()
def visualize(weight_grid):
    fig = go.Figure(
        data=go.Contour(
            z=weight_grid,
            contours_coloring='heatmap'
        ))
    fig.show()
Esempio n. 17
0
 def __init__(self,unique_id,model,size = 100,number_of_peaks = 40):
     super().__init__(unique_id,model)
     self.model = model
     self.topic = len([agent for agent in model.schedule.agents if agent.category == 'Elandscape'])
     self.category = 'Elandscape'
     self.unique_id = 'Elandscape_' + str(self.topic)
     self.max_height = 10
     self.size = size
     self.matrix = np.random.rand(self.size, self.size)
     self.diff_matrix = np.random.rand(self.size, self.size)
     self.explored = np.zeros([self.size,self.size])
     self.num_peaks = number_of_peaks
     self.simulate_guassian_peaks(self.num_peaks,width = 7 , height = 3)
     self.x_arr = []    # Explored corrdinates on the landscape
     self.y_arr = []    # Explored corrdinates on the landscape
     self.visible_x = []
     self.visible_y = []
     self.C_ = np.linspace(2_0000,7_0000,self.model.topics)[int(self.topic)]
     self.bid_store = np.zeros([self.size,self.size])
     self.num_wining_bids = []
     self.explored_rate = []
     self.colorscale=[[0.0, "rgb(255, 0, 0)"],[1.0, "rgb(255, 0, 0)"]]
     self.frame1  = go.Contour(z=self.matrix,colorscale='Greys',opacity = 0.65,visible = True,autocolorscale=False)
     self.frame2  = go.Heatmap(z=np.where(self.bid_store == 1,1,None),colorscale=self.colorscale,
       showscale = False,opacity = 1 )
     #self.frame2 = go.Scatter(x = [],y=[])
     self.frames = []
    def plot_rho(self, p_relative=False):

        if p_relative:
            the_field = self.fields.rho - self.fields.rho0
        else:
            the_field = self.fields.rho

        fig = go.Figure(
            layout=go.Layout(
                title=go.layout.Title(text="Density plot")
            ))
        fig.add_trace(go.Contour(
            z=the_field,
            colorscale="aggrnyl",
            colorbar=dict(
                title='rho-rho0 (kg/m3)'
            )
        ))

        # fig.update_layout()
        fig.update_xaxes(title_text="VCx")
        fig.update_yaxes(title_text="VCy")
        fig.update_layout(font={'size':28})

        fig.show()
        pio.write_image(fig, files_output_path + self.output_files_name + 'Density.png', width=2864, height=1356)
    def plot_pressure(self, p_cp=False, p_relative=False):
        if p_cp:
            # Plot the pressure coefficient.
            field_to_plot = self.fields.Cp
            title = '-'
        else:
            # Plot the pressure.
            if p_relative:
                field_to_plot = self.fields.P - self.fields.P0
            else:
                field_to_plot = self.fields.P
            title = 'P-P0 (Pa)'

        fig = go.Figure(
            layout=go.Layout(
                title=go.layout.Title(text="Pressure plot")
            ))
        fig.add_trace(go.Contour(
            z=field_to_plot,
            colorscale="aggrnyl",
            colorbar=dict(
                title=title
            )
        ))

        # fig.update_layout()
        fig.update_xaxes(title_text="VCx")
        fig.update_yaxes(title_text="VCy")
        fig.update_layout(font={'size':28})

        fig.show()
        pio.write_image(fig, files_output_path + self.output_files_name + 'Pressure.png', width=2864, height=1356)
Esempio n. 20
0
def decision_surface(predict, xrange, yrange, density=120, dotted=False, colorscale=custom, showscale=True):
    xrange, yrange = np.linspace(*xrange, density), np.linspace(*yrange, density)
    xx, yy = np.meshgrid(xrange, yrange)
    pred = predict(np.c_[xx.ravel(), yy.ravel()])

    if dotted:
        return go.Scatter(x=xx.ravel(), y=yy.ravel(), opacity=1, mode="markers", marker=dict(color=pred, size=1, colorscale=colorscale, reversescale=False), hoverinfo="skip", showlegend=False)
    return go.Contour(x=xrange, y=yrange, z=pred.reshape(xx.shape), colorscale=colorscale, reversescale=False, opacity=.7, connectgaps=True, hoverinfo="skip", showlegend=False, showscale=showscale)
Esempio n. 21
0
def plot_grid_search_2d(x, y, slopes, intercepts):
    mse = np.zeros((len(slopes), len(intercepts)))
    for i, slope in enumerate(slopes):
        for j, intercept in enumerate(intercepts):
            mse[i, j] = mean_squared_error(y, x * slope + intercept)
    fig = make_subplots(
        rows=1,
        cols=2,
        subplot_titles=("Surface Plot", "Contour Plot"),
        specs=[[{"type": "surface"}, {"type": "contour"}]],
    )
    fig.add_trace(
        go.Surface(
            z=mse, x=intercepts, y=slopes, name="", colorscale="viridis"
        ),
        row=1,
        col=1,
    )
    fig.add_trace(
        go.Contour(
            z=mse,
            x=intercepts,
            y=slopes,
            name="",
            showscale=False,
            colorscale="viridis",
        ),
        row=1,
        col=2,
    )
    fig.update_layout(
        scene=dict(
            zaxis=dict(title="MSE"),
            yaxis=dict(title="slope (w<sub>1</sub>)"),
            xaxis=dict(title="intercept (w<sub>0</sub>)"),
        ),
        scene_camera=dict(eye=dict(x=2, y=1.1, z=1.2)),
        margin=dict(l=0, r=0, b=60, t=90),
    )
    fig.update_xaxes(
        title="intercept (w<sub>0</sub>)",
        range=[intercepts.max(), intercepts.min()],
        tick0=intercepts.max(),
        row=1,
        col=2,
        title_standoff=0,
    )
    fig.update_yaxes(
        title="slope (w<sub>1</sub>)",
        range=[slopes.min(), slopes.max()],
        tick0=slopes.min(),
        row=1,
        col=2,
        title_standoff=0,
    )
    fig.update_layout(width=900, height=475, margin=dict(t=60))
    return fig
def plot_slice(fname):
    """
    Plot a 2D contour plot of a slice of a 3D array

    Parameters
    ----------
    fname: str with the filename containing the array slice with the tumor diffusion coefficients

    Returns
    -------
    plotly Figure holding the contour plot
    """

    titles = ["2D Slice Tumor Evolution", "2D Slice Normal Brain"]
    specs = [[{'type': 'contour'}, {'type': 'contour'}]]
    fig = make_subplots(rows=1,
                        cols=2,
                        shared_yaxes=True,
                        subplot_titles=titles,
                        specs=specs)

    data = get_contour_data(fname)
    fig1 = go.Contour(z=data,
                      colorscale=DEFAULT_COLORSCALE,
                      visible=True,
                      coloraxis="coloraxis",
                      showlegend=False)

    data = get_contour_data(brain_fname)
    fig2 = go.Contour(z=data,
                      colorscale=DEFAULT_COLORSCALE,
                      coloraxis="coloraxis",
                      visible=True)

    # fig = go.Figure()
    fig.add_trace(fig1, row=1, col=1)
    fig.add_trace(fig2, row=1, col=2)
    fig.update_layout(width=1500,
                      height=750,
                      autosize=False,
                      coloraxis={'colorscale': DEFAULT_COLORSCALE})

    return dcc.Graph(id=PLOT_ID, figure=fig)
Esempio n. 23
0
def plot_simple_contour(x,y,z,cmap="Viridis"):
	fig = go.Figure()
	fig.add_trace(go.Contour(
			z=z,
			x=x,
			y=y,
			colorscale=cmap,
			showscale=True))
	fig = set_basic_layout(fig)
	return fig
Esempio n. 24
0
def contour_map(ucb, axis='x', r0=1):
    ucb_100_f = take_slice(ucb, axis, r0)
    ucb_100 = ucb_100_f.cartesian()
    Z = np.reshape(ucb_100.vals,
                   (len(set(ucb_100_f.y)), len(set(ucb_100_f.z))))
    fig = go.Figure(data=go.Contour(z=np.transpose(Z)))
    fig.update_layout(yaxis=dict(scaleanchor="x", scaleratio=1),
                      plot_bgcolor='rgb(255,255,255)',
                      width=700,
                      height=700)
    fig.show()
Esempio n. 25
0
def Ambiguity_2D(ambiguity, smooth=0.85):
    z = np.absolute(ambiguity)
    N, M = z.shape

    x = np.linspace(-1, 1, M)
    fig = px.imshow(np.absolute(z))

    fig.show()

    fig = go.Figure(
        data=go.Contour(z=np.absolute(z), x=x, line_smoothing=smooth))
    fig.show()
Esempio n. 26
0
def plot2d(time, x, temp_field, boundary_ix=[]):

    hlines = []
    trace_lines = []
    for ix in boundary_ix:
        hline = {
            'type': 'line',
            'x0': x[ix],
            'y0': time[0],
            'x1': x[ix],
            'y1': time[-1],
            'line': {
                'color': 'black',
                'width': 2
            }
        }

    hlines.append(hline)

    #layout = {'shapes': hlines }
    layout = go.Layout(
        title=go.layout.Title(text='Heat Flow Map', x=0.5),
        xaxis=go.layout.XAxis(title=go.layout.xaxis.Title(text='position')),
        yaxis=go.layout.YAxis(title=go.layout.yaxis.Title(text='time')),
    )
    layout['shapes'] = hlines

    trace_contour = go.Contour(
        x=x,
        y=time,
        z=temp_field,
        showscale=False,
        contours=dict(coloring='heatmap',
                      showlabels=True,
                      labelfont=dict(
                          family='Raleway',
                          size=12,
                          color='white',
                      )),
        line=dict(smoothing=0.85),
        #layout=layout
        #shapes={'type': 'line',
        #        'x0': 20,
        #        'y0': 0,
        #       'x1': 20,
        #       'y1': 100}
    )

    fig1 = {'data': [trace_contour], 'layout': layout}
    #plot(fig1,filename='single.html')
    #layout_2=go.Layout()
    #lot(fig1,filename='heatmap.html')
    fig1.write_html('heatmap.html')
Esempio n. 27
0
def plotly_contour_chart(df: pd.DataFrame):
    """
    The input is a dataframe with columns and rows. Use well the column and row names!
    See example input at the end of the file.
    Create a plotly contour chart with the inputs.
    DO NOT PLOT IT!!
    Return the fig only.
    """

    # Plotting the required Contour Plot
    fig = go.Figure(data=go.Contour(z=df))
    return fig
Esempio n. 28
0
    def step_stage_final(self):
        self.tot_sig.append(np.sum(self.matrix))
        self.bid_win_store.append(sum(self.bid_win_sig_store))
        self.best_bid_store.append(
            sum(top_k_2d_array(self.original_mat,
                               len(self.bid_win_sig_store))))
        temp_bider = np.where(self.bid_store == 1, 1, None)
        self.frames.append(
            go.Frame(
                data=[
                    go.Heatmap(
                        z=temp_bider,
                        colorscale=self.colorscale,
                        showscale=False,
                        opacity=1,
                    ),
                    go.Contour(
                        z=self.matrix,
                        colorscale="Greys",
                        opacity=0.7,
                        autocolorscale=False,
                    ),
                ],
                traces=[0, 1],
            ))
        # self.frames.append(go.Frame(data = [go.Contour(z=self.matrix,colorscale='Greys',opacity = 1,visible = True),
        # go.Scatter(x = np.where(self.bid_store == 1)[1],
        # y =np.where(self.bid_store == 1)[0],mode='markers',marker = dict(size = 5,line=dict(width=1,color='DarkSlateGrey')))]))

        tot_view = len(np.where(self.explored == 1)[1])
        num_wining_bids = len(np.where(self.bid_store == 1)[1])
        self.num_wining_bids.append(num_wining_bids)
        self.explored_rate.append(tot_view)
        self.bid_win_count = 0
        self.bid_win_sig_store = []
        to_plot = self.model.to_plot
        if self.model.timestep % int(
                self.model.plot_interval) == 0 and to_plot:

            plt.figure(figsize=(15, 15))
            plt.suptitle(
                str(self.unique_id + "(" + str(tot_view) + "/" +
                    str(self.size**2) + ")____" + str(num_wining_bids)))

            plt.subplot(121)
            plt.imshow(self.explored)
            plt.contour(self.matrix, alpha=0.75)

            plt.subplot(122)
            plt.contour(self.matrix, alpha=0.75)
            plt.imshow(self.bid_store)
            plt.show()
def plot_surface_of_error():
    surf_theta0 = np.arange(-10, 10, 0.1)
    surf_theta1 = np.arange(-10, 10, 0.1)
    surface = surface_of_loss(surf_theta0, surf_theta1, train_x, train_y)

    fig = plotly.subplots.make_subplots(rows=1, cols=2)
    fig.add_trace(go.Surface(x=surf_theta0, y=surf_theta1, z=surface))
    fig.add_trace(go.Contour(x=surf_theta0, y=surf_theta1, z=surface))
    fig.update_layout(title='Loss surface',
                      autosize=False,
                      width=1980,
                      height=1080)
    fig.show()
Esempio n. 30
0
def get_contour_plot(study, x_param, y_param):
    trials = [t for t in study.trials if t.state == TrialState.COMPLETE]

    x_indices = sorted(list({t.params[x_param] for t in trials if x_param in t.params}))
    y_indices = sorted(list({t.params[y_param] for t in trials if y_param in t.params}))

    z = [[float("nan") for _ in range(len(x_indices))] for _ in range(len(y_indices))]

    x_values = []
    y_values = []
    for trial in trials:
        if x_param not in trial.params or y_param not in trial.params:
            continue

        if trial.state != TrialState.COMPLETE:
            continue

        value = trial.user_attrs["error_cases"]
        if value > 2:
            continue

        x_values.append(trial.params[x_param])
        y_values.append(trial.params[y_param])
        x_i = x_indices.index(trial.params[x_param])
        y_i = y_indices.index(trial.params[y_param])

        z[y_i][x_i] = value

    colorscale = plotly.colors.PLOTLY_SCALES["Blues"]
    colorscale = [[1 - t[0], t[1]] for t in colorscale]
    colorscale.reverse()

    contour = go.Contour(
        x=x_indices,
        y=y_indices,
        z=z,
        colorbar={"title": "Objective Value"},
        colorscale=colorscale,
        connectgaps=True,
        contours_coloring="heatmap",
        hoverinfo="none",
        line_smoothing=1.3,
    )

    scatter = go.Scatter(
        x=x_values, y=y_values, marker={"color": "black"}, mode="markers", showlegend=False
    )

    layout = go.Layout(title="Contour Plot", xaxis_title=x_param, yaxis_title=y_param)

    return go.Figure(data=[contour, scatter], layout=layout)