Python matplotlib.pyplot.gca() Examples

The following are code examples for showing how to use matplotlib.pyplot.gca(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: b2ac   Author: hbldh   File: point.py    MIT License 6 votes vote down vote up
def mpl_patch_arguments(self):
        """Returns Matplotlib Patch arguments. Can then be plotted by with following
        snippet:

        .. code-block:: python

            import matplotlib.pyplot as plt
            from matplotlib.patches import Point
            from b2ac.geometry.point import B2ACPoint

            p = B2ACPoint((3.0, 5.0))
            plt.gca().add_patch(Point(p.mpl_patch_arguments, color='g'))
            plt.show()

        """
        return self.point, 
Example 2
Project: b2ac   Author: hbldh   File: polygon.py    MIT License 6 votes vote down vote up
def mpl_patch_arguments(self):
        """Returns Matplotlib patch arguments. Can then be plotted by with following
        snippet:

        .. code-block:: python

            import matplotlib.pyplot as plt
            from matplotlib.patches import Polygon
            from b2ac.geometry.polygon import B2ACPolygon

            p = B2ACPolygon([(2.1, 1.2), (5.2, 2.4), (1.0, 0.2)])
            plt.gca().add_patch(Polygon(
                p.mpl_patch_arguments, closed=True, fill=False, edgecolor='r')
            plt.show()

        """
        return self.polygon_points, 
Example 3
Project: b2ac   Author: hbldh   File: ellipse.py    MIT License 6 votes vote down vote up
def mpl_patch_arguments(self):
        """Returns Matplotlib patch arguments. Can then be plotted by with following
        snippet:

        .. code-block:: python

            import matplotlib.pyplot as plt
            from matplotlib.patches import Ellipse
            from b2ac.ellipse import B2ACEllipse

            e = B2ACEllipse((3.0, 5.0), (2.0, 6.0, 1.57))
            plt.gca().add_patch(Ellipse(
                e.mpl_patch_arguments, fill=False, edgecolor='g'))
            plt.show()

        """
        return self.center_point, self.radii[0] * 2, self.radii[1] * 2, np.rad2deg(self.rotation_angle) 
Example 4
Project: nn_framework   Author: brohrer   File: framework.py    MIT License 6 votes vote down vote up
def report(self):
        n_bins = int(len(self.error_history) // self.reporting_bin_size)
        smoothed_history = []
        for i_bin in range(n_bins):
            smoothed_history.append(np.mean(self.error_history[
                i_bin * self.reporting_bin_size:
                (i_bin + 1) * self.reporting_bin_size
            ]))
        error_history = np.log10(np.array(smoothed_history) + 1e-10)
        ymin = np.minimum(self.report_min, np.min(error_history))
        ymax = np.maximum(self.report_max, np.max(error_history))
        fig = plt.figure()
        ax = plt.gca()
        ax.plot(error_history)
        ax.set_xlabel(f"x{self.reporting_bin_size} iterations")
        ax.set_ylabel("log error")
        ax.set_ylim(ymin, ymax)
        ax.grid()
        fig.savefig(os.path.join(self.reports_path, self.report_name))
        plt.close() 
Example 5
Project: Deformable-ConvNets   Author: guanfuchen   File: show_boxes.py    MIT License 6 votes vote down vote up
def show_boxes(im, dets, classes, scale = 1.0):
    plt.cla()
    plt.axis("off")
    plt.imshow(im)
    for cls_idx, cls_name in enumerate(classes):
        cls_dets = dets[cls_idx]
        for det in cls_dets:
            bbox = det[:4] * scale
            color = (rand(), rand(), rand())
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                  bbox[2] - bbox[0],
                                  bbox[3] - bbox[1], fill=False,
                                  edgecolor=color, linewidth=2.5)
            plt.gca().add_patch(rect)

            if cls_dets.shape[1] == 5:
                score = det[-1]
                plt.gca().text(bbox[0], bbox[1],
                               '{:s} {:.3f}'.format(cls_name, score),
                               bbox=dict(facecolor=color, alpha=0.5), fontsize=9, color='white')
    plt.show()
    return im 
Example 6
Project: pyhanlp   Author: hankcs   File: plot_name.py    Apache License 2.0 6 votes vote down vote up
def newline(p1, p2, color=None, marker=None):
    """
    https://stackoverflow.com/questions/36470343/how-to-draw-a-line-with-matplotlib
    :param p1:
    :param p2:
    :return:
    """
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if (p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1] + (p2[1] - p1[1]) / (p2[0] - p1[0]) * (xmax - p1[0])
        ymin = p1[1] + (p2[1] - p1[1]) / (p2[0] - p1[0]) * (xmin - p1[0])

    l = mlines.Line2D([xmin, xmax], [ymin, ymax], color=color, marker=marker)
    ax.add_line(l)
    return l 
Example 7
Project: ml-eeg   Author: pbrusco   File: visualizations.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_epochs_average(data, y_lim, tmin, window, freq, marks=[], ax=None, color="red", label="epochs mean"):
    # Data shape: (samples, trial)
    if not ax:
        ax = plt.gca()

    t0, tf = window
    t0_frame = signal_processing.frame_at(t0, freq, tmin)
    tf_frame = signal_processing.frame_at(tf, freq, tmin)

    samples = data.shape[0]

    for epoch_id in range(0, data.shape[1]):
        c_plt, = ax.plot([t0 + (s / freq) for s in range(0, samples)], data[:, epoch_id], color=color, alpha=0.05)

    epochs_mean = data[t0_frame:tf_frame, :].mean(1)

    c2_plt, = ax.plot([t0 + (s / freq) for s in range(0, samples)], epochs_mean, color=color, linewidth=2.0, label=label)
    set_plot(plt, y_lim, window, t0, tf, marks, ax)
    draw_rectangle(plt, window, ax, label=None) 
Example 8
Project: ml-eeg   Author: pbrusco   File: visualizations.py    GNU General Public License v3.0 6 votes vote down vote up
def draw_rectangle(plt, window, ax=None, label="stimulus"):
    if not ax:
        ax = plt.gca()
    rect = patches.Rectangle((window[0], -40), width=-window[0] - 0.4, height=80,
                             color='grey',
                             alpha=0.5)
    ax.add_patch(rect)

    rect = patches.Rectangle((0, -40), width=window[1], height=80,
                             color='grey',
                             alpha=0.5)
    ax.add_patch(rect)

    rect = patches.Rectangle((-0.4, -40), width=0.4, height=80,
                             fill=None, edgecolor="black", label=label)
    ax.add_patch(rect)
    return rect 
Example 9
Project: quadcopter-simulation   Author: hbd730   File: quadPlot.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_frame(frame):
    # convert 3x6 world_frame matrix into three line_data objects which is 3x2 (row:point index, column:x,y,z)
    lines_data = [frame[:,[0,2]], frame[:,[1,3]], frame[:,[4,5]]]
    ax = plt.gca()
    lines = ax.get_lines()
    for line, line_data in zip(lines[:3], lines_data):
        x, y, z = line_data
        line.set_data(x, y)
        line.set_3d_properties(z)

    global history, count
    # plot history trajectory
    history[count] = frame[:,4]
    if count < np.size(history, 0) - 1:
        count += 1
    zline = history[:count,-1]
    xline = history[:count,0]
    yline = history[:count,1]
    lines[-1].set_data(xline, yline)
    lines[-1].set_3d_properties(zline)
    # ax.plot3D(xline, yline, zline, 'blue') 
Example 10
Project: bayesian_tree   Author: UBS-IB   File: helper.py    Apache License 2.0 6 votes vote down vote up
def plot_1d_perpendicular(root, X_train, y_train, info_train, X_test, y_test, info_test):
    plt.figure(figsize=[10, 16], dpi=75)
    plt.subplot(211)
    plt.plot(X_train[:, 0], y_train, 'o-')
    plt.title(info_train)
    draw_node_1d_perpendicular(root, bounds=(X_train[:, 0].min(), X_train[:, 0].max()))
    plt.xlabel('x0')
    plt.ylabel('x1')
    plt.legend()
    plt.gca().set_aspect(1)

    plt.subplot(212)
    plt.plot(X_test[:, 0], y_test, 'o-')
    draw_node_1d_perpendicular(root, bounds=(X_test[:, 0].min(), X_test[:, 0].max()))
    plt.title(info_test)
    plt.xlabel('x0')
    plt.ylabel('x1')
    plt.legend()
    plt.gca().set_aspect(1)

    plt.show() 
Example 11
Project: EarlyWarning   Author: wjlei1990   File: generate_measurements.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_arrival_window(trace, windows, origin_time):
    plt.plot(trace.data)
    ax = plt.gca()
    ymin, ymax = ax.get_ylim()

    idx = (UTCDateTime(windows["pick_arrival"]) - trace.stats.starttime) / \
        trace.stats.delta
    plt.vlines([idx], ymin, ymax, linestyles="dotted", color='r')

    idx = (UTCDateTime(windows["theo_arrival"]) - trace.stats.starttime) / \
        trace.stats.delta
    plt.vlines([idx], ymin, ymax, linestyles="dotted", color='b')

    idx = (origin_time - trace.stats.starttime) / \
        trace.stats.delta
    plt.vlines([idx], ymin, ymax, linestyles="dotted", color='b')

    plt.show() 
Example 12
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 6 votes vote down vote up
def plot_ball_trajectory(var, filename, idx=0, scale=30, cmap='Blues'):
    # Calc optimal radius of ball
    x_min, y_min = np.min(var[:, :, :2], axis=(0, 1))
    x_max, y_max = np.max(var[:, :, :2], axis=(0, 1))
    r = max((x_max - x_min), (y_max - y_min)) / scale

    fig = plt.figure(figsize=[4, 4])
    ax = fig.gca()
    collection = construct_ball_trajectory(var[idx], r=1, cmap=cmap)
    ax.add_collection(collection)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.axis("equal")
    ax.set_xlabel('$a_{t,1}$', fontsize=24)
    ax.set_ylabel('$a_{t,2}$', fontsize=24)

    plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
    plt.close() 
Example 13
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 6 votes vote down vote up
def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w) / max_weight)
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis() 
Example 14
Project: pytorch-lstd   Author: JiasiWang   File: eval.py    MIT License 6 votes vote down vote up
def vis(im, index, dets, w, h, thresh=0.0):
    import numpy as np
    import matplotlib.pyplot as plt
    npimg = im.cpu().numpy()
    npimg = (npimg + 128)/255
    im = np.transpose(npimg, (1, 2, 0))
    plt.cla()
    plt.imshow(im)
    #print(bbox) 
    for i in range(np.minimum(10, dets.shape[0])):
        bbox = dets[i, :4]
        score = dets[i, -1]
        if score > thresh:
            plt.gca().add_patch(
                plt.Rectangle((bbox[0]*300/w, bbox[1]*300/h),
                              (bbox[2] - bbox[0])*300/w,
                              (bbox[3] - bbox[1])*300/h, fill=False,
                              edgecolor='g', linewidth=3)
                )
    plt.show() 
