Esempio n. 1
0
    def plot_correlation(df, show_fig=True):
        '''

        :return: None

        Creates plotly correlation plot of all present cegaltools logs

        '''
        temp_df = df.corr().dropna(how='all', axis=0).dropna(how='all', axis=1)
        fig = px.imshow(temp_df,
                        labels=dict(x="Well log (horizontal)", y="Well log (vertical)", color="Correlation"),
                        x=temp_df.columns,
                        y=temp_df.columns)

        fig.update_xaxes(side='top')
        fig.update_layout(
            margin=dict(t=150, l=30, r=30, b=30),
            title={'text': '<b>Well log correlation matrix</b>',
                   'y': 0.9,
                   'x': 0.1,
                   'yanchor': 'top'},
        )
        if show_fig:
            fig.show()
        else:
            return fig
def search_video(search_query, display_heatmap=True, display_results_count=3):

    # Encode and normalize the search query using CLIP
    with torch.no_grad():
        text_features = model.encode_text(
            clip.tokenize(search_query).to(device))
        text_features /= text_features.norm(dim=-1, keepdim=True)

    # Compute the similarity between the search query and each frame using the Cosine similarity
    similarities = (100.0 * video_features @ text_features.T)
    values, best_photo_idx = similarities.topk(display_results_count, dim=0)

    # Display the heatmap
    if display_heatmap:
        print("Search query heatmap over the frames of the video:")
        fig = px.imshow(similarities.T.cpu().numpy(),
                        height=50,
                        aspect='auto',
                        color_continuous_scale='viridis')
        fig.update_layout(coloraxis_showscale=False)
        fig.update_xaxes(showticklabels=False)
        fig.update_yaxes(showticklabels=False)
        fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
        fig.show(renderer="png")
        print()

    # Display the top 3 frames
    for frame_id in best_photo_idx:
        # display(video_frames[frame_id])
        video_frames[frame_id].show()
        print()
Esempio n. 3
0
def plot_heatmap(event, figure_filename=None, figsize=[500, 2000]):
    X, Y, Z = create_XYZ_data(event)
    Z_xr = xr.DataArray(Z,
                        dims=(
                            "time",
                            "sensor_location",
                        ),
                        coords={
                            "sensor_location": X[0, :],
                            "time": Y[:, 0]
                        })
    heatmap = px.imshow(
        Z_xr,
        labels=dict(x="Sensor Location", y="Time (seconds)", color="Strain"),
        width=figsize[0],
        height=figsize[1],
        aspect='auto',
        color_continuous_midpoint=0,
    )
    heatmap.update_xaxes(side="top")
    if figure_filename is not None:
        if not os.path.exists("heatmap_plots"):
            os.mkdir("heatmap_plots")
            print('heatmap_plots folder created.')
        heatmap.write_image(f'heatmap_plots/{figure_filename}.png')
        print('heatmap image saved.')
    return heatmap
def error_structure(data, n_clicks):
    df = pd.DataFrame(data)
    if n_clicks is None or n_clicks % 2 == 0:
        pass
    elif n_clicks % 2 == 1:
        for i in range(0, len(combined_columns), 2):
            df[combined_columns[i]] = df[combined_columns[i]].fillna(
                df[combined_columns[i + 1]])
            df[combined_columns[i]] = df[combined_columns[i]].mask(df[combined_columns[i]] == 0).fillna(
                df[combined_columns[i + 1]])

        for i in range(1, len(combined_columns), 2):
            df[combined_columns[i]] = df[combined_columns[i]].fillna(
                df[combined_columns[i - 1]])
            df[combined_columns[i]] = df[combined_columns[i]].mask(df[combined_columns[i]] == 0).fillna(
                df[combined_columns[i - 1]])

    for i in range(len(summer_columns)):
        df[error_columns[i]] = df[summer_columns[i]] != df[winter_columns[i]]

    fig = px.imshow(df[error_columns].T, color_continuous_scale=px.colors.sequential.Greys,
                    title="Errors Structure")
    fig.update_layout(title_font={'size': 27}, title_x=0.5)

    return fig
