Example #1
0
def execute_solver(IMAGE_FILE):
    sample4x4_crop = import_image(IMAGE_FILE)
    cluster_image = get_clustering_image(sample4x4_crop)
    cluster_groupings_dict = cluster_grouper(cluster_image).execute()
    final = pre_process_image(IMAGE_FILE)
    prediction_dict = clean_prediction_dict(get_predictions(final))
    write_puzzle_file(cluster_groupings_dict,prediction_dict)
    try:
        solution = solve_puzzle('cv_puzzle.txt',False)
    except:
        return 'error'

    #get image of result
    fig = plt.figure(figsize=(2, 2), dpi=100,frameon=False)
    plt.axis('off')
    plt.imshow(sample4x4_crop, cmap=mpl.cm.Greys_r)
    for k,v in solution.items():
        if v == None:
            return 'error'
        plt.annotate('{}'.format(v), xy=(k[0]*50+12,k[1]*50+40), fontsize=14)
    plt.tight_layout()
    plt.savefig('static/images/solution.jpg', bbox_inches='tight', dpi=100)

    #theres an issue with the saved layout, tight_layout
    #doesn't appear to work so I need to apply my own cropping again
    resize_final = import_image('static/images/solution.jpg',80)
    imsave('static/images/solution.jpg',resize_final)
    return 'good'
Example #2
0
def showCumulOverlap(mode, modes, *args, **kwargs):
    """Show cumulative overlap using :func:`~matplotlib.pyplot.plot`.

    :type mode: :class:`.Mode`, :class:`.Vector`
    :arg modes: multiple modes
    :type modes: :class:`.ModeSet`, :class:`.ANM`, :class:`.GNM`, :class:`.PCA`
    """

    import matplotlib.pyplot as plt
    if not isinstance(mode, (Mode, Vector)):
        raise TypeError('mode must be NMA, ModeSet, Mode or Vector, not {0}'
                        .format(type(mode)))
    if not isinstance(modes, (NMA, ModeSet)):
        raise TypeError('modes must be NMA, ModeSet, or Mode, not {0}'
                        .format(type(modes)))
    cumov = (calcOverlap(mode, modes) ** 2).cumsum() ** 0.5
    if isinstance(modes, NMA):
        arange = np.arange(0.5, len(modes)+0.5)
    else:
        arange = modes.getIndices() + 0.5
    show = plt.plot(arange, cumov, *args, **kwargs)
    plt.title('Cumulative overlap with {0}'.format(str(mode)))
    plt.xlabel('{0} mode index'.format(modes))
    plt.ylabel('Cumulative overlap')
    plt.axis((arange[0]-0.5, arange[-1]+0.5, 0, 1))
    if SETTINGS['auto_show']:
        showFigure()
    return show
Example #3
0
def showCumulFractVars(modes, *args, **kwargs):
    """Show fraction of variances of *modes* using :func:`~matplotlib.pyplot.
    plot`.  Note that mode indices are incremented by 1.  See also
    :func:`.showFractVars` function."""

    import matplotlib.pyplot as plt
    if not isinstance(modes, (Mode, NMA, ModeSet)):
        raise TypeError('modes must be a Mode, NMA, or ModeSet instance, '
                        'not {0}'.format(type(modes)))
    if isinstance(modes, Mode):
        indices = modes.getIndices() + 0.5
        modes = [modes]
    elif isinstance(modes, ModeSet):
        indices = modes.getIndices() + 0.5
    else:
        indices = np.arange(len(modes)) + 0.5

    fracts = calcFractVariance(modes).cumsum()
    show = plt.plot(indices, fracts, *args, **kwargs)
    axis = list(plt.axis())
    axis[0] = 0.5
    axis[2] = 0
    axis[3] = 1
    plt.axis(axis)
    plt.xlabel('Mode index')
    plt.ylabel('Fraction of variance')
    if SETTINGS['auto_show']:
        showFigure()
    return show
Example #4
0
 def test_prop(self):
     N = 800.0
     V = linspace(5.0,51.0,50)
     rho = 1.2255
     beta = 45.0
     J    = list()
     CT   = list()
     CP   = list()
     effy = list()
     for v in V:
         data = self.analyze_prop(beta,N,v,rho)
         J.append(data[2])
         CT.append(data[3])
         CP.append(data[4])
         effy.append(data[5])
     plt.figure(1)
     plt.grid(True)
     plt.hold(True)
     plt.plot(J,CT,'o-')
     plt.xlabel('J')
     plt.plot(J,CP,'ro-')
     plt.axis([0,2.5,0,0.15])
     plt.figure(2)
     plt.plot(J,effy,'gs-')
     plt.hold(True)
     plt.grid(True)
     plt.axis([0,2.5,0,1.0])
     plt.xlabel('advance ratio')
     plt.ylabel('efficiency')
     plt.show()
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
File: ACGAN.py Project: CODEJIN/GAN
    def Test(self):
        test_Dir = "Result";        
        if not os.path.exists(test_Dir):
            os.makedirs(test_Dir);

        test_Label_List = [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5];
        test_Label_Pattern = np.zeros((16, 10));
        test_Label_Pattern[np.arange(16), test_Label_List] = 1;            
        feed_Dict = {
            self.noise_Placeholder: np.random.uniform(-1., 1., size=[16, self.noise_Size]),
            self.label_for_Fake_Placeholder: test_Label_Pattern,
            self.is_Training_Placeholder: False
            };   #Batch is constant in the test.
        global_Step, mnist_List = self.tf_Session.run(self.test_Tensor_List, feed_dict = feed_Dict);

        fig = plt.figure(figsize=(4, 4))
        gs = gridspec.GridSpec(4, 4)
        gs.update(wspace=0.05, hspace=0.05)

        for index, mnist in enumerate(mnist_List):
            ax = plt.subplot(gs[index])
            plt.axis('off')
            ax.set_xticklabels([])
            ax.set_yticklabels([])
            ax.set_aspect('equal')
            plt.imshow(mnist.reshape(28, 28), cmap='Greys_r')

        plt.savefig('%s/S%d.png' % (test_Dir, global_Step), bbox_inches='tight');
        plt.close();
def do_plot(mode, content, wide):
	global style
	style.apply(mode, content, wide)

	data = np.load("data/prr_AsAu_%s%s.npz"%(content, wide))

	AU, TAU = np.meshgrid(-data["Au_range_dB"], data["tau_range"])
	Zu = data["PRR_U"]
	Zs = data["PRR_S"]

	assert TAU.shape == AU.shape == Zu.shape, "The inputs TAU, AU, PRR_U must have the same shape for plotting!"

	plt.clf()

	if mode in ("sync",):
		# Plot the inverse power ratio, sync signal is stronger for positive ratios
		CSf = plt.contourf(TAU, AU, Zs, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0), colors=("1.0", "0.75", "0.5", "0.25", "0.15", "0.0"), origin="lower")
		CS2 = plt.contour(CSf, colors = ("r",)*5+("w",), linewidths=(0.75,)*5+(1.0,), origin="lower", hold="on")
	else:
		CSf  = plt.contourf(TAU, AU, Zs, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0), colors=("1.0", "0.75", "0.5", "0.25", "0.15", "0.0"), origin="lower")
		CS2f = plt.contour(CSf, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0), colors=4*("r",)+("w",), linewidths=(0.75,)*4+(1.0,), origin="lower", hold="on")
		#CS2f = plt.contour(TAU, -AU, Zu, levels=(0.9, 1.0), colors=("0.0",), linewidths=(1.0,), origin="lower", hold="on")
		if content in ("unif",):
			CSu  = plt.contourf(TAU, AU, Zu, levels=(0.2, 1.0), hatches=("////",), colors=("0.75",), origin="lower")
			CS2  = plt.contour(CSu, levels=(0.2,), colors = ("r",), linewidths=(1.0,), origin="lower", hold="on")

	style.annotate(mode, content, wide)

	plt.axis([data["tau_range"][0], data["tau_range"][-1], -data["Au_range_dB"][-1], -data["Au_range_dB"][0]])

	plt.ylabel(r"Signal power ratio ($\mathrm{SIR}$)", labelpad=2)
	plt.xlabel(r"Time offset $\tau$ ($/T$)", labelpad=2)

	plt.savefig("pdf/prrc2_%s_%s%s_z.pdf"%(mode, content, wide))
def plotTestData(tree):
	plt.figure()
	plt.axis([0,1,0,1])
	plt.xlabel("X axis")
	plt.ylabel("Y axis")
	plt.title("Green: Class1, Red: Class2, Blue: Class3, Yellow: Class4")
	for value in class1:
		plt.plot(value[0],value[1],'go')
	plt.hold(True)
	for value in class2:
		plt.plot(value[0],value[1],'ro')
	plt.hold(True)
	for value in class3:
		plt.plot(value[0],value[1],'bo')
	plt.hold(True)
	for value in class4:
		plt.plot(value[0],value[1],'yo')
	plotRegion(tree)
	for value in classPlot1:
		plt.plot(value[0],value[1],'g.',ms=3.0)
	plt.hold(True)
	for value in classPlot2:
		plt.plot(value[0],value[1],'r.', ms=3.0)
	plt.hold(True)
	for value in classPlot3:
		plt.plot(value[0],value[1],'b.', ms=3.0)
	plt.hold(True)
	for value in classPlot4:
		plt.plot(value[0],value[1],'y.', ms=3.0)
	plt.grid(True)
	plt.show()
Example #9
0
def vis_detections (im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
        )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
Example #10
0
def heatmap(vals, size=6, aspect=1):
    """
    Plot a heatmap from matrix data
    """
    plt.figure(figsize=(size, size))
    plt.imshow(vals, cmap="gray", aspect=aspect, interpolation="none", vmin=0, vmax=1)
    plt.axis("off")
Example #11
0
    def zplane(self, title="", fontsize=18):
        """ Display filter in the complex plane

        Parameters
        ----------

        """
        rb = self.z
        ra = self.p

        t = np.arange(0, 2 * np.pi + 0.1, 0.1)
        plt.plot(np.cos(t), np.sin(t), "k")

        plt.plot(np.real(ra), np.imag(ra), "x", color="r")
        plt.plot(np.real(rb), np.imag(rb), "o", color="b")
        M1 = -10000
        M2 = -10000
        if len(ra) > 0:
            M1 = np.max([np.abs(np.real(ra)), np.abs(np.imag(ra))])
        if len(rb) > 0:
            M2 = np.max([np.abs(np.real(rb)), np.abs(np.imag(rb))])
        M = 1.6 * max(1.2, M1, M2)
        plt.axis([-M, M, -0.7 * M, 0.7 * M])
        plt.title(title, fontsize=fontsize)
        plt.show()
    def draw(self):
        cols, rows = self.size
        minx, maxx = self.xlimits
        miny, maxy = self.ylimits

        width, height = self.cell_dimensions

        x = map(lambda i: minx + width*i, range(cols+1))
        y = map(lambda i: miny + height*i, range(rows+1))

        f = plt.figure(figsize=self.figsize)

        hlines = np.column_stack(np.broadcast_arrays(x[0], y, x[-1], y))
        vlines = np.column_stack(np.broadcast_arrays(x, y[0], x, y[-1]))
        lines = np.concatenate([hlines, vlines]).reshape(-1, 2, 2)
        line_collection = LineCollection(lines, color="black", linewidths=0.5)
        ax = plt.gca()
        ax.add_collection(line_collection)
        ax.set_xlim(x[0]-1, x[-1]+1)
        ax.set_ylim(y[0]-1, y[-1]+1)
        plt.gca().set_aspect('equal', adjustable='box')
        plt.axis('off')
        self.draw_obstacles(plt.gca())

        return plt.gca()
Example #13
0
    def render(self, interval=50, **kwargs):
        import matplotlib.cm as cm
        import matplotlib.animation as animation
        import matplotlib.pyplot as plt

        p = self.plot_layout
        _axs = []
        for i in range(self.image_list[0].shape[2]):
            plt.subplot(p[0], p[1], 1 + i)
            # Hide the x and y labels
            plt.axis('off')
            _ax = plt.imshow(self.image_list[0][:, :, i], cmap=cm.Greys_r,
                             **kwargs)
            _axs.append(_ax)

        def init():
            return _axs

        def animate(j):
            for k, _ax in enumerate(_axs):
                _ax.set_data(self.image_list[j][:, :, k])
            return _axs

        self._ani = animation.FuncAnimation(self.figure, animate,
                                            init_func=init,
                                            frames=len(self.image_list),
                                            interval=interval, blit=True)
        return self
