Python plotly.graph_objects.Figure() Examples

The following are 30 code examples of plotly.graph_objects.Figure(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module plotly.graph_objects , or try the search function .
Example #1
Source File: Benchmarking Jupytext.py    From jupytext with MIT License 6 votes vote down vote up
def performance_plot(perf, title):
    formats = ['nbformat'] + JUPYTEXT_FORMATS
    mean = perf.groupby('implementation').mean().loc[formats]
    std = perf.groupby('implementation').std().loc[formats]
    data = [go.Bar(x=mean.index,
                   y=mean[col],
                   error_y=dict(
                       type='data',
                       array=std[col],
                       color=color,
                       thickness=0.5
                   ) if col != 'size' else dict(),
                   name=col,
                   yaxis={'read': 'y1', 'write': 'y2', 'size': 'y3'}[col])
            for col, color in zip(mean.columns, DEFAULT_PLOTLY_COLORS)]
    layout = go.Layout(title=title,
                       xaxis=dict(title='Implementation', anchor='y3'),
                       yaxis=dict(domain=[0.7, 1], title='Read (secs)'),
                       yaxis2=dict(domain=[0.35, .65], title='Write (secs)'),
                       yaxis3=dict(domain=[0, .3], title='Size')
                       )
    return go.Figure(data=data, layout=layout) 
Example #2
Source File: view.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_chart(title):
    import json

    import plotly.graph_objects as go
    import plotly

    layout = go.Layout(title=title)

    data = go.Scatter(
        x=[1, 2, 3, 4],
        y=[10, 11, 12, 13],
        mode="markers",
        marker=dict(size=[40, 60, 80, 100], color=[0, 1, 2, 3]),
    )

    fig = go.Figure(data=data)
    fig = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    layout = json.dumps(layout, cls=plotly.utils.PlotlyJSONEncoder)
    return fig, layout 
Example #3
Source File: visualization.py    From AeroSandbox with MIT License 6 votes vote down vote up
def __init__(self):
        self.fig = go.Figure()

        # Vertices of the faces
        self.x_face = []
        self.y_face = []
        self.z_face = []

        # Connectivity and color of the faces
        self.i_face = []
        self.j_face = []
        self.k_face = []
        self.intensity_face = []

        # Vertices of the lines
        self.x_line = []
        self.y_line = []
        self.z_line = []

        # Vertices of the streamlines
        self.x_streamline = []
        self.y_streamline = []
        self.z_streamline = [] 
Example #4
Source File: plotly_wrapper.py    From qiskit-ibmq-provider with Apache License 2.0 6 votes vote down vote up
def savefig(
            self,
            filename: str,
            figsize: Tuple[Optional[int]] = (None, None),
            scale: float = 1,
            transparent: bool = False
    ) -> None:
        """Save the figure.

        Args:
            filename: Filename to save to.
            figsize: Figure size (W x H) in pixels.
            scale: Scale of the output figure.
            transparent: Whether to use transparent background.
        """
        if transparent:
            plot_color = self._fig.layout['plot_bgcolor']
            paper_color = self._fig.layout['paper_bgcolor']
            self._fig.update_layout(paper_bgcolor='rgba(0,0,0,0)',
                                    plot_bgcolor='rgba(0,0,0,0)')
        self._fig.write_image(filename, width=figsize[0], height=figsize[1], scale=scale)
        if transparent:
            self._fig.update_layout(plot_bgcolor=plot_color,
                                    paper_bgcolor=paper_color) 
Example #5
Source File: bearing_seal_element.py    From ross with MIT License 6 votes vote down vote up
def plot(self, **kwargs):
        """Plot damping coefficient vs frequency.

        Parameters
        ----------
        **kwargs : optional
            Additional key word arguments can be passed to change the plot layout only
            (e.g. width=1000, height=800, ...).
            *See Plotly Python Figure Reference for more information.

        Returns
        -------
        fig : Plotly graph_objects.Figure()
            The figure object with the plot.

        Example
        -------
        >>> bearing = bearing_example()
        >>> fig = bearing.cxx.plot()
        >>> # fig.show()
        """
        fig = super().plot(**kwargs)
        fig.update_yaxes(title_text="<b>Damping (Ns/m)</b>")

        return fig 
Example #6
Source File: bearing_seal_element.py    From ross with MIT License 6 votes vote down vote up
def plot(self, **kwargs):
        """Plot stiffness coefficient vs frequency.

        Parameters
        ----------
        **kwargs : optional
            Additional key word arguments can be passed to change the plot layout only
            (e.g. width=1000, height=800, ...).
            *See Plotly Python Figure Reference for more information.

        Returns
        -------
        fig : Plotly graph_objects.Figure()
            The figure object with the plot.

        Example
        -------
        >>> bearing = bearing_example()
        >>> fig = bearing.kxx.plot()
        >>> # fig.show()
        """
        fig = super().plot(**kwargs)
        fig.update_yaxes(title_text="<b>Stiffness (N/m)</b>")

        return fig 
Example #7
Source File: PlotPlotly.py    From Grid2Op with Mozilla Public License 2.0 5 votes vote down vote up
def init_fig(self, fig, reward, done, timestamp):
        if fig is None:
            fig = go.Figure()
        elif not isinstance(fig, self.type_fig_allowed):
            raise PlotError("PlotPlotly cannot plot on figure of type {}. The accepted type is {}. You provided an "
                            "invalid argument for \"fig\"".format(type(fig), self.type_fig_allowed))
        return fig 
Example #8
Source File: topic_flow_viewer.py    From TopicNet with MIT License 5 votes vote down vote up
def plot(self, topics, significance_threshold=1e-2):
        """
        Function for plotly graph building.

        Parameters
        ----------
        topics : list of int
            topics that need to be visualized
        significance_threshold : float
            plot ignores values lower than threshold
        """
        fig = go.Figure()

        for t in topics:
            fig.add_trace(go.Scatter(x=np.arange(len(self.unique_time_labels)),
                                     y=[
                                         value if value > significance_threshold
                                         else None
                                         for value in self.topic_values[t, :]
                                     ],
                                     text=self.topic_tokens_str[f'topic_{t}'],
                                     hoverinfo='text',
                                     mode=None,
                                     hoveron='points+fills',
                                     fill='tozeroy',
                                     name=f'topic_{t}'))

        fig.update_layout(
            title='Trending Topics Over Time',
            title_font_size=30,
            autosize=True,
            paper_bgcolor='LightSteelBlue'
        )

        fig.update_xaxes(title_text='Time',
                         tickvals=np.arange(len(self.unique_time_labels))[::4],
                         ticktext=self.unique_time_labels[::4])
        fig.update_yaxes(title_text='Value')
        fig.show() 
Example #9
Source File: parkDataVisulization.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def LinePlot_facility(df):
    # print(df.columns)
    '''
    Index(['park_no_left', 'label', 'park_class', 'location', 'acres',
       'shape_area', 'shape_leng', 'perimeter', 'geometry', 'index_right',
       'facility_n', 'facility_t', 'park', 'park_no_right', 'x_coord',
       'y_coord'],
      dtype='object')
    '''
    facilityLabelFre=df.facility_n.value_counts()
    print(facilityLabelFre.index)
    print(len(facilityLabelFre.index))
    
    #Create traces
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=facilityLabelFre.index, y=facilityLabelFre, mode='lines+markers',name='lines+markers',
                             line=dict(color='firebrick', width=1),marker_size=7
                             ))   
    fig.update_layout(
    title_text=" ",
    font=dict(
            family='SimHei', #'Times New Roman'
            size=12,
           # color="#7f7f7f"
         ),
    plot_bgcolor='rgb(240, 240, 240)',
    )    
    fig.show()