Esempio n. 5
0
def evaluate_clusters(start_from=0, mode="sawp"):
    """
    Evaluates the DWT clusters and exports the image of the matrix obtained and the relative matrix in a csv file.

    Parameters
    ----------
    mode: str = {"direct","sawp"}
        Select feature representation.
    """
    import plotly.express as px
    import numpy as np
    meta = metaframe.MetaFrame(path_data=shared.DATASET_PATH,
                               path_meta=shared.META_PATH)
    for identifier, uid in enumerate(meta.UUID):
        if identifier > start_from:
            X = clu.Cluster(uid)
            for side in X.sides:
                for sensor in X.sensors:
                    print("[{}] # ".format(time.ctime()) +
                          "Starting DTW Matrix Computation.")
                    dtw_matrix = X.dist_matrix(side=side,
                                               sensor=sensor,
                                               mode=mode)
                    fig = px.imshow(dtw_matrix)
                    image_path = f"images/DTW_matrices/DTW_{X.train}_{X.direction}_{X.avg_speed}" \
                                 f"_{X.component}_{X.num_trip}_{X.engine_conf}_{side}_{sensor}_{uid}.png"
                    fig.write_image(image_path)
                    print("[{}] # ".format(time.ctime()) + "Image Exported.")
                    matrix_path = f"private/export/DTW_matrices/DTW_{X.train}_{X.direction}_{X.avg_speed}" \
                                  f"_{X.component}_{X.num_trip}_{X.engine_conf}_{side}_{sensor}_{uid}.dat"
                    np.savetxt(matrix_path, dtw_matrix, delimiter=";")
                    print("[{}] # ".format(time.ctime()) + "File Exported.")
def plt_tab6_2():
    df = pd.DataFrame([[20, 2], [2, 100]],
                      columns=["predict_True", "predict_False"],
                      index=["actual_True", "actual_False"])

    fig = px.imshow(df, labels=dict(color="Num of Event"))
    return fig
Esempio n. 7
0
    def exclusions_plotly(self,
                          cmap='Viridis',
                          plot_step=100,
                          out_path=None,
                          **kwargs):
        """
        Plot exclusions mask as a plotly heatmap

        Parameters
        ----------
        cmap : str | px.color, optional
            Continuous color scale to use, by default 'Viridis'
        plot_step : int
            Step between points to plot
        out_path : str, optional
            File path to save plot to, can be a .html or static image,
            by default None
        kwargs : dict
            Additional kwargs for plotly.express.imshow
        """
        fig = px.imshow(self.mask[::plot_step, ::plot_step],
                        color_continuous_scale=cmap,
                        **kwargs)
        fig.update_layout(font=dict(family="Arial", size=18, color="black"))

        if out_path is not None:
            SummaryPlots._save_plotly(fig, out_path)

        fig.show()
Esempio n. 8
0
    def get_uncertainty(index):
        try:
            im = cifar[index][0]
        except Exception as e:
            print(e)
            return px.scatter(title="Error: " + e)
        im = np.transpose(im.numpy(), (1, 2, 0))
        fig = px.imshow(im)
        fig.update_xaxes(showticklabels=False)
        fig.update_yaxes(showticklabels=False)

        distrib_fig = go.Figure(
            [go.Bar(x=cifar.classes_labels, y=cifar[index][1][0].numpy())])

        raw = cifar.get_raw()
        raw = raw[raw.cifar10_test_test_idx == index]
        raw = raw[(raw.is_attn_check != 1) & (raw.reaction_time > 0)]
        boxplots = px.box(raw, x="correct_guess", y="reaction_time")
        return (
            distrib_fig,
            fig,
            boxplots,
            "The true label is {}".format(
                cifar.classes_labels[cifar.true_targets[index]]),
        )
Esempio n. 9
0
def layout(params):
    selection = dcc.Dropdown(
        id = "image-selection",
        options = render_options,
        value = render_options[0]['value'],
        clearable = False
    )

    logo_path = f"{Path(__file__).parent}/assets/pystachio_logo.tif"
    logo_tif = tifffile.imread(logo_path)
    logo_fig = px.imshow(
        logo_tif[:,:,0],
        color_continuous_scale='gray',
        zmin = 0,
        zmax = np.max(logo_tif[:,:,:]),
    )

    img_pane = html.Div(id="img-pane",
        children=[
            selection,
            dcc.Graph(id='image-graph', className='img-graph', figure=logo_fig),
            html.Label('Frame 1 of 1', id='image-frame'),
            dcc.Slider(id='image-slider', min=1, max=params.num_frames, value=0),
        ])

    return img_pane