Example #14
0
def visualize(u1, t1, u2, t2, U, omega):
    plt.figure(1)
    plt.plot(t1, u1, 'r--o')
    t_fine = np.linspace(0, t1[-1], 1001)  # мелкая сетка для точного решения
    u_e = u_exact(t_fine, U, omega)
    plt.hold('on')
    plt.plot(t_fine, u_e, 'b-')
    plt.legend([u'приближенное', u'точное'], loc='upper left')
    plt.xlabel('$t$')
    plt.ylabel('$u$')
    tau = t1[1] - t1[0]
    plt.title('$\\tau = $ %g' % tau)
    umin = 1.2*u1.min();
    umax = -umin
    plt.axis([t1[0], t1[-1], umin, umax])
    plt.savefig('tmp1.png');  plt.savefig('tmp1.pdf')
    plt.figure(2)
    plt.plot(t2, u2, 'r--o')
    t_fine = np.linspace(0, t2[-1], 1001)  # мелкая сетка для точного решения
    u_e = u_exact(t_fine, U, omega)
    plt.hold('on')
    plt.plot(t_fine, u_e, 'b-')
    plt.legend([u'приближенное', u'точное'], loc='upper left')
    plt.xlabel('$t$')
    plt.ylabel('$u$')
    tau = t2[1] - t2[0]
    plt.title('$\\tau = $ %g' % tau)
    umin = 1.2 * u2.min();
    umax = -umin
    plt.axis([t2[0], t2[-1], umin, umax])
    plt.savefig('tmp2.png');
    plt.savefig('tmp2.pdf')
Example #15
0
def influence_plot(X, y_true, y_pred, **kwargs):
    """Produces an influence plot.

    Parameters
    ----------
    X : array
        Design matrix.
    y_true : array_like
        Observed labels, either 0 or 1.
    y_pred : array_like
        Predicted probabilities, floats on [0, 1].

    Notes
    -----
    .. plot:: pyplots/influence_plot.py
    """
    r = pearson_residuals(y_true, y_pred)
    leverages = pregibon_leverages(X, y_pred)

    delta_X2 = case_deltas(r, leverages)
    dbetas = pregibon_dbetas(r, leverages)

    plt.scatter(y_pred, delta_X2, s=dbetas * 800, **kwargs)

    __, __, y1, y2 = plt.axis()
    plt.axis((0, 1, y1, y2))

    plt.xlabel('Predicted Probability')
    plt.ylabel(r'$\Delta \chi^2$')

    plt.tight_layout()
Example #16
0
def vis_square(data):
    data = (data - data.min()) / (data.max() - data.min())
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = ((0, 0), (0, 0), (1, 1), (1, 1))
    data = np.pad(data, padding, mode = 'constant', constant_values = 0)
    #data = data.squeeze()
    total_array = np.array([])
    for i in range(data.shape[0]):
        row_array = np.array([])
        for j in range(data.shape[1]):
            if j == 0:
                row_array = data[i, j, :, :]
            else:
                row_array = np.vstack((row_array, data[i, j, :, :]))
        if i == 0:
            total_array = row_array
        else:
            total_array = np.hstack((total_array, row_array))
    print("shape of total_array: {}".format(total_array.shape))
    #data = data.reshape((n, n) + data.shape[1:])
    #data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    
    plt.imshow(total_array);
    plt.axis('off')
    plt.show()
def plot(i, pcanc, lr, pp, labelFlag, Y):
    if len(str(i)) == 1:
        fig = plt.figure(i)
    else:
        fig = plt.subplot(i)
    if pcanc == 0:
        plt.title(
                  ' learning_rate: ' + str(lr)
                + ' perplexity: ' + str(pp))
        print("Plotting tSNE")
    else:
        plt.title(
                  'PCA-n_components: ' + str(pcanc)
                + ' learning_rate: ' + str(lr)
                + ' perplexity: ' + str(pp))
        print("Plotting PCA-tSNE")
    plt.scatter(Y[:, 0], Y[:, 1], c=colors)
    if labelFlag == 1:
        for label, cx, cy in zip(y, Y[:, 0], Y[:, 1]):
            plt.annotate(
                label.decode('utf-8'),
                xy = (cx, cy),
                xytext = (-10, 10),
                fontproperties=font,
                textcoords = 'offset points', ha = 'right', va = 'bottom',
                bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.9))
                #arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
    ax.xaxis.set_major_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(NullFormatter())
    plt.axis('tight')
    print("Done.")
Example #18
0
    def plot_unit_cell(self):
        r'''Plots the unit cell and atoms of the material.

        '''

        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D  # @UnresolvedImport
        from itertools import product, combinations

        fig = plt.figure()
        ax = fig.gca(projection='3d')

        # draw unit cell
        for s, e in combinations(np.array(list(product([0, self.abc[0]], [0, self.abc[1]], [0, self.abc[2]]))), 2):
            if np.sum(np.abs(s - e)) in self.abc:
                ax.plot3D(*zip(s, e), color="b")

        # plot atoms
        x, y, z, m = [], [], [], []
        for item in self.atoms:
            x.append(item.pos[0] * self.abc[0])
            y.append(item.pos[1] * self.abc[1])
            z.append(item.pos[2] * self.abc[2])
            m.append(item.mass)

        ax.scatter(x, y, z, s=m)

        plt.axis('scaled')
        plt.axis('off')

        plt.show()
Example #19
0
def word_cloud_fre_all(domain_dirs, merged_flag=False):
    '''
    通过所有domain的wordcloud对象绘制wordcloud图像并保存在相应domain下
    :return:
    '''
    for domain_name in listdir(domain_dirs):
        domain_dir = path.join(domain_dirs, domain_name)
        wordclouds = word_cloud_frequency(domain_dir, domain_name, merged_flag)

        if merged_flag:
            wordcloud_dir = path.join(domain_dir, domain_name + '_merged_wordcloud1/')
        else:
            wordcloud_dir = path.join(domain_dir, domain_name + '_wordcloud1/')

        if not path.exists(wordcloud_dir):
            makedirs(wordcloud_dir)

        for topic_id, wordcloud in enumerate(wordclouds):
            # dump(wordcloud, open(path.join(wordcloud_dir, 'topic' + str(topic_id)), 'wb'))
            plt.imshow(wordcloud)
            plt.axis("off")
            # plt.show()
            plt.savefig(path.join(wordcloud_dir, 'topic' + str(topic_id)))

        print(domain_name, ' complete!!!')

        break
Example #20
0
def main():
    G=nx.Graph()

    G.add_edge('a','b',weight=0.6)
    G.add_edge('a','c',weight=0.2)
    G.add_edge('c','d',weight=0.1)
    G.add_edge('c','e',weight=0.7)
    G.add_edge('c','f',weight=0.9)
    G.add_edge('a','d',weight=0.3)

    elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5]
    esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5]

    pos=nx.spring_layout(G) # positions for all nodes

# nodes
    nx.draw_networkx_nodes(G,pos,node_size=700)

# edges
    nx.draw_networkx_edges(G,pos,edgelist=elarge,width=6)
    nx.draw_networkx_edges(G,pos,edgelist=esmall,width=6,alpha=0.5,edge_color='b',style='dashed')

# labels
    nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')

    plt.axis('off')
#plt.savefig("weighted_graph.png") # save as png
    plt.show() # display
    return
def plotGenomicregions(GPcount, name):
    """
    :param GPcount: is a list of tuples [(region, size),....()]
    :return:
    """
    """ Now we produce some pie charts """

    gr = ['tss', 'intergenic', 'intron', 'exon', 'upstream']
    size = [0, 0, 0, 0, 0]
    for a, b in GPcount:
        if a == 'tss':
            size[0] = b
        if a == 'intergenic':
            size[1] = b
        if a == 'intron':
            size[2] = b
        if a == 'exon':
            size[3] = b
        if a == 'upstream':
            size[4] = b
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'cyan']
    explode = (0.1, 0, 0, 0, 0)  # only "explode" the 2nd slice
    plt.pie(size, explode=explode, labels=gr, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    #plt.legend(['tss', 'intergenic', 'intron', 'exon', 'upstream'], loc='upper left')
    plt.axis('equal')
    plt.savefig('/ps/imt/e/20141009_AG_Bauer_peeyush_re_analysis/further_analysis/plots/' + name + '.svg')
    plt.clf()
Example #22
0
def yplot(data, limits=[None,None], fname='', xval=[0.5], label='',
        loc='upper left', ext='png'):
    """Make transverse plots of data

    Usage: yplot(data, limits=[None,None], fname='', xval=[0.5], label='',
        loc='upper left', ext='ext')
    xval is a list of axial distances in units of nx
    If no filename is specified a plot is displayed
    The special filename 'M' turns "hold" on (for multiplots)
    File format is ext (default is png)
    """

    nx, ny = data.shape[0], data.shape[1]

    y = np.array(range(ny)) + 0.5
    for x in xval:
        ix = int(x*nx)
        plt.plot(y, data[ix,:], label=label+" : "+"x="+str(x))

    if (fname == 'M'):
        plt.hold=True
    else:
        plt.axis([0,data.shape[1],limits[0],limits[1]])
        plt.legend(loc=loc)
        plt.hold=False
        if len(fname) == 0:
            plt.show()
        else:
            plt.savefig(fname+'-y.'+ext, format=ext)
            plt.close()
Example #23
0
def cplot(data, limits=[None,None], CM = 'jet', fname='', ext='png'):
    """Make a color contour plot of data

    Usage: cplot(data, limits=[None,None], fname='')
    If no filename is specified a plot is displayed
    File format is ext (default is png)
    """

    SIZE = 12
    DPI  = 100

    nx, ny = data.shape[0], data.shape[1]
    data = data.reshape(nx,ny)
    scale  = SIZE/float(max(nx,ny))
    plt.figure(figsize=(scale*nx, scale*ny+1.0))
    plt.clf()
    c = plt.imshow(np.transpose(data), cmap=CM)
    plt.clim(limits)
    plt.axis([0,nx,0,ny])
    #cbar = plt.colorbar(c, ticks=np.arange(0.831,0.835,0.001), aspect = 20, orientation='vertical', shrink=0.72, extend='neither', spacing='proportional')
    #cbar = plt.colorbar(c, aspect = 40, orientation='vertical', shrink=0.72, extend='neither', spacing='proportional')
    #cbar = plt.colorbar(c, orientation='horizontal', shrink=1.0)
    cbar = plt.colorbar(c, orientation='vertical', shrink=0.72, extend='neither', spacing='proportional')
    
    cbar.ax.tick_params(labelsize=21,size=10)
    #cbar.ax.yaxis.set_ticks_position('left')
    #c.cmap.set_under(color='black')
    if len(fname) == 0:
        plt.show()
    else:
        plt.savefig(fname+'.'+ ext, format=ext, dpi=DPI, bbox_inches='tight', pad_inches=0.1)
        plt.close()
def plot_residuals(turnstile_weather, predictions):
    '''
    Using the same methods that we used to plot a histogram of entries
    per hour for our data, why don't you make a histogram of the residuals
    (that is, the difference between the original hourly entry data and the predicted values).

    Based on this residual histogram, do you have any insight into how our model
    performed?  Reading a bit on this webpage might be useful:

    http://www.itl.nist.gov/div898/handbook/pri/section2/pri24.htm
    '''
    
    plt.figure()
    residuals = (turnstile_weather['ENTRIESn_hourly'] - predictions)
    residuals_mean = np.mean(residuals)
    residuals_std = np.std(residuals)
    residuals.hist(color='blue', bins=100, alpha=0.5)
    the_axis = [-15000, 20000, 0, 40000]
    plt.axis(the_axis)
    plt.xlabel('Actual Hourly Entries - Predictions')
    plt.ylabel('Freq')
    plt.title('Linear Regression with Gradient Descent Residuals')


    return plt, residuals_mean, residuals_std
Example #25
0
	def plot_fun(self, x, y, x_min, x_max, y_min, y_max, style):
		fig = plt.figure()
		plt.axis([x_min, x_max, y_min, y_max])
		ax = fig.add_subplot(1, 1, 1)
		ax.plot(x, y, 'g')
		ax.set_xscale('log')
		plt.savefig('plot.png')
Example #26
0
def plothist():

	n_groups = 3

	means_men = (42.3113658071, 39.7803247373, 67.335243553)
	std_men = (1, 2, 3)

	fig, ax = plt.subplots()

	index = np.array([0.5,1.5,2.5])
	bar_width = 0.4

	opacity = 0.4
	error_config = {'ecolor': '0'}

	rects1 = plt.bar(index, means_men, bar_width,
	                 alpha=opacity,
	                 color='b',
	                 error_kw=error_config)

	plt.xlabel('Approach')
	plt.ylabel('Accuracy')
	plt.axis((0,3.4,0,100))
	plt.title('Evaluation')
	plt.xticks(index + bar_width/2, ('Bing Liu', 'AFINN', 'SentiWordNet'))
	plt.legend()

	plt.tight_layout()
	# plt.show()
	plt.savefig('foo.png')
Example #27
0
 def png(self, start_timestamp, end_timestamp):
     self.load(start_timestamp, end_timestamp)
     plt.figure(figsize=(10, 7.52))
     plt.rc("axes", labelsize=12, titlesize=14)
     plt.rc("font", size=10)
     plt.rc("legend", fontsize=7)
     plt.rc("xtick", labelsize=8)
     plt.rc("ytick", labelsize=8)
     plt.axes([0.08, 0.08, 1 - 0.27, 1 - 0.15])
     for plot in self.plots:
         plt.plot(self.timestamps, self.plots[plot], self.series_fmt(plot), label=self.series_label(plot))
     plt.axis("tight")
     plt.gca().xaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: time.strftime("%H:%M\n%b %d", time.localtime(x)))
     )
     plt.gca().yaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: locale.format("%.*f", (0, x), True))
     )
     plt.grid(True)
     plt.legend(loc=(1.003, 0))
     plt.xlabel("Time/Date")
     plt.title(
         self.description()
         + "\n%s to %s"
         % (
             time.strftime("%H:%M %d-%b-%Y", time.localtime(start_timestamp)),
             time.strftime("%H:%M %d-%b-%Y", time.localtime(end_timestamp)),
         )
     )
     output_buffer = StringIO.StringIO()
     plt.savefig(output_buffer, format="png")
     return output_buffer.getvalue()
