Example #1
0
def im_plot(x, y, images):
    
    # First we build an array of the indicaes contianing the first ten images for each digit.
    vals = np.where(y == 0)[0][:10]
    
    for i in range(1, 10):
        vals = np.vstack((vals, np.where(y == i)[0][:10]))
        
    nrows, ncols = vals.shape
    
    plt.figure(figsize=(8.5,8))
    plt.gray()

    # Build a list of the indices in the order I want.
    # plot them, one by one.

    for idx, i in enumerate(vals.T.ravel()):
        ax = plt.subplot(nrows, ncols, idx + 1)
        
        # We want square images
        ax.set_aspect('equal')
        
        # Now show the images, by default pixels are shown as white on black.
        # To show black on white, reverse colormap: cmap=plt.cm.gray_r
        # To smooth pixelated images: interpolation='nearest'
        ax.imshow(images[i])
        
        # No tick marks for small plots
        plt.xticks([]) ; plt.yticks([])
        
        # Only put plot lables over columns
        if idx < 10:
            plt.title(y[i])
Example #2
0
def resetTicks(x, y=None):
    """Reset X (and Y) axis ticks using values in given *array*.  Ticks in the
    current figure should not be fractional values for this function to work as
    expected."""

    import matplotlib.pyplot as plt
    if x is not None:
        try:
            xticks = plt.xticks()[0]
            xlist = list(xticks.astype(int))
            if xlist[-1] > len(x):
                xlist.pop()
            if xlist:
                xlist = list(x[xlist])
                plt.xticks(xticks, xlist + [''] * (len(xticks) - len(xlist)))
        except:
            LOGGER.warning('xticks could not be reset.')
    if y is not None:
        try:
            yticks = plt.yticks()[0]
            ylist = list(yticks.astype(int))
            if ylist[-1] > len(y):
                ylist.pop()
            if ylist:
                ylist = list(y[ylist])
                plt.yticks(yticks, ylist + [''] * (len(yticks) - len(ylist)))
        except:
            LOGGER.warning('xticks could not be reset.')
    def plot(self, standardized=False, **kwargs):
        """
        standardized: standardize each estimated coefficient and confidence interval endpoints by the standard error of the estimate.

        """
        from matplotlib import pyplot as plt

        ax = kwargs.get('ax', None) or plt.figure().add_subplot(111)
        yaxis_locations = range(len(self.hazards_.columns))

        summary = self.summary
        lower_bound = self.confidence_intervals_.loc['lower-bound'].copy()
        upper_bound = self.confidence_intervals_.loc['upper-bound'].copy()
        hazards = self.hazards_.values[0].copy()

        if standardized:
            se = summary['se(coef)']
            lower_bound /= se
            upper_bound /= se
            hazards /= se

        order = np.argsort(hazards)
        ax.scatter(upper_bound.values[order], yaxis_locations, marker='|', c='k')
        ax.scatter(lower_bound.values[order], yaxis_locations, marker='|', c='k')
        ax.scatter(hazards[order], yaxis_locations, marker='o', c='k')
        ax.hlines(yaxis_locations, lower_bound.values[order], upper_bound.values[order], color='k', lw=1)

        tick_labels = [c + significance_code(p).strip() for (c, p) in summary['p'][order].iteritems()]
        plt.yticks(yaxis_locations, tick_labels)
        plt.xlabel("standardized coef" if standardized else "coef")
        return ax
Example #4
0
def plot_jobs_by_skills(cur, skills):

    skill_jobs = {}
    
    for skill in skills:
        cur.execute('''select count(j.id) amount from jobs j where j.id in
                    (select js.job_id from job_skills js where js.skill=?)''',
                    (skill,))
        res = cur.fetchone()
        skill_jobs[skill] = res[0]
    
    sorted_skill_jobs = zip(*sorted(skill_jobs.items(),
                            key=operator.itemgetter(1), reverse=False))

    fig = plt.figure()
    
    y_pos = np.arange(len(skill_jobs))
    print y_pos
    
    ax = plt.barh(y_pos, sorted_skill_jobs[1], align='center', alpha=0.3)
    plt.yticks(y_pos, ['\n'.join(wrap(x, 10)) for x in sorted_skill_jobs[0]])
    plt.ylabel('Skill')
    plt.xlabel('Amount of jobs')
    autolabel_h(ax)
    
    plt.gcf().subplots_adjust(left=0.20)
    
    return fig
Example #5
0
def showOverlapTable(modes_x, modes_y, **kwargs):
    """Show overlap table using :func:`~matplotlib.pyplot.pcolor`.  *modes_x*
    and *modes_y* are sets of normal modes, and correspond to x and y axes of
    the plot.  Note that mode indices are incremented by 1.  List of modes
    is assumed to contain a set of contiguous modes from the same model.

    Default arguments for :func:`~matplotlib.pyplot.pcolor`:

      * ``cmap=plt.cm.jet``
      * ``norm=plt.normalize(0, 1)``"""

    import matplotlib.pyplot as plt

    overlap = abs(calcOverlap(modes_y, modes_x))
    if overlap.ndim == 0:
        overlap = np.array([[overlap]])
    elif overlap.ndim == 1:
        overlap = overlap.reshape((modes_y.numModes(), modes_x.numModes()))

    cmap = kwargs.pop('cmap', plt.cm.jet)
    norm = kwargs.pop('norm', plt.normalize(0, 1))
    show = (plt.pcolor(overlap, cmap=cmap, norm=norm, **kwargs),
            plt.colorbar())
    x_range = np.arange(1, modes_x.numModes() + 1)
    plt.xticks(x_range-0.5, x_range)
    plt.xlabel(str(modes_x))
    y_range = np.arange(1, modes_y.numModes() + 1)
    plt.yticks(y_range-0.5, y_range)
    plt.ylabel(str(modes_y))
    plt.axis([0, modes_x.numModes(), 0, modes_y.numModes()])
    if SETTINGS['auto_show']:
        showFigure()
    return show