#散点分布图_地表覆盖 
Example #10
Source File: cacheGraph.py    From nanoBench with GNU Affero General Public License v3.0 5 votes vote down vote up
def getPlotlyGraphDiv(title, x_title, y_title, traces):
   fig = go.Figure()
   fig.update_layout(title_text=title)
   fig.update_xaxes(title_text=x_title)
   fig.update_yaxes(title_text=y_title)

   for name, y_values in traces:
      fig.add_trace(go.Scatter(y=y_values, mode='lines+markers', name=name))

   return plot(fig, include_plotlyjs=False, output_type='div') 
Example #11
Source File: result.py    From arche with MIT License 5 votes vote down vote up
def build_box_subplots(stat: pd.DataFrame) -> go.Figure:
        """Create a figure with box subplots showing fields coverages for jobs.

        Args:
            stat: a dataframe with field coverages

        Returns:
            A figure with box subplots
        """
        stat = stat.drop(columns=["std", "mean", "target deviation"])
        traces = [
            go.Box(
                y=row[1],
                name=row[0],
                boxpoints="all",
                jitter=0.3,
                boxmean="sd",
                hoverinfo="y",
            )
            for row in stat.iterrows()
        ]
        cols = 4
        rows = math.ceil(len(stat) / cols)
        fig = make_subplots(rows=rows, cols=cols)
        x = 0
        for i, j in itertools.product(range(1, rows + 1), range(1, cols + 1)):
            if x == len(traces):
                break
            fig.append_trace(traces[x], i, j)
            x += 1

        fig.update_layout(height=rows * 300 + 200, width=cols * 300, showlegend=False)
        fig.update_yaxes(tickformat=".4p")
        return fig 