Example 15
Project: striatum   Author: ntucllab   File: simulation.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot_tuning_curve(tuning_region, ctr_tuning, label):
    """Draw the parameter tuning plot

    Parameters
    ----------
    tuning_region: array
        The region for tuning parameter.

    ctr_tuning: array
        The resulted ctrs for each number of the tuning parameter.

    label: string
        The name of label want to show.
    """

    plt.plot(tuning_region, ctr_tuning, 'ro-', label=label)
    plt.xlabel('parameter value')
    plt.ylabel('CTR')
    plt.legend()
    axes = plt.gca()
    axes.set_ylim([0, 1])
    plt.title("Parameter Tunning Curve")
    plt.show() 
Example 16
Project: striatum   Author: ntucllab   File: movielens_bandit.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    streaming_batch, user_feature, actions, reward_list, action_context = get_data()
    streaming_batch_small = streaming_batch.iloc[0:10000]

    # conduct regret analyses
    experiment_bandit = ['LinUCB', 'LinThompSamp', 'Exp4P', 'UCB1', 'Exp3', 'random']
    regret = {}
    col = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
    i = 0
    for bandit in experiment_bandit:
        policy = policy_generation(bandit, actions)
        seq_error = policy_evaluation(policy, bandit, streaming_batch_small, user_feature, reward_list,
                                      actions, action_context)
        regret[bandit] = regret_calculation(seq_error)
        plt.plot(range(len(streaming_batch_small)), regret[bandit], c=col[i], ls='-', label=bandit)
        plt.xlabel('time')
        plt.ylabel('regret')
        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        axes = plt.gca()
        axes.set_ylim([0, 1])
        plt.title("Regret Bound with respect to T")
        i += 1
    plt.show() 
Example 17
Project: radiometric_normalization   Author: planetlabs   File: display.py    Apache License 2.0 6 votes vote down vote up
def plot_pixels(file_name, candidate_data_single_band,
                reference_data_single_band, limits=None, fit_line=None):

    logging.info('Display: Creating pixel plot - {}'.format(file_name))
    fig = plt.figure()
    plt.hexbin(
        candidate_data_single_band, reference_data_single_band, mincnt=1)
    if not limits:
        min_value = 0
        _, ymax = plt.gca().get_ylim()
        _, xmax = plt.gca().get_xlim()
        max_value = max([ymax, xmax])
        limits = [min_value, max_value]
    plt.plot(limits, limits, 'k-')
    if fit_line:
        start = limits[0] * fit_line.gain + fit_line.offset
        end = limits[1] * fit_line.gain + fit_line.offset
        plt.plot(limits, [start, end], 'g-')
    plt.xlim(limits)
    plt.ylim(limits)
    plt.xlabel('Candidate DNs')
    plt.ylabel('Reference DNs')
    fig.savefig(file_name, bbox_inches='tight')
    plt.close(fig) 
Example 18
Project: reinforcement-learning-exercises   Author: NickCellino   File: blackjack.py    MIT License 6 votes vote down vote up
def plot_policy(policy, title='Blackjack Policy', figure=1):
        policy = np.transpose(policy)
        fig = plt.figure(figure)
        ax = fig.subplots()
        fig.suptitle(title)
        plt.imshow(policy, cmap='jet')
        plt.gca().invert_yaxis()

        plt.xlabel('Dealer showing')
        plt.xticks(np.arange(0, len(BlackjackStates.DEALER_CARDS), 1))
        ax.set_xticklabels(BlackjackStates.DEALER_CARDS)

        plt.ylabel('Agent sum')
        plt.yticks(np.arange(0, len(BlackjackStates.AGENT_SUMS), 1))
        ax.set_yticklabels(BlackjackStates.AGENT_SUMS)

        for i in range(policy.shape[0]):
            for j in range(policy.shape[1]):
                if policy[i, j] == Blackjack.HIT_ACTION:
                    label = 'HIT'
                else:
                    label = 'STAY'
                plt.text(j, i, f'{label}', horizontalalignment='center', verticalalignment='center') 
Example 19
Project: reinforcement-learning-exercises   Author: NickCellino   File: car_rentals.py    MIT License 6 votes vote down vote up
def plot_policies(self, policies, starting_fig=1):
        figure = starting_fig
        for i in range(len(policies)):
            fig = plt.figure(figure)
            figure += 1
            policy = policies[i]
            plt.imshow(policy, cmap='jet')
            plt.ylabel('# of Cars at Dealership A')
            plt.xlabel('# of Cars at Dealership B')
            plt.xticks(np.arange(0, policy.shape[0], 1))
            plt.yticks(np.arange(0, policy.shape[1], 1))
            plt.gca().invert_yaxis()
            if i == (len(policies) - 1):
                fig.suptitle('Optimal Policy')
            else:
                fig.suptitle(f'Policy {i}')

            # Annotate states
            for i in range(policy.shape[0]):
                for j in range(policy.shape[1]):
                    plt.text(j, i, '%d' % policy[i,j], horizontalalignment='center', verticalalignment='center')

            plt.colorbar() 
Example 20
Project: carla_py   Author: IamWangYunKai   File: draw_trajectory.py    MIT License 6 votes vote down vote up
def draw_trajectory(points):
    x = []
    y = []
    for point in points:
        x.append(point.x)
        y.append(point.y)
        
    fig = plt.figure(figsize=(5,5))
    ax = plt.gca()
    ax.set_title('Trajectory of Dataset')
    ax.set_xlabel('x/m')
    ax.set_ylabel('y/m')
    plt.xlim(-185, 285)
    plt.ylim(-235, 235)
    plt.plot(points[0].x, points[0].y, 'ro', alpha=0.8, label="start")
    plt.plot(points[-1].x, points[-1].y, 'go', alpha=0.8, label="end")
    plt.plot(x,y,"b-",linewidth=1, alpha=0.8, label="trajectory")
    plt.legend(loc='best')
    plt.show()
    fig.savefig('trajectory.pdf', bbox_inches='tight')
    plt.close(fig) 
Example 21
Project: sfcc   Author: kv-kunalvyas   File: auxiliary.py    MIT License 5 votes vote down vote up
def plotLearningCurves(train, classifier):
    #P.show()
    X = train.values[:, 1::]
    y = train.values[:, 0]

    train_sizes, train_scores, test_scores = learning_curve(
            classifier, X, y, cv=10, n_jobs=-1, train_sizes=np.linspace(.1, 1., 10), verbose=0)

    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)

    plt.figure()
    plt.title("Learning Curves")
    plt.legend(loc="best")
    plt.xlabel("Training samples")
    plt.ylabel("Error Rate")
    plt.ylim((0, 1))
    plt.gca().invert_yaxis()
    plt.grid()

    # Plot the average training and test score lines at each training set size
    plt.plot(train_sizes, train_scores_mean, 'o-', color="b", label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="r", label="Test score")

    # Plot the std deviation as a transparent range at each training set size
    plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,
                     alpha=0.1, color="b")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
                     alpha=0.1, color="r")

    # Draw the plot and reset the y-axis
    plt.draw()
    plt.gca().invert_yaxis()

    # shuffle and split training and test sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25)
    classifier.fit(X_train, y_train)
    plt.show() 
Example 22
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: vis.py    Apache License 2.0 5 votes vote down vote up
def vis_detection(im_orig, detections, class_names, thresh=0.7):
    """visualize [cls, conf, x1, y1, x2, y2]"""
    import matplotlib.pyplot as plt
    import random
    plt.imshow(im_orig)
    colors = [(random.random(), random.random(), random.random()) for _ in class_names]
    for [cls, conf, x1, y1, x2, y2] in detections:
        cls = int(cls)
        if cls > 0 and conf > thresh:
            rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
                                 fill=False, edgecolor=colors[cls], linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(x1, y1 - 2, '{:s} {:.3f}'.format(class_names[cls], conf),
                           bbox=dict(facecolor=colors[cls], alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 23
Project: helloworld   Author: pip-uninstaller-python   File: matplotlibTest.py    GNU General Public License v2.0 5 votes vote down vote up
def main():
    # line
    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    c, s = np.cos(x), np.sin(x)
    plt.figure(1)
    plt.plot(x, c, color="blue", linewidth=1.0, linestyle="-", label="COS", alpha=0.5)  # 自变量, 因变量
    plt.plot(x, s, "r.", label="SIN")  # 正弦  "-"/"r-"/"r."
    plt.title("COS & SIN")
    ax = plt.gca()
    ax.spines["right"].set_color("none")
    ax.spines["top"].set_color("none")
    ax.spines["left"].set_position(("data", 0))  # 横轴位置
    ax.spines["bottom"].set_position(("data", 0))  # 纵轴位置
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("left")
    plt.xticks([-np.pi, -np.pi / 2.0, np.pi / 2, np.pi],
               [r'$-\pi/2$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$-\pi$'])
    plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(16)
        label.set_bbox(dict(facecolor="white", edgecolor="None", alpha=0.2))
    plt.legend(loc="upper left")  # 左上角的显示图标
    plt.grid()  # 网格线
    # plt.axis([-1, 1, -0.5, 1])  # 显示范围
    plt.fill_between(x, np.abs(x) < 0.5, c, c < 0.5, color="green", alpha=0.25)
    t = 1
    plt.plot([t, t], [0, np.cos(t)], "y", linewidth=3, linestyle="--")
    # 注释
    plt.annotate("cos(1)", xy=(t, np.cos(1)), xycoords="data", xytext=(+10, +30),
                 textcoords="offset points", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.2"))
    plt.show()


# Scatter --> 散点图 
Example 24
Project: gullikson-scripts   Author: kgullikson88   File: bayesian.py    MIT License 5 votes vote down vote up
def plot_samples(self, x, N=100, ax=None, highest=False, *plot_args, **plot_kws):
        """
        Plot sample curves.

        Parameters:
        ===========
        - x:         numpy.ndarray
                     The x-values to plot at

        - N:         integer
                     The number of samples to take

        - highest:   boolean
                     If True, use the N most probable samples.
                     Otherwise, just take N random samples.

        - ax:        matplotlib axis object
                     The axis to plot the curves on. A new figure will be made if no axis is given.

        Returns:
        =========
        matplotlib axis object, with which to plot other stuff, labels, etc
        """

        y = self.predict(x, N=N)
        if ax is None:
            ax = plt.gca()

        for i in range(N):
            ax.plot(x, y[i], *plot_args, **plot_kws)

        return ax 
Example 25
Project: DiscEvolution   Author: rbooth200   File: plot_R-t.py    GNU General Public License v3.0 5 votes vote down vote up
def pcolor_plot(x,y,z, **kwargs):
    ax = plt.gca()
    plt.pcolormesh(x,y,z, **kwargs)
    ax.format_coord = Formatter(x,y,z) 
Example 26
Project: relay-bench   Author: uwsampl   File: plot_util.py    Apache License 2.0 5 votes vote down vote up
def ax(self):
        return plt.gca() 
Example 27
Project: Parallel.GAMIT   Author: demiangomez   File: test_voronoi.py    GNU General Public License v3.0 5 votes vote down vote up
def set_axes_equal(ax):
    '''Make axes of 3D plot have equal scale so that spheres appear as spheres,
    cubes as cubes, etc..  This is one possible solution to Matplotlib's
    ax.set_aspect('equal') and ax.axis('equal') not working for 3D.

    Input
      ax: a matplotlib axis, e.g., as output from plt.gca().
    '''

    x_limits = ax.get_xlim3d()
    y_limits = ax.get_ylim3d()
    z_limits = ax.get_zlim3d()

    x_range = abs(x_limits[1] - x_limits[0])
    x_middle = np.mean(x_limits)
    y_range = abs(y_limits[1] - y_limits[0])
    y_middle = np.mean(y_limits)
    z_range = abs(z_limits[1] - z_limits[0])
    z_middle = np.mean(z_limits)

    # The plot bounding box is a sphere in the sense of the infinity
    # norm, hence I call half the max range the plot radius.
    plot_radius = 0.5*max([x_range, y_range, z_range])

    ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])
    ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])
    ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius]) 