Example #6
0
def plot_scenario(strategies, names, scenario_id=1):
    probabilities = get_scenario(scenario_id)

    plt.figure(figsize=(6, 4.5))

    ax = plt.subplot(111)
    ax.spines["top"].set_visible(False)
    ax.spines["bottom"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(False)

    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    plt.yticks(fontsize=14)
    plt.xticks(fontsize=14)
    plt.xlim((0, 1300))

    # Remove the tick marks; they are unnecessary with the tick lines we just plotted.
    plt.tick_params(axis="both", which="both", bottom="on", top="off",
                    labelbottom="on", left="off", right="off", labelleft="on")

    for rank, (strategy, name) in enumerate(zip(strategies, names)):
        plot_strategy(probabilities, strategy, name, rank)

    plt.title("Bandits: " + str(probabilities), fontweight='bold')
    plt.xlabel('Number of Trials', fontsize=14)
    plt.ylabel('Cumulative Regret', fontsize=14)
    plt.legend(names)
    plt.show()
Example #7
0
def filterFunc():
    rects = []
    hsv_planes = [[[]]]
    if os.path.isfile(Image_File):
        BGR=cv2.imread(Image_File)
        gray = cv2.cvtColor(BGR, cv2.COLOR_BGR2GRAY)
        img = gray
        f = np.fft.fft2(img)
        fshift = np.fft.fftshift(f)
        magnitude_spectrum = 20*np.log(np.abs(fshift))
        
        plt.subplot(221),plt.imshow(img, cmap = 'gray')
        plt.title('Input Image'), plt.xticks([]), plt.yticks([])
        
        plt.subplot(222),plt.imshow(magnitude_spectrum, cmap = 'gray')
        plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
        
        FiltzeredFFT = HighPassFilter(fshift, 60)
        plt.subplot(223),plt.imshow(np.abs(FiltzeredFFT), cmap = 'gray')
        plt.title('Filtered'), plt.xticks([]), plt.yticks([])
        
		
        f_ishift = np.fft.ifftshift(FiltzeredFFT)
        img_back = np.fft.ifft2(f_ishift)
        img_back = np.abs(img_back)
        plt.subplot(224),plt.imshow(np.abs(img_back), cmap = 'gray')
        plt.title('Filtered Image'), plt.xticks([]), plt.yticks([])
        plt.show()
def export(data, F, k):
    '''Write data to a png image
    
    Arguments
    ---------
    data : numpy.ndarray
        array containing the data to be written as png image
    F : float
        feed rate of the current configuration
    k : float
        rate constant of the current configuration
    '''
        
    figsize = tuple(s / 72.0 for s in data.shape)
    fig = plt.figure(figsize=figsize, dpi=72.0, facecolor='white')
    fig.add_axes([0, 0, 1, 1], frameon=False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(data, cmap=plt.cm.RdBu_r, interpolation='bicubic')
    plt.gci().set_clim(0, 1)

    filename = './study/F{:03d}-k{:03d}.png'.format(int(1000*F), int(1000*k))
    plt.savefig(filename, dpi=72.0)
    plt.close()
Example #9
0
    def as_pyplot_figure(self, label=1, **kwargs):
        """Returns the explanation as a pyplot figure.

        Will throw an error if you don't have matplotlib installed
        Args:
            label: desired label. If you ask for a label for which an
                   explanation wasn't computed, will throw an exception.
            kwargs: keyword arguments, passed to domain_mapper

        Returns:
            pyplot figure (barchart).
        """
        import matplotlib.pyplot as plt
        exp = self.as_list(label, **kwargs)
        fig = plt.figure()
        vals = [x[1] for x in exp]
        names = [x[0] for x in exp]
        vals.reverse()
        names.reverse()
        colors = ['green' if x > 0 else 'red' for x in vals]
        pos = np.arange(len(exp)) + .5
        plt.barh(pos, vals, align='center', color=colors)
        plt.yticks(pos, names)
        plt.title('Local explanation for class %s' % self.class_names[label])
        return fig
Example #10
0
    def make_line(
        x,
        y,
        f_name,
        title=None,
        legend=None,
        x_label=None,
        y_label=None,
        x_ticks=None,
        y_ticks=None,
    ):
        fig = plt.figure()

        if title is not None:
            plt.title(title, fontsize=16)
        if x_label is not None:
            plt.ylabel(x_label)
        if y_label is not None:
            plt.xlabel(y_label)
        if x_ticks is not None:
            plt.xticks(x, x_ticks)
        if y_ticks is not None:
            plt.yticks(y_ticks)

        if isinstance(y[0], list):
            for data in y:
                plt.plot(x, data)
        else:
            plt.plot(x, y)

        if legend is not None:
            plt.legend(legend)

        plt.savefig(f_name)
        plt.close(fig)
Example #11
0
def tuning(x, y, err=None, smooth=None, ylabel=None, pal=None):
    """
    Plot a tuning curve
    """
    if smooth is not None:
        xs, ys = smoothfit(x, y, smooth)
        plt.plot(xs, ys, linewidth=4, color="black", zorder=1)
    else:
        ys = asarray([0])
    if pal is None:
        pal = sns.color_palette("husl", n_colors=len(x) + 6)
        pal = pal[2 : 2 + len(x)][::-1]
    plt.scatter(x, y, s=300, linewidth=0, color=pal, zorder=2)
    if err is not None:
        plt.errorbar(x, y, yerr=err, linestyle="None", ecolor="black", zorder=1)
    plt.xlabel("Wall distance (mm)")
    plt.ylabel(ylabel)
    plt.xlim([-2.5, 32.5])
    errTmp = err
    errTmp[isnan(err)] = 0
    rng = max([nanmax(ys), nanmax(y + errTmp)])
    plt.ylim([0 - rng * 0.1, rng + rng * 0.1])
    plt.yticks(linspace(0, rng, 3))
    plt.xticks(range(0, 40, 10))
    sns.despine()
    return rng
Example #12
0
def plot_jacobian(A, name, cmap= plt.cm.coolwarm, normalize=True, precision=1e-6):

    """
    Customized visualization of jacobian matrices for observing
    sparsity patterns
    """
    
    plt.figure()
    fig, ax = plt.subplots()
    
    if normalize is True:
        plt.imshow(A, interpolation='none', cmap=cmap,
                   norm = mpl.colors.Normalize(vmin=-1.,vmax=1.))
    else:
        plt.imshow(A, interpolation='none', cmap=cmap)        
    plt.colorbar(format=ticker.FuncFormatter(fmt))
    
    ax.spy(A, marker='.', markersize=0,  precision=precision)
    
    ax.spines['right'].set_visible(True)
    ax.spines['bottom'].set_visible(True)
    ax.xaxis.set_ticks_position('top')
    ax.yaxis.set_ticks_position('left')

    xlabels = np.linspace(0, A.shape[0], 5, True, dtype=int)
    ylabels = np.linspace(0, A.shape[1], 5, True, dtype=int)

    plt.xticks(xlabels)
    plt.yticks(ylabels)

    plt.savefig(name, bbox_inches='tight', pad_inches=0.05)
    
    plt.close()

    return
Example #13
0
    def make_bar(
        x,
        y,
        f_name,
        title=None,
        legend=None,
        x_label=None,
        y_label=None,
        x_ticks=None,
        y_ticks=None,
    ):
        fig = plt.figure()

        if title is not None:
            plt.title(title, fontsize=16)
        if x_label is not None:
            plt.ylabel(x_label)
        if y_label is not None:
            plt.xlabel(y_label)
        if x_ticks is not None:
            plt.xticks(x, x_ticks)
        if y_ticks is not None:
            plt.yticks(y_ticks)

        plt.bar(x, y, align="center")

        if legend is not None:
            plt.legend(legend)

        plt.savefig(f_name)
        plt.close(fig)
Example #14
0
    def plotPath(self, seq, poses_gt, poses_result):
        plot_keys = ["Ground Truth", "Ours"]
        fontsize_ = 20
        plot_num = -1

        poses_dict = {}
        poses_dict["Ground Truth"] = poses_gt
        poses_dict["Ours"] = poses_result

        fig = plt.figure()
        ax = plt.gca()
        ax.set_aspect('equal')

        for key in plot_keys:
            pos_xz = []
            # for pose in poses_dict[key]:
            for frame_idx in sorted(poses_dict[key].keys()):
                pose = poses_dict[key][frame_idx]
                pos_xz.append([pose[0, 3], pose[2, 3]])
            pos_xz = np.asarray(pos_xz)
            plt.plot(pos_xz[:, 0], pos_xz[:, 1], label=key)

        plt.legend(loc="upper right", prop={'size': fontsize_})
        plt.xticks(fontsize=fontsize_)
        plt.yticks(fontsize=fontsize_)
        plt.xlabel('x (m)', fontsize=fontsize_)
        plt.ylabel('z (m)', fontsize=fontsize_)
        fig.set_size_inches(10, 10)
        png_title = "sequence_{:02}".format(seq)
        plt.savefig(self.plot_path_dir + "/" + png_title + ".pdf", bbox_inches='tight', pad_inches=0)
Example #15
0
def make_entity_plot(filename, title, fixed_noip, fixed_ip, dynamic_noip, dynamic_ip):
    plt.figure(figsize=(12,5))

    plt.title("Settings comparison - " + title)
    
    plt.xlabel('Time (ms)', fontsize=12)
    plt.xlim([0,62000])

    x = 0
    barwidth = 0.5
    bargroupspacing = 1.5

    fixed_noip_mean,fixed_noip_conf = conf_stats(fixed_noip)
    fixed_ip_mean,fixed_ip_conf = conf_stats(fixed_ip)
    dynamic_noip_mean,dynamic_noip_conf = conf_stats(dynamic_noip)
    dynamic_ip_mean,dynamic_ip_conf = conf_stats(dynamic_ip)

    values = [fixed_noip_mean,fixed_ip_mean,dynamic_noip_mean, dynamic_ip_mean]
    errs = [fixed_noip_conf,fixed_ip_conf,dynamic_noip_conf, dynamic_ip_conf]

    y_pos = numpy.arange(len(values))
    plt.barh(y_pos, values, xerr=errs, align='center', color=['r', 'b', 'r', 'b'],  ecolor='black', alpha=0.7)
    plt.yticks(y_pos, ["Fixed | no I.P.", "Fixed | I.P.", "Dynamic | no I.P.", "Dynamic | I.P."])
    plt.savefig(output_file(filename))
    plt.clf()
Example #16
0
def plot_gen(ping, now, t, nans, host, interactive=False, size="1280x640"):
    ''' Generates ping vs time plot '''
    if not interactive:
        import matplotlib
        matplotlib.use("Agg") # no need to load gui toolkit, can run headless
    import matplotlib.pyplot as plt
    
    size      = [int(dim) for dim in size.split('x')]
    datestr   = now[0].ctime().split()
    datestr   = datestr[0] + " " + datestr[1] + " " + datestr[2] + " " + datestr[-1]
    plt.figure(figsize=(size[0]/80.,size[1]/80.)) # dpi is 80
    plt.plot(now[~nans], ping[~nans], drawstyle='steps', marker='+')
    plt.title("Ping Results for {0}".format(host))
    plt.ylabel("Latency [ms]")
    plt.xlabel("Time, {0} [GMT -{1} hrs]".format(datestr, time.timezone/3600))
    plt.xticks(size=10)
    plt.yticks(size=10)
    plt.ylim(ping[~nans].min()-5, ping[~nans].max()+5)
    
    # plot packet losses
    start  = []
    finish = []
    for i in range(len(nans)):
        if nans[i] == True:
            if i == 0:
                start.append(i)
            elif nans[i] != nans[i-1]:
                start.append(i)
            #if i != len(nans) and nans[i+1] != nans[i]:
            #    finish.append(i)
                
    # add the red bars for bad pings
    for i in range(len(start)):
        plt.axvspan(now[start[i]], now[finish[i]+1], color='red')
    return plt
Example #17
0
def fig(data, target):
    #FIXME
    plt.scatter(data, target,  color='black')
    plt.xticks(())
    plt.yticks(())

    plt.show()
def test_rotated_labels_parameters_different_values(x_tick_label_width,
                                                    y_tick_label_width):
    fig, ax = __plot()

    plt.xticks(ha='left', rotation=90)
    plt.yticks(ha='left', rotation=90)
    ax.xaxis.get_majorticklabels()[0].set_rotation(20)
    ax.yaxis.get_majorticklabels()[0].set_horizontalalignment('right')

    # convert to tikz file
    _, tmp_base = tempfile.mkstemp()
    tikz_file = tmp_base + '_tikz.tex'

    extra_dict = {}

    if x_tick_label_width:
        extra_dict['x tick label text width'] = x_tick_label_width
    if y_tick_label_width:
        extra_dict['y tick label text width'] = y_tick_label_width

    matplotlib2tikz.save(
        tikz_file,
        figurewidth='7.5cm',
        extra_axis_parameters=extra_dict
        )

    # close figure
    plt.close(fig)

    # delete file
    os.unlink(tikz_file)
def template_matching():
    img = cv2.imread('messi.jpg',0)
    img2 = img.copy()
    template = cv2.imread('face.png',0)
    w, h = template.shape[::-1]

    # All the 6 methods for comparison in a list
    methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']

    for meth in methods:
        img = img2.copy()
        method = eval(meth)

        # Apply template Matching
        res = cv2.matchTemplate(img,template,method)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

        # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc
        bottom_right = (top_left[0] + w, top_left[1] + h)

        cv2.rectangle(img,top_left, bottom_right, 255, 2)

        plt.subplot(121),plt.imshow(res,cmap = 'gray')
        plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
        plt.subplot(122),plt.imshow(img,cmap = 'gray')
        plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
        plt.suptitle(meth)

        plt.show()
Example #20
0
def plt_data():
    t = [[0,1], [1,0], [1, 1], [0, 0]]
    t2 = [1, 1, 1, 0]
    X = np.array(t)
    Y = np.array(t2)

    h = .02  # step size in the mesh

    logreg = linear_model.LogisticRegression(C=1e5)

    # we create an instance of Neighbours Classifier and fit the data.
    logreg.fit(X, Y)
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(4, 3))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
    plt.xlabel('Sepal length')
    plt.ylabel('Sepal width')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show()
def test_rotated_labels_parameters(x_alignment, y_alignment,
                                   x_tick_label_width, y_tick_label_width,
                                   rotation):
    fig, _ = __plot()

    if x_alignment:
        plt.xticks(ha=x_alignment, rotation=rotation)
    if y_alignment:
        plt.yticks(ha=y_alignment, rotation=rotation)

    # convert to tikz file
    _, tmp_base = tempfile.mkstemp()
    tikz_file = tmp_base + '_tikz.tex'

    extra_dict = {}

    if x_tick_label_width:
        extra_dict['x tick label text width'] = x_tick_label_width
    if y_tick_label_width:
        extra_dict['y tick label text width'] = y_tick_label_width

    matplotlib2tikz.save(
        tikz_file,
        figurewidth='7.5cm',
        extra_axis_parameters=extra_dict
        )

    # close figure
    plt.close(fig)

    # delete file
    os.unlink(tikz_file)
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
def nodeplot(xnode,figtitle):
    fig = demo.figure(figtitle,'', '',[-0.0001, 1.0001], [-0.05, 0.05],figsize=[6,1.5])
    plt.plot(xnode, np.zeros_like(xnode),'bo',ms=8)
    plt.xticks([0,1])
    plt.yticks([])
    
    figures.append(fig)
Example #24
0
def _plot(_df, fig, ax):
    """
    """

    _df = pd.DataFrame(_df)
    df = _df.sort('ratio')
    df['color'] = 'grey'
    df.color[(df.lower > 1) & (df.upper > 1)] = 'blue'
    df.color[(df.lower < 1) & (df.upper < 1)] = 'red'

    df.index = range(len(df))  # reset the index to reflect order

    if fig is None and ax is None:
        fig, ax = plt.subplots(figsize=(8, 12))

    ax.set_aspect('auto')
    ax.set_xlabel('Odds ratio')
    ax.grid(False)
    ax.set_ylim(-.5, len(df) - .5)
    plt.yticks(df.index)

    ax.scatter(df.ratio, df.index, c=df.color, s=50)
    for pos in range(len(df)):
        ax.fill_between([df.lower[pos], df.upper[pos]], pos-.01, pos+.01, color='grey', alpha=.3)

    ax.set_yticklabels(df.names)
    ax.vlines(x=1, ymin=-.5, ymax=len(df)-.5, colors='grey', linestyles='--')

    return fig, ax
Example #25
0
def plot_heat_net(net_mat, sectors):
    """Plot a heat map of the net relations.

    Parameters
    ----------
    net_mat: np.ndarray
        the net represented in a matrix way.
    sectors: list
        the name of the elements of the adjacency matrix network.

    Returns
    -------
    fig: matplotlib.pyplot.figure
        the figure of the matrix heatmap.

    """
    vmax = np.sort([np.abs(net_mat.max()), np.abs(net_mat.min())])[::-1][0]
    n_sectors = len(sectors)
    assert(net_mat.shape[0] == net_mat.shape[1])
    assert(n_sectors == len(net_mat))

    fig = plt.figure()
    plt.imshow(net_mat, interpolation='none', cmap=plt.cm.RdYlGn,
               vmin=-vmax, vmax=vmax)
    plt.xticks(range(n_sectors), sectors)
    plt.yticks(range(n_sectors), sectors)
    plt.xticks(rotation=90)
    plt.colorbar()
    return fig
Example #26
0
def makePlot(
                k,
                counts,
                yaxis=[],
                width=0.8,
                figsize=[14.0,8.0],
                title="",
                ylabel='tmpylabel',
                xlabel='tmpxlabel',
                labels=[],
                show=False,
                grid=True,
                xticks=[],
                yticks=[],
                steps=5,
                save=False
            ):
    '''
    '''
    if not list(yaxis):
        yaxis = np.arange(len(counts))
    if not labels:
        labels = yaxis
    index = np.arange(len(yaxis))

    fig, ax = plt.subplots()
    fig.set_size_inches(figsize[0],figsize[1])
    plt.bar(index, counts, width)

    plt.title(title)
    if not xticks:
        print ('Making xticks')
        ticks = makeTicks(yMax=len(yaxis),steps=steps)
        xticks.append(ticks+width/2.)
        xticks.append(labels)
        print ('Done making xticks')

    if yticks:
        print ('Making yticks')
        # plt.yticks([1,2000],[0,100])
        plt.yticks(yticks[0],yticks[1])
        # ax.set_yticks(np.arange(0,100,10))
        print ('Done making yticks')

    plt.xticks(xticks[0]+width/2., xticks[1])
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    # ax.set_xticks(range(0,len(counts)+2))

    fig.autofmt_xdate()
    # ax.set_xticklabels(ks)

    plt.axis([0, len(yaxis), 0, max(counts) + (max(counts)/100)])
    plt.grid(grid)
    location = ROOT_FOLDER + "/../muchBazar/src/image/" + k + "distribution.png"
    if save:
        plt.savefig(location)
        print ('Distribution written to: %s' % location)
    if show:
        plt.show()
Example #27
0
def tiCarryPlot(getTIresult):
    conCarry = getTIresult.ix[:,0]*getTIresult.ix[:,1]
    disCarry = getTIresult.ix[:,0]*getTIresult.ix[:,2]
    cumBetas = np.cumprod(getTIresult.ix[:,0]/100+1)-1
    cumConBetas = np.cumprod(conCarry/100+1)-1
    cumDisBetas = np.cumprod(disCarry/100+1)-1

    fig = plt.figure()

    ax1 = fig.add_subplot(311)
    ax1.set_title('Cumulative Betas')
    cumBetas.plot(style='r',label='Original Beta')
    cumConBetas.plot(style='b', label='Discrete Weights')
    cumDisBetas.plot(style='g', label='Digital Weights')
    plt.legend(loc=2)

    ax2 = fig.add_subplot(312)
    ax2.set_title('Discrete Weights')
    getTIresult.ix[:,1].plot(style='b')
    plt.ylim([0, 1.2])
    plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2])

    ax3 = fig.add_subplot(313)
    ax3.set_title('Digital Weights')
    getTIresult.ix[:,2].plot(style='g')
    plt.ylim([-0.1, 1.1])
    plt.yticks([-0.1, 0.1, 0.3, 0.5, 0.7, 0.9, 1.1])

    fig.tight_layout()
    plt.show()