Example #12
Source File: plotly_wrapper.py    From qiskit-ibmq-provider with Apache License 2.0 5 votes vote down vote up
def __init__(self, fig: go.Figure):
        """PlotlyFigure class.

        Args:
            fig: Figure to use.
        """
        self._fig = fig 
Example #13
Source File: test_fluid_flow.py    From ross with MIT License 5 votes vote down vote up
def test_plots():
    bearing = fluid_flow_short_numerical()
    bearing.calculate_pressure_matrix_numerical()
    figure_type = type(go.Figure())
    assert isinstance(plot_shape(bearing), figure_type)
    assert isinstance(plot_eccentricity(bearing), figure_type)
    assert isinstance(plot_pressure_theta(bearing), figure_type)
    assert isinstance(plot_pressure_z(bearing), figure_type)
    assert isinstance(plot_pressure_theta_cylindrical(bearing), figure_type)
    assert isinstance(plot_pressure_surface(bearing), figure_type) 
Example #14
Source File: PlotPlotly.py    From Grid2Op with Mozilla Public License 2.0 5 votes vote down vote up
def create_figure(self):
        f = go.Figure()
        self._set_layout(f)
        return f 
Example #15
Source File: PlotPlotly.py    From Grid2Op with Mozilla Public License 2.0 5 votes vote down vote up
def create_figure(self):
        f = go.Figure()
        self._set_layout(f)
        return f 
Example #16
Source File: PlotPlotly.py    From Grid2Op with Mozilla Public License 2.0 5 votes vote down vote up
def init_fig(self, fig, reward, done, timestamp):
        if fig is None:
            fig = go.Figure()
        elif not isinstance(fig, self.type_fig_allowed):
            raise PlotError("PlotPlotly cannot plot on figure of type {}. The accepted type is {}. You provided an "
                            "invalid argument for \"fig\"".format(type(fig), self.type_fig_allowed))
        return fig 
Example #17
Source File: distributed_logger.py    From rl_algorithms with MIT License 5 votes vote down vote up
def write_worker_log(self, worker_logs: List[dict]):
        """Log the mean scores of each episode per update step to wandb."""
        # NOTE: Worker plots are passed onto wandb.log as matplotlib.pyplot
        #       since wandb doesn't support logging multiple lines to single plot
        if self.args.log:
            self.set_wandb()
            # Plot individual workers
            fig = go.Figure()
            worker_id = 0
            for worker_log in worker_logs:
                fig.add_trace(
                    go.Scatter(
                        x=list(worker_log.keys()),
                        y=smoothen_graph(list(worker_log.values())),
                        mode="lines",
                        name=f"Worker {worker_id}",
                        line=dict(width=2),
                    )
                )
                worker_id = worker_id + 1

            # Plot mean scores
            steps = worker_logs[0].keys()
            mean_scores = []
            for step in steps:
                each_scores = [worker_log[step] for worker_log in worker_logs]
                mean_scores.append(np.mean(each_scores))

            fig.add_trace(
                go.Scatter(
                    x=list(worker_logs[0].keys()),
                    y=mean_scores,
                    mode="lines+markers",
                    name="Mean scores",
                    line=dict(width=5),
                )
            )

            # Write to wandb
            wandb.log({"Worker scores": fig}) 