Example 28
Project: Parallel.GAMIT   Author: demiangomez   File: test_voronoi.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_clusters(data, algorithm, args, kwds):
    start_time = time.time()
    labels = algorithm(*args, **kwds).fit_predict(data)
    end_time = time.time()
    palette = sns.color_palette('deep', np.unique(labels).max() + 1)
    colors = [palette[x] if x >= 0 else (0.0, 0.0, 0.0) for x in labels]
    plt.scatter(data.T[0], data.T[1], c=colors, **plot_kwds)
    frame = plt.gca()
    frame.axes.get_xaxis().set_visible(False)
    frame.axes.get_yaxis().set_visible(False)
    plt.title('Clusters found by {}'.format(str(algorithm.__name__)), fontsize=24)
    plt.text(-0.5, 0.7, 'Clustering took {:.2f} s'.format(end_time - start_time), fontsize=14) 
Example 29
Project: SNN   Author: arnogranier   File: compare_times.py    MIT License 5 votes vote down vote up
def stuff_on_all_graph():
        """Things that will alway be used for those plots"""
        plt.gca().grid()
        plt.xscale('log')
        plt.xlabel('Number of synapses')

    # Get computation times 
Example 30
Project: SLiPy   Author: glentner   File: lasso_plot.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, xs, ys):
        self.axes = gca()
        self.canvas = self.axes.figure.canvas
        self.xys = array([xs,ys]).T#[d for d in zip(xs,ys)]
        fig = self.axes.figure
        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
        self.ind = None
        self.mask = None
        self.verts = None 
Example 31
Project: SLiPy   Author: glentner   File: Plot.py    GNU General Public License v2.0 5 votes vote down vote up
def xoffset(self, value):
        """
        Toggle the offset for the x axis
        """
        plt.gca().get_xaxis().get_major_formatter().set_useOffset(value) 
Example 32
Project: SLiPy   Author: glentner   File: Plot.py    GNU General Public License v2.0 5 votes vote down vote up
def yoffset(self, value):
        """
        Toggle the offset for the y axis
        """
        plt.gca().get_yaxis().get_major_formatter().set_useOffset(value) 
Example 33
Project: Deformable-ConvNets   Author: guanfuchen   File: tester.py    MIT License 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale, cfg, threshold=1e-3):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, cfg.network.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            if score < threshold:
                continue
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 34
Project: Deformable-ConvNets   Author: guanfuchen   File: show_offset.py    MIT License 5 votes vote down vote up
def show_boxes_simple(bbox, color='r', lw=2):
    rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False, edgecolor=color, linewidth=lw)
    plt.gca().add_patch(rect) 
Example 35
Project: Deformable-ConvNets   Author: guanfuchen   File: tester.py    MIT License 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale, cfg, threshold=1e-3):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, cfg.network.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            if score < threshold:
                continue
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 36
Project: pyCEST   Author: pganssle   File: cjlib.py    MIT License 5 votes vote down vote up
def roipoly():
    XY = ginput(-1)

    blah1, blah2, ncols, nrows = gca().dataLim.bounds

    mask = array([ pnpoly(i,j,XY) for i in range(nrows) for j in range(ncols)  ]).reshape(ncols,nrows)

    return mask 
Example 37
Project: pyCEST   Author: pganssle   File: cjlib.py    MIT License 5 votes vote down vote up
def roipolyXY():
    XY = ginput(-1)

    blah1, blah2, ncols, nrows = gca().dataLim.bounds
    
    nrows, ncols = int(nrows), int(ncols)
    
    mask = array([ pnpoly(j,i,XY) for i in range(nrows) for j in range(ncols)  ]).reshape(ncols,nrows)

    return XY,mask 
Example 38
Project: pyCEST   Author: pganssle   File: cjlib.py    MIT License 5 votes vote down vote up
def vimage(d):
    """ Very slow at this point """

    mimage(d[:,:,1])
    main_ax = gca()
    
    axslice  = axes([0.1, 0.1, 0.8, 0.05])
    axis('off')
    slice_slider = Slider(axslice, 'Slice', 1, d.shape[2], valinit=1)

    def update(val):
        axes(main_ax)
        mimage(d[:,:,int(slice_slider.val)])

    slice_slider.on_changed(update) 
Example 39
Project: pyCEST   Author: pganssle   File: cjlib.py    MIT License 5 votes vote down vote up
def mimage(d, cmap=gray):
    imshow( d )
    axis('image') # needed so that ginput doesn't resize the image
    clim([ prctile(d,1) , prctile(d, 99) ])
    xticks([])
    yticks([])
#    gca().get_axes().set_position([0,0,1,1]) #commented out by ny temporarily 
Example 40
Project: pyCEST   Author: pganssle   File: cjlib.py    MIT License 5 votes vote down vote up
def plotcest( freq, data ):

    plot( freq, data )
    xlabel('Frequency Offset from Water (ppm)')
    ylabel('Relative Signal (%)')
    grid('on')
    xl = gca().get_xlim()
    if xl[0] < xl[-1]:
        gca().set_xlim( xl[::-1] )

##==============================================================================
##
##  Fitting
##
##============================================================================== 
Example 41
Project: xia2   Author: xia2   File: MultiCrystalAnalysis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unit_cell_clustering(experiments, threshold, log=True, plot_name=None):
        from dials.algorithms.clustering.unit_cell import UnitCellCluster

        crystal_symmetries = []
        for expt in experiments:
            crystal_symmetry = expt.crystal.get_crystal_symmetry(
                assert_is_compatible_unit_cell=False
            )
            crystal_symmetries.append(crystal_symmetry.niggli_cell())
        lattice_ids = [expt.identifier for expt in experiments]
        ucs = UnitCellCluster.from_crystal_symmetries(
            crystal_symmetries, lattice_ids=lattice_ids
        )
        if plot_name is not None:
            import matplotlib

            matplotlib.use("Agg")
            from matplotlib import pyplot as plt

            plt.figure("Andrews-Bernstein distance dendogram", figsize=(12, 8))
            ax = plt.gca()
        else:
            ax = None
        clusters, dendrogram, _ = ucs.ab_cluster(
            threshold,
            log=log,
            labels="lattice_id",
            write_file_lists=False,
            schnell=False,
            doplot=(plot_name is not None),
            ax=ax,
        )
        if plot_name is not None:
            plt.tight_layout()
            plt.savefig(plot_name)
            plt.clf()
        return clusters, dendrogram 
Example 42
Project: torchtrainers   Author: NVlabs   File: trainer.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot(self, axis=None, **kw):
        axis = axis or plt.gca()
        if len(self.avg_losses)==0: return
        xs = [p[0] for p in self.avg_losses]
        ys = [p[1] for p in self.avg_losses]
        axis.plot(xs, ys, **kw) 
Example 43
Project: quadcopter-simulation   Author: hbd730   File: quadPlot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_waypoints(waypoints):
    ax = plt.gca()
    lines = ax.get_lines()
    lines[-2].set_data(waypoints[:,0], waypoints[:,1])
    lines[-2].set_3d_properties(waypoints[:,2]) 
Example 44
Project: quadcopter-simulation   Author: hbd730   File: quadPlot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_limit(x, y, z):
    ax = plt.gca()
    ax.set_xlim(x)
    ax.set_ylim(y)
    ax.set_zlim(z) 
Example 45
Project: bayesian_tree   Author: UBS-IB   File: helper.py    Apache License 2.0 5 votes vote down vote up
def plot_2d_perpendicular(root, X_train, y_train, info_train, X_test, y_test, info_test):
    plt.figure(figsize=[10, 16], dpi=75)

    n_classes = int(y_train.max()) + 1
    colormap = cm.gist_rainbow

    def plot(X, y, info):
        for i in range(n_classes):
            class_i = y == i
            plt.plot(X[np.where(class_i)[0], 0],
                     X[np.where(class_i)[0], 1],
                     'o',
                     ms=4,
                     c=colormap(i/n_classes),
                     label='Class {}'.format(i))

            bounds = ((X[:, 0].min(), X[:, 0].max()), (X[:, 1].min(), X[:, 1].max()))
            draw_node_2d_perpendicular(root, bounds, colormap, n_classes)
        plt.title(info)
        plt.xlabel('x0')
        plt.ylabel('x1')
        plt.legend()

    plt.subplot(211)
    plot(X_train, y_train, info_train)
    plt.gca().set_aspect(1)

    plt.subplot(212)
    plot(X_test, y_test, info_test)
    plt.gca().set_aspect(1)

    plt.show() 