Example #28
0
def streamlineBxz_dens():
    fig=plt.figure()
    ppy=yt.ProjectionPlot(ds, "y", "Bxz", weight_field="density") #Project X-component of B-field from z-direction
    By=ppy._frb["density"]
    ax=fig.add_subplot(111)
    plt.xticks(tick_locs,tick_lbls)
    plt.yticks(tick_locs,tick_lbls)
    Bymag=ax.pcolormesh(np.log10(By), cmap="YlGn")
    cbar_m=plt.colorbar(Bymag)
    cbar_m.set_label("density")
    res=800

    #densxy=Density2D(0,1) #integrated density along given axis
    U=Flattenx(0,1) #X-magnetic field integrated along given axis
    V=Flattenz(0,1) #Z-magnetic field
    #U=np.asarray(zip(*x2)[::-1]) #rotate the matrix 90 degrees to correct orientation to match projected plots
    #V=np.asarray(zip(*y2)[::-1])
    norm=np.sqrt(U**2+V**2) #magnitude of the vector
    Unorm=U/norm #normalise vectors 
    Vnorm=V/norm
    #mask_Unorm=np.ma.masked_where(densxy<np.mean(densxy),Unorm) #create a masked array of Unorm values only in high density regions
    #mask_Vnorm=np.ma.masked_where(densxy<np.mean(densxy),Vnorm)
    X,Y=np.meshgrid(np.linspace(0,res,64, endpoint=True),np.linspace(0,res,64,endpoint=True))
    streams=plt.streamplot(X,Y,Unorm,Vnorm,color=norm*1e6,density=(3,3),cmap=plt.cm.autumn)
    cbar=plt.colorbar(orientation="horizontal")
    cbar.set_label('Bxz streamlines (uG)')
    plt.title("Bxz streamlines on weighted density projection")
    plt.xlabel("(1e4 AU)")
    plt.ylabel("(1e4 AU)")
Example #29
0
def plotresult(i=0, j=101, step=1):
    import matplotlib.pyplot as mpl
    from numpy import arange

    res = getevaluation(i, j, step)
    x = [k / 100.0 for k in range(i, j, step)]
    nbcurve = len(res[0])
    nres = [[] for i in xrange(nbcurve)]
    mres = []
    maxofmin = -1, 0.01
    for kindex, kres in enumerate(res):
        minv = min(kres.values())
        if minv > maxofmin[1]:
            maxofmin = kindex, minv
        lres = [(i, j) for i, j in kres.items()]
        lres.sort(lambda x, y: cmp(x[0], y[0]))
        for i, v in enumerate(lres):
            nres[i].append(v[1])
        mres.append(sum([j for i, j in lres]) / nbcurve)
    print maxofmin
    for y in nres:
        mpl.plot(x, y)
    mpl.plot(x, mres, linewidth=2)
    mpl.ylim(0.5, 1)
    mpl.xlim(0, 1)
    mpl.axhline(0.8)
    mpl.axvline(0.77)
    mpl.xticks(arange(0, 1.1, 0.1))
    mpl.yticks(arange(0.5, 1.04, 0.05))
    mpl.show()
Example #30
0
def tagcloud(worddict, n=10, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0):
    from matplotlib import pyplot as plt
    import random

    worddict = wordfreq_to_weightsize(worddict, minsize, maxsize, minalpha, maxalpha)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_position([0.0,0.0,1.0,1.0])
    plt.xticks([])
    plt.yticks([])

    words = worddict.keys()
    alphas = [v[0] for v in worddict.values()]
    sizes = [v[1] for v in worddict.values()]
    items = zip(alphas, sizes, words)
    items.sort(reverse=True)
    for alpha, size, word in items[:n]:
        # xpos = random.normalvariate(0.5, 0.3)
        # ypos = random.normalvariate(0.5, 0.3)
        xpos = random.uniform(0.0,1.0)
        ypos = random.uniform(0.0,1.0)
        ax.text(xpos, ypos, word.lower(), alpha=alpha, fontsize=size)
    ax.autoscale_view()
    return ax
Example #31
0

plt.figure(figsize=(10, 8))
plt.title('Parity plot of the training and testing data for Catboost Algorithm',
        fontsize=16)
plt.grid(color='blue', linestyle='dotted', linewidth=0.8)
plt.xlabel("Experimental Rupture Time [hrs]", fontsize=16)
plt.ylabel("Predicted Ruptrue Time [hrs]", fontsize=16)
plt.plot(np.arange(0, 200000), np.arange(0, 200000), 
        c='darkblue', linewidth=4, zorder=0, label='parity line')
plt.scatter(data['y_cv_tr'], data['y_cv_tr_pred'], 
    marker='h', s=50, color='darkred', alpha=0.8, label='Train')
plt.scatter(data['y_cv_ts'], data['y_cv_ts_pred'], 
    marker='h', s=50, color='darkgreen', alpha=0.8, label='Test')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.legend(loc='best', fontsize=14)
ax = plt.gca()
text = r'$PCC_{0}$: {1:0.2f} $\pm$ {2:0.2f} {3} $PCC_{4}$: {5:0.2f} '
text += r'$\pm$ {6:0.2f}'
text = text.format('{test}', data['pr_mean_test'], data['pr_std_test'], '\n',
        '{train}', data['pr_mean_train'], data['pr_std_train'])
plt.text(0.2, 0.7, text,
         ha='center', va='center', fontsize=14,
         bbox=dict(facecolor='lightblue',
         edgecolor='green',
         boxstyle='round',
         pad=1),
         transform=ax.transAxes)