Example #18
Source File: ATARI_DQN_CNN.py    From FitML with MIT License 5 votes vote down vote up
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('DQN_CNN_Trend_figure.html') 
Example #19
Source File: plotly.py    From dynamicslearn with MIT License 5 votes vote down vote up
def plot_rewards_over_trials(rewards, env_name, save=False):
    import plotly.graph_objects as go
    data = []
    traces = []
    colors = plt.get_cmap('tab10').colors

    i = 0
    cs_str = 'rgb' + str(colors[i])
    ys = np.stack(rewards)
    data.append(ys)
    err_traces, xs, ys = generate_errorbar_traces(np.asarray(data[i]), color=cs_str, name=f"simulation")
    for t in err_traces:
        traces.append(t)

    layout = dict(title=f"Learning Curve Reward vs Number of Trials (Env: {env_name})",
                  xaxis={'title': 'Trial Num'},
                  yaxis={'title': 'Cum. Reward'},
                  plot_bgcolor='white',
                  showlegend=False,
                  font=dict(family='Times New Roman', size=30, color='#7f7f7f'),
                  height=1000,
                  width=1500,
                  legend={'x': .83, 'y': .05, 'bgcolor': 'rgba(50, 50, 50, .03)'})

    fig = {
        'data': traces,
        'layout': layout
    }

    fig = go.Figure(fig)

    if save:
        fig.write_image(os.getcwd() + "/learning.png")
    else:
        fig.show()

    return fig 
Example #20
Source File: simulate_bopid.py    From dynamicslearn with MIT License 5 votes vote down vote up
def plot_learning(exp, cfg):
    objective_means = np.array([[exp.trials[trial].objective_mean] for trial in exp.trials])
    cumulative = optimization_trace_single_method(
        y=np.maximum.accumulate(objective_means.T, axis=1), ylabel=cfg.metric.name,
        trace_color=(83, 78, 194),
        # optimum=-3.32237,  # Known minimum objective for Hartmann6 function.
    )
    all = optimization_trace_single_method(
        y=objective_means.T, ylabel=cfg.metric.name,
        model_transitions=[cfg.bo.random], trace_color=(114, 110, 180),
        # optimum=-3.32237,  # Known minimum objective for Hartmann6 function.
    )
    layout_learn = cumulative[0]['layout']
    layout_learn['paper_bgcolor'] = 'rgba(0,0,0,0)'
    layout_learn['plot_bgcolor'] = 'rgba(0,0,0,0)'

    d1 = cumulative[0]['data']
    d2 = all[0]['data']

    for t in d1:
        t['legendgroup'] = cfg.metric.name + ", cum. max"
        if 'name' in t and t['name'] == 'Generator change':
            t['name'] = 'End Random Iterations'
        else:
            t['name'] = cfg.metric.name + ", cum. max"

    for t in d2:
        t['legendgroup'] = cfg.metric.name
        if 'name' in t and t['name'] == 'Generator change':
            t['name'] = 'End Random Iterations'
        else:
            t['name'] = cfg.metric.name

    fig = {
        "data": d1 + d2,  # data,
        "layout": layout_learn,
    }
    import plotly.graph_objects as go
    return go.Figure(fig) 
Example #21
Source File: Advantage_Actor_Critic.py    From FitML with MIT License 5 votes vote down vote up
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('Trend_figure.html') 
Example #22
Source File: Advantage_Actor_Critic.py    From FitML with MIT License 5 votes vote down vote up
def plot_score(all_scores):
    fig = go.Figure(data=go.Bar(y=all_scores))
    fig.write_html('Trend_figure.html') 