Esempio n. 10
0
def get_operated_image(contents, image_mode, operation, filenames, dates):
    if contents is not None:
        imsrc = parse_contents(contents, filenames, dates)
        imo = ImageOperations(image_file_src=imsrc)
        if (operation == 'equalize'):
            out_img = imo.equalize_this(gray_scale=True) if image_mode else imo.equalize_this()
        elif (operation == 'flip'):
            out_img = imo.flip_this(gray_scale=True) if image_mode else imo.flip_this()
        elif (operation == 'mirror'):
            out_img = imo.mirror_this(gray_scale=True) if image_mode else imo.mirror_this()
        elif (operation == 'binarize'):
            out_img = imo.binarize_this(gray_scale=True) if image_mode else imo.binarize_this()
        elif (operation == 'invert'):
            out_img = imo.invert_this(gray_scale=True) if image_mode else imo.invert_this()
        elif (operation == 'solarize'):
            out_img = imo.solarize_this(gray_scale=True) if image_mode else imo.solarize_this()
        else:
            out_img = imo.read_this(gray_scale=True) if image_mode else imo.read_this()

        out_image_fig = px.imshow(out_img, color_continuous_scale='gray') if image_mode else px.imshow(out_img)
        out_image_fig.update_layout(
            coloraxis_showscale=False, 
            width=600, height=400, 
            margin=dict(l=0, r=0, b=0, t=0)
        )
        out_image_fig.update_xaxes(showticklabels=False)
        out_image_fig.update_yaxes(showticklabels=False)

        output_result = html.Div([
            dcc.Graph(id='out-op-img', figure=out_image_fig)
        ], style={'paddingTop' : 50})

        return output_result
Esempio n. 11
0
def plot_image(path):
    fig = go.Figure();
#     plt.figure(figsize=(12, 12));
    # path = image_fetcher.fetch('data/cells.tif')
    # path = image_fetcher.fetch('data/cells.tif')
    try:
        if path != None:
            path = path
    except:
        print(f"Default image:")
        path = 'С:/Users/Admin/Documents/JN/NN/COVID_detection_picture/MRI/sick_7c7160149aec1ebf15b28166f5458c49.nii'
#     print(type(path))
    data = nib.load(path);
    print(type(data))
    
    data = data.get_data();
    print(type(data[0]), data[0].shape)
    data = data.transpose(2,1,0)
    print(type(data), data.shape)
    
    data = ndimage.zoom(data, (1, 1, 1), order = 1)
    print(data.shape)
    img = data[:]
    fig = px.imshow(img, 
                    animation_frame = 0, 
                    binary_string = True, 
                    labels = dict(animation_frame = "slice"),    
                    width = 512,
                    height = 512, 
#                     title = "NIFTI Detection scanner"
                   )
#     fig.show()    
    return fig
 def _generate_heatmap(self):
     df = self.pp.get_numeric_df(self.settings['data']).copy()
     numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
     df = df.select_dtypes(include=numerics)
     df.rename(columns=lambda x: x[:11], inplace=True)
     fig = px.imshow(df)
     return html.Div([
         html.Div(html.H1(children='Хитмап'),
                  style={'text-align': 'center'}),
         html.Div([
             html.Div(dcc.Graph(id='heatmap', figure=fig),
                      style={
                          'width': '78%',
                          'display': 'inline-block',
                          'border-color': 'rgb(220, 220, 220)',
                          'border-style': 'solid',
                          'padding': '5px'
                      }),
             html.Div(dcc.Markdown(children=markdown_text_heatmap),
                      style={
                          'width': '18%',
                          'float': 'right',
                          'display': 'inline-block'
                      })
         ])
     ],
                     style={'margin': '100px'})