plt.savefig('Parity_Plot.png')
plt.show()
Example #32
0
    def __init__(self, visualization=True):
        global WIDTH, HEIGHT, COL_NUM, ROW_NUM, GRID_SIZE

        self.visualization = visualization
        plt.cla()
        plt.rcParams["figure.figsize"] = (16, 8)
        ax = plt.subplot(111)
        # ========== Board setup ========== #
        GRID_SIZE = 7
        COL_NUM = 180
        ROW_NUM = 90
        WIDTH = GRID_SIZE * COL_NUM
        HEIGHT = GRID_SIZE * ROW_NUM

        #=========== Variables ============ #
        dist_min = 110  #함선끼리 떨어져 있는 min 거리
        mRange = 7  #missile Range

        # Reset board
        self.board = np.zeros((ROW_NUM, COL_NUM))
        self.saturation_matrix = self.board.copy()
        self.ships = []
        self.enemies = []

        # =========== Ship information =========== #
        self.aNum = input("How many ships do you want? ::")
        self.eNum = input("How many enemies? ::")

        #여기는 함선이 너무 따닥따닥 붙어있어서 경로 겹치는 것을 방지하고자 만든 곳임.
        for i in range(self.aNum):
            # 1: enemy, 2: me

            while True:
                ts = dist_min
                index_y = random.randrange(ROW_NUM)
                index_x = random.randrange(COL_NUM // 4)
                for j in range(len(self.ships)):
                    ts = (index_y - self.ships[j][0])**2 + (
                        index_x - self.ships[j][1])**2
                    if ts < dist_min:
                        break
                if ts < dist_min:
                    continue
                #이부분이 배 위치 저장하는 곳
                #index_y, index_x가 좌표, math_pi/8.0 방향, 속동, 각속도
                #진아님이 배 정보를 추가하고 싶다면 append에서 [] 안에 컬럼 하나 넣어주면 됩니당
                self.board[index_y][index_x] = 2
                self.ships.append([index_y, index_x, math.pi / 8.0, 0.0, 0.0])
                #grid에 추구하는 부분
                plt.plot(index_x, index_y, "xb")  #점 표시
                plot_arrow(index_x, index_y, math.pi / 8.0)  #화살표 표시
                c = plt.Circle((index_x, index_y), mRange, fc='w', ec='b')
                ax.add_patch(c)
                break

        for i in range(self.eNum):
            # 1: enemy, 2: me
            while True:
                ts = dist_min
                index_y = random.randrange(ROW_NUM)
                index_x = random.randrange(COL_NUM // 4) + COL_NUM * 3 // 4
                for j in range(len(self.enemies)):
                    ts = (index_y - self.enemies[j][0])**2 + (
                        index_x - self.enemies[j][1])**2
                    if ts < dist_min:
                        break
                if ts < dist_min:
                    continue
                #이부분이 적군 위치 저장하는 곳
                #index_y, index_x가 좌표, math_pi/8.0 방향, 속동, 각속도
                #진아님이 배 정보를 추가하고 싶다면 append에서 [] 안에 컬럼 하나 넣어주면 됩니당
                self.board[index_y][index_x] = 1
                self.enemies.append(
                    [index_y, index_x, math.pi / 8.0, 0, 0, 0, 0])
                plt.plot(index_x, index_y, "xr")
                plot_arrow(index_x, index_y, math.pi / 8.0)
                c = plt.Circle((index_x, index_y), mRange, fc='w', ec='r')
                ax.add_patch(c)
                break

# ========== Graphics setup ========== #
        if self.visualization:
            """self.window = tk.Tk()

			self.window.title("AI with Weapon System")
			self.window.configure(background="white")
			self.canvas = tk.Canvas(self.window, width=WIDTH, height=HEIGHT)
			self.GRID_SIZE = GRID_SIZE
			self.canvas.grid(row=GRID_SIZE, column=GRID_SIZE, columnspan=COL_NUM, rowspan=ROW_NUM)
"""
            #fig = plt.figure(figsize=(50,100))
            #fig.add_subplot(1, 1, 1)
            plt.xlim([0, 180])
            plt.ylim([0, 90])
            plt.grid(True)

            plt.xticks([i for i in range(0, 180)])
            plt.yticks([i for i in range(0, 90)])  #i for i in range(0,90)
            plt.grid(
                color='#BDBDBD',
                linestyle='-',
                linewidth=1,
            )

        plt.show()
import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread("messi5.jpg", 0)
plt.imshow(img, cmap="gray", interpolation="bicubic")

plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()
from matplotlib import pyplot as plt

nodeVec=[2,4,6,8,10,12]
acc=[0.8240,0.8070,0.7920,0.7440,0.7790,0.7580]
# GAT_m=[0.8,14.1,56.6,81.5]
# nodeVecSpecial=[1000,5000,10000,12000]

xshow=nodeVec
yshow=[0,0.20,0.40,0.60,0.80,1.00]

plt.plot(nodeVec,acc,marker='D',mec='b',mfc='w',label='FastGAT(our method)')
# plt.plot(nodeVecSpecial,GAT_m,marker='*',mec='b',ms=10,label='GAT(baseline)')
plt.legend()
plt.xticks(xshow)

# plt.margins(0)

plt.subplots_adjust(bottom=0.10)
plt.xlabel('Number of Buckets') #X轴标签
plt.ylabel("accuarcy ") #Y轴标签
plt.yticks(yshow)

plt.savefig('./sdata_plot_bucket.png',dpi=1000)
Example #35
0
def gantt(time_schedule, figure_name):
    plt.rcParams['figure.figsize'] = (16.0, 9.0)
    ax = plt.gca()
    [ax.spines[i].set_visible(False) for i in ["top", "right"]]
    x = []
    y = []
    time_schedule.reverse()
    for i in range(len(time_schedule)):
        if i == 0:
            y.append(time_schedule[i][0])
            x.append(time_schedule[i][1])
            plt.plot([time_schedule[i][1], time_schedule[i][1]], [-1, i + 1.2],
                     color='black',
                     linestyle='--',
                     linewidth=0.4)
            plt.barh(i,
                     time_schedule[i][2],
                     height=0.6,
                     color='r',
                     hatch='///',
                     label='Waiting costs',
                     left=time_schedule[i][1])
            plt.barh(i,
                     time_schedule[i][3],
                     height=0.6,
                     color='b',
                     hatch='++',
                     label='Service time',
                     left=time_schedule[i][1] + time_schedule[i][2])
            plt.barh(i,
                     time_schedule[i][4],
                     height=0.6,
                     color='y',
                     hatch='oo',
                     label='Travel costs',
                     left=time_schedule[i][1] + time_schedule[i][2] +
                     time_schedule[i][3])
        else:
            y.append(time_schedule[i][0])
            x.append(time_schedule[i][1])
            plt.plot([time_schedule[i][1], time_schedule[i][1]], [-1, i + 1.2],
                     color='black',
                     linestyle='--',
                     linewidth=0.4)
            plt.barh(i,
                     time_schedule[i][2],
                     height=0.6,
                     color='r',
                     hatch='///',
                     left=time_schedule[i][1])
            plt.barh(i,
                     time_schedule[i][3],
                     height=0.6,
                     color='b',
                     hatch='++',
                     left=time_schedule[i][1] + time_schedule[i][2])
            plt.barh(i,
                     time_schedule[i][4],
                     height=0.6,
                     color='y',
                     hatch='oo',
                     left=time_schedule[i][1] + time_schedule[i][2] +
                     time_schedule[i][3])
    plt.ylabel('Elders\' labels')
    plt.xlabel('Time line starting from 8 A.M. / min')
    plt.yticks(np.arange(len(time_schedule)), y, size=10)
    plt.xticks(x[:-1], size=10)
    plt.ylim(-0.1, len(time_schedule))
    plt.legend(loc='upper right', frameon=False, fontsize=12)
    name = figure_name + '.png'
    plt.savefig(name, dpi=700)
    plt.close()
fig, ax = plt.subplots(figsize=(5.5,5))
ax.plot(f,plvtap_2.T,label='CORR',linewidth=2,color='b')
ax.plot(f,plvtap_1.T,label='ACORR',linewidth=2,color='r')

np.max(plvtap_2[:,150:167],axis=1)

fig, ax = plt.subplots(figsize=(5.5,5))
fontsize=15
ax.plot(f,plvtap_2[13,:],label='CORR',linewidth=2)
ax.plot(f,plvtap_1[13,:],label='ACORR',linewidth=2)
ax.legend(fontsize=fontsize)
plt.xlabel('Frequency (Hz)',fontsize=fontsize,fontweight='bold')
#plt.ylabel('PLV',fontsize=fontsize,fontweight='bold')
plt.xlim((35,45))
plt.xticks([35,40,45],fontsize=fontsize)
plt.yticks([0,0.04,0.08],fontsize=fontsize)


fig, ax = plt.subplots(figsize=(5.5,5))
fontsize=15
ax.plot(f,plvtap_2.T,label='CORR',linewidth=2,color='b')
ax.plot(f,plvtap_1.T,label='ACORR',linewidth=2,color='r')

plt.figure()
plt.plot(f,plvtap_1.T)
plt.title(labels[0])

plt.figure()
plt.plot(f,plvtap_2.T)
plt.title(labels[1])
Example #37
0
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# 边缘检测
img = cv2.imread('./images/messi.jpg', cv2.IMREAD_GRAYSCALE)
laplacian = cv2.Laplacian(img, cv2.CV_64F)
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)

# 图像对比
plt.figure(figsize=(10, 5))
plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original')
plt.xticks([])
plt.yticks([])

plt.subplot(2, 2, 2)
plt.imshow(laplacian, cmap='gray')
plt.title('Laplacian')
plt.xticks([])
plt.yticks([])

plt.subplot(2, 2, 3)
plt.imshow(sobelx, cmap='gray')
plt.title('Sobel X')
plt.xticks([])
plt.yticks([])

plt.subplot(2, 2, 4)
plt.imshow(sobely, cmap='gray')
### Plot
trendp = plt.plot(linep,linewidth=1.4,linestyle='-',color='steelblue'),
sg = plt.plot(mean_sitsg,linestyle='-',linewidth=0.8,color='saddlebrown',
             label=r'\textbf{ICESat-G}',marker='o',markersize=3)
sj = plt.plot(mean_sitsj,linestyle='-',linewidth=0.8,color='seagreen',
             label=r'\textbf{ICESat-J}',marker='o',markersize=3)
c = plt.plot(mean_cryo,linestyle='-',linewidth=0.8,color='fuchsia',
             label=r'\textbf{CryoSat-2}',marker='o',markersize=3)
p = plt.plot(mean_sitp,linestyle='-',linewidth=0.8,color='steelblue',
             label=r'\textbf{PIOMAS}',marker='^',markersize=4)            

### Labels for x/y
labelsy = map(str,np.arange(1,5,1))
labelsx = map(str,np.arange(1979,2016,3))
plt.xticks(np.arange(0,37,3),labelsx)
plt.yticks(np.arange(1,5,1),labelsy)
plt.ylabel(r'\textbf{Thickness (m)}',fontsize=11)

### Adjust axes in time series plots 
def adjust_spines(ax, spines):
    for loc, spine in ax.spines.items():
        if loc in spines:
            spine.set_position(('outward', 10))
        else:
            spine.set_color('none')  
    if 'left' in spines:
        ax.yaxis.set_ticks_position('left')
    else:
        ax.yaxis.set_ticks([])

    if 'bottom' in spines:
cwd = os.path.dirname(os.path.abspath(__file__))

# Change the working directory
os.chdir(cwd)

# Load a grayscale image
img_color = cv2.imread('traffic-light.jpg')
cv2.imshow('Traffic Light', img_color)
cv2.waitKey(0)

# Color Channels
img_B, img_G, img_R = cv2.split(img_color)

# Image thresholding
thld, max_v = 200, 255
ret, img_R_thld = cv2.threshold(img_R, thld, max_v, cv2.THRESH_BINARY)
ret, img_G_thld = cv2.threshold(img_G, thld, max_v, cv2.THRESH_BINARY)
ret, img_B_thld = cv2.threshold(img_B, thld, max_v, cv2.THRESH_BINARY)

# Display results
titles = ['Red', 'Green', 'Blue']
images = [img_R_thld, img_G_thld, img_B_thld]

for i in range(3):
    plt.subplot(1, 3, i + 1)
    plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])

plt.show()
Example #40
0
import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([0.650, 0.660, 0.675, 0.685])
my_xticks = ['a', 'b', 'c', 'd']
plt.xticks(x, my_xticks)
plt.yticks(np.arange(y.min(), y.max(), 0.005))
plt.plot(x, y)
plt.grid(axis='x', linestyle='-')
plt.show()
Example #41
0
for label in os.listdir(label_path):
    if label not in ['1553066274T0_1_.txt']:
        continue
    print(label)
    name = label.strip().split('.')
    if name[-1] == 'json':
        continue
    path = img_path + os.sep + str(name[0]) + ".jpg"
    img = cv2.imread(path)
    # cv2.imshow('a.jpg',img)
    # cv2.waitKey()
    f = open(os.path.join(label_path, label), 'r')
    # if len(f.readlines())!=1:
    #     print(label)
    for i in f.readlines():
        info = i.strip().split()
        print(info)
        n = info[0]
        info = [int(float(x)) for x in info[1:]]
        cv2.line(img, (info[0], info[1]), (info[2], info[3]), (0, 255, 0))
        cv2.line(img, (info[0], info[1]), (info[6], info[7]), (0, 255, 0))
        cv2.line(img, (info[4], info[5]), (info[2], info[3]), (0, 255, 0))
        cv2.line(img, (info[4], info[5]), (info[6], info[7]), (0, 255, 0))
        print(info)
    img2 = img[:, :, ::-1]
    # plt.subplot(111)
    plt.xticks([]), plt.yticks([])  # 隐藏x和y轴
    plt.imshow(img2)
    plt.show()