Example 46
Project: bayesian_tree   Author: UBS-IB   File: helper.py    Apache License 2.0 5 votes vote down vote up
def draw_node_2d_perpendicular(node, bounds, colormap, n_classes):
    if node.is_leaf():
        x = bounds[0][0]
        y = bounds[1][0]
        w = bounds[0][1] - x
        h = bounds[1][1] - y

        mean = node._compute_posterior_mean()
        if not node.is_regression:
            mean = (np.arange(len(mean)) * mean).sum()

        plt.gca().add_patch(patches.Rectangle((x, y), w, h, color=colormap(mean/n_classes), alpha=0.1, linewidth=0))
    else:
        draw_node_2d_perpendicular(node.child1, compute_child_bounds_2d_perpendicular(bounds, node, True), colormap, n_classes)
        draw_node_2d_perpendicular(node.child2, compute_child_bounds_2d_perpendicular(bounds, node, False), colormap, n_classes) 
Example 47
Project: neat-python   Author: CodeReclaimers   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
    """ Plots the population's average and best fitness. """
    if plt is None:
        warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
        return

    generation = range(len(statistics.most_fit_genomes))
    best_fitness = [c.fitness for c in statistics.most_fit_genomes]
    avg_fitness = np.array(statistics.get_fitness_mean())
    stdev_fitness = np.array(statistics.get_fitness_stdev())

    plt.plot(generation, avg_fitness, 'b-', label="average")
    #plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
    plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
    plt.plot(generation, best_fitness, 'r-', label="best")

    plt.title("Population's average and best fitness")
    plt.xlabel("Generations")
    plt.ylabel("Fitness")
    plt.grid()
    plt.legend(loc="best")
    if ylog:
        plt.gca().set_yscale('symlog')

    plt.savefig(filename)
    if view:
        plt.show()

    plt.close() 
Example 48
Project: neat-python   Author: CodeReclaimers   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
    """ Plots the population's average and best fitness. """
    if plt is None:
        warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
        return

    generation = range(len(statistics.most_fit_genomes))
    best_fitness = [c.fitness for c in statistics.most_fit_genomes]
    avg_fitness = np.array(statistics.get_fitness_mean())
    stdev_fitness = np.array(statistics.get_fitness_stdev())

    plt.plot(generation, avg_fitness, 'b-', label="average")
    plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
    plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
    plt.plot(generation, best_fitness, 'r-', label="best")

    plt.title("Population's average and best fitness")
    plt.xlabel("Generations")
    plt.ylabel("Fitness")
    plt.grid()
    plt.legend(loc="best")
    if ylog:
        plt.gca().set_yscale('symlog')

    plt.savefig(filename)
    if view:
        plt.show()

    plt.close() 
Example 49
Project: neat-python   Author: CodeReclaimers   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
    """ Plots the population's average and best fitness. """
    if plt is None:
        warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
        return

    generation = range(len(statistics.most_fit_genomes))
    best_fitness = [c.fitness for c in statistics.most_fit_genomes]
    avg_fitness = np.array(statistics.get_fitness_mean())
    stdev_fitness = np.array(statistics.get_fitness_stdev())

    plt.plot(generation, avg_fitness, 'b-', label="average")
    plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
    plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
    plt.plot(generation, best_fitness, 'r-', label="best")

    plt.title("Population's average and best fitness")
    plt.xlabel("Generations")
    plt.ylabel("Fitness")
    plt.grid()
    plt.legend(loc="best")
    if ylog:
        plt.gca().set_yscale('symlog')

    plt.savefig(filename)
    if view:
        plt.show()

    plt.close() 
Example 50
Project: neat-python   Author: CodeReclaimers   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
    """ Plots the population's average and best fitness. """
    if plt is None:
        warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
        return

    generation = range(len(statistics.most_fit_genomes))
    best_fitness = [c.fitness for c in statistics.most_fit_genomes]
    avg_fitness = np.array(statistics.get_fitness_mean())
    #stdev_fitness = np.array(statistics.get_fitness_stdev())

    plt.plot(generation, avg_fitness, 'b-', label="average")
    #plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
    #plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
    plt.plot(generation, best_fitness, 'r-', label="best")

    plt.title("Population's average and best fitness")
    plt.xlabel("Generations")
    plt.ylabel("Fitness")
    plt.grid()
    plt.legend(loc="best")
    if ylog:
        plt.gca().set_yscale('symlog')

    plt.savefig(filename)
    if view:
        plt.show()

    plt.close() 
Example 51
Project: neat-python   Author: CodeReclaimers   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
    """ Plots the population's average and best fitness. """
    if plt is None:
        warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
        return

    generation = range(len(statistics.most_fit_genomes))
    best_fitness = [c.fitness for c in statistics.most_fit_genomes]
    avg_fitness = np.array(statistics.get_fitness_mean())
    stdev_fitness = np.array(statistics.get_fitness_stdev())

    plt.plot(generation, avg_fitness, 'b-', label="average")
    plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
    plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
    plt.plot(generation, best_fitness, 'r-', label="best")

    plt.title("Population's average and best fitness")
    plt.xlabel("Generations")
    plt.ylabel("Fitness")
    plt.grid()
    plt.legend(loc="best")
    if ylog:
        plt.gca().set_yscale('symlog')

    plt.savefig(filename)
    if view:
        plt.show()

    plt.close() 
Example 52
Project: DETAD   Author: HumamAlwassel   File: false_postive_analysis.py    MIT License 5 votes vote down vote up
def subplot_error_type_impact(fig, ax, values, labels, colors, xlabel, ylabel, title,
                              fontsize=14, bottom=0, top=100, bar_width=1, spacing=1.1,
                              grid_color='gray', grid_linestyle=':', grid_lw=1):
    
    ax.yaxis.grid(color=grid_color, linestyle=grid_linestyle, lw=grid_lw)
    
    index = np.linspace(0, spacing*(len(values)+1),1)
    for i in range(len(values)):
        rects1 = ax.bar(index + i*spacing*bar_width, values[i]*100, bar_width,
                         capsize = i,
                         color=colors[i],
                         label=labels[i])
        for bari in rects1:
            height = bari.get_height()
            plt.gca().text(bari.get_x() + bari.get_width()/2, bari.get_height()+0.001*100, '%.1f' % height,
                         ha='center', color='black', fontsize=fontsize/1.1)
   
    ax.set_ylabel(ylabel, fontsize=fontsize)
    ax.set_xlabel(xlabel, fontsize=fontsize)
    plt.xticks([])
    plt.yticks(fontsize=fontsize/1.2)
    ax.set_ylim(bottom=bottom,top=top)
    ax.set_title(title, fontsize=fontsize)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.yaxis.grid(True, linestyle='dotted')
    ax.set_axisbelow(True)
    ax.yaxis.set_tick_params(size=10, direction='in', width=2)
    for axis in ['bottom','left']:
        ax.spines[axis].set_linewidth(2.5) 
Example 53
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 5 votes vote down vote up
def plot_alpha(alpha, filename, idx=0):
    fig = plt.figure(figsize=[6, 6])
    ax = fig.gca()

    for line in np.swapaxes(alpha[idx], 1, 0):
        ax.plot(line, linestyle='-')

    ax.set_xlabel('Steps', fontsize=30)
    ax.set_ylabel('Mixture weight', fontsize=30)
    plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
    plt.close() 
Example 54
Project: pykaldi   Author: pykaldi   File: compute-vad.py    Apache License 2.0 5 votes vote down vote up
def show_plot(
    key, segment_times, sample_freqs, spec, duration, wav_data, vad_feat
):
    """This function plots the vad against the signal and the spectrogram.

    Args:
        segment_times: the time intervals acting as the x axis
        sample_freqs: the frequency bins acting as the y axis
        spec: the spectrogram
        duration: duration of the wave file
        wav_data: the wave data
        vad_feat: VAD features
    """

    import matplotlib.pyplot as plt
    import matplotlib.mlab as mlb

    plt.subplot(3, 1, 1)
    plt.pcolormesh(segment_times, sample_freqs, 10 * np.log10(spec), cmap="jet")
    plt.ylabel("Frequency [Hz]")
    plt.xlabel("Time [sec]")

    plt.subplot(3, 1, 2)
    axes = plt.gca()
    axes.set_xlim([0, duration])
    tmp_axis = np.linspace(0, duration, wav_data.shape[0])
    plt.plot(tmp_axis, wav_data / np.abs(np.max(wav_data)))
    plt.xlabel("Time [sec]")

    plt.subplot(3, 1, 3)
    axes = plt.gca()
    axes.set_xlim([0, duration])
    tmp_axis = np.linspace(0, duration, vad_feat.shape[0])
    plt.plot(tmp_axis, vad_feat)
    plt.xlabel("Time [sec]")

    plt.savefig("plots/" + key, bbox_inches="tight") 