Example #23
Source File: mpc.py    From dynamicslearn with MIT License 4 votes vote down vote up
def get_action(self, state, metric=None):
        # if self.internal % self.update_period == 0:
        # repeat the state
        state0 = torch.tensor(state).repeat(self.N, 1)
        states = torch.zeros(self.N, self.T + 1, state.shape[-1])
        states[:, 0, :] = state0
        rewards = torch.zeros(self.N, self.T)
        if self.hold:
            action_candidates = self.action_sampler.sample(sample_shape=(self.N, 1)).repeat(1, self.T, 1)
        else:
            action_candidates = self.action_sampler.sample(sample_shape=(self.N, self.T))

        # TODO
        for t in range(self.T):
            action_batch = action_candidates[:, t, :]
            state_batch = states[:, t, :]
            next_state_batch = state_batch + torch.tensor(self.model.predict(state_batch, action_batch)).float()
            states[:, t + 1, :] = next_state_batch
            if metric is not None:
                rewards[:, t] = metric(next_state_batch, action_batch)
            else:
                rewards[:, t] = self.env.get_reward_torch(next_state_batch, action_batch)

        # TODO compute rewards
        cumulative_reward = torch.sum(rewards, dim=1)

        if False:
            # Basic waterfall plot
            import plotly.graph_objects as go
            fig = go.Figure()
            # Create and style traces
            for i, vec in enumerate(states[:,:,0]):
                if i < 500:
                    fig.add_trace(go.Scatter(y=vec))
            fig.show()

        best = torch.argmax(cumulative_reward)
        actions_seq = action_candidates[best, :, :]
        best_action = actions_seq[0]

        self.last_action = best_action
        self.internal += 1
        return best_action
        # else:
        #     self.internal += 1
        #     best_action = self.last_action
        #     return best_action, False 
Example #24
Source File: parkDataVisulization.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
def boxPlot_treeHeight(df):
    x_data = ['HVege_count_perc', 'MVege_count_perc', 'LVege_count_perc']
    y_data = df[x_data].values.T    
    colors = ['rgba(44, 160, 101, 0.5)', 'rgba(255, 144, 14, 0.5)','rgba(93, 164, 214, 0.5)'] # ['rgba(44, 160, 101, 0.5)', 'rgba(255, 144, 14, 0.5)','rgba(93, 164, 214, 0.5)']
    fig = go.Figure()    
    x_data_label=["高","中","低",]
    for xd, yd, cls in zip(x_data_label, y_data, colors):
            fig.add_trace(go.Box(
                y=yd,
                name=xd,
                boxpoints='all',
                jitter=0.5,
                whiskerwidth=0.2,
                fillcolor=cls,
                marker_size=2,
                line_width=1)
            )
    
    fig.update_layout(
        title='',
        yaxis=dict(
            autorange=True,
            showgrid=True,
            zeroline=True,
            dtick=5,
            gridcolor='rgb(243, 243, 243)',
            gridwidth=1,
            zerolinecolor='rgb(243, 243, 243)',
            zerolinewidth=2,
            tickfont=dict(
                family='SimHei',
                size=10,
                color='black'
                ),
        ),
        margin=dict(
            l=40,
            r=30,
            b=80,
            t=100,
        ),
        paper_bgcolor='rgb(255, 255, 255)', #paper_bgcolor='rgb(243, 243, 243)'
        plot_bgcolor='rgb(255, 255, 255)',
        showlegend=False,
        
        font=dict(
            family='SimHei', #'Times New Roman'
            size=12,
            # color="#7f7f7f"
        ),
    )
    
    fig.show()

#箱型图_冠层高_B 
Example #25
Source File: parkDataVisulization.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
def boxPlot_a(df):
    x_data = ['cla_treeCanopy_perc', 'cla_grassShrub_perc','cla_bareSoil_perc', 'cla_buildings_perc', 'cla_roadsRailraods_perc','cla_water_perc', 'cla_otherPavedSurfaces_perc',]
    y_data = df[x_data].values.T    
    colors = ['rgba(44, 160, 101, 0.5)', 'rgba(255, 144, 14, 0.5)','rgba(255, 65, 54, 0.5)', 'rgba(207, 114, 255, 0.5)', 'rgba(127, 96, 0, 0.5)','rgba(93, 164, 214, 0.5)','rgba(189, 189, 189, 0.5)']
    fig = go.Figure()    
    x_data_label=["树冠覆盖层","草地/灌木层","裸地","建筑","道路/铁路","水体","其它铺设面"]
    for xd, yd, cls in zip(x_data_label, y_data, colors):
            fig.add_trace(go.Box(
                y=yd,
                name=xd,
                boxpoints='all',
                jitter=0.5,
                whiskerwidth=0.2,
                fillcolor=cls,
                marker_size=2,
                line_width=1)
            )    
    fig.update_layout(
        title='',
        yaxis=dict(
            autorange=True,
            showgrid=True,
            zeroline=True,
            dtick=5,
            gridcolor='rgb(243, 243, 243)',
            gridwidth=1,
            zerolinecolor='rgb(243, 243, 243)',
            zerolinewidth=2,
            tickfont=dict(
                family='SimHei',
                size=10,
                color='black'
                ),
        ),
        margin=dict(
            l=40,
            r=30,
            b=80,
            t=100,
        ),
        paper_bgcolor='rgb(255, 255, 255)', #paper_bgcolor='rgb(243, 243, 243)'
        plot_bgcolor='rgb(255, 255, 255)',
        showlegend=False,
        
        font=dict(
            family='SimHei', #'Times New Roman'
            size=12,
            # color="#7f7f7f"
        ),
    )    
    fig.show()