Example #42
0
def main(out_dir=None,
         metadata_file=None,
         corpus_name=None,
         default_annotator=None,
         metadata_criteria={},
         win_params={},
         slowfast_csv_params={},
         label_types=('event', 'action', 'part')):
    out_dir = os.path.expanduser(out_dir)
    metadata_file = os.path.expanduser(metadata_file)

    logger = utils.setupRootLogger(filename=os.path.join(out_dir, 'log.txt'))

    fig_dir = os.path.join(out_dir, 'figures')
    if not os.path.exists(fig_dir):
        os.makedirs(fig_dir)

    out_labels_dir = os.path.join(out_dir, 'labels')
    if not os.path.exists(out_labels_dir):
        os.makedirs(out_labels_dir)

    data_dirs = {
        name: os.path.join(out_dir, f"{name}-dataset")
        for name in label_types
    }
    for name, dir_ in data_dirs.items():
        if not os.path.exists(dir_):
            os.makedirs(dir_)
    assembly_data_dir = os.path.join(out_dir, 'assembly-dataset')
    if not os.path.exists(assembly_data_dir):
        os.makedirs(assembly_data_dir)

    (seq_ids, event_labels, assembly_seqs, frame_fn_seqs, frame_fn_idx_seqs,
     vocabs, assembly_action_vocab,
     metadata) = load_all_labels(corpus_name,
                                 default_annotator,
                                 metadata_file,
                                 metadata_criteria,
                                 start_video_from_first_touch=True,
                                 subsample_period=None,
                                 use_coarse_actions=True)

    assembly_vocab = []
    assembly_idx_seqs = tuple(
        tuple(labels.gen_eq_classes(state_seq, assembly_vocab))
        for state_seq in assembly_seqs)
    utils.saveVariable(assembly_vocab, 'vocab', assembly_data_dir)
    utils.saveVariable(assembly_action_vocab, 'assembly-action-vocab',
                       data_dirs['event'])
    vocabs = {label_name: vocabs[label_name] for label_name in label_types}
    for name, vocab in vocabs.items():
        utils.saveVariable(vocab, 'vocab', data_dirs[name])

    utils.saveMetadata(metadata, out_labels_dir)
    for name, dir_ in data_dirs.items():
        utils.saveMetadata(metadata, dir_)

    assembly_attrs = labels.blockConnectionsSeq(assembly_vocab)
    utils.saveVariable(assembly_attrs, 'assembly-attrs', assembly_data_dir)
    plt.matshow(assembly_attrs.T)
    plt.savefig(os.path.join(fig_dir, 'assembly-attrs.png'))

    logger.info(
        f"Loaded {len(seq_ids)} sequence labels from {corpus_name} dataset")

    part_names = [name for name in vocabs['part'] if name != '']
    col_names = [f"{name}_active" for name in part_names]
    integerizers = {
        label_name: {name: i
                     for i, name in enumerate(label_vocab)}
        for label_name, label_vocab in vocabs.items()
    }

    all_slowfast_labels_seg = collections.defaultdict(list)
    all_slowfast_labels_win = collections.defaultdict(list)
    counts = np.zeros((len(vocabs['action']), len(vocabs['part'])), dtype=int)
    for i, seq_id in enumerate(seq_ids):
        logger.info(f"Processing sequence {i + 1} / {len(seq_ids)}")

        seq_id_str = f"seq={seq_id}"

        event_segs = event_labels[i]
        frame_fns = frame_fn_seqs[i]
        frame_fn_idxs = frame_fn_idx_seqs[i]
        assembly_seq = assembly_seqs[i]
        assembly_label_seq = make_assembly_labels(assembly_seq,
                                                  assembly_idx_seqs[i],
                                                  **win_params)

        # video_dir = os.path.dirname(frame_fns[0]).split('/')[-1]
        video_dir = f"{seq_id}"

        event_data = make_event_data(event_segs, frame_fns, frame_fn_idxs,
                                     integerizers['event'],
                                     integerizers['action'],
                                     integerizers['part'],
                                     vocabs['event'].index(''),
                                     vocabs['action'].index(''), False)

        # Redefining event segments from the sequence catches background segments
        # that are not annotated in the source labels
        event_segs = make_clips(event_data,
                                vocabs['event'],
                                vocabs['action'],
                                clip_type='segment')
        event_wins = make_clips(event_data,
                                vocabs['event'],
                                vocabs['action'],
                                clip_type='window',
                                **win_params)

        for name in ('event', 'action'):
            event_segs[f'{name}_id'] = [
                integerizers[name][n] for n in event_segs[name]
            ]
            event_wins[f'{name}_id'] = [
                integerizers[name][n] for n in event_wins[name]
            ]

        event_data.to_csv(os.path.join(out_labels_dir,
                                       f"{seq_id_str}_data.csv"),
                          index=False)
        event_segs.to_csv(os.path.join(out_labels_dir,
                                       f"{seq_id_str}_segs.csv"),
                          index=False)
        event_wins.to_csv(os.path.join(out_labels_dir,
                                       f"{seq_id_str}_wins.csv"),
                          index=False)

        utils.saveVariable(assembly_label_seq, f'seq={seq_id}_label-seq',
                           assembly_data_dir)

        filenames = event_data['fn'].to_list()
        label_indices = {}
        bound_keys = ['start', 'end']
        for name in label_types:
            if name == 'part':
                label_indices[name] = event_data[col_names].to_numpy()
                label_keys = col_names
            else:
                label_indices[name] = event_data[name].to_numpy()
                label_keys = [f'{name}_id']

            seg_labels_slowfast = make_slowfast_labels(
                event_segs[bound_keys], event_segs[label_keys],
                [video_dir for _ in range(event_segs.shape[0])])
            win_labels_slowfast = make_slowfast_labels(
                event_wins[bound_keys], event_wins[label_keys],
                [video_dir for _ in range(event_wins.shape[0])])

            utils.saveVariable(filenames, f'{seq_id_str}_frame-fns',
                               data_dirs[name])
            utils.saveVariable(label_indices[name], f'{seq_id_str}_labels',
                               data_dirs[name])
            seg_labels_slowfast.to_csv(os.path.join(
                data_dirs[name], f'{seq_id_str}_slowfast-labels.csv'),
                                       index=False,
                                       **slowfast_csv_params)
            win_labels_slowfast.to_csv(os.path.join(
                data_dirs[name], f'{seq_id_str}_slowfast-labels.csv'),
                                       index=False,
                                       **slowfast_csv_params)

            all_slowfast_labels_seg[name].append(seg_labels_slowfast)
            all_slowfast_labels_win[name].append(win_labels_slowfast)

        plot_event_labels(os.path.join(fig_dir, f"{seq_id_str}.png"),
                          label_indices['event'], label_indices['action'],
                          label_indices['part'], vocabs['event'],
                          vocabs['action'], part_names)
        plot_assembly_labels(
            os.path.join(fig_dir, f"{seq_id_str}_assembly.png"),
            assembly_label_seq, label_indices['event'], vocabs['event'])

        for part_activity_row, action_index in zip(label_indices['part'],
                                                   label_indices['action']):
            for i, is_active in enumerate(part_activity_row):
                part_index = integerizers['part'][part_names[i]]
                counts[action_index, part_index] += int(is_active)

    for name, sf_labels in all_slowfast_labels_seg.items():
        pd.concat(sf_labels, axis=0).to_csv(
            os.path.join(data_dirs[name], 'slowfast-labels_seg.csv'),
            **slowfast_csv_params)
    for name, sf_labels in all_slowfast_labels_win.items():
        pd.concat(sf_labels, axis=0).to_csv(
            os.path.join(data_dirs[name], 'slowfast-labels_win.csv'),
            **slowfast_csv_params)

    utils.saveVariable(counts, 'action-part-counts', out_labels_dir)

    plt.matshow(counts)
    plt.xticks(ticks=range(len(vocabs['part'])),
               labels=vocabs['part'],
               rotation='vertical')
    plt.yticks(ticks=range(len(vocabs['action'])), labels=vocabs['action'])
    plt.savefig(os.path.join(fig_dir, 'action-part-coocurrence.png'),
                bbox_inches='tight')
def plot_scatter(ax,
                 X,
                 Y,
                 x_label,
                 y_label,
                 title,
                 legend_hide=True,
                 legend_loc=4,
                 label_dict=False,
                 legend_size=7,
                 legend_col=1,
                 color_schemes_idx=1):
    #plt.rc('text', usetex=True)
    global color_schemes

    target = list(set(Y))
    target.sort()
    color_idx = [target.index(x) for x in Y]
    color_list = color_schemes[color_schemes_idx]

    for current_color in range(len(target)):
        color = color_list
        current_idxs = [
            idx for idx, v in enumerate(color_idx) if v == current_color
        ]
        if label_dict:
            ax.scatter(X[current_idxs, 0],
                       X[current_idxs, 1],
                       c=color[current_color],
                       label=label_dict[target[current_color]],
                       cmap='viridis',
                       alpha=0.4,
                       edgecolors=None)
        else:
            ax.scatter(X[current_idxs, 0],
                       X[current_idxs, 1],
                       c=color[current_color],
                       label=target[current_color],
                       cmap='viridis',
                       alpha=0.4,
                       edgecolors=None)
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.xticks([])
    plt.yticks([])
    ax.set_title(title)
    if not legend_hide:
        ax.legend(loc=legend_loc,
                  bbox_to_anchor=(0.5, -0.1),
                  prop={'size': legend_size},
                  ncol=legend_col,
                  edgecolor='black',
                  facecolor='white',
                  frameon=True)
    matplotlib.rcParams['mathtext.fontset'] = 'stix'
    matplotlib.rcParams['font.family'] = 'STIXGeneral'
    matplotlib.rcParams['mathtext.fontset'] = 'custom'
    matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans'
    matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic'
    matplotlib.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold'
    matplotlib.rcParams["axes.edgecolor"] = "black"
    matplotlib.rcParams["axes.linewidth"] = 0.6
    rect = ax.patch
    rect.set_facecolor('white')
Example #44
0
# -*- coding: utf-8 -*-
"""
Created on Wed Aug  1 09:45:17 2018

@author: user
"""

import pandas as pd
import matplotlib.pyplot as plt

file = pd.read_excel(r'C:\Users\user\Desktop\Niranjana\1 aug\ca_result.xlsx',
                     header=[0, 1])
print(file)
plt.hist([
    file['Group I']['Pass %'].astype(float),
    file['Group II']['Pass %'].astype(float),
    file['Both Group']['Pass %'].astype(float)
],
         color=['red', 'green', 'yellow'])
plt.xticks(range(2013, 2018))
plt.yticks(range(0, 26))
plt.ylabel("Pass %")
plt.xlabel("Year")
plt.title("CA Results")
import cv2
import numpy as np
from matplotlib import pyplot as plt

# loading image
#img0 = cv2.imread('sepatu.jpg')
img0 = cv2.imread('sepatu.jpg', )

# converting to gray scale
gray = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY)

# remove noise
img = cv2.GaussianBlur(gray, (3, 3), 0)

# convolute with proper kernels
laplacian = cv2.Laplacian(img, cv2.CV_64F)
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)

plt.subplot(2, 2, 1), plt.imshow(img, cmap='gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 2), plt.imshow(laplacian, cmap='gray')
plt.title('Laplacian'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 3), plt.imshow(sobelx, cmap='gray')
plt.title('Sobel X'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 4), plt.imshow(sobely, cmap='gray')
plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])