Esempio n. 13
0
def visualize(data):
    # Histogram Plot
    st.sidebar.header('Visualize Data:')
    if st.sidebar.checkbox('Plot Histograms of each column:'):
        column = st.selectbox('hist_column', data.columns)
        color_var = st.selectbox('Color_variable_hist',
                                 [None] + list(data.columns))
        bins = st.slider('No:Of Bins',
                         min_value=1,
                         max_value=50,
                         value=10,
                         step=1)
        fig = px.histogram(data, x=column, nbins=bins, color=color_var)
        st.plotly_chart(fig, )

    if st.sidebar.checkbox("Scatter plot:"):
        column1 = st.selectbox('X-axis_scatter', data.columns)
        column2 = st.selectbox('Y-axis_scatter', data.columns)
        color_var = st.selectbox('Color_variable_scat',
                                 [None] + list(data.columns))
        fig = px.scatter(data, x=column1, y=column2, color=color_var)
        st.plotly_chart(fig)

    if st.sidebar.checkbox("Feature Correlation Plot:"):
        corr = data.corr()
        fig = px.imshow(corr)
        st.plotly_chart(fig)
Esempio n. 14
0
def get_plot(img, bboxes, class_names, rad_ids, box_ids, width=600):
    fig = px.imshow(img, binary_string=True)
    # Add image
    img_height, img_width = img.shape[:2]
    fig.update_layout(width=width, height=width * img_height / img_width)

    for box, rad_id, class_name, box_id in zip(bboxes, rad_ids, class_names,
                                               box_ids):
        if 'No finding' in class_name:
            fig.add_trace(
                go.Scatter(
                    x=[300],
                    y=[300],
                    name=f'{rad_id}, {class_name}',
                    opacity=0,
                ))
        else:
            x0, y0, x1, y1 = box
            fig.add_trace(
                go.Scatter(
                    x=[x0, x1, x1, x0, x0],
                    y=[y0, y0, y1, y1, y0],
                    uid=int(box_id),
                    hovertemplate=
                    f'<b>{box_id}</b><br> {rad_id}<br>{class_name}',
                    text=[class_name],
                    name=f'{rad_id}, {class_name}',
                    line=dict(width=2, color=get_contrasted_color(rad_id)),
                    fillcolor=get_contrasted_color(rad_id),
                    mode="lines+text",
                    opacity=1,
                ))

    return fig
Esempio n. 15
0
def visualize(myimage):
    # Converting the image ndarray into image using imshow from plotly.express package and then displaying it using streamlit.plotly_chart
    wc_img = px.imshow(myimage)
    wc_img.update_xaxes(showticklabels=False).update_yaxes(
        showticklabels=False)
    st.plotly_chart(wc_img)
    return wc_img
Esempio n. 16
0
def plot_input_layer(arr,
                     infos=None,
                     return_fig=False,
                     render_in_browser=True):
    # x expected shape: W,H,16
    fig = make_subplots(rows=4, cols=4)
    x = arr

    for i in range(0, 4):
        for j in range(0, 4):
            cur_img = x[:, :, i * 4 + j]
            title = f"max:{np.amax(cur_img):.4f} min:{np.amin(cur_img):.4f} mean:{np.mean(cur_img):.4f}"
            plot = px.imshow(cur_img, labels=dict(x=title))

            fig.add_traces(plot.data, rows=i + 1, cols=j + 1)
            # plt.title(f"max:{np.amax(x[:,:,i]):.4f} min:{np.amin(x[:,:,i]):.4f} mean:{np.mean(x[:,:,i]):.4f}")
    # fig.update_layout(coloraxis_showscale=False)
    if infos:
        fig.update_layout(
            title=
            f"train_step:{infos[0]}, ca_step:{infos[1]}, layer:{infos[2]}, batch:{infos[3]}"
        )

    if render_in_browser:
        pio.renderers.default = "browser"

    if return_fig:
        return fig
    else:
        fig.show()