Example #28
0
def xplot(data, limits=[None,None], fname='', func='max', label='',
        loc='upper right', ext='png'):
    """Make an axial plot of a funtion of data

    Usage: xplot(data, limits=[None,None], fname='', loc='upper left', ext='png')
    Possible functions to plot are max, min, avg
    If no filename is specified a plot is displayed
    The special filename 'M' turns "hold" on (for multiplots)
    File format is ext (default is png)
    """

    nx,ny = data.shape[0],data.shape[1]
    z = np.zeros([3,nx])
    for x in range(nx):
        z[0,x] = data[x,:].min()
        z[1,x] = data[x,:].max()
        z[2,x] = data[x,:].sum()/float(ny)

    #plt.plot(z[0], label=label+' min')
    #plt.plot(z[1], label=label+' max')
    plt.plot(z[2], label=label+' avg')

    if (fname == 'M'):
        plt.hold=True
    else:
        plt.legend(loc=loc)
        plt.axis([0,data.shape[0]-1,limits[0],limits[1]])
        plt.hold=False
        if len(fname) == 0:
            plt.show()
        else:
            plt.savefig(fname+'-x.'+ext, format=ext)
            plt.close()
Example #29
0
def Figure_Cannon_with_AirResistance():
	def Cannon(b= 150,ya=0.,va=35.,phi=np.pi/4,nu=0.):
		g = 9.8067
		def ode_f(x,y):
			# y = [z,v,phi]
			return np.array([np.tan(y[2]), -(g*np.sin(y[2]) + nu*y[1]**2.)/(y[1]*np.cos(y[2])),
					-g/y[1]**2.])


		a= 0.
		abstol,reltol= 1e-4,1e-4

		dim, T = 3, np.linspace(a,b,801)
		example = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol)
		example.set_initial_value(np.array([ya,va,phi]),a)
		Y = np.zeros((len(T),dim))
		Y[0,:] = np.array([0.,.5,np.pi/4.])
		for j in range(1,len(T)):
			Y[j,:] = example.integrate(T[j])
			if Y[j,0]<(-1e-3): break

		return T, T[:j],Y[:j,0]


	T,X,Y = Cannon(nu = 0.,va = 45,phi=np.pi/3,b=200)
	T,X1,Y1 = Cannon(nu = 0.0003,va = 45,phi=np.pi/3,b=200)
	#plt.plot(T,np.zeros(T.shape),'-k',np.zeros(10),np.linspace(0,80,10),'-k')
	plt.plot(X1, Y1, '--r', linewidth=2.0)
	plt.plot(X1[-1], Y1[-1], 'or', markersize=6.)
	plt.plot(X, Y, '-k', linewidth=2.0)
	plt.plot(X[-1], Y[-1], 'ok', markersize=6.)

	plt.axis([0, 200, 0, 85])
	plt.savefig("Cannon_with_AirResistance.pdf")
	plt.clf()
Example #30
0
def main():
    fname = iris.sample_data_path('ostia_monthly.nc')
    
    # load a single cube of surface temperature between +/- 5 latitude
    cube = iris.load_cube(fname, iris.Constraint('surface_temperature', latitude=lambda v: -5 < v < 5))
    
    # Take the mean over latitude
    cube = cube.collapsed('latitude', iris.analysis.MEAN)
    
    # Now that we have our data in a nice way, lets create the plot
    # contour with 20 levels
    qplt.contourf(cube, 20)
    
    # Put a custom label on the y axis 
    plt.ylabel('Time / years')
    
    # Stop matplotlib providing clever axes range padding
    plt.axis('tight')
    
    # As we are plotting annual variability, put years as the y ticks
    plt.gca().yaxis.set_major_locator(mdates.YearLocator())
    
    # And format the ticks to just show the year
    plt.gca().yaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    
    plt.show()
opts = {'maxiter' : 100}    # Preferred value.                                                
w_init = np.zeros((X_i.shape[1],1))
for lambd in lambdas:
    args = (X_i, y, lambd)
    w_l = minimize(regressionObjVal, w_init, jac=True, args=args,method='CG', options=opts)
    w_l_1 = np.zeros((X_i.shape[1],1))
    for j in range(len(w_l.x)):
        w_l_1[j] = w_l.x[j]
    rmses4[i] = testOLERegression(w_l_1,Xtest_i,ytest)
    i = i + 1

plt.plot(lambdas,rmses4)
plt.plot(lambdas,rmses3)
plt.xlabel('lambda')
plt.title('Figure 1')
plt.axis([0, .5, 4.5, 7])
plt.legend(('RMSE 4','RMSE 3'))
plt.show()

######################################### Problem 5 ###############################
pmax = 7
lambda_opt = lambdas[np.argmin(rmses3)]
rmses5 = np.zeros((pmax,2))
for p in range(pmax):
	Xd = mapNonLinear(X[:,2],p)
	Xdtest = mapNonLinear(Xtest[:,2],p)
	w_d1 = learnRidgeRegression(Xd,y,0)
	rmses5[p,0] = testOLERegression(w_d1,Xdtest,ytest)
	w_d2 = learnRidgeRegression(Xd,y,lambda_opt)
	rmses5[p,1] = testOLERegression(w_d2,Xdtest,ytest)
plt.plot(range(pmax), rmses5)
Example #32
0
plt.axhline(5.5, color = 'blue', linestyle = '--', linewidth = 2, alpha = 0.6)
plt.legend(fontsize = 'xx-large', loc = 'best')    
plt.title('Chain A', fontsize = 36)                                     
B = plt.subplot(212, sharex = A, sharey = A)
plt.plot(Fen_B, label = 'Fenestration', color = 'blue', linewidth = 3)
plt.plot(Zip_B, label = 'Zipper', color = 'green', linewidth = 3)
plt.plot(Exp_B, label = 'Expansion', color = 'red', linewidth = 3)
plt.setp(B.get_xticklabels(), fontsize = 18)
plt.setp(B.get_yticklabels(), fontsize = 18)
plt.xlabel("time (ns)", fontsize = '24')
plt.ylabel("z ($\AA$)", fontsize = '24')
plt.axhline(11.5, color = 'green', linewidth = 2, alpha = 0.6)
plt.axhline(11.5, color = 'red', linestyle = '--', linewidth = 2, alpha = 0.6)
plt.axhline(5.5, color = 'blue', linestyle = '--', linewidth = 2, alpha = 0.6)
v = [0,100,3,18]
plt.axis(v)
plt.title('Chain B', fontsize = 36) 
plt.savefig("{}_FEZ_AB.png".format(args.o), format='png', dpi=300)
plt.savefig("{}_FEZ_AB.svg".format(args.o), format='svg', dpi=300)

plt.clf()
plt.figure(figsize=(16,8))
FZ = plt.subplot(121)
plt.scatter(Zip_A, Fen_A, label = 'Chain A', color = 'green')
plt.scatter(Zip_B, Fen_B, label = 'Chain B', color = 'gray')
plt.plot(Zip_A, Fen_A, label = 'Chain A', color = 'green', alpha = 0.5)
plt.plot(Zip_B, Fen_B, label = 'Chain B', color = 'gray', alpha = 0.5)
plt.scatter((ZAup[0] + ZBup[0])/2, (FAup[0] + FBup[0])/2, label = '4BW5 (Up)', color = 'black', marker = 'D', s = 40)
plt.scatter((ZAdn[0] + ZBdn[0])/2, (FAdn[0] + FBdn[0])/2, label = '4XDJ (Down)', color = 'blue', marker = 'D', s = 40)
plt.scatter(Zip_A[0], Fen_A[0], label = 'Chain A start', color = 'green', marker = '^', s = 40, edgecolor = 'black')
plt.scatter(Zip_B[0], Fen_B[0], label = 'Chain B start', color = 'grey', marker = '^', s = 40, edgecolor = 'black')
Example #33
0
lon_units = Dset.variables["lon"].units
lon_max = Dset.variables["lon"].valid_max 
lon_min = Dset.variables["lon"].valid_min

lat_scale = Dset.variables["lat"][:] 
lat_units = Dset.variables["lat"].units
lat_max = Dset.variables["lat"].valid_max 
lat_min = Dset.variables["lat"].valid_min
plt.figure()
#____________________
# These lines create the basemap for the data.
Mbase = bm.Basemap(projection = 'cyl', llcrnrlat = -24.0, llcrnrlon = -44.0, urcrnrlat = -21.0, urcrnrlon = -40.0, resolution='f')

Mbase.drawparallels(np.array([-24, -23, -22, -21]), labels=[0,0,0,1])
Mbase.drawmeridians(np.array([-44, -43, -42, -41, -40]), labels = [0,0,0,1])

#Mbase.drawsmask(land_color='0.8', ocean_color='w', lsmask=None, lsmask_lons=None, lsmask_lats=None, lakes=True, resolution='l', grid=5)
Mbase.drawcoastlines()
Mbase.fillcontinents(color = 'gray') # blue can be changed to any color that you would like
#____________________

mymap = plt.contour(lon_scale, lat_scale, sst[0,:,:], 6,levels=[17.,23.,24.,25.,26.,32.], colors = 'k')
mymap2 = plt.contourf(lon_scale, lat_scale, sst[0,:,:], 6,levels=[17.,23.,24.,25.,26.,32.])
plt.colorbar(mymap2, orientation = 'horizontal') 
plt.plot(-41.78,-22.37,'*k', markersize=20)

plt.axis([-44,-40,-24,-21])
plt.xlabel(lon_units)
plt.ylabel(lat_units)
plt.show()
# Set the working directory to be the current one
os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Load grayscale images
img_orig = cv2.imread('j.png', 0)

# Settings
kernel_sizes = [3, 5, 7]
kernel_shapes = ['RECT', 'CROSS', 'ELLIPSE']
index = 1
for size in kernel_sizes:
    # Display original
    plt.subplot(3, 4, index); index += 1
    plt.imshow(img_orig, 'gray')
    plt.title('Original')
    plt.axis('off')

    for shape in kernel_shapes:
        # Kernel
        kernel = cv2.getStructuringElement(getattr(cv2, 'MORPH_' + shape), (size, size))

        # Dilation
        img_res = cv2.dilate(img_orig, kernel, iterations=1)

        # Display results
        plt.subplot(3, 4, index); index += 1
        plt.imshow(img_res, 'gray')
        plt.title(shape + ' @ ' + str(size) + ' x ' + str(size))
        plt.axis('off')
plt.show()
# load the images -- the original, the original + contrast,
# and the original + photoshop
original = cv2.imread("images/jp_gates_original.png")
contrast = cv2.imread("images/jp_gates_contrast.png")
shopped = cv2.imread("images/jp_gates_photoshopped.png")

# convert the images to grayscale
original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
contrast = cv2.cvtColor(contrast, cv2.COLOR_BGR2GRAY)
shopped = cv2.cvtColor(shopped, cv2.COLOR_BGR2GRAY)

# initialize the figure
fig = plt.figure("Images")
images = ("Original", original), ("Contrast", contrast), ("Photoshopped", shopped)

# loop over the images
for (i, (name, image)) in enumerate(images):
	# show the image
	ax = fig.add_subplot(1, 3, i + 1)
	ax.set_title(name)
	plt.imshow(image, cmap = plt.cm.gray)
	plt.axis("off")

# show the figure
plt.show()