plt.show()
Example #46
0
def segment_from_image():
    # net initialize
    env_id = ailia.get_gpu_environment_id()
    print(f'env_id: {env_id}')
    net = ailia.Net(MODEL_PATH, WEIGHT_PATH, env_id=env_id)

    ailia_input_w = net.get_input_shape()[3]
    ailia_input_h = net.get_input_shape()[2]
    input_shape = [ailia_input_h, ailia_input_w]

    # prepare input data
    img = load_image(
        args.input, input_shape, normalize_type='127.5', gen_input_ailia=True
    )

    # compute execution time
    for i in range(5):
        start = int(round(time.time() * 1000))
        preds_ailia = net.predict(img)[0]
        end = int(round(time.time() * 1000))
        print(f'ailia processing time {end - start} ms')        

    # postprocessing
    seg_map = np.argmax(preds_ailia.transpose(1, 2, 0), axis=2)
    seg_image = label_to_color_image(seg_map).astype(np.uint8)

    # save just segmented image (simple)
    # seg_image = cv2.cvtColor(seg_image, cv2.COLOR_RGB2BGR)
    # cv2.imwrite('seg_test.png', seg_image)  

    # save org_img, segmentation-map, segmentation-overlay
    org_img = cv2.cvtColor(cv2.imread(args.input), cv2.COLOR_BGR2RGB)
    org_img = cv2.resize(org_img, (seg_image.shape[1], seg_image.shape[0]))

    plt.figure(figsize=(15, 5))
    grid_spec = gridspec.GridSpec(1, 4, width_ratios=[6, 6, 6, 1])

    plt.subplot(grid_spec[0])
    plt.imshow(org_img)
    plt.axis('off')
    plt.title('input image')

    plt.subplot(grid_spec[1])
    plt.imshow(seg_image)
    plt.axis('off')
    plt.title('segmentation map')

    plt.subplot(grid_spec[2])
    plt.imshow(org_img)
    plt.imshow(seg_image, alpha=0.7)
    plt.axis('off')
    plt.title('segmentation overlay')

    unique_labels = np.unique(seg_map)
    ax = plt.subplot(grid_spec[3])
    plt.imshow(
        FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation='nearest'
    )
    ax.yaxis.tick_right()
    plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])
    plt.xticks([], [])
    ax.tick_params(width=0.0)
    plt.grid('off')
    plt.savefig(args.savepath)
Example #47
0


#plt.scatter(mass,stat_sum,c='r',alpha=0.8,s=20)
#plt.fill_between(mass,stat_sum-std_sum,stat_sum+std_sum,alpha=0.2,color='k')
#plt.show()

#h_chi2_gp.GetXaxis().SetRange(0,h_chi2_gp.GetBinCenter)
#h_chi2_gp.Draw()
#canvas1.Update()
#input("Press enter to exit!")

#h_chi2_param.SetLineColor(2)
#h_chi2_param.Draw()
#canvas1.Update()
#h_loglik.Draw()
#input("Press enter to exit!")
#h_1.Draw("PE")
#canvas1.Update()
#input("Press enter to exit!")


plt.errorbar(lum,chi2_lum_gp,yerr=chi2_lum_gp_err,marker="o",label='GP')
plt.errorbar(lum,chi2_lum_par,yerr=chi2_lum_par_err,marker="o",label='ad-hoc')
plt.xlabel("Luminosity scale factor")
plt.ylabel(r'$\chi^2$/ndf')
plt.yticks(np.arange(-1,max(chi2_lum_gp.max(),chi2_lum_par.max()))+1)
plt.legend()
plt.show()

os.chdir(os.getcwd() + r'/info')

if not os.path.isdir(os.getcwd() + r'/relaxation_profiles'):
     os.makedirs(os.getcwd() + r'/relaxation_profiles')
os.chdir(os.getcwd() + r'/relaxation_profiles')

np.savetxt('amplitude_decay.txt', amp_dec, delimiter='\t')
np.savetxt('wavelength_growth.txt', wav_gro, delimiter='\t')
np.savetxt('details.txt', detail_txt, delimiter='\t')

plt.figure()
plt.title(r'%s; $\Delta \theta$ = %0.1f$^{\circ}$' %(def_files[img3+6],delta_theta))
plt.xlim(0,900)
plt.ylim(0,900)
plt.xticks([0, 150, 300, 450, 600, 750, 900])
plt.yticks([0, 150, 300, 450, 600, 750, 900])
plt.xlabel('x [px]')
plt.ylabel('y [px]')
plt.imshow(def_second,'gray')
theta1 = theta - (theta_inc)
xs1 = int(round(xc-(s*np.cos(np.deg2rad(-theta1)))))
ys1 = int(round(yc-(s*np.sin(np.deg2rad(-theta1)))))
xm1 = int(round(xc+(nn*np.cos(np.deg2rad(-theta1)))))
ym1 = int(round(yc+(nn*np.sin(np.deg2rad(-theta1)))))
xf1 = int(round(xc+(s*np.cos(np.deg2rad(-theta1)))))
yf1 = int(round(yc+(s*np.sin(np.deg2rad(-theta1)))))
theta2 = theta
xs2 = int(round(xc-(s*np.cos(np.deg2rad(-theta2)))))
ys2 = int(round(yc-(s*np.sin(np.deg2rad(-theta2)))))
xm2 = int(round(xc+(nn*np.cos(np.deg2rad(-theta2)))))
ym2 = int(round(yc+(nn*np.sin(np.deg2rad(-theta2)))))
Example #49
0
    return doabs(elem[1])


keylist.sort(key=takeSecond, reverse=True)

for i in range(15):
    print("[%d] KEY=0x%02x prob=%f file=%s" %
          (i, keylist[i][0], keylist[i][1], file))

#plt.ylabel('Correlation', fontsize=fontsize)
plt.ylabel('Correlation ' + f'(10\N{SUPERSCRIPT MINUS}\N{SUPERSCRIPT THREE})',
           fontsize=fontsize)
plt.xlabel('Key', fontsize=fontsize)

plt.xticks(fontsize=fontsize)
plt.yticks(fontsize=fontsize)

ax = plt.axes()
ax.xaxis.offsetText.set_fontsize(fontsize)
ax.xaxis.set_tick_params(width=ticksize, length=ticksize * 2)
ax.yaxis.offsetText.set_fontsize(fontsize)
ax.yaxis.set_tick_params(width=ticksize, length=ticksize * 2)

f = plt.figure(1)
addval = 0.06
addup = 0.05
plt.subplots_adjust(left=f.subplotpars.left + addval,
                    right=f.subplotpars.right + addval,
                    bottom=f.subplotpars.bottom + addup,
                    top=f.subplotpars.top + addup)
Example #50
0
def main(save=True):
    #data for 20180404 reduction
    #vars = ['R0', 'ALP_I', 'ALP_O', 'KSI0', 'G', 'E']
    #r0 = [63, 73, 83] #73-83
    #alp_i = [2.5, 5, 7.5] #5-7.5
    #alp_o = [-2.5, -5] #-2.5
    #ksi0 = [1.5, 2, 3] #1.5
    #g = [0.2, 0.4, 0.6] #0.6
    #e = [0, 0.06, 0.1] #doesn't matter
    #params = [r0, alp_i, alp_o, ksi0, g, e]

    #set variables to plot against each other
    vars = ['R0', 'ALP_I', 'ALP_O', 'G', 'KSI0', 'BETA']
    dir = '20180503/'

    data = np.loadtxt(dir + 'grid_search_stats_20180503.txt', dtype='str')

    for i in range(len(vars)):
        col = np.squeeze(np.where(data[0, :] == vars[i]))  #eg 9
        values = np.unique(data[1:, col]).astype('float')
        if i == 0:
            params = [values]
        else:
            params.append(values)

    chi_col_index = np.squeeze(np.where(data[0, :] == 'CHISQ/dof'))

    for i in range(np.shape(params)[0] - 1):
        for j in range(i + 1, np.shape(params)[0]):
            xparam = vars[i]  #eg 'r0'
            yparam = vars[j]  #eg 'alp_i'

            xcol = np.squeeze(np.where(data[0, :] == vars[i]))  #eg 9
            ycol = np.squeeze(np.where(data[0, :] == vars[j]))  #eg 3

            im = np.zeros((len(params[j]), len(params[i])))

            for x in range(len(params[i])):
                for y in range(len(params[j])):
                    loc = np.where(
                        (data[1:, xcol].astype('float') == params[i][x])
                        & (data[1:, ycol].astype('float') == params[j][y]))
                    loc = np.squeeze(np.array(loc))

                    im[y, x] = np.mean(data[loc + 1,
                                            chi_col_index].astype('float'))

            if xparam == 'R0': tit1 = r'$r_0$'
            elif xparam == 'ALP_I': tit1 = r'$\alpha_{in}$'
            elif xparam == 'ALP_O': tit1 = r'$\alpha_{out}$'
            elif xparam == 'BETA': tit1 = r'$\beta$'
            elif xparam == 'ksi0': tit1 = r'$\xi$'
            elif xparam == 'G': tit1 = r'$g$'

            if yparam == 'R0': tit2 = r'$r_0$'
            elif yparam == 'ALP_I': tit2 = r'$\alpha_{in}$'
            elif yparam == 'ALP_O': tit2 = r'$\alpha_{out}$'
            elif yparam == 'BETA': tit2 = r'$\beta$'
            elif yparam == 'ksi0': tit2 = r'$\xi$'
            elif yparam == 'G': tit2 = r'$g$'

            plt.imshow(im, interpolation='none')
            plt.xticks(range(len(params[i])), params[i])
            plt.yticks(range(len(params[j])), params[j])
            plt.title(tit1 + ' vs. ' + tit2 + " mean " + r'$\chi_{\nu}^{2}$',
                      fontsize=21)
            plt.tight_layout()
            plt.subplots_adjust(bottom=0.1, top=0.93)  #make space for title
            plt.xlabel(tit1, fontsize=21)
            plt.ylabel(tit2, fontsize=21)
            plt.colorbar()

            if save == True:
                plt.savefig(dir + 'contour ' + xparam + ' vs ' + yparam +
                            '.png')
                plt.close()
            else:
                plt.show()
def camshift():

    # Code written by Gavin Morrison D12124782

    # Opening an image using a File Open dialog:
    # f = easygui.fileopenbox()
    # I = cv2.imread(f)

    # Import image to be treated
    original_image = cv2.imread("Ilovecats1.bmp")

    # Copy of image to isolate region of interest
    tracking_image = cv2.imread("Ilovecats1Copy.bmp")

    # Coordinates of region of interest [row:row, column:column]
    region_of_interest = tracking_image[125:160, 210:250]

    # Coordinates for right eye
    # region_of_interest = tracking_image[125: 175, 145: 200]

    # The region of interest is converted to HSV colour space
    HSV_region_of_interest = cv2.cvtColor(region_of_interest,
                                          cv2.COLOR_BGR2HSV)

    #Create histogram of region of interest, using hue. The hue  range is from 0 to 179.
    region_of_interest_histogram = cv2.calcHist([HSV_region_of_interest], [0],
                                                None, [180], [0, 180])

    #Original image is converted to HSV colour space
    original_image_HSV = cv2.cvtColor(original_image, cv2.COLOR_BGR2HSV)

    # Back projection used to create mask from the hue of the region of interest histogram
    mask = cv2.calcBackProject([original_image_HSV], [0],
                               region_of_interest_histogram, [0, 180], 1)

    # Filter applied in an attempt to reduce noise in the mask (later addition)
    filter_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    mask = cv2.filter2D(mask, -1, filter_kernel)
    _, mask = cv2.threshold(mask, 10, 255, cv2.THRESH_BINARY)

    # The coordinates of our region of interest are assigned to variables
    row = 210
    column = 125
    width = 250 - row
    height = 160 - column

    # Coordinates for right eye
    # row = 145
    # column = 125
    # width = 200 - row
    # height = 175 - column

    # define criteria
    criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)

    #rectangle of tracking area is created using camshift function
    rectangle, tracking_area = cv2.CamShift(mask, (row, column, width, height),
                                            criteria)

    #These are the points for the rectangle
    points = cv2.boxPoints(rectangle)
    points = np.int0(points)

    # cv2.polylines used instead of 'cv2.rectangle' to accommodate rotation of bound space.
    cv2.polylines(original_image, [points], True, (0, 255, 0), 2)

    # Display our processed image
    finished_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
    plt.subplot(111), plt.imshow(
        finished_image,
        cmap='gray'), plt.title('Camshift'), plt.xticks([]), plt.yticks([])
    plt.show()

    raw_input("Please press enter to return to Main Menu")
    main_menu()