Esempio n. 17
0
def colorhist(img,imgtype,grayimg=None,save=False):
    #Plolty Hist 
    if imgtype=="BGR":
        colors=["blue","green","red"]
        labels=["blue","green","red"]
    elif imgtype=="HSV":
        colors=["blue","green","red"]
        labels=["H","S","V"]
    coldict={}
    ff=go.Figure()
    bgr_img=None
    for i,col in enumerate(colors):
        c_img=img[:,:,i]
        coldict[col]=c_img
        ff.add_trace(go.Histogram(x=c_img.flatten()[c_img.flatten()!=0],marker_color=col,name=labels[i]))
        if bgr_img is None:
            bgr_img=c_img
        else:
            bgr_img=cv2.hconcat([bgr_img,c_img])
    if grayimg:
        ff.add_trace(go.Histogram(x=grayimg.flatten()[grayimg.flatten()!=0],marker_color="gray",name="gray"))
    if save:           
        bgr=px.imshow(bgr_img)
        bgr.write_html(f"{imgtype}_colors.html")
        bgr.show()
        ff.write_html(f"{imgtype}_hist.html")
        ff.show()
Esempio n. 18
0
def update_output_div(year, quarter):
    time = str(year) + 'Q' + str(quarter)
    wordcloud = WordCloud(font_path=wordcloudFont,
                          width=300,
                          height=400,
                          background_color='white',
                          max_font_size=10,
                          max_words=20,
                          colormap='Set2')
    words = countsByQuarter[time]
    wordcloud.fit_words(words)

    # plot the WordCloud image

    fig = px.imshow(wordcloud)
    fig.update_yaxes(visible=False, showticklabels=False)
    fig.update_xaxes(visible=False, showticklabels=False)
    fig.update_layout(title=str(time),
                      yaxis={
                          'visible': False,
                          'showticklabels': False
                      },
                      xaxis={
                          'visible': False,
                          'showticklabels': False
                      },
                      font=dict(family="Courier New, monospace",
                                size=18,
                                color="RebeccaPurple"))

    return fig
Esempio n. 19
0
def run_model(n_clicks, n_submit, url):
    try:
        im = Image.open(requests.get(url, stream=True).raw)
    except Exception as e:
        print(e)
        return px.scatter(title="Error: " + e)

    fig = px.imshow(im, title="Original Image")

    im_pt = transform(im).unsqueeze(0)
    with torch.no_grad():
        preds = torch.softmax(model(im_pt), dim=1)
        scores = preds.numpy().squeeze()

    topk_idx = scores.argsort()[::-1][:10]
    top_classes = CLASSES[topk_idx][::-1]
    top_scores = scores[topk_idx][::-1]

    scores_fig = px.bar(
        x=top_scores,
        y=top_classes,
        labels=dict(x="Confidence", y="Classes"),
        title="ImageNet predictions by DEiT-base",
        orientation="h",
    )

    return fig, scores_fig
Esempio n. 20
0
def update_heatmap(patients_select):
    features_nice = [columns_mapping[x] for x in features]
    if len(patients_select) > 0:
        df_ind_sub = pd.DataFrame(
            append_spaceshifts_to_individual_parameters_dataframe(
                pd.DataFrame(df_ind[np.isin(df_ind["ID"], patients_select)]),
                leaspy)[[
                    "w_{}".format(i) for i in range(leaspy.model.dimension)
                ]].mean())
        df_ind_sub.index = features_nice
    else:
        df_ind_sub = pd.DataFrame([0] * leaspy.model.dimension,
                                  index=features_nice)
    fig = px.imshow(-df_ind_sub.T,
                    color_continuous_scale="RdYlGn",
                    range_color=[-range_w, range_w],
                    height=height_w)

    fig.update_yaxes(showticklabels=False)

    fig.update_layout(
        margin=dict(l=2, r=2, t=40, b=10),
        paper_bgcolor="#f9f9f9",
        autosize=True,
        #showscale=False,
        title={
            'text': "Patient space-shifts",
            "x": 0.5,
            "y": 0.95,
            'xanchor': 'center'
        })
    return fig
def make_default_figure(
        images=filelist[0],
        stroke_color=class_to_color(DEFAULT_LABEL_CLASS),
        stroke_width=int(round(2 ** (DEFAULT_STROKE_WIDTH))),
        shapes=[],
):
    fig = px.imshow(io.imread(images))
    fig.update_layout(
        dragmode="drawclosedpath",
        margin=dict(l=0, r=0, b=0, t=0, pad=4),
        shapes=shapes,
        uirevision=images,
        newshape=dict(
            line_color=stroke_color,
            line_width=stroke_width,
            opacity=0.5,
            fillcolor= stroke_color,

        )
    )
    fig.update_layout(
        dragmode="drawclosedpath",
    )

    return fig