#计算百分比_冠层高 
Example #26
Source File: object.py    From DALEX with GNU General Public License v3.0 4 votes vote down vote up
def plot(self, objects=None, title="Reverse cumulative distribution of |residual|", show=False):
        """
        Plot function for ModelPerformance class.

        :param objects: object of ModelPerformance class or list or tuple containing such objects
        :param title: str, the plot's title
        :param show: True shows the plot, False returns the plotly Figure object that can be saved using `write_image()` method

        :return None or plotly Figure (see :param show)
        """

        # are there any other objects to plot?
        if objects is None:
            n = 1
            _residuals_df_list = [self.residuals.copy()]
        elif isinstance(objects, self.__class__):  # allow for objects to be a single element
            n = 2
            _residuals_df_list = [self.residuals.copy(), objects.residuals.copy()]
        else:  # objects as tuple or array
            n = len(objects) + 1
            _residuals_df_list = [self.residuals.copy()]
            for ob in objects:
                if not isinstance(ob, self.__class__):
                    raise TypeError("Some explanations aren't of ModelPerformance class")
                _residuals_df_list += [ob.residuals.copy()]

        fig = go.Figure()

        for i in range(n):
            _residuals_df = _residuals_df_list[i]
            _abs_residuals = np.abs(_residuals_df['residuals'])
            _unique_abs_residuals = np.unique(_abs_residuals)

            fig.add_scatter(
                x=_unique_abs_residuals,
                y=1 - ecdf(_abs_residuals)(_unique_abs_residuals),
                line_shape='hv',
                name=_residuals_df.iloc[0, _residuals_df.columns.get_loc('label')]
            )

        fig.update_yaxes({'type': 'linear', 'gridwidth': 2, 'zeroline': False, 'automargin': True, 'ticks': 'outside',
                          'tickcolor': 'white', 'ticklen': 10, 'fixedrange': True, 'tickformat': ',.0%'})

        fig.update_xaxes({'type': 'linear', 'gridwidth': 2, 'zeroline': False, 'automargin': True, 'ticks': "outside",
                          'tickcolor': 'white', 'ticklen': 10, 'fixedrange': True, 'title_text': '|residual|'})

        fig.update_layout(title_text=title, title_x=0.15, font={'color': "#371ea3"}, template="none",
                          margin={'t': 78, 'b': 71, 'r': 30})

        if show:
            fig.show(config={'displaylogo': False, 'staticPlot': False,
                             'modeBarButtonsToRemove': ['sendDataToCloud', 'lasso2d', 'autoScale2d', 'select2d',
                                                        'zoom2d',
                                                        'pan2d', 'zoomIn2d', 'zoomOut2d', 'resetScale2d',
                                                        'toggleSpikelines', 'hoverCompareCartesian',
                                                        'hoverClosestCartesian']})
        else:
            return fig 