#Drawing a barplot
(count_States * 100 / len(Beneficiarydata)).plot(kind='bar',
                                                 rot=0,
                                                 figsize=(16, 8),
                                                 fontsize=12,
                                                 legend=True)

#Giving titles and labels to the plot

plt.annotate('Maximum Beneficiaries are from this State',
             xy=(0.01, 8),
             xytext=(8, 6.5),
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.yticks(np.arange(0, 10, 2), ('0 %', '2 %', '4 %', '6 %', '8 %', '10%'))
plt.title("State - wise Beneficiary Distribution", fontsize=18)
plt.xlabel("State Number", fontsize=15)
plt.ylabel("Percentage of Beneficiaries " '%', fontsize=15)
plt.show()

plt.savefig('StateWiseBeneficiaryDistribution')

# In[52]:

#PLotting the frequencies of race-wise beneficiaries
count_Race = pd.value_counts(Beneficiarydata['Race'], sort=True)

#Drawing a barplot
(count_Race * 100 / len(Beneficiarydata)).plot(kind='bar',
                                               rot=0,
Example #53
0
def barplot(acc_matrix,filename, model_name):

    print("Start to plot the barplot of single sheet");
    img1=mpimg.imread('../training_data/origin/musical_symbol_g_clef.png')
    img2=mpimg.imread('../training_data/origin/musical_symbol_half_note.png')
    img3=mpimg.imread('../training_data/origin/musical_symbol_quarter_note.png')

    arr1 = acc_matrix[0]
    arr2 = acc_matrix[1]
    arr3 = acc_matrix[2]
    sum_1 = sum(arr1)
    sum_2 = sum(arr2)
    sum_3 = sum(arr3)
    for i in range(0, len(arr1)):
        if (sum_1!=0): 
            arr1[i] = arr1[i]/sum_1
        if (sum_2!=0):
            arr2[i] = arr2[i]/sum_2
        if (sum_3!=0):
            arr3[i] = arr3[i]/sum_3
    classes = ("g_clef","half_note","quarter_note")
    y_pos = np.arange(len(classes))

    plt.figure(1)
    basefilename = os.path.basename(filename);
    big_title = "case: "+basefilename+", model: "+ model_name;
    plt.figure(1).suptitle(big_title, fontsize=12)
    
    plt.subplot(321)
    imgplot1 = plt.imshow(img1)
    plt.title("g_clef")

    plt.subplot(322)
    plt.xlim([0.0, 1.0])
    plt.barh(y_pos, arr1, align='center', alpha=0.5, color = 'blue')
    plt.yticks(y_pos, classes)
    plt.xlabel('Probability')
    plt.title('Accuracy of g_clef')

    plt.subplot(323)             # the second subplot in the first figure
    imgplot2 = plt.imshow(img2)
    plt.title("half_note")

    plt.subplot(324)
    plt.xlim([0.0, 1.0])
    plt.barh(y_pos, arr2, align='center', alpha=0.5, color = 'blue')
    plt.yticks(y_pos, classes)
    plt.xlabel('Probability')
    plt.title('Accuracy of half_note')

    plt.subplot(325) 
    imgplot3 = plt.imshow(img3)
    plt.title("quarter_note")

    plt.subplot(326)
    plt.xlim([0.0, 1.0])
    plt.barh(y_pos, arr3, align='center', alpha=0.5, color = 'blue')
    plt.yticks(y_pos, classes)
    plt.xlabel('Probability')
    plt.title('Accuracy of quarter_note')
    plt.subplots_adjust(top=0.90, bottom=0.1, left=0.10, right=0.95, hspace=1.0,
                    wspace=0.35)
    store_img = "";
    if (len(filename)==15):
        store_img = "../Output/Predict_Output/"+filename[10]+"/summary/"+model_name+".png"
    if (len(filename)==16):
        store_img = "../Output/Predict_Output/"+filename[10:12]+"/summary/"+model_name+".png"
    plt.savefig(store_img)
    plt.close()
    print("----------------------------------------------------");
    
Example #54
0
def plot_confusion_matrix(step, y_true, y_pred, output_size):
    # check result directory
    result_dir = 'result'
    check_existing_dir(result_dir)

    print('plot confusion matrix start: ', end='')

    # preprocessing
    y_true = [x for x in y_true if x != -1]
    y_pred = [x for x in y_pred if x != -1]

    # compute confusion matrix
    cnf_matrix = confusion_matrix(y_true=y_true, y_pred=y_pred)

    # configuration
    np.set_printoptions(precision=2)

    if output_size == 2:
        labels = ['benign', 'malware']
    else:
        # toy dataset label
        # labels = ['Virus', 'Worm', 'Trojan', 'not-a-virus:Downloader', 'Trojan-Ransom', 'Backdoor']
        labels = list(range(output_size))
    tick_marks = np.arange(len(labels))
    plt.xticks(tick_marks, labels, rotation=90)
    plt.xticks(tick_marks, labels)
    plt.yticks(tick_marks, labels)

    norm_flag = True
    plot_title = 'Confusion matrix'
    cmap = plt.cm.Blues

    if norm_flag:
        cnf_matrix = cnf_matrix.astype('float') / cnf_matrix.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    for row in cnf_matrix:
        for val in row:
            print('{0:.2f}'.format(val), end=' ')
        print()

    # plotting start
    plt.figure()
    plt.imshow(cnf_matrix, interpolation='nearest', cmap=cmap)
    plt.title(plot_title)
    plt.colorbar()

    # information about each block's value
    fmt = '.3f' if norm_flag else 'd'
    thresh = cnf_matrix.max() / 2.
    for i, j in itertools.product(range(cnf_matrix.shape[0]), range(cnf_matrix.shape[1])):
        plt.text(j, i, format(cnf_matrix[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cnf_matrix[i, j] > thresh else "black")

    # insert legend information
    # import matplotlib.patches as mpatches
    # patches = [mpatches.Patch(color='white', label='G{num} = {group}'.format(num=i+1, group=labels[i])) for i in range(len(labels))]
    # plt.legend(handles=patches, bbox_to_anchor=(-0.60, 1), loc=2, borderaxespad=0.)

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    # plt.show()
    plt.savefig(os.path.join(result_dir, 'conf_matrix{}'.format(step)))
    print('--plot confusion matrix finish--')
    pass
Example #55
0
def sequence_analysis(filenames_prefix='logs/stats', sortby='MotionModel'):
    df = create_sequence_dataframe(filenames_prefix)

    unique_values = np.unique(df.filter(items=[sortby]).values)
    n_unique_sequences = len(np.unique(df.filter(items=['SeqId']).values))

    if len(unique_values) < 2:
        print('Found 1 unique setting. Plotting sequence stats...')
        return plot_sequence_stats(filenames_prefix=filenames_prefix, disp='save'), None

    nof_uv = len(unique_values)
    print('Found {} unique settings and {} unique sequences. Plotting sequence stats...'.format(nof_uv, n_unique_sequences))

    row_names = ['AvgPase', 'AvgMOTA', 'AvgMOTP', 'AvgGOSPA', 'AvgMT', 'AvgSwitches', 'AvgML']

    #fig, ax = plt.subplots(7, nof_uv, sharey='row')
    fig, ax = plt.subplots(6, nof_uv, sharey='row')
    inch_per_ax = 2
    fig.set_size_inches(int(inch_per_ax * nof_uv), inch_per_ax * len(row_names), forward=True)

    # For pred gospas (prego)
    fig_prego, ax_prego = plt.subplots(1, 1)
    plt.xticks(fontsize=30)
    plt.yticks(fontsize=30)
    fig_prego.set_size_inches(10, 10, forward=True)
    #time_steps_ahead = np.array(range(1, len(df.PredGOSPA[0]) + 1))

    # For pred gospas (prego)
    fig_sub_prego, ax_sub_prego = plt.subplots(n_unique_sequences, 1)
    fig_sub_prego.set_size_inches(7, n_unique_sequences*7, forward=True)

    rows = []
    max_avg_id_switches = 0
    for i, uv in enumerate(unique_values):
        row = []
        a = df.loc[df[sortby] == uv]
        a = a.sort_values('SeqId')

        seqIds = [int(b) for b in a.SeqId.values]
        pases = [float(b) for b in a.Pase.values]
        motas = [float(b) for b in a.MOTA.values]
        motps = [float(b) for b in a.MOTP.values]
        gospas = [float(b) for b in a.GOSPA.values]
        predicted_gospas = a.PredGOSPA.values
        mts = [float(b) for b in a.MostlyTracked.values]
        mls = [float(b) for b in a.MostlyLost.values]
        switches = [float(b) for b in a['#Switches'].values]

        time_steps_ahead = np.array(range(1, len(predicted_gospas[0]) + 1))

        ax[0, i].bar(seqIds, pases)
        _mean = np.mean(pases)
        ax[0, i].axhline(y=_mean, color='r')
        row.append(_mean)

        ax[1, i].bar(seqIds, motas)
        _mean = np.mean(motas)
        ax[1, i].axhline(y=_mean, color='r')
        row.append(_mean)

        _mean = np.mean(motps)
        ax[2, i].bar(seqIds, motps)
        ax[2, i].axhline(y=_mean, color='r')
        row.append(_mean)

        _mean = np.mean(gospas)
        ax[3, i].bar(seqIds, gospas)
        ax[3, i].axhline(y=_mean, color='r')
        row.append(_mean)

        _mean = np.mean(mts)
        ax[4, i].bar(seqIds, mts)
        ax[4, i].axhline(y=_mean, color='r')
        row.append(_mean)

        _mean = np.mean(switches)
        ax[5, i].bar(seqIds, switches)
        ax[5, i].axhline(y=_mean, color='r')
        row.append(_mean)
        if _mean > max_avg_id_switches:
            max_avg_id_switches = _mean

        _mean = np.mean(mls)
        #ax[5, i].bar(seqIds, mls)
        #ax[5, i].axhline(y=_mean, color='r')
        row.append(_mean)

        rows.append(row)

        ax[0, i].set_xlabel('Sequence [idx]')
        ax[0, i].set_title(uv + '\nAvg time/iter')

        ax[1, i].set_xlabel('Sequence [idx]')
        ax[1, i].set_title(uv + '\nMOTA')

        ax[2, i].set_xlabel('Sequence [idx]')
        ax[2, i].set_title(uv + '\nMOTP')

        ax[3, i].set_xlabel('Sequence [idx]')
        ax[3, i].set_title(uv + '\nMean GOSPA')

        ax[4, i].set_xlabel('Sequence [idx]')
        ax[4, i].set_title(uv + '\nMostly Tracked')

        ax[5, i].set_xlabel('Sequence [idx]')
        ax[5, i].set_title(uv + '\nID Switches')

        #ax[6, i].set_xlabel('Sequence [idx]')
        #ax[6, i].set_title(uv + '\nMostly Lost')

        if uv == 'CV':
            style = '-o'
        elif uv == 'Mixed':
            style = ':s'
        elif uv == 'BC':
            style = '--*'
        elif uv == 'CA' :
            style = '-.+'
        elif uv == 'Car-CV':
            style = '-o'
        elif uv == 'Ped-CV':
            style = ':s'
        elif uv == 'Car-BC':
            style = '--*'
        elif uv == 'Ped-BC':
            style = '-.+'
        else:
            style = '-x'
        mean_pg = np.zeros(len(predicted_gospas[0]) , dtype=float)
        for ix, pg in enumerate(predicted_gospas):
            if n_unique_sequences != 1:
                ax_sub_prego[ix].plot(time_steps_ahead, pg, style,  label=uv + '-seq' + str(seqIds[ix]))
                ax_sub_prego[ix].set_xlabel('Time steps ahead')
                ax_sub_prego[ix].set_ylabel('Average prediction GOSPA')
            else:
                ax_sub_prego.plot(time_steps_ahead, pg, style, label=uv + '-seq' + str(seqIds[ix]))
                ax_sub_prego.set_xlabel('Time steps ahead')
                ax_sub_prego.set_ylabel('Average prediction GOSPA')
            mean_pg = np.add(mean_pg, pg)
        mean_pg = mean_pg / n_unique_sequences
        ax_prego.plot(time_steps_ahead, mean_pg, style, label=uv)

    ax[0, 0].set_ylabel('Time [s]')
    ax[1, 0].set_ylabel('MOTA score')
    ax[2, 0].set_ylabel('MOTP score')
    ax[3, 0].set_ylabel('Mean GOSPA score')
    ax[4, 0].set_ylabel('Mostly Tracked')
    ax[5, 0].set_ylabel('nof ID Switches')
    #ax[6, 0].set_ylabel('Mostly Lost')

    ax[1, 0].set_ylim([0, 1])
    ax[2, 0].set_ylim([0, 1])

    ax[5, 0].set_ylim([0, max_avg_id_switches*1.2])

    ax_prego.set_xlabel('Time steps ahead', fontsize=30)
    ax_prego.set_ylabel('Average GOSPA score', fontsize=30)
    ax_prego.set_title('Average Prediction GOSPA over sequences: \n {}'.format(seqIds))
    ax_prego.legend(fontsize=30)

    if n_unique_sequences != 1:
        for ix in range(n_unique_sequences):
            ax_sub_prego[ix].legend()
            ax_sub_prego[ix].set_title('Sequence ' + str(seqIds[ix]))
    else:
        ax_sub_prego.legend()
        ax_sub_prego.set_title('Sequence ' + str(seqIds[ix]))

    fig.tight_layout()
    fig_prego.tight_layout()
    fig_sub_prego.tight_layout()

    if not os.path.exists('showroom'):
        os.mkdir('showroom')
    fig.savefig('showroom/sequence_stats' + '.pdf')
    fig_prego.savefig('showroom/prego_stats' + '.pdf')
    fig_sub_prego.savefig('showroom/prego_sub_stats' + '.pdf')

    #plt.show()

    I = pd.Index(row_names, name="Metric")
    C = pd.Index(unique_values, name=sortby)

    avg_df = pd.DataFrame(data=rows, index=C, columns=I)

    # PLOT AVERAGE STUFF for pase, mota, motp and gospa
    to_plot = ['AvgPase', 'AvgMOTA', 'AvgMOTP', 'AvgGOSPA']
    titles = ['Average Time per iteration', 'Average MOTA', 'Average MOTP', 'Average GOSPA']
    for mi, metric in enumerate(to_plot):
        avg_fig, avg_ax = plt.subplots(1, 1, sharey='row')
        avg_fig.set_size_inches(10, 10, forward=True)
        styles = []
        names = []
        values = []
        for name in avg_df[metric].keys():
            # For comparing motion models
            if name == 'BC':
                style = '#1f77b4'
            elif name == 'CA':
                style = '#ff7f0e'
            elif name == 'CV':
                style = '#2ca02c'
            elif name == 'Mixed':
                style = '#d62728'
            # For car vs pedestrian tracking
            elif name == 'Car-BC':
                style = '#1f77b4'
            elif name == 'Car-CV':
                style = '#ff7f0e'
            elif name == 'Ped-BC':
                style = '#2ca02c'
            elif name == 'Ped-CV':
                style = '#d62728'
            # For FAFE variants
            elif name == 'bev_NN':
                style = '#1f77b4'
            elif name == 'bev_nn':
                style = '#ff7f0e'
            elif name == 'pp_NN':
                style = '#2ca02c'
            elif name == 'pp_nn':
                style = '#d62728'
                # For fafe vs pmbm
            elif name == 'PMBM-CV-4':
                style = '#1f77b4'
            else:
                style = 'k'
            styles.append(style)
            names.append(name)
            values.append(avg_df[metric][name])
        avg_ax.bar(names, values, color=styles, alpha=1)
        for i, v in enumerate(values):
            avg_ax.text(names[i], v, str(round(v,3)), horizontalalignment='center', fontsize=40)

        avg_ax.set_title(titles[mi], fontsize=40)
        plt.xticks(fontsize=45)
        plt.yticks(fontsize=45)
        avg_fig.tight_layout()
        avg_fig.savefig('showroom/average_' + metric + '.pdf')
        #plt.show()
        avg_fig.clear()

    return df, avg_df
Example #56
0
opt_reward = np.ones(2000)
opt_reward[:1000] = opt_reward[:1000] * 2015
opt_reward[1000:] = opt_reward[1000:] * 1937

# pred_reward -= 100
# dqn_reward += 100
# fedcs_reward += 50

interval = 2000

x = np.linspace(0, 20000, num=interval)

fig, ax = plt.subplots()

plt.xticks([0, 5000, 10000, 15000, 20000])
plt.yticks([0, 500, 1000, 1500, 2000])

opt_line = ax.plot(x, opt_reward[:interval], '-', linewidth=2, color='#d62728', label="Offline")
# pred_line = ax.plot(x, pred_reward[:interval], '-.', linewidth=2, color='#d62728', label="Proactive FedCS")
ddqn_line = ax.plot(x, dqn_reward[:interval], '-', linewidth=2, color='#1f77b4', label="DDQN-based (Proposed)")
fedcs_line = ax.plot(x, fedcs_reward[:interval], '--', linewidth=2, color='#ff7f0e', label="FedCS [Nishio, 2019]")
rand_line = ax.plot(x, rand_reward[:interval], ':', linewidth=2, color='#2ca02c', label="FedAvg [Google Team]")

plt.ylabel('Numerical Reward', fontdict={'size': 23})
plt.xlabel('Episodes', fontdict={'size': 23})
plt.tick_params(labelsize=18)
leg = ax.legend(fontsize=17)# , frameon=False)

# first_legend = plt.legend(handles=[opt_line, pred_line, ddqn_line], fontsize=14)
# # ax = plt.gca().add_artist(first_legend)
# first_legend.set_draggable(True)
Example #57
0
# number of figures, representing volatility fitting, to be plotted

if n_fig == 1:
    t_fig = [0]
else:
    t_fig = linspace(0,t_-1,n_fig)

for h in t_fig:
    date_dt = array([date_mtop(i) for i in dates_t])
    myFmt = mdates.DateFormatter('%d-%b-%Y')
    f, ax = plt.subplots(1, 1, subplot_kw={'projection': '3d'})
    ax.view_init(32, -133)
    plt.axis([npmin(delta), npmax(delta), npmin(tau), npmax(tau)])
    xlabel('Delta', labelpad=10)
    xticks(delta[::2])
    yticks(tau[[0, 5, 7, 8, 9]])
    ylabel('Maturity', labelpad=10)
    ax.set_zlabel('$\sigma$')
    ax.set_zticks([10, 20, 30, 40], ['10%', '20%', '30%', '40%'])
    title('HESTON IMPLIED VOLATILITY SURFACE SP500')
    plt.grid(True)
    interpoints = 100
    delta_plot, tau_plot = meshgrid(delta, tau)
    xi = linspace(min(delta),max(delta),interpoints)
    yi = linspace(min(tau),max(tau),interpoints)
    xiplot, yiplot = meshgrid(xi,yi)
    grid_mkt = griddata((delta_plot.flatten(), tau_plot.flatten()), sigma_impl[:,:,h].flatten(), (xiplot.flatten() , yiplot.flatten()), method='cubic').reshape(xiplot.shape)
    grid_heston = griddata((delta_plot.flatten(), tau_plot.flatten()), sigma_heston[:,:,h].flatten(), (xiplot.flatten() , yiplot.flatten()), method='cubic').reshape(xiplot.shape)
    m, n = xiplot.shape
    colors = array([[0, 0, 0.7]]*(m*n)).reshape(m,n,-1)
    # colorsheston = array([[0.9, 0, 0.40]]*(m*n)).reshape(m,n,-1)
Example #58
0
import cv2
import numpy as np
from matplotlib import pyplot as plt
 
img = cv2.imread('noisy_leaf.jpg',0)
 
#ret1, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
 
ret, imgf = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
 
#blur = cv2.GaussianBlur(img, (5,5), 0)
#ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
 
plt.subplot(3,1,1), plt.imshow(img,cmap = 'gray')
plt.title('Original Noisy Image'), plt.xticks([]), plt.yticks([])
plt.subplot(3,1,2), plt.hist(img.ravel(), 256)
plt.axvline(x=ret, color='r', linestyle='dashed', linewidth=2)
plt.title('Histogram'), plt.xticks([]), plt.yticks([])
plt.subplot(3,1,3), plt.imshow(imgf,cmap = 'gray')
plt.title('Otsu thresholding'), plt.xticks([]), plt.yticks([])
plt.show()
Example #59
0
            col = []
            for j, sal_treshold in enumerate(sal_treshold_range):
                feeder = Feeder(feederID=feeder_id, include_three_phase=include_three_phase)
                phase_identification = PartialPhaseIdentification(feeder, ErrorClass(accuracy, s=s_range[i]))
                phase_identification.load_correlation_xu(salient_treshold=sal_treshold,
                                                      salient_components=salient_components, length=length)

                col += [phase_identification.accuracy()]
            scores.append(col)
        tot_scores += np.array(scores)
        print(round(rep/reps*100), "% complete")
    tot_scores = tot_scores/reps
    # Plot
    plt.figure(figsize=(9, 6), dpi=80)
    y = ["%.2f" % i for i in list(sal_treshold_range)]
    x = ["Class 0.2s","Class 0.5s","Class 0.1","Class 0.2","Class 0.5","Class 1.0"]
    #x = ["Class 0.1"]
    for i,c in enumerate(x):
        plt.plot(y, tot_scores[i], label=c)

    # Decorations
    plt.title(cases[case], fontsize=16)
    plt.xticks(fontsize=12)
    plt.xlabel("Correlation treshold",fontsize=16)
    plt.ylabel("Saliency treshold",fontsize=16)
    plt.yticks(fontsize=12)
    plt.legend()
    #plt.show()
    plt.savefig("treshold_sensitivity" + cases[case])

Example #60
0
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),np.arange(y_min, y_max, h))

#Titulos para las graficas
titles = ['SVC con kernel lineal', 'Lineal SVC', 'SVC con RBF kernel', 'SVC con polinomio(grado 3) kernel']


for i, clf in enumerate((svc,lin_svc, rbf_svc, poly_svc)):
	# Se grafican las fronteras
	plt.subplot(2, 2, i + 1)
	plt.subplots_adjust(wspace=0.4, hspace=0.4)

	Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

	#Color en las graficas
	Z = Z.reshape(xx.shape)
	plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)

	#Puntos de entrenamiento
	plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired)
	plt.xlabel('Longitud Sepal')
	plt.ylabel('Peso Sepal')
	plt.xlim(xx.min(), xx.max())
	plt.ylim(yy.min(), yy.max())
	plt.xticks(())
	plt.yticks(())
	plt.title(titles[i])

plt.show()