Example 55
Project: insightface   Author: deepinsight   File: tester.py    MIT License 5 votes vote down vote up
def vis_all_detection(im_array, detections, class_names, scale):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """
    import matplotlib.pyplot as plt
    import random
    im = image.transform_inverse(im_array, config.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show() 
Example 56
Project: derplearning   Author: notkarol   File: shapes.py    MIT License 5 votes vote down vote up
def verify_plot(self, points, x, y, w, h):
        fig = plt.figure(figsize=(w / 10, h / 10))
        plt.plot(x, y, 'k-')
        plt.plot(points[:, 0], points[:, 1], 'ro')
        plt.grid()
        plt.xlim(0, w)
        plt.ylim(0, h)
        plt.gca().invert_yaxis()
        plt.savefig('plt.png', dpi=100, bbox_inches='tight')    
    
# Generate board size and plot 
Example 57
Project: derplearning   Author: notkarol   File: roadgen.py    MIT License 5 votes vote down vote up
def save_images(self, Top_Images, Bot_Images, directory , titles = ('Input Image','Model Perception') ):
        
        max_intensity = 256

        curves_to_print = min(Top_Images.shape[0],Bot_Images.shape[0])

        if not os.path.exists(directory):
            os.makedirs(directory)

        for dp_i in range(curves_to_print):

            #This is the actual save images part
            plt.subplot(2, 1, 1)
            plt.title(titles[0])
            plt.imshow(Top_Images.astype(np.uint8)[dp_i,:,:,::-1], vmin=0, vmax=255)
            #plt.gca().invert_yaxis()

            plt.subplot(2, 1, 2)
            plt.title(titles[1])
            plt.imshow(Bot_Images.astype(np.uint8)[dp_i,:,:,::-1], vmin=0, vmax=255)
            #plt.gca().invert_yaxis()

            plt.savefig('%s/%06i.png' % (directory, dp_i), dpi=200, bbox_inches='tight')
            plt.close()

    #Function generates roads using a label vector passed to it
    # saves those generated roads in a location designated by the save name. 
Example 58
Project: derplearning   Author: notkarol   File: roadgen3d.py    MIT License 5 votes vote down vote up
def save_images(self, Top_Images, Bot_Images, directory , titles = ('Input Image','Model Perception') ):
        
        max_intensity = 256

        curves_to_print = min(Top_Images.shape[0],Bot_Images.shape[0])

        if not os.path.exists(directory):
            os.makedirs(directory)

        for dp_i in range(curves_to_print):

            #This is the actual save images part
            plt.subplot(2, 1, 1)
            plt.title(titles[0])
            plt.imshow(Top_Images.astype(np.uint8)[dp_i,:,:,::-1], vmin=0, vmax=255)
            #plt.gca().invert_yaxis()

            plt.subplot(2, 1, 2)
            plt.title(titles[1])
            plt.imshow(Bot_Images.astype(np.uint8)[dp_i,:,:,::-1], vmin=0, vmax=255)
            #plt.gca().invert_yaxis()

            plt.savefig('%s/%06i.png' % (directory, dp_i), dpi=200, bbox_inches='tight')
            plt.close()

    #Function generates roads using a label vector passed to it
    # saves those generated roads in a location designated by the save name. 
Example 59
Project: derplearning   Author: notkarol   File: line_validate.py    MIT License 5 votes vote down vote up
def plot_curves( val_points, model_out):

    n_points = 3
    n_segments = 10
    width = 64
    height = 64
    max_intensity = 255
    curves_to_print = model_out.shape[0]

    for i in range(curves_to_print):
     
        #Turns the validation points into a plottable curve
        x_val_points = val_points[i, :n_points]*width
        y_val_points = val_points[i, n_points:]*height
        x_val_curve, y_val_curve = bezier_curve(x_val_points, y_val_points, n_segments)
        
        #Turns the model output curve into a plottable curve
        x_model_points = model_out[i, :n_points]*width
        y_model_points = model_out[i, n_points:]*height
        x_mod_curve, y_mod_curve = bezier_curve(x_model_points, y_model_points, n_segments)
        
        fig = plt.figure(figsize=(width / 10, height / 10))
        plt.plot(x_val_curve, y_val_curve, 'k-')
        plt.plot(x_mod_curve, y_mod_curve, 'r-')
        plt.xlim(0, width)
        plt.ylim(0, height)
        plt.gca().invert_yaxis()
        plt.savefig('valplots/model_%06i.png' % i, dpi=100, bbox_inches='tight')
        plt.close()


#function invokes Model class, and saves the predictions as images 
Example 60
Project: aftershoq   Author: mfranckie   File: gaussopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotGP(self):
        '''Plot the GP at its current stage in the minimization.
        '''
        maxloc = self.maxloc; umax = self.umax
        xt = self.xt; mean = np.squeeze( self.mean )
        cov = self.cov; u = self.u;
        x = self.x; y = self.y;

        var = np.reshape( np.abs( np.diag( self.cov ) ), (self.Nx,1) )

        pl.figure(5)
        pl.clf()
        pl.plot(xt,mean)
        pl.plot(x,y,'*')
        pl.fill_between(np.squeeze(xt), mean-np.squeeze(2*np.sqrt(var)),
                        mean+np.squeeze(2*np.sqrt(var)),
                        facecolor = "grey", alpha=0.5)
        pl.plot(xt,u/5,'-g')
        pl.plot(maxloc,umax,'*')
        pl.ylim(-5, 5)

        lim_diff = (np.max(y) - np.min(y))/2.

        pl.gca().set_xlim( 0, np.max(x) )
        pl.gca().set_ylim( np.min(y) - lim_diff, np.max(y) + lim_diff )

        #writer.grab_frame()
        pl.pause(0.01) 
Example 61
Project: aftershoq   Author: mfranckie   File: gaussopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotGP_testfunc(self, model, hutil):
        '''Plot the GP at its current stage in the minimization
        with the test function "model".

        Parameters

        model: A tets function giving a fast merit function evaluation'''

        xt = self.xt; mean = np.squeeze( self.mean ); cov = self.cov; u = self.u;
        maxloc = self.maxloc; umax = self.umax
        x = self.x; y = self.y;

        var = np.reshape( np.abs( np.diag( self.cov ) ), (self.Nx,1) )

        yt = []
        [yt.append(-model.getMerit((hutil.interp_coords_from_dist(xx)/float(2**hutil.p)))) for xx in xt]

        pl.figure(5)
        pl.hold(False)
        pl.plot(xt,mean)
        pl.hold(True)
        pl.plot(x,y,'*')
        pl.fill_between(np.squeeze(xt), mean-np.squeeze(2*np.sqrt(var)),mean+np.squeeze(2*np.sqrt(var)), facecolor = "grey", alpha=0.5)
        pl.plot(xt,yt,'-')
        pl.plot(xt,u/5,'-g')
        pl.plot(maxloc,umax,'*')
        pl.ylim(-5, 5)

        lim_diff = (np.max(y) - np.min(y))/2.

        pl.gca().set_xlim( 0, np.max(x) )
        pl.gca().set_ylim( np.min(y) - lim_diff, np.max(y) + lim_diff )

        #writer.grab_frame()
        pl.pause(0.01) 
Example 62
Project: yolov3-detector   Author: ccerhan   File: main.py    MIT License 4 votes vote down vote up
def main():
    weights_path = 'data/yolov3.weights'
    config_path = 'data/yolov3.cfg'
    labels_path = 'data/coco.names'

    # Download yolov3.weights if it does not exist
    if not os.path.exists(weights_path):
        download_weights(weights_path)

    # Load the class labels and randomly generated colors
    labels, colors = load_labels(labels_path)

    # Load the sample image as numpy array (RGB)
    image = plt.imread('samples/dog.jpg')

    # Create YOLO detector
    model = yolo.Detector(config_path=config_path,
                          weights_path=weights_path,
                          input_size=(544, 608),
                          conf_thresh=0.5,
                          nms_thresh=0.4)

    if torch.cuda.is_available():
        model.cuda()

    # Perform detection for a single image
    detections = model(image)

    # Draw detected class labels and relevant bounding boxes
    plt.figure()
    fig, ax = plt.subplots(1)
    ax.imshow(image)

    if len(detections) > 0:
        for i, (x1, y1, x2, y2, obj_conf, cls_conf, cls_pred) in enumerate(detections[0]):
            x = round(x1.item())
            y = round(y1.item())
            w = round(x2.item() - x1.item())
            h = round(y2.item() - y1.item())

            label = labels[int(cls_pred)]
            color = colors[int(cls_pred)]

            ax.add_patch(patches.Rectangle((x, y), w, h, linewidth=2, edgecolor=color, facecolor='none'))
            plt.text(x, y, s=label, color='white', verticalalignment='top', bbox={'color': color, 'pad': 0})

            print(i, ':', label, 'x:', x, 'y:', y, 'w:', w, 'h:', h)

    plt.axis('off')
    plt.gca().xaxis.set_major_locator(ticker.NullLocator())
    plt.gca().yaxis.set_major_locator(ticker.NullLocator())

    plt.show()
    # plt.savefig('samples/dogs_.png', bbox_inches='tight', pad_inches=0.0)

    plt.close() 
Example 63
Project: wikilinks   Author: trovdimi   File: click_distributions.py    MIT License 4 votes vote down vote up
def plot_counts_category_distributions_ccdf():
    category_distributions = read_pickle(HOME+'output/category_counts_distribution.obj')

    for  i in category_distributions.values():
        print len(i)

    colors= {'lead':'r','infobox':'b', 'body':'g',  'left-body':'m','navbox':'c', 'counts':'k'}


    fig = plt.figure()
    ax = fig.add_subplot(111)

    for category in ['lead', 'infobox', 'body', 'left-body', 'navbox', 'counts']:

        data = category_distributions[category]
        data = [x[0] for x in data]
        powerlaw.plot_ccdf(data, ax, label=category,color=colors[category])
    # further plotting
    ax.set_xlabel("Number of clicks n")
    ax.set_ylabel("Pr(X>=n)")
    plt.legend(fancybox=True, loc=3, ncol=2, prop={'size':4})
    #leg = plt.gca().get_legend()
    #ltext  = leg.get_texts()  # all the text.Text instance in the legend
    #llines = leg.get_lines()
    #plt.setp(ltext, fontsize='small')    # the legend text fontsize
    #plt.setp(llines, linewidth=1)
    plt.tight_layout()
    plt.savefig('output/category_counts_distributions.pdf')

    data = category_distributions['counts']
    data = [int(x[0]) for x in data]

    hist, bin_edges = np.histogram(data, 100, density=True)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot( bin_edges[:-1],hist, marker='o')
    ax.set_xlabel('#Counts')
    ax.set_ylabel('#Pages')
    ax.set_yscale('log')
    ax.set_xscale('log')
    plt.legend(fancybox=True, loc=3,  prop={'size':4})
    plt.tight_layout()
    plt.savefig('output/counts_distribution.pdf') 
Example 64
Project: mmdetection   Author: open-mmlab   File: analyze_logs.py    Apache License 2.0 4 votes vote down vote up
def plot_curve(log_dicts, args):
    if args.backend is not None:
        plt.switch_backend(args.backend)
    sns.set_style(args.style)
    # if legend is None, use {filename}_{key} as legend
    legend = args.legend
    if legend is None:
        legend = []
        for json_log in args.json_logs:
            for metric in args.keys:
                legend.append('{}_{}'.format(json_log, metric))
    assert len(legend) == (len(args.json_logs) * len(args.keys))
    metrics = args.keys

    num_metrics = len(metrics)
    for i, log_dict in enumerate(log_dicts):
        epochs = list(log_dict.keys())
        for j, metric in enumerate(metrics):
            print('plot curve of {}, metric is {}'.format(
                args.json_logs[i], metric))
            if metric not in log_dict[epochs[0]]:
                raise KeyError('{} does not contain metric {}'.format(
                    args.json_logs[i], metric))

            if 'mAP' in metric:
                xs = np.arange(1, max(epochs) + 1)
                ys = []
                for epoch in epochs:
                    ys += log_dict[epoch][metric]
                ax = plt.gca()
                ax.set_xticks(xs)
                plt.xlabel('epoch')
                plt.plot(xs, ys, label=legend[i * num_metrics + j], marker='o')
            else:
                xs = []
                ys = []
                num_iters_per_epoch = log_dict[epochs[0]]['iter'][-1]
                for epoch in epochs:
                    iters = log_dict[epoch]['iter']
                    if log_dict[epoch]['mode'][-1] == 'val':
                        iters = iters[:-1]
                    xs.append(
                        np.array(iters) + (epoch - 1) * num_iters_per_epoch)
                    ys.append(np.array(log_dict[epoch][metric][:len(iters)]))
                xs = np.concatenate(xs)
                ys = np.concatenate(ys)
                plt.xlabel('iter')
                plt.plot(
                    xs, ys, label=legend[i * num_metrics + j], linewidth=0.5)
            plt.legend()
        if args.title is not None:
            plt.title(args.title)
    if args.out is None:
        plt.show()
    else:
        print('save curve to: {}'.format(args.out))
        plt.savefig(args.out)
        plt.cla() 
Example 65
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: coco.py    Apache License 2.0 4 votes vote down vote up
def showAnns(self, anns):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
            datasetType = 'instances'
        elif 'caption' in anns[0]:
            datasetType = 'captions'
        else:
            raise Exception('datasetType not supported')
        if datasetType == 'instances':
            ax = plt.gca()
            ax.set_autoscale_on(False)
            polygons = []
            color = []
            for ann in anns:
                c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
                if 'segmentation' in ann:
                    if type(ann['segmentation']) == list:
                        # polygon
                        for seg in ann['segmentation']:
                            poly = np.array(seg).reshape((int(len(seg)/2), 2))
                            polygons.append(Polygon(poly))
                            color.append(c)
                    else:
                        # mask
                        raise NotImplementedError("maskUtils disabled!")
                if 'keypoints' in ann and type(ann['keypoints']) == list:
                    # turn skeleton into zero-based index
                    sks = np.array(self.loadCats(ann['category_id'])[0]['skeleton'])-1
                    kp = np.array(ann['keypoints'])
                    x = kp[0::3]
                    y = kp[1::3]
                    v = kp[2::3]
                    for sk in sks:
                        if np.all(v[sk]>0):
                            plt.plot(x[sk],y[sk], linewidth=3, color=c)
                    plt.plot(x[v>0], y[v>0],'o',markersize=8, markerfacecolor=c, markeredgecolor='k',markeredgewidth=2)
                    plt.plot(x[v>1], y[v>1],'o',markersize=8, markerfacecolor=c, markeredgecolor=c, markeredgewidth=2)
            p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
            ax.add_collection(p)
            p = PatchCollection(polygons, facecolor='none', edgecolors=color, linewidths=2)
            ax.add_collection(p)
        elif datasetType == 'captions':
            for ann in anns:
                print(ann['caption']) 
Example 66
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: detector.py    Apache License 2.0 4 votes vote down vote up
def visualize_detection(self, img, dets, classes=[], thresh=0.6):
        """
        visualize detections in one image

        Parameters:
        ----------
        img : numpy.array
            image, in bgr format
        dets : numpy.array
            ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...])
            each row is one object
        classes : tuple or list of str
            class names
        thresh : float
            score threshold
        """
        import matplotlib.pyplot as plt
        import random
        plt.imshow(img)
        height = img.shape[0]
        width = img.shape[1]
        colors = dict()
        for det in dets:
            (klass, score, x0, y0, x1, y1) = det
            if score < thresh:
                continue
            cls_id = int(klass)
            if cls_id not in colors:
                colors[cls_id] = (random.random(), random.random(), random.random())
            xmin = int(x0 * width)
            ymin = int(y0 * height)
            xmax = int(x1 * width)
            ymax = int(y1 * height)
            rect = plt.Rectangle((xmin, ymin), xmax - xmin,
                                 ymax - ymin, fill=False,
                                 edgecolor=colors[cls_id],
                                 linewidth=3.5)
            plt.gca().add_patch(rect)
            class_name = str(cls_id)
            if classes and len(classes) > cls_id:
                class_name = classes[cls_id]
            plt.gca().text(xmin, ymin - 2,
                            '{:s} {:.3f}'.format(class_name, score),
                            bbox=dict(facecolor=colors[cls_id], alpha=0.5),
                                    fontsize=12, color='white')
        plt.show() 
Example 67
Project: Deformable-ConvNets   Author: guanfuchen   File: coco.py    MIT License 4 votes vote down vote up
def showAnns(self, anns):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if 'segmentation' in anns[0]:
            datasetType = 'instances'
        elif 'caption' in anns[0]:
            datasetType = 'captions'
        if datasetType == 'instances':
            ax = plt.gca()
            polygons = []
            color = []
            for ann in anns:
                c = np.random.random((1, 3)).tolist()[0]
                if type(ann['segmentation']) == list:
                    # polygon
                    for seg in ann['segmentation']:
                        poly = np.array(seg).reshape((len(seg)/2, 2))
                        polygons.append(Polygon(poly, True,alpha=0.4))
                        color.append(c)
                else:
                    # mask
                    t = self.imgs[ann['image_id']]
                    if type(ann['segmentation']['counts']) == list:
                        rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
                    else:
                        rle = [ann['segmentation']]
                    m = mask.decode(rle)
                    img = np.ones( (m.shape[0], m.shape[1], 3) )
                    if ann['iscrowd'] == 1:
                        color_mask = np.array([2.0,166.0,101.0])/255
                    if ann['iscrowd'] == 0:
                        color_mask = np.random.random((1, 3)).tolist()[0]
                    for i in range(3):
                        img[:,:,i] = color_mask[i]
                    ax.imshow(np.dstack( (img, m*0.5) ))
            p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
            ax.add_collection(p)
        elif datasetType == 'captions':
            for ann in anns:
                print ann['caption'] 
Example 68
Project: snn_global_pattern_induction   Author: chrhenning   File: recordings.py    Apache License 2.0 4 votes vote down vote up
def _plot_slice(time, var, sind, eind, var_name, ind_names, title, unit,
                    folder=None, miny=None, maxy=None):
        """Plot a time slice for a variable recording.

        Args:
            time: The time array.
            var: The recorded values.
            sind: Start index of slice.
            eind: End index of slice.
            var_name: Name of the recorded variable.
            ind_names: Names of the recorded indices.
            title: Plot titel.
            unit: Variable unit.
            folder: Where to store plot.
            miny: Minimum y limit.
            maxy: Maximum y limit.

        Returns:
        """
        if len(var.shape) == 2:
            for i in range(var.shape[0]):
                label = '%s_%d' % (var_name, ind_names[i])

                values = var[i,sind:eind]
                b2.plot(time[sind:eind], values, label=label)
        else:
            label = var_name
            values = var[sind:eind]
            b2.plot(time[sind:eind], values, label=label)

        plt.legend()
        plt.title(title)
        plt.xlabel('time (seconds)')
        unit = str(unit)
        if unit == 'rad':
            plt.ylabel('%s' % (var_name))
        else:
            plt.ylabel('%s (%s)'  % (var_name, unit))
        axes = plt.gca()
        # Make sure one also can see min and max vals in plot.
        if miny is not None and maxy is not None:
            eps = 0.01 * (maxy - miny)
            miny -= eps
            maxy += eps
        if miny is not None:
            axes.set_ylim(bottom=miny)
        if maxy is not None:
            axes.set_ylim(top=maxy)
        if folder is not None:
            plot_name = 'plot_%s_%d_%d.png' % (var_name, sind, eind)
            plot_name = os.path.join(folder, plot_name)
            plt.savefig(plot_name)
        plt.close() 
Example 69
Project: snn_global_pattern_induction   Author: chrhenning   File: recordings.py    Apache License 2.0 4 votes vote down vote up
def _scatter_slice(time, neurons, sind, eind, xmin, xmax, ymin, ymax,
                       title, y_label='Neuron i', var=None, var_min=None,
                       var_max=None, var_name=None, var_unit='rad',
                       folder=None):
        """Create a scatter plot of a time slice for a spike recording.
        Variables recorded on spike events might be plottet as color coded
        points.

        Args:
            time: The time array.
            neurons: Which neuron spiked at a time point.
            sind: Start index of slice.
            eind: End index of slice.
            xmin: Start Time (needed to set x-range).
            xmax: End Time (needed to set x-range).
            ymin: Lowest y-value.
            ymax: Highest y-value.
            title: Plot titel.
            ylabel: y label.
            var: An optional color coded variable, that was recorded on spike
                events.
            var_min: Minimal var value.
            var_max: Maximum var value.
            var_name: Name of var.
            var_unit: Unit of var.
            folder: Where to store plot.

        Returns:
        """
        if var is None:
            b2.scatter(time[sind:eind], neurons[sind:eind])
        else:
            cm = plt.cm.get_cmap('coolwarm')
            sp = b2.scatter(time[sind:eind], neurons[sind:eind],
                            c=var[sind:eind], vmin=var_min, vmax=var_max,
                            cmap=cm)

            cb = plt.colorbar(sp)
            if var_name is not None:
                unit = str(var_unit)
                if unit == 'rad':
                    cb.ax.set_xlabel('%s' % (var_name))
                else:
                    cb.ax.set_xlabel('%s (%s)'  % (var_name, unit))

        axes = plt.gca()
        axes.set_xlim(left=xmin, right=xmax)
        axes.set_ylim(bottom=ymin, top=ymax)
        plt.title(title)
        plt.xlabel('time (seconds)')
        plt.ylabel(y_label)
        if folder is not None:
            if var_name is None:
                plot_name = 'plot_spikes_%d_%d.png' % (sind, eind)
            else:
                plot_name = 'plot_spikes_%s_%d_%d.png' % (var_name, sind, eind)
            plot_name = os.path.join(folder, plot_name)
            plt.savefig(plot_name)
        plt.close() 
Example 70
Project: ddpg-curiosity-and-multi-criteria-her   Author: CDMCH   File: dynamics_loss_mapping.py    MIT License 4 votes vote down vote up
def generate_dynamics_loss_map_from_npy_records(self, file_prefix, delete_records=False):

        file_names = [file_name for file_name in os.listdir(self.working_dir)
                      if file_name.endswith(".npy") and file_name.startswith(file_prefix)]

        losses_locations_records = np.concatenate([np.load(os.path.join(self.working_dir, file_name)) for file_name in file_names],
                                          axis=0)

        max_heatmap_samples = 10000

        losses_locations_records = losses_locations_records[np.random.choice(len(losses_locations_records),
                                                             min(max_heatmap_samples, len(losses_locations_records)),
                                                             replace=False)]

        # print("\n\n\nlosses_locations_records:\n{}\n".format(losses_locations_records))
        # exit(0)

        # Add a minuscule amount of location variation in case agent doesn't move on a certain axis.

        # print("z min: {} max: {}".format(min(z), max(z)))

        losses_locations_records[:, 1:] = losses_locations_records[:, 1:] * 100 + (np.random.randn(*losses_locations_records[:, 1:].shape) / 1000)

        losses_locations_records = losses_locations_records.swapaxes(0, 1)

        z = losses_locations_records[0, :]

        idx = z.argsort()
        x, y, z = losses_locations_records[1, idx], losses_locations_records[2, idx], z[idx]

        plt.figure(figsize=(3, 3))
        plt.scatter(x, y, c=z, s=80, edgecolors='', cmap=plt.cm.jet, alpha=0.5)
        plt.colorbar()
        plt.xlim(0, 100)
        plt.ylim(0, 100)

        im = plt.imread(os.path.join(self.working_dir, 'level.png'))
        plt.imshow(im, extent=[0, 100, 0, 100], aspect='auto')
        plt.axis('equal')
        plt.axis('off')
        plt.margins(0, 0)
        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())
        plt.title("Dynamics Loss " + file_prefix)

        heatmap_image_path = os.path.join(self.working_dir, "{}_dynamics_loss.png".format(file_prefix))
        plt.savefig(heatmap_image_path, transparent=False, bbox_inches='tight', pad_inches=0)

        plt.close()

        if delete_records:
            for file_name in file_names:
                try:
                    os.remove(os.path.join(self.working_dir, file_name))
                except OSError:
                    pass

        return heatmap_image_path 
Example 71
Project: remixt   Author: amcpherson   File: plot_results.py    MIT License 4 votes vote down vote up
def create_plot(**args):
    store = pd.HDFStore(args['results'], 'r')

    seaborn.set_style('ticks')

    if args['plot_type'] == 'depth':
        read_depth = store['/read_depth']
        minor_modes = store['/minor_modes']

        fig = plt.figure(figsize=(8, 5))
        ax = plt.gca()

        remixt.cn_plot.plot_depth(ax, read_depth, minor_modes=minor_modes)
        seaborn.despine(trim=True)

        fig.savefig(args['plot_file'], bbox_inches='tight')

    elif args['plot_type'] == 'scatter':
        cnv = store['/cn']

        fig = plt.figure(figsize=(8, 8))
        ax = plt.gca()

        remixt.cn_plot.plot_cnv_scatter(ax, cnv, major_col='major_raw', minor_col='minor_raw')

        fig.savefig(args['plot_file'], bbox_inches='tight')

    elif args['plot_type'] == 'raw':
        cnv = store['/cn']

        cnv['actual_length'] = cnv['end'] - cnv['start']

        cnv = cnv[
            (cnv['length'] > 1e5) &
            (cnv['length'] > 0.75 * cnv['actual_length'])]

        fig = plt.figure(figsize=(12, 2))
        ax = plt.gca()

        remixt.cn_plot.plot_cnv_genome(ax, cnv, major_col='major_raw', minor_col='minor_raw', maxcopies=6)

        fig.savefig(args['plot_file'], bbox_inches='tight') 
Example 72
Project: bayesian_tree   Author: UBS-IB   File: helper.py    Apache License 2.0 4 votes vote down vote up
def plot_2d_hyperplane(root, X_train, y_train, info_train, X_test, y_test, info_test):
    plt.figure(figsize=[10, 16], dpi=75)

    n_classes = int(y_train.max()) + 1
    colormap = cm.gist_rainbow

    x_min = min(X_train[:, 0].min(), X_test[:, 0].min())
    x_max = max(X_train[:, 0].max(), X_test[:, 0].max())
    y_min = min(X_train[:, 1].min(), X_test[:, 1].min())
    y_max = max(X_train[:, 1].max(), X_test[:, 1].max())

    bounds = []
    bounds.append(Line((x_min, y_min), (1, 0)))
    bounds.append(Line((x_min, y_min), (0, 1)))
    bounds.append(Line((x_max, y_max), (1, 0)))
    bounds.append(Line((x_max, y_max), (0, 1)))

    def plot(X, y, info):
        for i in range(n_classes):
            class_i = y == i
            plt.plot(X[np.where(class_i)[0], 0],
                     X[np.where(class_i)[0], 1],
                     'o',
                     ms=4,
                     c=colormap(i/n_classes),
                     label='Class {}'.format(i))

        draw_node_2d_hyperplane(root, bounds, colormap, n_classes)

        plt.title(info)
        plt.xlabel('x0')
        plt.ylabel('x1')
        plt.legend()

    plt.subplot(211)
    plot(X_train, y_train, info_train)
    plt.xlim((x_min, x_max))
    plt.ylim((y_min, y_max))
    plt.gca().set_aspect(1)

    plt.subplot(212)
    plot(X_test, y_test, info_test)
    plt.xlim((x_min, x_max))
    plt.ylim((y_min, y_max))
    plt.gca().set_aspect(1)

    plt.show() 
Example 73
Project: bayesian_tree   Author: UBS-IB   File: helper.py    Apache License 2.0 4 votes vote down vote up
def draw_node_2d_hyperplane(node, bounds, colormap, n_classes):
    if node.is_leaf():
        pass
        # x = bounds[0][0]
        # y = bounds[1][0]
        # w = bounds[0][1] - x
        # h = bounds[1][1] - y

        # mean = node.compute_posterior_mean()
        # mean = (np.arange(len(mean)) * mean).sum()

        # plt.gca().add_patch(patches.Rectangle((x, y), w, h, color=colormap(mean/n_classes), alpha=0.1, linewidth=0))
    else:
        line = Line(node.best_hyperplane_origin, node.best_hyperplane_normal)

        x_min = -np.inf
        x_max = np.inf
        y_min = -np.inf
        y_max = np.inf

        for bound in bounds:
            x, y = line.intersect(bound)

            if x < line.origin[0]:
                x_min = max(x_min, x)
            else:
                x_max = min(x_max, x)

            if y < line.origin[1]:
                y_min = max(y_min, y)
            else:
                y_max = min(y_max, y)

        xs = np.array([x_min, x_max])
        ln = plt.plot(xs, line.compute_y(xs), label='Split at level {}'.format(node.level))
        # plt.plot(line.origin[0], line.origin[1], 'o', c=ln[0].get_color())
        # if node.level >= 2:
        #     return

        bounds_for_children = bounds.copy()
        bounds_for_children.append(line)
        draw_node_2d_hyperplane(node.child1, bounds_for_children, colormap, n_classes)
        draw_node_2d_hyperplane(node.child2, bounds_for_children, colormap, n_classes) 
Example 74
Project: ommprotocol   Author: insilichem   File: analyze.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def plot_rmsd(trajectories, topology=None, subset=None, output='rmsd.dat', chunksize=100,
              reimage=False):
    import mdtraj
    import numpy as np
    from tqdm import tqdm
    if topology:
        topology = mdtraj.load_topology(topology)
    if subset:
        subset = topology.select(subset)
    trajectories = sorted(trajectories, key=sort_key_for_numeric_suffixes)
    first_frame = mdtraj.load_frame(trajectories[0], 0, top=topology)
    frame_size = first_frame.xyz[0].nbytes
    if reimage:
        first_frame.image_molecules(inplace=True)
    rmsds = []
    for trajectory in tqdm(trajectories, unit='file'):
        _, ext = os.path.splitext(trajectory)
        total, unit_scale = None, None
        if ext.lower() == '.dcd':
            n_frames = round(os.path.getsize(trajectory) / frame_size, -1 * len(str(chunksize)[1:]))
            total = int(n_frames/chunksize)
            unit_scale = chunksize
        itertraj = mdtraj.iterload(trajectory, top=topology, chunk=chunksize)
        tqdm_kwargs = {'total': total, 'unit': 'frames', 'unit_scale': unit_scale,
                       'postfix': {'traj': trajectory}}
        for chunk in tqdm(itertraj, **tqdm_kwargs):
            if reimage:
                chunk.image_molecules(inplace=True)
            rmsd = mdtraj.rmsd(chunk, first_frame, atom_indices=subset) * 10.0 # nm->A
            rmsds.append(rmsd)

    rmsds = np.concatenate(rmsds)
    with open(output, 'w') as f:
        f.write('\n'.join(map(str, rmsds)))
    print('\nWrote RMSD values to', output)
    print('Plotting results...')
    plt.plot(rmsds)
    fig = plt.gca()
    fig.set_title('{}{}'.format(trajectories[0], ' and {} more'.format(len(trajectories[1:])
                                                 if len(trajectories) > 1 else '')))
    fig.set_xlabel('Frames')
    fig.set_ylabel('RMSD (A)')
    plt.show() 
Example 75
Project: brooks   Author: sixty-north   File: plot_timeseries.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def plot_timeseries(tsvs,
                    time_attr,
                    attribute,
                    start_color,
                    output,
                    xsize=None,
                    ysize=None,
                    dpi=None,
                    xmax=None,
                    ymax=None):
    """
    Args:
        tsvs: An iterable of (source, name) tuples where source is any valid
            value for pandas.read_table.
    """
    run_frames = []
    for tsv, run_name in tsvs:
        loaded_frame = pandas.read_table(tsv, na_values=['None'])
        run_frame = loaded_frame[[time_attr, attribute]].copy()
        run_frame.rename(columns={attribute: run_name}, inplace=True)
        run_frames.append(run_frame)

    frame = reduce(
        lambda a, b: pandas.merge(a, b, on=time_attr, how='outer'),
        run_frames)
    frame.set_index(time_attr, inplace=True, verify_integrity=True)
    frame.fillna(0, inplace=True)

    if xsize is not None:
        assert ysize is not None
        assert dpi is not None
        plt.figure(figsize=(xsize, ysize), dpi=dpi)

    start_color_index = start_color - 1
    color_cycle = plt.gca()._get_lines.color_cycle
    for i in range(start_color_index):
        next(color_cycle)

    frame.plot(ax=plt.gca())

    plt.ylim(ymin=0)
    if xmax is None:
        xlim_min, xlim_max = plt.xlim()
        plt.xlim(xmax=(xlim_max - xlim_min) * 1.05)
    else:
        plt.xlim(xmax=xmax)

    if ymax is not None:
        plt.ylim(ymax=ymax)

    plt.ylabel(attribute)

    if output == 'interactive':
        plt.show()
    else:
        savefig_args = {}
        if dpi is not None:
            savefig_args['dpi'] = dpi

        plt.gcf().savefig(output, **savefig_args) 
Example 76
Project: neat-python   Author: CodeReclaimers   File: evolve.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(config_file):
    # Load configuration.
    config = neat.Config(CircuitGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         config_file)
    #config.save('test_save_config.txt')

    # Create the population, which is the top-level object for a NEAT run.
    p = neat.Population(config)

    # Add a stdout reporter to show progress in the terminal.
    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)

    # Run for up to 1000 generations.
    pe = neat.ParallelEvaluator(4, simulate)
    p.run(pe.evaluate, 1000)

    # Write run statistics to file.
    stats.save()

    # Display the winning genome.
    winner = stats.best_genome()
    print('\nBest genome:\nfitness {!s}\n{!s}'.format(winner.fitness, winner))

    winner_circuit = create_circuit(winner, config)
    print(winner_circuit)

    simulator = winner_circuit.simulator(temperature=25, nominal_temperature=25)
    analysis = simulator.dc(Vbase=slice(0, V_MAX, .01))

    inputs = np.array(analysis.input1)
    outputs = np.array(analysis.node0)
    expected = get_expected(inputs)

    plt.plot(inputs, outputs, 'r-', label='output')
    plt.plot(inputs, expected, 'g-.', label='target')
    plt.grid()
    plt.legend(loc='best')
    plt.gca().set_aspect(1)
    plt.show()

    visualize.plot_stats(stats, ylog=False, view=True)
    visualize.plot_species(stats, view=False) 
Example 77
Project: bearing-vibration-diagnostics-toolbox   Author: andrek10   File: stats.py    MIT License 4 votes vote down vote up
def EHNR(x, Fs = 1.0, debug=False):
    '''
    Get Envelope Harmonic-to-noise ratio 
    Based on:
    Xu, X., Zhao, M., Lin, J., & Lei, Y. (2016). 
    Envelope harmonic-to-noise ratio for periodic impulses 
        detection and its application to bearing diagnosis. 
    Measurement, 91, 385-397.

    Parameters
    ----------
    x : float 1D array
        Signal
    Fs : float, optional
        Sampling frequency
    debug : boolean, optional
        Whether debug information is returned

    Returns
    -------
    EHNR : float
        The EHNR value
    '''

    if x.size % 2 == 1:
        x = x[0:-1]
    Env_prime = envelope(x)
    Env = Env_prime - np.mean(Env_prime)
    
    t_i = x.size/2 - 1
    dt = 1.0/Fs
    temp = Env[:t_i]
    r_Env = fftwconvolve(Env[:2*t_i], temp[::-1], 'valid')*dt
    i_rem = int(t_i/20.0)
    for i in range(i_rem, t_i):
        der = r_Env[i] - r_Env[i-1]
        if der > 0.0:
            i_rem = i
            break
    if i == t_i - 1:
        return 0.0
    tauMax_i = np.argmax(r_Env[i_rem:]) + i_rem
    r_EnvMax = r_Env[tauMax_i]
    if debug is True:
        plt.figure()
        axes = plt.gca()
        plt.plot(r_Env)
        plt.title('i_rem = %i' % (i_rem))
        ylim = axes.get_ylim()
        plt.plot([i_rem, i_rem], [ylim[0], ylim[1]], '-g')
        plt.plot([tauMax_i, tauMax_i], [ylim[0], ylim[1]], '--r')
        plt.show()
    EHNR = r_EnvMax/(r_Env[0] - r_EnvMax)
    return EHNR 
Example 78
Project: pytorch-lstd   Author: JiasiWang   File: coco.py    MIT License 4 votes vote down vote up
def showAnns(self, anns):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if 'segmentation' in anns[0]:
            datasetType = 'instances'
        elif 'caption' in anns[0]:
            datasetType = 'captions'
        if datasetType == 'instances':
            ax = plt.gca()
            polygons = []
            color = []
            for ann in anns:
                c = np.random.random((1, 3)).tolist()[0]
                if type(ann['segmentation']) == list:
                    # polygon
                    for seg in ann['segmentation']:
                        poly = np.array(seg).reshape((len(seg)/2, 2))
                        polygons.append(Polygon(poly, True,alpha=0.4))
                        color.append(c)
                else:
                    # mask
                    t = self.imgs[ann['image_id']]
                    if type(ann['segmentation']['counts']) == list:
                        rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
                    else:
                        rle = [ann['segmentation']]
                    m = mask.decode(rle)
                    img = np.ones( (m.shape[0], m.shape[1], 3) )
                    if ann['iscrowd'] == 1:
                        color_mask = np.array([2.0,166.0,101.0])/255
                    if ann['iscrowd'] == 0:
                        color_mask = np.random.random((1, 3)).tolist()[0]
                    for i in range(3):
                        img[:,:,i] = color_mask[i]
                    ax.imshow(np.dstack( (img, m*0.5) ))
            p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
            ax.add_collection(p)
        elif datasetType == 'captions':
            for ann in anns:
                print(ann['caption']) 
Example 79
Project: cube_browser   Author: SciTools   File: explorer.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _goplot(self, sender):
        """Create the cube_browser.Plot2D and cube_browser.Browser"""
        IPython.display.clear_output()
        fig = plt.figure(figsize=(16, 7))
        sub_plots = 110
        if self._subplots.value == 2:
            sub_plots = 120

        confs = []
        for spl, pc in enumerate(self.plot_controls):
            spl += 1
            cube = None
            if pc.cube_picker.value is not None:
                cube = self.cubes[pc.cube_picker.value]
            if cube and spl <= self._subplots.value:
                pc_x_name = pc.x_coord.value
                pc_y_name = pc.y_coord.value
                x_coords = cube.coords(axis='X', dim_coords=True)
                if len(x_coords) == 1:
                    x_name = x_coords[0].name()
                else:
                    x_name = None
                y_coords = cube.coords(axis='Y', dim_coords=True)
                if len(y_coords) == 1:
                    y_name = y_coords[0].name()
                else:
                    y_name = None
                if x_name == pc_x_name and y_name == pc_y_name:
                    proj = iplt.default_projection(cube) or ccrs.PlateCarree()
                    ax = fig.add_subplot(sub_plots + spl, projection=proj)
                    # If the spatial extent is small, use high-res coastlines
                    extent = iplt.default_projection_extent(cube)
                    x0, y0 = ccrs.PlateCarree().transform_point(extent[0],
                                                                extent[2],
                                                                proj)
                    x1, y1 = ccrs.PlateCarree().transform_point(extent[1],
                                                                extent[3],
                                                                proj)
                    if x1-x0 < 20 and y1-y0 < 20:
                        ax.coastlines(resolution='10m')
                    elif x1-x0 < 180 and y1-y0 < 90:
                        ax.coastlines(resolution='50m')
                    else:
                        ax.coastlines()
                else:
                    ax = plt.gca()
                    ax = fig.add_subplot(sub_plots+spl)
                plot_type = pc.plot_type
                coords = [pc_x_name, pc_y_name]
                confs.append(plot_type.value(cube, ax, coords=coords,
                                             **pc.mpl_kwargs))
                title = cube.name().replace('_', ' ').capitalize()
                ax.set_title(title)
        self.browser = cube_browser.Browser(confs)
        self.browser.on_change(None)
        # For each PlotControl, assign the plot's mpl_kwargs back to
        # that PlotControl.
        for pc, plot in zip(self.plot_controls, confs):
            pc.mpl_kwargs = plot.kwargs
        self._plot_container.children = [self.browser.form] 
Example 80
Project: faster-rcnn.pytorch_resnet50   Author: kentaroy47   File: coco.py    MIT License 4 votes vote down vote up
def showAnns(self, anns):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if 'segmentation' in anns[0]:
            datasetType = 'instances'
        elif 'caption' in anns[0]:
            datasetType = 'captions'
        if datasetType == 'instances':
            ax = plt.gca()
            polygons = []
            color = []
            for ann in anns:
                c = np.random.random((1, 3)).tolist()[0]
                if type(ann['segmentation']) == list:
                    # polygon
                    for seg in ann['segmentation']:
                        poly = np.array(seg).reshape((len(seg)/2, 2))
                        polygons.append(Polygon(poly, True,alpha=0.4))
                        color.append(c)
                else:
                    # mask
                    t = self.imgs[ann['image_id']]
                    if type(ann['segmentation']['counts']) == list:
                        rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
                    else:
                        rle = [ann['segmentation']]
                    m = mask.decode(rle)
                    img = np.ones( (m.shape[0], m.shape[1], 3) )
                    if ann['iscrowd'] == 1:
                        color_mask = np.array([2.0,166.0,101.0])/255
                    if ann['iscrowd'] == 0:
                        color_mask = np.random.random((1, 3)).tolist()[0]
                    for i in range(3):
                        img[:,:,i] = color_mask[i]
                    ax.imshow(np.dstack( (img, m*0.5) ))
            p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
            ax.add_collection(p)
        elif datasetType == 'captions':
            for ann in anns:
                print(ann['caption'])