Example #27
Source File: visualization.py    From AeroSandbox with MIT License 4 votes vote down vote up
def spy(
        matrix,
        show=True,
):
    """
    Plots the sparsity pattern of a matrix.
    :param matrix: The matrix to plot the sparsity pattern of. [2D ndarray or CasADi array]
    :param show: Whether or not to show the sparsity plot. [boolean]
    :return: The figure to be plotted [go.Figure]
    """
    try:
        matrix = matrix.toarray()
    except:
        pass
    abs_m = np.abs(matrix)
    sparsity_pattern = abs_m >= 1e-16
    matrix[sparsity_pattern] = np.log10(abs_m[sparsity_pattern] + 1e-16)
    j_index_map, i_index_map = np.meshgrid(np.arange(matrix.shape[1]), np.arange(matrix.shape[0]))

    i_index = i_index_map[sparsity_pattern]
    j_index = j_index_map[sparsity_pattern]
    val = matrix[sparsity_pattern]
    val = np.ones_like(i_index)
    fig = go.Figure(
        data=go.Heatmap(
            y=i_index,
            x=j_index,
            z=val,
            # type='heatmap',
            colorscale='RdBu',
            showscale=False,
        ),
    )
    fig.update_layout(
        plot_bgcolor="black",
        xaxis=dict(showgrid=False, zeroline=False),
        yaxis=dict(showgrid=False, zeroline=False, autorange="reversed", scaleanchor="x", scaleratio=1),
        width=800,
        height=800 * (matrix.shape[0] / matrix.shape[1]),
    )
    if show:
        fig.show()
    return fig 
Example #28
Source File: strideGraph.py    From nanoBench with GNU Affero General Public License v3.0 4 votes vote down vote up
def main():
   parser = argparse.ArgumentParser(description='Generates a graph obtained by sweeping over a memory area repeatedly with a given stride')
   parser.add_argument("-stride", help="Stride (in bytes) (Default: 64)", type=int, default=64)
   parser.add_argument("-startSize", help="Start size of the memory area (in kB) (Default: 4)", type=int, default=4)
   parser.add_argument("-endSize", help="End size of the memory area (in kB) (Default: 32768)", type=int, default=32768)
   parser.add_argument("-loop", help="Loop count (Default: 100)", type=int, default=100)
   parser.add_argument("-output", help="Output file name", default='strideGraph.html')
   args = parser.parse_args()

   resetNanoBench()
   setNanoBenchParameters(config=getDefaultCacheConfig(), nMeasurements=1, warmUpCount=0, unrollCount=1, loopCount=args.loop, basicMode=False, noMem=True)

   nbDicts = []
   xValues = []
   nAddresses = []
   tickvals = []

   pt = args.startSize*1024
   while pt <= args.endSize*1024:
      tickvals.append(pt)
      for x in ([int(math.pow(2, math.log(pt, 2) + i/16.0)) for i in range(0,16)] if pt < args.endSize*1024 else [pt]):
         print x/1024
         xValues.append(str(x))
         addresses = range(0, x, args.stride)
         nAddresses.append(len(addresses))
         ec = getCodeForAddressLists([AddressList(addresses, False, False, False)], wbinvd=True)
         nbDicts.append(runNanoBench(code=ec.code, init=ec.init, oneTimeInit=ec.oneTimeInit))
      pt *= 2

   title = cpuid.cpu_name(cpuid.CPUID())
   html = ['<html>', '<head>', '<title>' + title + '</title>', '<script src="https://cdn.plot.ly/plotly-latest.min.js">', '</script>', '</head>', '<body>']
   html += ['<h3>' + title + '</h3>']

   for evtType in ['Core cycles', 'APERF', 'HIT', 'MISS']:
      if not any(e for e in nbDicts[0].keys() if evtType in e): continue

      fig = go.Figure()
      fig.update_layout(showlegend=True)
      fig.update_xaxes(title_text='Size (in kB)', type='category', tickvals=tickvals, ticktext=[x/1024 for x in tickvals])

      for event in sorted(e for e in nbDicts[0].keys() if evtType in e):
         yValues = [nb[event]/nAddr for nb, nAddr in zip(nbDicts, nAddresses)]
         fig.add_trace(go.Scatter(x=xValues, y=yValues, mode='lines+markers', name=event))

      html.append(plot(fig, include_plotlyjs=False, output_type='div'))

   html += ['</body>', '</html>']

   with open(args.output ,'w') as f:
      f.write('\n'.join(html))
      print 'Graph written to ' + args.output 