Esempio n. 22
0
def plot_heatmap(fobject,
                 other_objects=None,
                 metrics='all',
                 title=None,
                 verbose=True,
                 **kwargs):
    if metrics == 'all':
        metrics = list(fobject.parity_loss.index)

    data = _unwrap_parity_loss_data(fobject, other_objects, metrics, verbose=verbose)
    score_data = data.score.values.reshape(len(data.label.unique()), len(data.metric.unique()))

    fig = px.imshow(score_data,
                    labels=dict(x="parity loss metrics", y="model", color="Metric's parity loss"),
                    x=list(data.metric.unique()),
                    y=list(data.label.unique()),
                    color_continuous_scale=["#c7f5bf", "#8bdcbe", "#46bac2", "#4378bf", "#371ea3"])

    if title is None:
        title = "Fairness Heatmap"
    fig.update_layout(_fairness_theme(title))

    fig.update_traces(
        hovertemplate="<br>".join([
            "<b>%{y}</b><br>",
            "Parity loss metric: %{x}",
            "parity loss: %{z:.3f}",
            "<extra></extra>"
        ]))

    return fig
Esempio n. 23
0
def missing_structure(data, n_clicks):
    df = pd.DataFrame(data)

    if n_clicks is None or n_clicks % 2 == 0:
        pass
    elif n_clicks % 2 == 1:
        for i in range(0, len(combined_columns), 2):
            df[combined_columns[i]] = df[combined_columns[i]].fillna(
                df[combined_columns[i + 1]])
            df[combined_columns[i]] = df[combined_columns[i]].mask(df[combined_columns[i]] == 0).fillna(
                df[combined_columns[i + 1]])

        for i in range(1, len(combined_columns), 2):
            df[combined_columns[i]] = df[combined_columns[i]].fillna(
                df[combined_columns[i - 1]])
            df[combined_columns[i]] = df[combined_columns[i]].mask(df[combined_columns[i]] == 0).fillna(
                df[combined_columns[i - 1]])

    for i in range(len(summer_columns)):
        df[error_columns[i]] = df[[summer_columns[i], winter_columns[i]]
                                  ].isnull().apply(lambda x: any(x), axis=1)

    fig = px.imshow(df[error_columns].T, color_continuous_scale=px.colors.sequential.Greys,
                    title="Missing Structure")
    fig.update_layout(title_font={'size': 27}, title_x=0.5)

    return fig
Esempio n. 24
0
def plotgraphs(e,acu,val_acu,loss,val_loss,m,accuracy_score):
    file = open(base_dir+"/classification/templates/temp_graphs.html","r+")

    file.truncate(0)

    file.close()



    fig = go.Figure()
    fig.add_trace(go.Scatter(x=list(range(1,e)), y=acu, name='training accuracy',line=dict(color='firebrick'),mode='lines'))
    fig.add_trace(go.Scatter(x=list(range(1,e)), y=val_acu, name='val accuracy',line=dict(color='royalblue'),mode='lines'))
    fig.update_layout(title='Accuracy', xaxis_title='Epochs',yaxis_title='accuracy')
    with open(base_dir+'/classification/templates/temp_graphs.html', 'a') as f:
        f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))


    fig = go.Figure()
    fig.add_trace(go.Scatter(x=list(range(1,e)), y=loss, name='training loss',line=dict(color='firebrick'),mode='lines'))
    fig.add_trace(go.Scatter(x=list(range(1,e)), y=val_loss, name='val loss',line=dict(color='royalblue'),mode='lines'))
    fig.update_layout(title='Loss', xaxis_title='epochs',yaxis_title='loss')
    with open(base_dir+'/classification/templates/temp_graphs.html', 'a') as f:
        f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))


    fig=px.imshow(m)

    fig.update_layout(title='accuracy = {}'.format(accuracy_score))
    with open(base_dir+'/classification/templates/temp_graphs.html', 'a') as f:
        f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))