# compare the images
compare_images(original, original, "Original vs. Original")
compare_images(original, contrast, "Original vs. Contrast")
compare_images(original, shopped, "Original vs. Photoshopped")
Example #36
0
def plotvars(BB,Wi=None,short=False,Nob=False,bx=bx,mode="save",formatf=["pdf","svg","pgn"][0]):
    outputs={1:cpy(indict),2:cpy(indict),3:cpy(indict)}
    axs=(0,-2,-1)
    hol=[WAR,bs][BB]
    WV = wid if (Wi is None) else WAR[Wi]
    ding=0
    BS= np.array(hol) if BB==1 else bs[bsvi]
    if BB==0:
        WS=np.array(hol)
    wu=np.unique(WS).shape[0]
    bu=np.unique(BS).shape[0]
    BD="{}Weight_{}".format(wu, "no-B_" if No_B else " {}B({})_".format(bu,bsvi)) if BB==0 else "{}Bias_{}W({})_".format(bu,wu,Wi if not(Wi is None) else "wid")
    if short:#subsample data
        for bb in hol:#bb are upscaled 5 times
            #print(bb)
            #print('B',bs[bsvi],'B')
            if BB==1:
                print('W',wid,'W')
                print('B',bb,'B')
                #print(wid.shape,bb.shape)
                d1=vecvari10(inputcols, WV,BB=0, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                d2=vecvari10(inputcols, WV,BB=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                d3=vecvari10(inputcols, WV,BB=0,BS=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)#-vecvari10(inputcols, wid,noB=0, B=bb,square=0,sqrt=0,verbose=0)
                p1=vecvari1(inputcols, WV, B=bb,BB=0,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                p2=vecvari1(inputcols, WV, B=bb,BB=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                p3=vecvari1(inputcols, WV, B=bb,BB=0,BS=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
            elif BB==0:
                if Nob:
                    bval=None
                else:
                    bval=bs[bsvi]
                print('W',bb,'W')
                print('B',bval,'B')
                print(bb.shape,bs[9].shape)
                d1=vecvari10(inputcols, bb,BB=0, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                p1=vecvari1(inputcols, bb,BB=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                d2=vecvari10(inputcols, bb,BB=0,BS=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                p2=vecvari1(inputcols, bb,BB=0, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                d3=vecvari10(inputcols, bb,BB=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                p3=vecvari1(inputcols, bb,BB=0,BS=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
            for iou,out in enumerate([(d1,d2,d3),(p1,p2,p3),(d1-p1,d2-p2,d3-p3)]):
                if iou==0:
                    ding+=1
                iou+=1
                #print(iou)
                #print(out.mean(axs).shape)
                out1=out[0]
                out2=out[1]
                out3=out[2]#out1-out2
                [outputs[iou]['1mean'].append(oo) for oo in out1.mean(axs)]
                [outputs[iou]['1max'].append(oo) for oo in out1.max(axs)]
                [outputs[iou]['1min'].append(oo) for oo in out1.min(axs)]
                [outputs[iou]['2mean'].append(oo) for oo in out2.mean(axs)]
                [outputs[iou]['2max'].append(oo) for oo in out2.max(axs)]
                [outputs[iou]['2min'].append(oo) for oo in out2.min(axs)]
                [outputs[iou]['mean'].append(oo) for oo in out3.mean(axs)]
                [outputs[iou]['max'].append(oo) for oo in out3.max(axs)]
                [outputs[iou]['min'].append(oo) for oo in out3.min(axs)]
    else:#do each data point
        for kl in hol:
            for bb in kl:
                bb=np.broadcast_to(bb, kl.shape)
                #print(bb[:,0])
                #print('B',bs[bsvi],'B')
                if BB==1:
                    print('W',wid,'W')
                    print('B',bb,'B')
                    #print(wid.shape,bb.shape)
                    d1=vecvari10(inputcols, wid,BB=0, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                    d2=vecvari10(inputcols, wid,BB=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                    d3=vecvari10(inputcols, wid,BB=0,BS=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)#-vecvari10(inputcols, wid,noB=0, B=bb,square=0,sqrt=0,verbose=0)
                    p1=vecvari1(inputcols, wid, B=bb,BB=0,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                    p2=vecvari1(inputcols, wid, B=bb,BB=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                    p3=vecvari1(inputcols, wid, B=bb,BB=0,BS=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                elif BB==0:
                    if Nob:
                        bval=None
                    else:
                        bval=bs[bsvi]
                    print('W',bb,'W')
                    print('B',bval,'B')
                    print(bb.shape,bs[9].shape)
                    print(bb.shape,bs[9].shape)
                    d1=vecvari10(inputcols, bb,BB=0, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                    p1=vecvari1(inputcols, bb,BB=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                    d2=vecvari10(inputcols, bb,BB=0,BS=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                    p2=vecvari1(inputcols, bb,BB=0, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                    d3=vecvari10(inputcols, bb,BB=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)
                    p3=vecvari1(inputcols, bb,BB=0,BS=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v)
                for iou,out in enumerate([(d1,d2,d3),(p1,p2,p3),(d1-p1,d2-p2,d3-p3)]):
                    if iou==0:
                        ding+=1
                    iou+=1
                    #print(iou)
                    #print(out.mean(axs).shape)
                    out1=out[0]
                    out2=out[1]
                    out3=out[2]#out1-out2
                    outputs[iou]['1mean'].append(out1.mean()) 
                    outputs[iou]['1max'].append(out1.max())  
                    outputs[iou]['1min'].append(out1.min())
                    outputs[iou]['2mean'].append(out2.mean())
                    outputs[iou]['2max'].append(out2.max()) 
                    outputs[iou]['2min'].append(out2.min()) 
                    outputs[iou]['mean'].append(out3.mean())
                    outputs[iou]['max'].append(out3.max())
                    outputs[iou]['min'].append(out3.min())
    #bx=bxx#np.linspace(0, bxx[-1], num=outputs[1]['mean'].__len__(),  dtype=np.float32)
    #print(ding,(np.array(outputs[1]['mean']),np.array(outputs[2]['mean'])))
    #print([outputs[d]['min'] for d in outputs ])
    tree=1#tree plots instead of one
    ylog=[1,1,0]#set wich plot to have the y axes as a log
    coloros=["xkcd:racing green","xkcd:bright pink","xkcd:raw umber",
             "xkcd:bright orange", "xkcd:barney purple","xkcd:light green",
             "xkcd:piss yellow","xkcd:bright aqua","xkcd:fire engine red",]
    markers=['+--','*--','x-']#markers for each group of plot
    mks=[8,6,6]#size of the markers
    ALPH=0.58#alpha of the plot
    if tree: #tree plots
        fig, axs = plt.subplots(3, 1)
        #fig.set_xscale('log')
        plt.axis([0,np.amax(bs[-1]),min(outputs[3]['min']),max([max(outputs[d]['max']) for d in outputs ])])
        f1=plt.subplot(311)
        f1y=outputs[1]
        plt.plot(bx,f1y['1mean'],markers[0],color=coloros[0],markersize=mks[0],alpha=ALPH,)
        plt.plot(bx,f1y['1max'],markers[0],color=coloros[1],markersize=mks[0],alpha=ALPH,)
        plt.plot(bx,f1y['1min'],markers[0],color=coloros[2],markersize=mks[0],alpha=ALPH,)
        plt.plot(bx,f1y['2mean'],markers[1],color=coloros[3],markersize=mks[1],alpha=ALPH,)
        plt.plot(bx,f1y['2max'],markers[1],color=coloros[4],markersize=mks[1],alpha=ALPH,)
        plt.plot(bx,f1y['2min'],markers[1],color=coloros[5],markersize=mks[1],alpha=ALPH,)
        plt.plot(bx,f1y['mean'],markers[2],color=coloros[6],markersize=mks[2],alpha=ALPH,)
        plt.plot(bx,f1y['max'],markers[2],color=coloros[7],markersize=mks[2],alpha=ALPH,)
        plt.plot(bx,f1y['min'],markers[2],color=coloros[8],markersize=mks[2],alpha=ALPH,)
        plt.setp(f1.set_xscale('log'))
        plt.setp(f1.set_title('{},vecvari10,V3:{},sizz:{},mulb:{},mul2v:{}'.format(BD,v3v,sizz,mulbv,mul2v)))
        if ylog[0]:
            plt.setp(f1.set_yscale('log'))
        f2=plt.subplot(312,sharex=f1)#,sharey=f1)
        f2y=outputs[2]
        plt.plot(bx,f2y['1mean'],markers[0],color=coloros[0],markersize=mks[0],alpha=ALPH,)
        plt.plot( bx,f2y['1max'],markers[0],color=coloros[1],markersize=mks[0],alpha=ALPH,)
        plt.plot( bx,f2y['1min'],markers[0],color=coloros[2],markersize=mks[0],alpha=ALPH,)
        plt.plot(bx,f2y['2mean'],markers[1],color=coloros[3],markersize=mks[1],alpha=ALPH,)
        plt.plot(bx,f2y['2max'],markers[1],color=coloros[4],markersize=mks[1],alpha=ALPH,)
        plt.plot( bx,f2y['2min'],markers[1],color=coloros[5],markersize=mks[1],alpha=ALPH,)
        plt.plot(bx,f2y['mean'],markers[2],color=coloros[6],markersize=mks[2],alpha=ALPH,)
        plt.plot(bx,f2y['max'],markers[2],color=coloros[7],markersize=mks[2],alpha=ALPH,)
        plt.plot(bx,f2y['min'],markers[2],color=coloros[8],markersize=mks[2],alpha=ALPH,)
        plt.setp(f2.set_xscale('log'))
        plt.setp(f2.set_title('{},vecvari1,V3:{},sizz:{},mulb:{},mul2v:{}'.format(BD,v3v,sizz,mulbv,mul2v)))
        if ylog[1]:
            plt.setp(f2.set_yscale('log'))
        f3=plt.subplot(313,sharex=f1)#,sharey=f1)
        f3y=outputs[3]
        plt.plot(bx,f3y['1mean'],markers[0],color=coloros[0],markersize=mks[0],alpha=ALPH,)
        plt.plot( bx,f3y['1max'],markers[0],color=coloros[1],markersize=mks[0],alpha=ALPH,)
        plt.plot( bx,f3y['1min'],markers[0],color=coloros[2],markersize=mks[0],alpha=ALPH,)
        plt.plot(bx,f3y['2mean'],markers[1],color=coloros[3],markersize=mks[1],alpha=ALPH,)
        plt.plot(bx,f3y['2max'],markers[1],color=coloros[4],markersize=mks[1],alpha=ALPH,)
        plt.plot( bx,f3y['2min'],markers[1],color=coloros[5],markersize=mks[1],alpha=ALPH,)
        plt.plot(bx,f3y['mean'],markers[2],color=coloros[6],markersize=mks[2],alpha=ALPH,)
        plt.plot(bx,f3y['max'],markers[2],color=coloros[7],markersize=mks[2],alpha=ALPH,)
        plt.plot(bx,f3y['min'],markers[2],color=coloros[8],markersize=mks[2],alpha=ALPH,)
        plt.setp(f3.set_xscale('log'))
        plt.setp(f3.set_title('{},vecvari10-vecvari1,V3:{},sizz:{},mulb:{},mul2v:{}'.format(BD,v3v,sizz,mulbv,mul2v)))
        if ylog[2]:
            plt.setp(f3.set_yscale('log'))
    else: #all in one plot
        fig=plt.figure(1, figsize=(10,10))
        #plt.yscale('log')
        #plt.xscale('log')
        plt.axis([0,max(bx),min(outputs[3]['min']),max([max(outputs[d]['max']) for d in outputs ])])
        #plt.Axes.set_yscale(ax,'log')
        #plt.Axes.set_xscale(ax,'log')
        fg=plt.plot(bx,outputs[1]['mean'],'gs-',bx,outputs[1]['max'],'bs-',bx,outputs[1]['min'],'rs-',
           bx,outputs[2]['mean'],'go-',bx,outputs[2]['max'],'bo-',bx,outputs[2]['min'],'ro-',    
           bx,outputs[3]['mean'],'yH-',bx,outputs[3]['max'],'mH-',bx,outputs[3]['min'],'cH-',markersize=6)
        #print(fg)
        #plt.setp(fg,plt.yscale('log'))
        #plt.setp(fg,plt.xscale('log'))
    for I in range(3):
        I+=1
        print(outputs[I]['mean'][0],outputs[I]['mean'][9*4],outputs[I]['mean'][-1])
        print(outputs[I]['max'][0],outputs[I]['max'][9*4],outputs[I]['max'][-1])
        print(outputs[I]['min'][0],outputs[I]['min'][9*4],outputs[I]['min'][-1])
    #plt.ion() 
    plt.tight_layout(pad=1, h_pad=0.35, w_pad=0.35,rect=(0,0.07,1,1))
    plt.legend(['BB:0,BS:0, mean','BB:0,BS:0, max','BB:0,BS:0, min',
                'BB:1,BS:0, mean','BB:1,BS:0, max','BB:1,BS:0, min',
                'BB:0,BS:1, mean','BB:0,BS:1, max','BB:0,BS:1, min'],markerfirst=True,
               bbox_to_anchor=(0,0,1,0), loc=2,
               ncol=3, mode="expand", borderaxespad=0.5) 
    #https://matplotlib.org/users/legend_guide.html
    if mode=="save":
        outf=".//varplots//{}siz{}_ml{}_ml2{}_v3{}_rt{}.{}".format(BD,sizz,mulbv,mul2v,v3v,sqrtv,formatf)
        print(outf)
        plt.savefig(outf,format=formatf)
        #exit()
    else:
        plt.show()
Example #37
0
            # Get the heading from the quaternion
            yaw = math.atan2(2.0*(x*y + w*z), w*w + x*x - y*y - z*z);
            gps_point = (gps_points[point[0]==gps_points[:,0]]).flatten()
            pos_x, pos_y, pos_z = gps_point[1:4]
            
            all_heading_points = np.vstack((all_heading_points, np.array([point[0], pos_x, pos_y, pos_z, yaw])))
            
            if math.fabs(yaw - previous_yaw) < 1e-3:
                new_heading_points = np.vstack((new_heading_points, np.array([point[0], pos_x, pos_y, pos_z, yaw])))
            else:           
                old_heading_points = np.vstack((old_heading_points, np.array([point[0], pos_x, pos_y, pos_z, yaw])))
                
            previous_yaw = yaw

plt.figure()
plt.axis('equal')

# Plot all the GPS points and draw lines from one to the next
x = all_heading_points[:,1]
y = all_heading_points[:,2]
plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], scale_units='xy', angles='xy', scale=1)

# Transform angles from radians to degrees and plot the heading at the position of the GPS points
x = old_heading_points[:,1]
y = old_heading_points[:,2]
angles = old_heading_points[:,4] * 180 / math.pi
plt.quiver(x, y, 1, 0, scale_units='xy', angles=angles, scale=20, pivot='tail', color='r')

x = new_heading_points[:,1]
y = new_heading_points[:,2]
angles = new_heading_points[:,4] * 180 / math.pi
Example #38
0
    def plotProbability(self,fig, ax):

        # These shold be settings
        contours = 12

        bins=50
        minX,maxX = self.axX[0],self.axX[1]
        minY,maxY = self.axY[0],self.axY[1]

        if minX == maxX:
            minX = min(self.data[self.geoX])
            maxX = max(self.data[self.geoX])
            minY = min(self.data[self.geoY])
            maxY = max(self.data[self.geoY])


        #fig, ax = plt.subplots()
        plt.axis([minX, maxX, minY, maxY])
        if self.hasMatrix:
            xgrid, ygrid, zgrid = self.numpy
        else:
            xgrid, ygrid, zgrid = self.kde2D_scipy(kde,[minX,maxX,minY,maxY], bins)

        xgrid = np.linspace(minX, maxX, bins)
        ygrid = np.linspace(minY,maxY, bins)

        # Don't allow the axis to be on top of your data

        extent = []
        if self.range != []:
            extent = [self.range[0], self.range[1],self.range[0],self.range[1]]
            plt.gca().set_aspect("equal")
            print(extent)

        ax.grid(True, which='major', axis='both', linestyle='-', color=(0.5, 0.5, 0.5), alpha=0.1)

        if self.centre:
            self.data[self.hue + '2'] = self.data[self.hue] ** 2
            self.data = self.data.sort_values(by=self.hue + '2', ascending=True)
            self.vmax = max(self.data[self.hue].max(), -1 * self.data[self.hue].min())
            self.vmin = self.vmax * -1

        alpha=1
        if self.title=='ghost':
            alpha = 0.4
            #self.palette = 'seismic'

        if self.vmin == self.vmax:
            im = plt.pcolormesh(xgrid, ygrid, zgrid, shading='gouraud', cmap=self.palette,alpha=alpha)
            if self.range == []:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='0.7', linewidths=0.4,alpha=alpha)
            else:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='0.7', linewidths=0.4, alpha=alpha,extent=extent)

        else:
            im = plt.pcolormesh(xgrid, ygrid, zgrid, shading='gouraud', cmap=self.palette, vmin=self.vmin, vmax=self.vmax,alpha=alpha)
            if self.range == []:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='tab:purple', linewidths=0.05,alpha=alpha)
            else:
                cs = plt.contour(xgrid, ygrid, zgrid, contours, colors='tab:purple', linewidths=0.05, alpha=alpha,extent=extent)

        ax.set_axisbelow(True)
        cbar = fig.colorbar(im, ax=ax)
        cbar.remove()


        ax.set_xlabel(self.geoX)
        ax.set_ylabel(self.geoY)

        if self.hasMatrix:
            if self.title == '':
                title = 'Difference Image'
            else:
                title = self.title + '\nDifference Image'
        else:
            count = len(self.data.index)
            title = self.title
            if title == '':
                title += 'Count=' + str(count)
            else:
                title += '\nCount=' + str(count)

        plt.title(title)
        return ''
Example #39
0
n_error_outliers = y_pred_outliers[y_pred_outliers == -1].size / len(
    y_pred_outliers)
printVar("n_error_outliers", n_error_outliers)

# plot the line, the points, and the nearest vectors to the plane
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.title("Novelty Detection")
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu)
a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='palevioletred')

s = 40
b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=s)
b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='blueviolet', s=s)
c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='gold', s=s)
plt.axis('tight')
plt.xlim((-5, 5))
plt.ylim((-5, 5))
plt.legend([a.collections[0], b1, b2, c], [
    "learned frontier", "training observations", "new regular observations",
    "new abnormal observations"
],
           loc="upper left",
           prop=matplotlib.font_manager.FontProperties(size=11))
plt.xlabel("error train: %d/200 ; errors novel regular: %d/40 ; "
           "errors novel abnormal: %d/40" %
           (n_error_train, n_error_test, n_error_outliers))
plt.show()
Example #40
0
    def plotHexbin(self,fig, ax):
        # These shold be settings
        contours = 12
        ax.grid(b=True, which='major', color='Gainsboro', linestyle='-',alpha=0.7,lw=0.7)
        #ax.set_axisbelow(True)can't set the lines below as the whole data is 1 image not scatters

        if self.operation == 'ABS':
            self.data[self.geoX] == abs(self.data[self.geoX])


        x = self.data[self.geoX]#.ravel()
        y = self.data[self.geoY]#.ravel()

        extent = []
        if self.range != []:
            extent = [self.range[0], self.range[1],self.range[0],self.range[1]]
            plt.gca().set_aspect("equal")

        if self.hue.lower() == 'count':
            if self.range == []:
                hb = plt.hexbin(x, y, bins=self.bins, cmap=self.palette,gridsize=self.gridsize)
            else:
                hb = plt.hexbin(x, y, bins=self.bins, cmap=self.palette, gridsize=self.gridsize,extent=extent)

            #cb = plt.colorbar()
            #cb.set_label('Count')
        else:
            z = self.data[self.hue]  # .ravel()
            self.vmin = z.min()
            self.vmax = z.max()
            #ax = self.data.plot.hexbin(x=self.geoX,y=self.geoY,C=self.hue,gridsize=10,cmap=self.palette)
            if self.range == []:
                hb = plt.hexbin(x,y,C=z,bins=self.bins, cmap=self.palette,gridsize=self.gridsize,reduce_C_function=np.mean)
                        #,vmin = self.vmin, vmax = self.vmax)
            else:
                hb = plt.hexbin(x, y, C=z, bins=self.bins, cmap=self.palette, gridsize=self.gridsize,reduce_C_function=np.mean, extent=extent)

            cb = plt.colorbar()
            cb.set_label('Average ' + self.hue)
            #cb.set_ticks(z.min(),z.max())
            cb.set_ticks(np.linspace(hb.get_array().min(), hb.get_array().max(), 10))
            lbls = np.linspace(round(z.min(),2), round(z.max(),2), 10)
            diff = z.max()-z.min()
            lblsrounded = []
            for lbl in lbls:
                if diff < 5:
                    lblsrounded.append(round(lbl,2))
                elif diff < 10:
                    lblsrounded.append(round(lbl, 1))
                else:
                    lblsrounded.append(int(round(lbl, 0)))
            #cb.set_ticklabels(np.linspace(round(z.min(),2), round(z.max(),2), 10))
            cb.set_ticklabels(lblsrounded)

        #if self.range != []:
        #    plt.xlim(xmin=self.range[0], xmax=self.range[1])
        #    plt.gca().set_aspect("equal")
        #    ax.grid(b=True, which='major', color='Gainsboro', linestyle='-')
        #    ax.set_axisbelow(True)

        plt.axis([x.min(), x.max(), y.min(), y.max()])
        if self.range !=[]:
            bnds = np.array([self.range[0], self.range[1]])
            ax.set_xlim(bnds)
            ax.set_ylim(bnds)

        #Labelling
        ax.set_xlabel(self.geoX)
        ax.set_ylabel(self.geoY)
        count = len(self.data.index)
        title = self.title
        if title == '':
            title += 'Count=' + str(count)
        else:
            title += '\nCount=' + str(count)

        plt.title(title)
        return ''
Example #41
0
import sys
import time

filename=sys.argv[1]
print('plot', filename)
plt.ion()
fig=plt.figure()

while(True):
    ifile=open(filename)
    #for i,l in enumerate(ifile):
    l=ifile.readline()
    ifile.close()
    #title=l.split(',')[0]+' '+l.split(',')[1]
    data=l.split(',')
    try:
        data=np.array(data,dtype=np.float)
    except:
        pass
    print(data[:10])
    fig.clf()
    plt.axis((0,4000,0,66000))
    plt.title(time.strftime("%d %b  %Y %H:%M:%S -0600",time.localtime()))
    plt.plot(data,'-')
    fig.canvas.draw()
    fig.canvas.flush_events()
    #plt.draw()
    #plt.show()
    time.sleep(3)
    #plt.close()
knn_graph = kneighbors_graph(X, 30, include_self=False)

for connectivity in (None, knn_graph):
    for n_clusters in (30, 3):
        plt.figure(figsize=(10, 4))
        for index, linkage in enumerate(('average',
                                         'complete',
                                         'ward',
                                         'single')):
            plt.subplot(1, 4, index + 1)
            model = AgglomerativeClustering(linkage=linkage,
                                            connectivity=connectivity,
                                            n_clusters=n_clusters)
            t0 = time.time()
            model.fit(X)
            elapsed_time = time.time() - t0
            plt.scatter(X[:, 0], X[:, 1], c=model.labels_,
                        cmap=plt.cm.spectral)
            plt.title('linkage=%s\n(time %.2fs)' % (linkage, elapsed_time),
                      fontdict=dict(verticalalignment='top'))
            plt.axis('equal')
            plt.axis('off')

            plt.subplots_adjust(bottom=0, top=.89, wspace=0,
                                left=0, right=1)
            plt.suptitle('n_cluster=%i, connectivity=%r' %
                         (n_clusters, connectivity is not None), size=17)


plt.show()
Example #43
0
def plot_mandel(mandel):
    plt.imshow(mandel)
    plt.axis('off')
    plt.show()
Example #44
0
def main(options):
    fig = plt.figure(figsize=(14, 9), dpi=100)
    fig.canvas.mpl_connect('pick_event', onpick)

    xdata = 2
    ydata = 1
    typespec = {
        't': ('Time', 0),
        's': ('Speed', 1),
        'd': ('Distance', 2),
        'a': ('Acceleration', 3),
        'i': ('Angle', 4),
        'x': ('x-Position', 5),
        'y': ('y-Position', 6),
    }

    shortFileNames = short_names(options.fcdfiles)
    if (len(options.ttype) == 2 and options.ttype[0] in typespec
            and options.ttype[1] in typespec):
        xLabel, xdata = typespec[options.ttype[0]]
        yLabel, ydata = typespec[options.ttype[1]]
        plt.xlabel(xLabel)
        plt.ylabel(yLabel)
        plt.title(','.join(shortFileNames
                           ) if options.label is None else options.label)
    else:
        sys.exit("unsupported plot type '%s'" % options.ttype)

    routes = defaultdict(list)  # vehID -> recorded edges
    # vehID -> (times, speeds, distances, accelerations, angles, xPositions, yPositions)
    data = defaultdict(lambda: ([], [], [], [], [], [], []))
    for fileIndex, fcdfile in enumerate(options.fcdfiles):
        for timestep, vehicle in parse_fast_nested(
                fcdfile, 'timestep', ['time'], 'vehicle',
            ['id', 'x', 'y', 'angle', 'speed', 'lane']):
            vehID = vehicle.id
            if len(options.fcdfiles) > 1:
                suffix = shortFileNames[fileIndex]
                if len(suffix) > 0:
                    vehID += "#" + suffix
            time = float(timestep.time)
            speed = float(vehicle.speed)
            prevTime = time
            prevSpeed = speed
            prevDist = 0
            if vehID in data:
                prevTime = data[vehID][0][-1]
                prevSpeed = data[vehID][1][-1]
                prevDist = data[vehID][2][-1]
            data[vehID][0].append(time)
            data[vehID][1].append(speed)
            data[vehID][4].append(float(vehicle.angle))
            data[vehID][5].append(float(vehicle.x))
            data[vehID][6].append(float(vehicle.y))
            if prevTime == time:
                data[vehID][3].append(0)
            else:
                data[vehID][3].append((speed - prevSpeed) / (time - prevTime))

            if options.ballistic:
                avgSpeed = (speed + prevSpeed) / 2
            else:
                avgSpeed = speed
            data[vehID][2].append(prevDist + (time - prevTime) * avgSpeed)
            edge = vehicle.lane[0:vehicle.lane.rfind('_')]
            if len(routes[vehID]) == 0 or routes[vehID][-1] != edge:
                routes[vehID].append(edge)

    def line_picker(line, mouseevent):
        if mouseevent.xdata is None:
            return False, dict()
        # minxy = None
        # mindist = 10000
        for x, y in zip(line.get_xdata(), line.get_ydata()):
            dist = math.sqrt((x - mouseevent.xdata)**2 +
                             (y - mouseevent.ydata)**2)
            if dist < options.pickDist:
                return True, dict(label=line.get_label())
            # else:
            #    if dist < mindist:
            #        print("   ", x,y, dist, (x - mouseevent.xdata) ** 2, (y - mouseevent.ydata) ** 2)
            #        mindist = dist
            #        minxy = (x, y)
        # print(mouseevent.xdata, mouseevent.ydata, minxy, dist,
        #        line.get_label())
        return False, dict()

    minY = uMax
    maxY = uMin
    minX = uMax
    maxX = uMin

    for vehID, d in data.items():
        if options.filterRoute is not None:
            skip = False
            route = routes[vehID]
            for required in options.filterRoute:
                if required not in route:
                    skip = True
                    break
            if skip:
                continue
        if options.invertDistanceAngle is not None:
            avgAngle = sum(d[4]) / len(d[4])
            if abs(avgAngle - options.invertDistanceAngle) < 45:
                maxDist = d[2][-1]
                for i, v in enumerate(d[2]):
                    d[2][i] = maxDist - v

        minY = min(minY, min(d[ydata]))
        maxY = max(maxY, max(d[ydata]))
        minX = min(minX, min(d[xdata]))
        maxX = max(maxX, max(d[xdata]))

        plt.plot(d[xdata], d[ydata], picker=line_picker, label=vehID)
    if options.invertYAxis:
        plt.axis([minX, maxX, maxY, minY])

    if options.legend > 0:
        plt.legend()

    plt.savefig(options.output)
    if options.csv_output is not None:
        write_csv(data, options.csv_output)
    if options.show:
        plt.show()
Example #45
0
def pie():
    ylist = [
        2001, 2002, 1999, 2001, 2002, 2001, 2002, 2001, 2001, 2003, 2000, 2003,
        2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2003, 2003, 2003,
        2003, 2003
    ]

    clist = [
        'kidnapping',
        'murder',
        'cyber_crime',
        'robbery',
        'accident',
        'accident',
        'accident',
        'robbery',
        'robbery',
        'robbery',
        'robbery',
        'robbery',
        'robbery',
        'murder',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'kidnapping',
        'cyber_crime',
        'cyber_crime',
    ]

    nlist = []
    colist = []
    for i in range(len(ylist)):
        if ylist[i] == 2000:
            nlist.append(clist[i])

    print nlist

    set1 = set(nlist)

    list2 = list(set1)

    lcrime = list2

    for crime in list2:
        print crime, nlist.count(crime)
        colist.append(nlist.count(crime))
    print colist

    #years = [2001,2002,2003,2004]
    '''murder = [4,5,2,3]
	kidnappingidnapping = [1,2,1,3]
	accident = [12,13,40,57]
	'''

    slices = colist
    activities = list2
    cols = ['y', 'r', 'g']
    explode = (0.1, 0.1, 0.1)

    plt.pie(slices,
            explode=explode,
            labels=lcrime,
            colors=cols,
            autopct='%1.1f%%',
            shadow=True,
            startangle=140)

    plt.axis('equal')
    #plt.title('2000 crime Rate')
    plt.ylabel('2000 crime Rate')
    #plt.xlabel('X axis')
    plt.legend()
    plt.show()
Example #46
0
def plot_graph(G,
               broken_graph,
               broken_partition,
               npartition,
               layer1,
               layer2,
               layer3,
               d1=1.5,
               d2=5.,
               d3=0,
               d4=.8,
               nodesize=1000,
               withlabels=True,
               edgelist=[],
               layout=True,
               alpha=0.5):

    if layout:
        pos = nx.spring_layout(G)
    else:
        pos = nx.random_layout(G)

    top_set = set()
    bottom_set = set()
    middle_set = set()
    down = []
    right = []
    left = []

    mlayer_part = {}
    for i in broken_partition:
        ii = i.split('_')
        if ii[1] not in mlayer_part:
            mlayer_part[ii[1]] = set([ii[2]])
        else:
            mlayer_part[ii[1]].add(ii[2])

    layers_m = Counter()
    for k, v in mlayer_part.items():
        if len(v) == 1:
            layers_m[1] += 1
        elif len(v) == 2:
            layers_m[2] += 1
        elif len(v) == 3:
            layers_m[3] += 1
        else:
            print k, v

    broken_pos = {}
    singles = 0

    for i, v in broken_partition.items():
        name = i.split('_')
        if name[-1] == 's':
            singles += 1
        ndnd = random.choice(v)
        npos = pos[ndnd]
        if ndnd in layer1:
            broken_pos[i] = [d2 * (npos[0] - d1), d2 * (npos[1] + d1)]
            top_set.add(i)
            left.append(broken_pos[i])
        elif ndnd in layer2:
            broken_pos[i] = [d2 * (npos[0] + d1), d2 * (npos[1] + d1)]
            bottom_set.add(i)
            right.append(broken_pos[i])
        else:
            broken_pos[i] = [d2 * npos[0], d2 * (npos[1] - d1)]
            middle_set.add(i)
            down.append(broken_pos[i])

    xleft = [i[0] for i in left]
    yleft = [i[1] for i in left]

    aleft = [min(xleft) - d1 / 2., max(yleft) + d1 / 2. + d3]
    bleft = [max(xleft) + d1 / 2., max(yleft) + d1 / 2. + 3 * d3]
    cleft = [max(xleft) + d1 / 2., min(yleft) - d1 / 2. - 3 * d3]
    dleft = [min(xleft) - d1 / 2., min(yleft) - d1 / 2. - d3]

    xright = [i[0] for i in right]
    yright = [i[1] for i in right]

    aright = [min(xright) - d1 / 2., max(yright) + d1 / 2. + d3]
    bright = [max(xright) + d1 / 2., max(yright) + d1 / 2. + 3 * d3]
    cright = [max(xright) + d1 / 2., min(yright) - d1 / 2. - 3 * d3]
    dright = [min(xright) - d1 / 2., min(yright) - d1 / 2. - d3]

    xdown = [i[0] for i in down]
    ydown = [i[1] for i in down]

    adown = [min(xdown) - d1 / 2., max(ydown) + d1 / 2. + d3]
    bdown = [max(xdown) + d1 / 2., max(ydown) + d1 / 2. + 3 * d3]
    cdown = [max(xdown) + d1 / 2., min(ydown) - d1 / 2. - 3 * d3]
    ddown = [min(xdown) - d1 / 2., min(ydown) - d1 / 2. - d3]

    fig = plt.figure(figsize=(20, 20))
    ax = fig.add_subplot(111)

    ax.add_patch(Polygon([aleft, bleft, cleft, dleft], color='r', alpha=0.1))
    plt.plot([aleft[0], bleft[0], cleft[0], dleft[0], aleft[0]],
             [aleft[1], bleft[1], cleft[1], dleft[1], aleft[1]], '-r')

    ax.add_patch(
        Polygon([aright, bright, cright, dright], color='b', alpha=0.1))
    plt.plot([aright[0], bright[0], cright[0], dright[0], aright[0]],
             [aright[1], bright[1], cright[1], dright[1], aright[1]], '-b')

    ax.add_patch(Polygon([adown, bdown, cdown, ddown], color='g', alpha=0.1))
    plt.plot([adown[0], bdown[0], cdown[0], ddown[0], adown[0]],
             [adown[1], bdown[1], cdown[1], ddown[1], adown[1]], '-g')

    nodeSize = [nodesize * len(broken_partition[i]) for i in list(top_set)]
    nodeColor = [broken_graph.node[i]['color'] for i in list(top_set)]

    nx.draw_networkx_nodes(broken_graph,
                           broken_pos,
                           nodelist=list(top_set),
                           node_shape='s',
                           node_color=nodeColor,
                           alpha=1,
                           node_size=nodeSize)
    nodeSize = [nodesize * len(broken_partition[i]) for i in list(middle_set)]
    nodeColor = [broken_graph.node[i]['color'] for i in list(middle_set)]

    nx.draw_networkx_nodes(broken_graph,
                           broken_pos,
                           nodelist=list(middle_set),
                           node_shape='s',
                           node_color=nodeColor,
                           alpha=1,
                           node_size=nodeSize)
    nodeSize = [nodesize * len(broken_partition[i]) for i in list(bottom_set)]
    nodeColor = [broken_graph.node[i]['color'] for i in list(bottom_set)]

    nx.draw_networkx_nodes(broken_graph,
                           broken_pos,
                           nodelist=list(bottom_set),
                           node_shape='s',
                           node_color=nodeColor,
                           alpha=1,
                           node_size=nodeSize)

    if withlabels:
        nx.draw_networkx_labels(G, pos)

    lay1_edges = [
        ed for ed in G.edges() if ed[0] in layer1 and ed[1] in layer1
    ]
    lay2_edges = [
        ed for ed in G.edges() if ed[0] in layer2 and ed[1] in layer2
    ]
    lay3_edges = [
        ed for ed in G.edges() if ed[0] in layer3 and ed[1] in layer3
    ]

    nx.draw_networkx_edges(broken_graph, broken_pos, alpha=0.3)  #0.15
    # orr=nx.attribute_assortativity_coefficient(broken_graph,'color')
    # for i,v in broken_partition.items():
    #     for nd in v:
    #         atrr=G.node[nd]
    #         G.add_node(nd,attr_dict=atrr,asso=i)

    # # print G.nodes(data=True)
    # rr=nx.attribute_assortativity_coefficient(G,'asso')
    rcom = nx.attribute_assortativity_coefficient(G, 'threeattributes')
    rlay = nx.attribute_assortativity_coefficient(G, 'layers_3')
    rr = nx.attribute_assortativity_coefficient(G, 'asso')
    # print 'Attribute assortativity coefficient wrt layer partition (old)= %f' %orr
    # title_s='%i communities (%i 3-layered, %i 2-layered, %i 1-layered)\nAssortativity_coef(%i_communities) = %.2f\nAssortativity_coef(3_layers) = %.2f\n Joint_Assortativity_coef(%i_communities, 3_layers) = %f' %(len(npartition),layers_m[3],layers_m[2],layers_m[1],len(npartition),rcom,rlay,len(npartition),rr)

    # print 'Attribute assortativity coefficient wrt layer partition (old) = %f' %orr

    # print 'Attribute assortativity coefficient wrt layer partition (old)= %f' %orr
    title_s = '%i Three vertex attributes (%i 3-layered, %i 2-layered, %i 1-layered)\nAssortativity_coef(%i_3Attributes) = %.2f\nAssortativity_coef(3_layers) = %.2f\n Joint_Assortativity_coef(%i_3Attributes, 3_layers) = %.2f ' % (
        len(npartition), layers_m[3], layers_m[2], layers_m[1],
        len(npartition), rcom, rlay, len(npartition), rr)

    # title_s='%i Three vertex attributes (%i 3-layered, %i 2-layered, %i 1-layered)' %(len(npartition),layers_m[3],layers_m[2],layers_m[1])
    plt.title(title_s, {'size': '20'})
    plt.axis('off')
    plt.show()
Example #47
0
#!/usr/bin/env python3
"""
Plots x -> y1 and x -> y2 as line graphs in the same figure.
"""
import numpy as np
import matplotlib.pyplot as plt


x = np.arange(0, 21000, 1000)
r = np.log(0.5)
t1 = 5730
t2 = 1600
y1 = np.exp((r / t1) * x)
y2 = np.exp((r / t2) * x)

plt.plot(x, y1, 'r--', x, y2, 'g')
plt.xlabel('Time (years)')
plt.ylabel('Fraction Remaining')
plt.title('Exponential Decay of Radioactive Elements')
plt.axis([0, 20000, 0, 1])
plt.legend(['C-14', 'Ra-226'])
plt.show()
Example #48
0
for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]):

    # We only take the two corresponding features
    feature_set = feature_data[:, pair]

    # Train
    clf = DecisionTreeClassifier().fit(feature_set, label_set)

    # Plot the decision boundary
    plt.subplot(2, 3, pairidx + 1)

    x_min, x_max = feature_set[:, 0].min() - 1, feature_set[:, 0].max() + 1
    y_min, y_max = feature_set[:, 1].min() - 1, feature_set[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                         np.arange(y_min, y_max, plot_step))

    plt.xlabel(feature_names[pair[0]])
    plt.ylabel(feature_names[pair[1]])
    plt.axis("tight")

    # Plot the training points
    for i, color in zip(range(n_classes), plot_colors):
        idx = np.where(label_set == i)
        plt.scatter(feature_set[idx, 0], feature_set[idx, 1], c=color, label=target_names[i],
                    cmap=plt.cm.Paired)

    plt.axis("tight")

plt.suptitle("Decision surface of a '{0}' using paired features".format("Decision Tree (DT)"))
plt.legend()
plt.show()
    for i in xrange(0,10):
        sel = random.sample(xrange(60000),n)
        X = ocr['data'][sel,:]
        Y = ocr['labels'][sel,:]
        results = predictions(X,Y,test)
        error.append((sum(results!=correct_preds)+0.0)/(10000))
    total_errors.append(error)
    error=[]

# Plot results

means = map(np.mean, total_errors)
std_devs = map(np.std, total_errors)

plt.errorbar(sizes, means, std_devs, linestyle='-', marker='o', linewidth=1.5)
plt.axis([500,8500,0.05,0.12])
plt.ylabel('Error rate')
plt.xlabel('Number of training points')
plt.title('Error rate vs. Number of training points')
plt.show()

print "Mean error for the different sizes:", means
print "Standard deviation for the different sizes:", std_devs

# Parameter generating function using Laplace smoothing to estimate the parameters of each class

def param_gen(X,Y):
    # X is data, Y is labels
    total= X.sum()
    num_lbls = np.unique(Y)
    params = []
# Plot the window and its frequency response:

from scipy import signal
from scipy.fftpack import fft, fftshift
import matplotlib.pyplot as plt

window = signal.hann(51)
plt.plot(window)
plt.title("Hann window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")

plt.figure()
A = fft(window, 2048) / (len(window)/2.0)
freq = np.linspace(-0.5, 0.5, len(A))
response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
plt.plot(freq, response)
plt.axis([-0.5, 0.5, -120, 0])
plt.title("Frequency response of the Hann window")
plt.ylabel("Normalized magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
Example #51
0
def display_fraudulent_labels_linear(
    mypath,
    percent_thres,
    model_1,
    be_l,
    num_bins,
    max_histo_level,
    target_image_file_name,
    x,
):
    file_list = []
    file_name_list = []
    for filename in glob.glob(mypath + "*.*"):
        if filename in target_image_file_name:
            continue
        else:
            file_list.append(filename)

    similar_diff = 0.1
    img_list = []

    imgTarget = Image.open(target_image_file_name)

    for fn in file_list:
        # Load test beer label image
        test_img = Image.open(fn)

        # Normalize beer label image
        test_img = test_img.convert("RGB")
        test_img_resized = test_img.resize((224, 224))
        test_img_array = np.array(test_img_resized)
        save_0 = test_img_array[:, :, 0]
        save_1 = test_img_array[:, :, 1]
        x[0] = test_img_array

        # Process normalized beer label through model to generate feature vectors
        x_out_2 = model_1.predict(x[0:1])
        x_out_2_r = np.ravel(x_out_2[0])

        # Generate histogram, and correlation product to determine if the label is fraudulent
        be_h, hist_h = np.histogram(x_out_2_r,
                                    bins=num_bins,
                                    range=[0.0, max_histo_level],
                                    density=True)
        cor02 = sum(np.abs(be_l[1:] - be_h[1:]))

        # Threshold the correlation product to determine fraudulence
        if cor02 < similar_diff * percent_thres:
            img_list.append(test_img_array)
            file_name_list.append(fn)

    # Plot the fraudulent beer labels
    num_figs = 5
    num_blocks = int(len(img_list) / num_figs)
    index = 0
    for block in range(num_blocks):
        (sub_plot1, sub_plot2) = plt.subplots(1, 5, figsize=(16, 16))
        for image_index in range(5):
            sub_plot2[image_index].imshow(img_list[index])
            sub_plot2[image_index].axis("off")
            index += 1
        plt.show()

    left_over = len(img_list) % num_figs
    if left_over > 1:
        (sub_plot1, sub_plot2) = plt.subplots(1, left_over, figsize=(10, 10))
        for image_index in range(left_over):
            sub_plot2[image_index].imshow(img_list[index])
            sub_plot2[image_index].axis("off")
            index += 1
        plt.show()
    elif left_over == 1:
        plt.subplots(1, 1, figsize=(10, 10))
        plt.imshow(img_list[index])
        plt.axis("off")
        plt.show()

    return file_name_list
def display(img):
    one_image = img.reshape(28, 28)
    plt.axis('off')
    plt.imshow(one_image, cmap=CM.binary)
Example #53
0
def main():
    args = parse_args()
    display = args.display
    use_dlibTracker  = args.use_dlibTracker
    saver = args.saver

    total_time = 0.0
    total_frames = 0

    # for disp
    if display:
        colours = np.random.rand(32, 3)  # used only for display
        plt.ion()
        fig = plt.figure()


    if not os.path.exists('output'):
        os.makedirs('output')
    out_file = 'output/townCentreOut.top'

    #init detector
    detector = GroundTruthDetections()

    #init tracker
    tracker =  Sort(use_dlib= use_dlibTracker) #create instance of the SORT tracker

    if use_dlibTracker:
        print "Dlib Correlation tracker activated!"
    else:
        print "Kalman tracker activated!"

    with open(out_file, 'w') as f_out:

        frames = detector.get_total_frames()
        for frame in range(0, frames):  #frame numbers begin at 0!
            # get detections
            detections = detector.get_detected_items(frame)

            total_frames +=1
            fn = 'test/Pictures%d.jpg' % (frame + 1)  # video frames are extracted to 'test/Pictures%d.jpg' with ffmpeg
            img = io.imread(fn)
            if (display):
                ax1 = fig.add_subplot(111, aspect='equal')
                ax1.imshow(img)
                if(use_dlibTracker):
                    plt.title('Dlib Correlation Tracker')
                else:
                    plt.title('Kalman Tracker')

            start_time = time.time()
            #update tracker
            trackers = tracker.update(detections,img)

            cycle_time = time.time() - start_time
            total_time += cycle_time

            print('frame: %d...took: %3fs'%(frame,cycle_time))

            for d in trackers:
                f_out.write('%d,%d,%d,%d,x,x,x,x,%.3f,%.3f,%.3f,%.3f\n' % (d[4], frame, 1, 1, d[0], d[1], d[2], d[3]))
                if (display):
                    d = d.astype(np.int32)
                    ax1.add_patch(patches.Rectangle((d[0], d[1]), d[2] - d[0], d[3] - d[1], fill=False, lw=3,
                                                    ec=colours[d[4] % 32, :]))
                    ax1.set_adjustable('box-forced')
                    #label
                    ax1.annotate('id = %d' % (d[4]), xy=(d[0], d[1]), xytext=(d[0], d[1]))
                    if detections != []:#detector is active in this frame
                        ax1.annotate(" DETECTOR", xy=(5, 45), xytext=(5, 45))

            if (display):
                plt.axis('off')
                fig.canvas.flush_events()
                plt.draw()
                fig.tight_layout()
                #save the frame with tracking boxes
                if(saver):
                    fig.savefig("./frameOut/f%d.jpg"%(frame+1),dpi = 200)
                ax1.cla()


    print("Total Tracking took: %.3f for %d frames or %.1f FPS"%(total_time,total_frames,total_frames/total_time))
Example #54
0
def display_fraudulent_labels_art(
    mypath,
    percent_thres,
    label_model,
    similar_diff,
    target_image_file_name,
    x_only,
    x,
):
    bin_group = 5
    max_histo_level = 40
    num_bins = 200
    print(percent_thres * similar_diff)

    file_list = []
    for filename in glob.glob(mypath + "*.*"):

        if filename in target_image_file_name:
            continue
        else:
            file_list.append(filename)

    file_name_list = []
    img_list = []
    for fn in file_list:
        # Load test beer label image
        test_label = Image.open(fn)

        # Normalize beer label image
        test_label = test_label.convert("RGB")
        test_label_resized = test_label.resize((224, 224))
        test_label_array = np.array(test_label_resized)
        save_0 = test_label_array[:, :, 0]
        save_1 = test_label_array[:, :, 1]
        x[0] = test_label_array

        x[0] = test_label_array
        x[1] = test_label_array
        x_out_1 = label_model.predict(x[0:2])
        x_out_1_r = np.ravel(x_out_1[0])
        x_out_2_r = np.ravel(x_out_1[1])
        print("file_name = " + str(fn))

        # Generate histogram, and correlation product to determine if the label is fraudulent
        be_h, hist_h = np.histogram(x_out_2_r,
                                    bins=num_bins,
                                    range=[0.0, max_histo_level],
                                    density=True)
        diff = dist.chebyshev(x_out_2_r, x_only)
        print(diff)

        # Threshold the correlation product to determine fraudulence
        if diff < similar_diff * percent_thres:
            img_list.append(test_label_array)
            file_name_list.append(fn)

    # Plot the fraudulent beer labels
    num_figs = 5
    num_blocks = int(len(img_list) / num_figs)
    index = 0
    for block in range(num_blocks):
        (sub_plot1, sub_plot2) = plt.subplots(1, 5, figsize=(16, 16))
        for image_index in range(5):
            sub_plot2[image_index].imshow(img_list[index])
            sub_plot2[image_index].axis("off")
            index += 1
        plt.show()

    left_over = len(img_list) % num_figs

    if left_over > 1:
        (sub_plot1, sub_plot2) = plt.subplots(1, left_over, figsize=(10, 10))
        for image_index in range(left_over):
            sub_plot2[image_index].imshow(img_list[index])
            sub_plot2[image_index].axis("off")
            index += 1
        plt.show()
    elif left_over == 1:
        plt.subplots(1, 1, figsize=(10, 10))
        plt.imshow(img_list[index])
        plt.axis("off")
        plt.show()

    return file_name_list
Example #55
0
import matplotlib.pyplot as mp
import numpy as np

mp.figure('pie',facecolor='lightgray')
mp.axis('equal')  # 设置x轴和Y轴等比
values = [23,25,29,28,65]
spaces = [0.05,0.01,0.01,0.01,0.01]
labels = ['php','c','c++','java','python']
colors = ['red','green','orangered','blue','yellow']
mp.pie(values,spaces,labels,colors,'%.1f%%')
mp.legend()
mp.show()
Example #56
0
def draw_network():
    with open(os.path.join(ABILITY_DIR, "output",
                           "network_for_draw.csv")) as f:
        reader = list(csv.reader(f))
    with open(os.path.join(ABILITY_DIR, "output", "network_helper.json")) as f:
        helper = json.load(f)
    header = reader[0]
    G = nx.Graph()
    labels = {}
    edge_colors = []
    node_sizes = []
    node_colors = []
    for row in reader[1:]:
        # print(row[0])
        G.add_node(row[0])
        node_sizes.append(float(helper[row[0]]["size"]))
        node_colors.append(helper[row[0]]["color"])
        labels[row[0]] = row[0]
    for row in reader[1:]:
        source = row[0]
        for index, r in enumerate(row[1:], 1):
            if r == "1":
                G.add_edge(source, header[index])
                edge_colors.append(helper[header[index]]["color"])
    pos = nx.spring_layout(G)
    # pos = nx.spring_layout(G, k=1, iterations=20)

    plt.figure(figsize=(24, 24))
    ax = plt.gca()
    options = {
        "linewidths": 0,
        "alpha": 0.8,
        "node_size": node_sizes,
        "node_color": node_colors,
    }
    for idx, edge in enumerate(G.edges()):
        source, target = edge
        rad = 0.4
        arrowprops = dict(
            linewidth=0.2,
            arrowstyle="-",
            color=helper[target]["color"],
            connectionstyle=f"arc3,rad={rad}",
            alpha=0.6,
        )
        ax.annotate("",
                    xy=pos[source],
                    xytext=pos[target],
                    arrowprops=arrowprops)

    nx.draw_networkx_nodes(G, pos, **options)
    # nx.draw_networkx_labels(G, pos, labels=labels, font_family="NanumGothic")

    # plt.text(x, y, node, fontsize=d[node] * 5, ha='center', va='center')
    plt.rc("font", family="NanumGothic")
    for node, (x, y) in pos.items():
        plt.text(
            x,
            y,
            node,
            fontsize=float(helper[node]["font_size"]),
            ha="center",
            va="center",
        )
    plt.axis("off")

    plt.savefig("network.svg", format="svg", dpi=400)
    plt.savefig("network.png", format="png", dpi=400)
#print(time_axis_data_app[0:60])
#print(time_axis_data_stack)

#'''
x = time_axis_data_app_array
plt.xlabel("Time elapsed (s)")
#y0 = latencies
#y = y0.copy() + 2.5
y = app_latencies
plt.ylabel("Latency (ms)")

#lines = plt.step(x, y, label='Delay between sending data and receiving application data')
lines = plt.plot(x, y, 'ro')
plt.setp(lines, markersize=0.4)
plt.setp(lines, markerfacecolor='r')
plt.axis([0, 300, 0, 175])

#y -= 0.5
#plt.step(x, y, where='post', label='post')

#y = ma.masked_where((y0 > -0.15) & (y0 < 0.15), y - 0.5)
#plt.step(x, y, label='masked (preplt.legend()

#plt.show()
#plt.savefig('app_latency/%s.pdf' % sys.argv[1][:-4])
#plt.savefig('app-%s.png' % filename[-1])
plt.savefig('%s/app-%s.png' % ("/".join(str(s)
                                        for s in filename[:-1]), filename[-1]))

#'''
l = lines.pop(0)
Example #58
0
def compare_plot(signal1,
                 signal2,
                 Fs,
                 fft_size=512,
                 norm=False,
                 equal=False,
                 title1=None,
                 title2=None):

    import matplotlib.pyplot as plt

    td_amp = np.maximum(np.abs(signal1).max(), np.abs(signal2).max())

    if norm:
        if equal:
            signal1 /= np.abs(signal1).max()
            signal2 /= np.abs(signal2).max()
        else:
            signal1 /= td_amp
            signal2 /= td_amp
        td_amp = 1.

    plt.subplot(2, 2, 1)
    plt.plot(np.arange(len(signal1)) / float(Fs), signal1)
    plt.axis('tight')
    plt.ylim(-td_amp, td_amp)
    if title1 is not None:
        plt.title(title1)

    plt.subplot(2, 2, 2)
    plt.plot(np.arange(len(signal2)) / float(Fs), signal2)
    plt.axis('tight')
    plt.ylim(-td_amp, td_amp)
    if title2 is not None:
        plt.title(title2)

    from .stft import stft, spectroplot
    from .windows import hann

    F1 = stft.stft(signal1, fft_size, fft_size / 2, win=windows.hann(fft_size))
    F2 = stft.stft(signal2, fft_size, fft_size / 2, win=windows.hann(fft_size))

    # try a fancy way to set the scale to avoid having the spectrum
    # dominated by a few outliers
    p_min = 1
    p_max = 99.5
    all_vals = np.concatenate((dB(F1 + eps), dB(F2 + eps))).flatten()
    vmin, vmax = np.percentile(all_vals, [p_min, p_max])

    cmap = 'jet'
    interpolation = 'sinc'

    plt.subplot(2, 2, 3)
    stft.spectroplot(F1.T,
                     fft_size,
                     fft_size / 2,
                     Fs,
                     vmin=vmin,
                     vmax=vmax,
                     cmap=plt.get_cmap(cmap),
                     interpolation=interpolation)

    plt.subplot(2, 2, 4)
    stft.spectroplot(F2.T,
                     fft_size,
                     fft_size / 2,
                     Fs,
                     vmin=vmin,
                     vmax=vmax,
                     cmap=plt.get_cmap(cmap),
                     interpolation=interpolation)
Example #59
0
def main():
    #=======================================================================
    # part 1: datamation
    #=======================================================================
    # set barrier width a
    a = 0.16

    # set ratio of E/U0
    ratio = float(input('please input ratio of E/U0: '))
    # example:
    # ratio = 0.6
    # ratio = 1
    # ratio = 1.4
    # to avoid ratio being smaller than 0.01 or equal to 1
    ratio = 0.01 if ratio < 0.01 else ratio if ratio != 1 else ratio + 1e-10

    # set barrier constant k0
    # k0 = cm.sqrt(2 * m * U0 / pow(h_, 2))
    # it will affect the wavelength of probability wave
    k0 = 4

    # define wave Energy E
    # E = ratio * U0

    # set scale value.()
    # it will contral the wave length on display
    # while scale = 0.5e-8, there are no auto scale
    # if you don't want auto scale, just del denominator: cm.sqrt(ratio)
    # scale = 1
    scale = 1 / cm.sqrt(ratio)

    # define wave vactor k
    # k1 = scale * cm.sqrt(2 * m * E / pow(h_, 2))
    # k2 = scale * cm.sqrt(2 * m * (E - U0) / pow(h_, 2))
    k1 = scale * k0 * cm.sqrt(ratio)        # wave vector of part 1 and 3
    k2 = scale * k0 * cm.sqrt(ratio - 1)    # wave vector of part 2

    # define intensity ratio of wave
    # A and A_ belong to wave of part 1
    # B and B_ belong to wave of part 2
    # C and C_ belong to wave of part 3
    # De is just a common denominator value
    # we define A = 1 and others will be directly proportional to A
    A = 1.2
    De = pow(k1 - k2, 2) * np.exp(1j * k2) - pow(k1 + k2, 2) * np.exp(-1j * k2)
    A_ = 2j * (pow(k1, 2) - pow(k2, 2)) * np.sin(k2) * A / De
    C = -4 * k1 * k2 * np.exp(-1j * k1) * A / De
    B = (A * k1 + A * k2 - A_ * k1 + A_ * k2) / (2 * k2)
    B_ = (A * k2 - A * k1 + A_ * k1 + A_ * k2)/ (2 * k2)

    # define three part
    x1 = np.linspace(-1, 0, 10e3)       # x limit of part 1
    x2 = np.linspace(0, a, 10e3)        # x limit of part 2
    x3 = np.linspace(a, a + 1, 10e3)    # x limit of part 3

    # define wave function
    y1_r = A * np.exp(1j * k1 * x1/a)     # right wave function of part 1
    y1_l = A_ * np.exp(-1j * k1 * x1/a)   # left wave function of part 1
    y2_r = B * np.exp(1j * k2 * x2/a)     # right wave function of part 2
    y2_l = B_ * np.exp(-1j * k2 * x2/a)   # left wave function of part 2
    y3_r = C * np.exp(1j * k1 * x3/a)     # right wave function of part 3

    y1 = y1_r + y1_l                    # wave function of part 1
    y2 = y2_r + y2_l                    # wave function of part 2
    y3 = y3_r                           # wave function of part 3

    w1 = abs(y1)**2
    w2 = abs(y2)**2
    w3 = abs(y3)**2

    # debug out
    # print('k1', k1, '\nk2', k2, '\nA', A, '\nA_', A_, '\nB', B, '\nB_', B_, '\nC', C, '\nDe', De)

    #=======================================================================
    # part 2: visualization
    #=======================================================================
    # set x, y half axis limit
    x_limit = 1
    y_limit = 4

    # create a new figure
    plt.figure(figsize=(10,45/8))

    # set axis scope
    plt.axis([-x_limit, a + x_limit, -y_limit, y_limit])

    # hide the axis
    plt.axis('off')

    # set hold on
    plt.hold(True)

    # set alpha of lines
    alpha = 1
    color_com = (0,0.5,0, alpha)
    color_inc = (0,0,1,alpha)
    color_ref = (1,0,0,alpha)
    color_pro = (0,0,0.5,0.6)
    color_fil = (0,0,0.5,0.3)
    # draw wave in part 1 and get three plot handle for data updating later
    h10, = plt.plot(x1, np.real(y1), color=color_com, linestyle='-', label='composite wave', linewidth=2)
    h11, = plt.plot(x1, np.real(y1_r), color=color_inc, linestyle='--', label='incident wave', linewidth=2)
    h12, = plt.plot(x1, np.real(y1_l), color=color_ref, linestyle='--', label='reflected wave', linewidth=2)
    # draw imag wave of part 1
    plt.plot(x1, np.imag(y1), color=color_com, linestyle=':', label='imag part', linewidth=2)
    # draw probability density line of part 1
    plt.plot(x1, w1 - y_limit + 1, color=color_pro, label='probability density')
    # fill probability line of part 1
    plt.fill_between(x1, np.zeros_like(x1)-y_limit+1, w1-y_limit+1, color=color_fil)
    # draw legend
    plt.legend(fontsize=14, frameon=True, fancybox=True, framealpha=0.3)

    # draw wave in part 2 and get three plot handle for data updating later
    h20, = plt.plot(x2, np.real(y2), color=color_com, linestyle='-', linewidth=2)
    h21, = plt.plot(x2, np.real(y2_r), color=color_inc, linestyle='--', linewidth=2)
    h22, = plt.plot(x2, np.real(y2_l), color=color_ref, linestyle='--', linewidth=2)
    # draw imag wave of part 1
    plt.plot(x2, np.imag(y2), color=color_com, linestyle=':', linewidth=2)
    # draw probability density line of part 2
    plt.plot(x2, w2 - y_limit + 1, color=color_pro)
    # fill probability line of part 2
    plt.fill_between(x2, np.zeros_like(x2)-y_limit+1, w2-y_limit+1, color=color_fil)
    
    # draw wave in part 3
    h30, = plt.plot(x3, np.real(y3), color=color_com, linestyle='-', linewidth=2)
    # draw imag wave of part 1
    plt.plot(x3, np.imag(y3), color=color_com, linestyle=':', linewidth=2)
    # draw probability density line of part 3
    plt.plot(x3, w3 - y_limit + 1, color=color_pro)
    # fill probability line of part 3
    plt.fill_between(x3, np.zeros_like(x3)-y_limit+1, w3-y_limit+1, color=color_fil)

    # draw barrier line
    plt.plot([-1,0,0,a,a,a+1], [-3,-3,3,3,-3,-3], color=(0,0,0,alpha), linestyle='-', linewidth=2)

    # draw reference center line
    plt.plot([-1, a + 1], [0, 0], color=(0.5,0.5,0.5,alpha), linestyle='-.')

    # set hold off
    plt.hold(False)

    # draw text information
    ## define font dict creater function
    def font(family='serif', color='black', weight='normal', size='16'):
        return {'family': family, 'color': color, 'weight': weight, 'size': size}
    # draw title
    plt.title('Barrier Penetration And Tunneling', fontdict=font(size=20))
    # draw barrier height value U0
    plt.text(a, 3, '$U_0$', fontdict=font(size=20))
    # draw value of k0
    plt.text(-.9, 3, '$\itK_0=%d$' % k0, fontdict=font(size=20))
    # draw value of E/U0
    plt.text(-.6, 3, '$\itE/\itU_0=\it%.2f$' % ratio, fontdict=font(size=20))
    # draw scale value text
    plt.text(-.7, -3.3, '$\itscale=%.2f$' % np.real(scale), fontdict=font())
    # draw barrier left limit
    plt.text(-.02, -3.3, '$0$', fontdict=font())
    # draw barrier right limit
    plt.text(a-.02, -3.3, '$a$', fontdict=font())
    # draw x axis mark 'x'
    plt.text(a+.95, -2.95, '$x$', fontdict=font())
    # draw water mark of author
    plt.text(a+.7, -3.4, '$author: ph$', fontdict=font(color='gray'))
    # show plot
    # plt.show()
    if len(sys.argv) > 1:
        if  sys.argv[1] == '-d':
            # set gif save root dir
            gif_root = './gif'
            # check gif root dir
            if not os.path.isdir(gif_root):
                os.makedirs(gif_root)
            # set frame number N
            FN = 40
            # pre storage allocation
            images = []
            for i in range(FN):
                # add time factor
                Et = np.exp(-2j * np.pi * i / FN)

                # update the plot data
                h10.set_ydata(np.real(y1 * Et))
                h11.set_ydata(np.real(y1_r * Et))
                h12.set_ydata(np.real(y1_l * Et))
                h20.set_ydata(np.real(y2 * Et))
                h21.set_ydata(np.real(y2_r * Et))
                h22.set_ydata(np.real(y2_l * Et))
                h30.set_ydata(np.real(y3 * Et))

                # create bytes buffer
                buf = BytesIO()

                # save plot date to buf
                plt.savefig(buf, format='png')

                # read buf as image date and append to images 
                images.append(im.open(buf))
            # set gif file save path
            gif_path = os.path.join(gif_root, 'slgc_%.2f.gif' % ratio)
            # create GIF dynamic plot from images
            im2gif.writeGif(filename=gif_path, images=images, duration=2 / FN)

            # print status message
            print('gif file created at path: %s.' % os.path.abspath(gif_path))
        elif sys.argv[1]=='-s':
            png_root = './png'
            if not os.path.isdir(png_root):
                os.makedirs(png_root)
            png_path = os.path.join(png_root, 'slgc_%.2f.png' % ratio)
            plt.savefig(png_path, format='png')
            print('png file created at path: %s.' % os.path.abspath(png_path))
    else:
        plt.show()
Example #60
0
def drawDigit(position, image, title):
    plt.subplot(*position)
    plt.imshow(image.reshape(-1, 28), cmap='gray_r')
    plt.axis('off')
    plt.title(title)