Example #29
Source File: plotly.py    From dynamicslearn with MIT License 4 votes vote down vote up
def plot_rollout(states, actions, pry=[1, 2, 0], save=False, loc=None):
    import plotly.graph_objects as go
    import numpy as np
    import plotly
    ar = np.stack(states)
    l = np.shape(ar)[0]
    xs = np.arange(l)

    yaw = np.degrees(ar[:, pry[2]])
    pitch = np.degrees(ar[:, pry[0]])
    roll = np.degrees(ar[:, pry[1]])

    actions = np.stack(actions)

    fig = plotly.subplots.make_subplots(rows=2, cols=1,
                                        subplot_titles=("Euler Angles", "Actions"),
                                        vertical_spacing=.15)  # go.Figure()
    fig.add_trace(go.Scatter(x=xs, y=yaw, name='Yaw',
                             line=dict(color='firebrick', width=4)), row=1, col=1)
    fig.add_trace(go.Scatter(x=xs, y=pitch, name='Pitch',
                             line=dict(color='royalblue', width=4)), row=1, col=1)
    fig.add_trace(go.Scatter(x=xs, y=roll, name='Roll',
                             line=dict(color='green', width=4)), row=1, col=1)

    fig.add_trace(go.Scatter(x=xs, y=actions[:, 0], name='M1',
                             line=dict(color='firebrick', width=4)), row=2, col=1)
    fig.add_trace(go.Scatter(x=xs, y=actions[:, 1], name='M2',
                             line=dict(color='royalblue', width=4)), row=2, col=1)
    fig.add_trace(go.Scatter(x=xs, y=actions[:, 2], name='M3',
                             line=dict(color='green', width=4)), row=2, col=1)
    fig.add_trace(go.Scatter(x=xs, y=actions[:, 3], name='M4',
                             line=dict(color='orange', width=4)), row=2, col=1)

    fig.update_layout(title='Euler Angles from MPC Rollout',
                      xaxis_title='Timestep',
                      yaxis_title='Angle (Degrees)',
                      plot_bgcolor='white',
                      xaxis=dict(
                          showline=True,
                          showgrid=False,
                          showticklabels=True, ),
                      yaxis=dict(
                          showline=True,
                          showgrid=False,
                          showticklabels=True, ),
                      )
    if save:
        fig.write_image(os.getcwd() + loc + "_rollout.png")
    else:
        fig.show() 
Example #30
Source File: results.py    From ross with MIT License 4 votes vote down vote up
def plot(self, plot_type="3d", dof=None, node=None, fig=None, **kwargs):
        """Plot time response.

        The plot type options are:
            - 1d: plot time response for a given degree of freedom of a rotor system.
            - 2d: plot orbit of a selected node of a rotor system.
            - 3d: plot orbits for each node on the rotor system in a 3D view.

        Parameters
        ----------
        plot_type: str
            String to select the plot type.
            - "1d": plot time response for a given degree of freedom of a rotor system.
            - "2d": plot orbit of a selected node of a rotor system.
            - "3d": plot orbits for each node on the rotor system in a 3D view.
            Default is 3d.
        dof : int
            Degree of freedom that will be observed.
            Fill this attribute only when selection plot_type = "1d".
            Default is None.
        node: int, optional
            Selected node to plot orbit.
            Fill this attribute only when selection plot_type = "2d".
            Default is None
        fig : Plotly graph_objects.Figure()
            The figure object with the plot.
        kwargs : optional
            Additional key word arguments can be passed to change the plot layout only
            (e.g. width=1000, height=800, ...).
            *See Plotly Python Figure Reference for more information.

        Raises
        ------
        ValueError
            Error raised if a non valid string is passed to plot_type.
        ValueError
            Error raised if no node is specified or an odd node is passed
            when plot_type = "2d".
        ValueError
            Error raised if no dof is specified or an odd dof is passed
            when plot_type = "1d".

        Returns
        -------
        fig : Plotly graph_objects.Figure()
            The figure object with the plot.
        """
        if plot_type == "3d":
            return self._plot3d(**kwargs)
        elif plot_type == "2d":
            if node is None:
                raise Exception("Select a node to plot orbit when plot_type '2d'")
            elif node not in self.nodes_list:
                raise Exception("Select a valid node to plot 2D orbit")
            return self._plot2d(node=node, **kwargs)
        elif plot_type == "1d":
            if dof is None:
                raise Exception("Select a dof to plot orbit when plot_type == '1d'")
            return self._plot1d(dof=dof, **kwargs)
        else:
            raise ValueError(f"{plot_type} is not a valid plot type.")