Esempio n. 25
0
def callback(url, run, threshold, head, options):
    try:
        im = download_img(url)
    except:
        return go.Figure().update_layout(title="Incorrect URL")

    ix = int(head)
    # Run model
    img = transform(im).to(device)
    attentions, w_featmap, h_featmap = predict(img)
    th_attn, scalar_attn = apply_threshold(attentions, w_featmap, h_featmap, threshold)

    attns = th_attn if "use threshold" in options else scalar_attn

    if "overlay" in options:
        fig = px.imshow(im)
        fig.add_trace(go.Heatmap(z=attns[ix], opacity=0.55))
    else:
        fig = make_subplots(1, 2)
        fig.add_trace(go.Image(z=im), 1, 1)
        fig.add_trace(go.Heatmap(z=attns[ix]), 1, 2)
        fig.update_xaxes(matches="x")
        fig.update_yaxes(matches="y")

    return fig
Esempio n. 26
0
def update_graph(select_pillar1):
    if not select_pillar1:
        raise PreventUpdate
    # topic = 'TRQ'

    topic = select_pillar1

    if 'data' in globals():
        del data
    data = load_data()

    selected = data[data['Topics'].str.contains(topic)].sort_values('Year')
    selected_symbols = selected['Symbol'].tolist()
    selected_docs = selected['Words'].tolist()
    sim_sorted = calc_similarity(selected_symbols,
                                 selected_docs,
                                 kRandom=3,
                                 nClusters=3,
                                 sortCluster=False)

    figure = px.imshow(sim_sorted)
    figure.update_layout(height=800,
                         width=800,
                         font=dict(family="Courier New, monospace",
                                   size=8,
                                   color="RebeccaPurple"),
                         xaxis=dict(autorange='reversed'))
    return figure
Esempio n. 27
0
 def _make_figure(self, overlap_matrix, labels):
     figure = px.imshow(overlap_matrix, x=labels, y=labels, zmin=0, zmax=100, color_continuous_scale=px.colors.sequential.Teal,
                        template='plotly_white')
     figure.update_traces(hovertemplate="Overlap of disease-associated<br>sequences between datasets<br>%{x} and %{y}:<br>%{z}%<extra></extra>")
     figure_path = self.result_path + "sequence_overlap.html"
     figure.write_html(figure_path)
     return figure_path
Esempio n. 28
0
def update_graph(select_pillar2):
    if not select_pillar2:
        raise PreventUpdate

    if 'data' in globals():
        del data
    data = load_data()

    topic = select_pillar2
    text = " ".join(
        review for review in data[data["Topics"].str.contains(topic)]['text'])
    # Generate a word cloud image
    wordcloud = WordCloud(background_color="white", width=900,
                          height=600).generate(text)

    # Display the generated image:
    figure = px.imshow(wordcloud)
    figure.update_layout(
        width=800,
        height=650,
        xaxis_visible=False,
        yaxis_visible=False,
        font=dict(family="Courier New, monospace",
                  size=8,
                  color="RebeccaPurple"),
    )
    return figure
Esempio n. 29
0
def update_test_output(n_clicks, contents,tab, patch_size, inline_number,filename):
        content_type, content_string = contents[0].split(',')
        decoded = base64.b64decode(content_string)
        file_like_object = io.BytesIO(decoded)
        vol = np.load(file_like_object,allow_pickle=True)
        
        volume=vol[:100,:patch_size,:patch_size]
        volume = volume.T
        
        if tab == 'tab-1':
            fig=show_cube(volume)
            return html.Div([
                dcc.Graph(figure=fig)
        
            ])
        elif tab == 'tab-2':
            fig2 = px.imshow(vol[inline_number])
            return html.Div([
                dcc.Graph(figure=fig2)
        
        ])
        elif tab == 'tab-3':
            #command="python test.py --patch_size "+str(patch_size)+"--inline_number"+str(inline_number)
            #subprocess.call(command, shell=True)

            return html.Div([
                html.H5("Tab content 3")
        
        ])   
Esempio n. 30
0
 def create_image(self, matrix, file_path):
     ratio = 8
     fig = px.imshow(matrix)
     fig.update_layout(width=int(matrix.shape[1] * ratio),
                       height=int(matrix.shape[0] * ratio),
                       margin=dict(l=2, r=2, b=2, t=2))
     fig.write_image(file_path)