コード例 #1
0
ファイル: Img.py プロジェクト: apvijay/image_proc
def stem_hist(img, plotTitle):
  import matplotlib.pyplot as plt
  from matplotlib import cm
  imgarray = img.calc_hist()
  plt.figure()
  plt.stem(arange(img.grayLevel), imgarray)
  plt.title(plotTitle)
コード例 #2
0
ファイル: bikedata.py プロジェクト: YoDaMa/BikeAnalysis
def plotstft(sxx, Fs=100):
    winlen = int(len(sxx[0]))

    # with plt.():
    fig1 = plt.figure()
    ax = fig1.add_subplot(1,1,1)
    ctr = int(winlen / 2)
    faxis = np.multiply(Fs / 2, np.linspace(0, 1, ctr))*60
    ratio = []
    for dft in sxx:
        mag = abs(dft[0:ctr])
        max_idx, max_val = max(enumerate(mag), key = lambda p: p[1])
        ptotal = np.square(np.linalg.norm(mag,2))
        pmax = np.square(np.absolute(max_val))
        # print('max power: {}'.format(max_val))
        frac = pmax/ptotal
        # print(frac)
        ratio.append(frac)

        ax.plot(faxis, mag, linewidth=3.0)
        ax.set_xlabel('Frequency (RPM)')
        ax.set_ylabel('|H(f)|')
        ax.set_title('User 4 STFT Spectrum')
        font = {'family' : 'sans-serif ',
                'weight' : 'bold',
                'size'   : 30}
        rc('font', **font)

    fig1.savefig('STFTPlot.png')
    fig2 = plt.figure()
    plt.stem(np.linspace(1,len(ratio),num=len(ratio)),ratio, linewidth=3.0)
    plt.xlabel('Window (10s)', fontsize = 60)
    plt.ylabel('Symmetry in Pedaling', fontsize = 60)
    fig2.savefig('RatioPlot.png')
コード例 #3
0
def show_spec_in_graph(graph, vertex, spec, pos, weight, file_name):
    dist = 1.0 - squareform(pdist(spec.T, 'cosine'))

    plt.figure()
    plt.stem(dist[vertex, :], markerfmt=' ')

    rim = graph.new_vertex_property('vector<double>')
    rim.set_2d_array(np.array([0, 0, 0, 1]))
    rim[graph.vertex(vertex)] = [0.8941176471, 0.1019607843, 0.1098039216, 1]
    rim_width = graph.new_vertex_property('float', vals=0.5)
    rim_width.a[vertex] = 2
    shape = graph.new_vertex_property('int', vals=0)
    shape[graph.vertex(vertex)] = 2
    size = graph.new_vertex_property('double', vals=10)
    size.a[vertex] = 15
    correlation = graph.new_vertex_property('double', vals=2)
    correlation.a = dist[vertex, :]
    vorder = graph.new_vertex_property('int', vals=0)
    vorder.a[vertex] = 1

    palette = sns.cubehelix_palette(256)
    cmap = colors.ListedColormap(palette)
    gt_draw.graph_draw(graph, pos=pos, vertex_color=rim, vorder=vorder,
                       vertex_pen_width=rim_width,
                       vertex_shape=shape, vertex_fill_color=correlation,
                       vcmap=cmap, vertex_size=size, edge_color=[0, 0, 0, 0.7],
                       edge_pen_width=weight, output=file_name + '.png',
                       output_size=(1200, 1200))

    plt.figure()
    utils.plot_colorbar(cmap, np.arange(0, 1.01, 0.2), file_name)
コード例 #4
0
ファイル: utils.py プロジェクト: Lx37/pambox
def impz(b, a=1):
    """Plot step and impulse response of an FIR filter.

    b : float
        Forward terms of the FIR filter.
    a : float
        Feedback terms of the FIR filter. (Default value = 1)

    From http://mpastell.com/2010/01/18/fir-with-scipy/

    Returns
    -------
    None

    """
    l = len(b)
    impulse = np.repeat(0., l)
    impulse[0] = 1.
    x = np.arange(0, l)
    response = sp.lfilter(b, a, impulse)
    plt.subplot(211)
    plt.stem(x, response)
    plt.ylabel('Amplitude')
    plt.xlabel(r'n (samples)')
    plt.title(r'Impulse response')
    plt.subplot(212)
    step = sp.cumsum(response)
    plt.stem(x, step)
    plt.ylabel('Amplitude')
    plt.xlabel(r'n (samples)')
    plt.title(r'Step response')
    plt.subplots_adjust(hspace=0.5)
コード例 #5
0
def stepplot(x, y, labels, plot_titles):

        """Generates Correlation Graph. 
        With the x,y coordinates, labels, and plot titles
        established, the step-plots can be generated. Output 
        is PDF file format"""

        plt.figure()      #makes new image for each plot  
        
        #plot x & y stemplot. format plot points
        plt.stem(x, y, linefmt='k--', markerfmt='ro', basefmt='k-')               
        
        #set x-axis labels and set them vertical. size 10 font.
        plt.xticks(x, labels, rotation='vertical', fontsize = 10)
              
        #set titles for graph and axes
        plt.title(plot_titles[0])
        plt.xlabel("Biomarkers")
        plt.ylabel("Correlation Values")
        
        # slightly move axis away from plot. prevents clipping the labels 
        plt.margins(0.2)
        
        # Tweak spacing to prevent clipping of tick-labels
        plt.subplots_adjust(bottom=0.15)
        
        plt.tight_layout()   #prevents labels from being clipped
                  

        with PdfPages(plot_titles[0]+'.pdf') as pdf: #creates new file for each figure
            pdf.savefig()
コード例 #6
0
def stemplotf(v, p):
	fig2=plt.figure()
	fig2.suptitle('Problem 2b: Data Set %s' % p)
	plt.stem(v)
	plt.xlabel('k')
	plt.ylabel('1/E[alpha_k]')
	fig2.savefig('Problem2b_data%s' % p)
コード例 #7
0
ファイル: rawDataProcess.py プロジェクト: asobolev/GJEMS
    def plotVibEpoch(self, epochTimes, signal=None, points=False):

        # indStart = int(epochTimes[0] * qu.s * self.entireVibrationSignal.sampling_rate + self.recordingStartIndex)
        # indEnd = int(epochTimes[1] * qu.s * self.entireVibrationSignal.sampling_rate + self.recordingStartIndex)

        # epochTVec = self.entireVibrationSignal.t_start + np.arange(indStart, indEnd) * self.entireVibrationSignal.sampling_period

        # plt.plot(epochTVec, self.entireVibrationSignal[indStart:indEnd], 'g' + extra)

        indStart = int(epochTimes[0] * qu.s * self.vibrationSignalDown.sampling_rate)
        indEnd = int(epochTimes[1] * qu.s * self.vibrationSignalDown.sampling_rate)

        epochTVec = self.vibrationSignalDown.t_start + np.arange(indStart, indEnd) * self.vibrationSignalDown.sampling_period

        stimEnds = (np.array(self.stimEndInds)) / self.downSamplingFactor
        stimStarts = (np.array(self.stimStartInds)) / self.downSamplingFactor

        stimEndsPresent = [x * self.vibrationSignalDown.sampling_period + self.vibrationSignalDown.t_start
                           for x in stimEnds if indStart <= x <= indEnd]
        stimStartsPresent = [x * self.vibrationSignalDown.sampling_period + self.vibrationSignalDown.t_start
                             for x in stimStarts if indStart <= x <= indEnd]

        extra = ''
        if points:
            extra = '*-'

        plt.plot(epochTVec, self.vibrationSignalDown[indStart:indEnd], 'g' + extra)
        plt.stem(stimStartsPresent, np.ones(np.shape(stimStartsPresent)), 'k')
        plt.stem(stimEndsPresent, np.ones(np.shape(stimEndsPresent)), 'm')
        if not signal is None:
            plt.plot(epochTVec, signal[indStart:indEnd], 'r' + extra)

        plt.plot(epochTVec, 2 * self.vibrationSignalDownStdDev * np.ones(epochTVec.shape), 'y')
コード例 #8
0
ファイル: AE_MNIST.py プロジェクト: MoDeep/MyoGAN
def show_ae(autoencoder):
    encoder = autoencoder.Encoder()
    decoder = autoencoder.Decoder()

    encoded_imgs = encoder.predict(X_test)
    decoded_imgs = decoder.predict(encoded_imgs)

    n = 10
    plt.figure(figsize=(20, 6))
    for i in range(n):

        ax = plt.subplot(3, n, i + 1)
        plt.imshow(X_test[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        ax = plt.subplot(3, n, i + 1 + n)
        plt.stem(encoded_imgs[i].reshape(-1))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        ax = plt.subplot(3, n, i + 1 + n + n)
        plt.imshow(decoded_imgs[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

    plt.show()
コード例 #9
0
ファイル: Utils.py プロジェクト: simaosr/pyWT
def plot_station_res(sta_res,ires,perr=False,scale=1):
    
    titles = ('Tangent Force','Normal Force','Tangent Moment','Normal moment','Inflow Angle','Angle of Attack','Reynolds number',
              'Local vel.','Axial induction','Radial Induction','Effective Velocity','Lift Coeff','Drag Coeff','Loss Factor',
              'CT','CQ','CP','dP','radius','azim','height','ind_vel_a','ind_vel_r')

    axis = get_station_res(sta_res,18)
    res = get_station_res(sta_res,ires)

    axis = np.array(axis) * scale

    #plt.figure()
    if perr is True:
        plt.subplot(211)
        plt.plot(axis,res,'-o')
        plt.subplot(212)
        err = get_station_res(sta_res,-1)
        plt.stem(axis, err, 'r-')
    else:
        plt.figure()
        plt.plot(axis,res,'-o')
    plt.grid()
    plt.title(titles[ires])
    plt.show()

    return 0
コード例 #10
0
ファイル: sigproc.py プロジェクト: bsinglet/davitpy
    def plotImpulseResponse(self, xmin=None, xmax=None, ymin_imp=None, ymax_imp=None, ymin_step=None, ymax_step=None):
        """Plot the frequency and phase response of the filter object.

      :param xmin: Minimum value for x-axis.
      :param xmax: Maximum value for x-axis.
      :param ymin_imp: Minimum value for y-axis for the impulse response plot.
      :param ymax_imp: Maximum value for y-axis for the impulse response plot.
      :param ymin_step: Minimum value for y-axis for the step response plot.
      :param ymax_step: Maximum value for y-axis for the step response plot.
      """
        #  def plotImpulseResponse(b,a=1):
        l = len(self.ir)
        impulse = np.repeat(0.0, l)
        impulse[0] = 1.0
        x = np.arange(0, l)
        response = sp.signal.lfilter(self.ir, 1, impulse)
        mp.subplot(211)
        mp.stem(x, response)
        mp.ylabel("Amplitude")
        mp.xlabel(r"n (samples)")
        mp.title(r"Impulse response")
        mp.subplot(212)

        step = np.cumsum(response)
        mp.stem(x, step)
        mp.ylabel("Amplitude")
        mp.xlabel(r"n (samples)")
        mp.title(r"Step response")
        mp.subplots_adjust(hspace=0.5)
        mp.show()
コード例 #11
0
ファイル: application.py プロジェクト: Lampadina/seasonal
def _periodogram_plot(title, column, data, trend, peaks):
    """display periodogram results using matplotlib"""

    periods, power = periodogram(data)
    plt.figure(1)
    plt.subplot(311)
    plt.title(title)
    plt.plot(data, label=column)
    if trend is not None:
        plt.plot(trend, linewidth=3, label="broad trend")
        plt.legend()
        plt.subplot(312)
        plt.title("detrended")
        plt.plot(data - trend)
    else:
        plt.legend()
        plt.subplot(312)
        plt.title("(no detrending specified)")
    plt.subplot(313)
    plt.title("periodogram")
    plt.stem(periods, power)
    for peak in peaks:
        period, score, pmin, pmax = peak
        plt.axvline(period, linestyle='dashed', linewidth=2)
        plt.axvspan(pmin, pmax, alpha=0.2, color='b')
        plt.annotate("{}".format(period), (period, score * 0.8))
        plt.annotate("{}...{}".format(pmin, pmax), (pmin, score * 0.5))
    plt.tight_layout()
    plt.show()
コード例 #12
0
ファイル: osomp.py プロジェクト: aweinstein/osomp
def run_OMP(plot=False, **options):
    """Recover one signal using OMP."""
    n = options.pop('n', 128)
    k = options.pop('k', 5)
    m = options.pop('m', 20)
    dist = options.pop('dist', 'uniform')
    seed = options.pop('seed', None)
    return_locals = options.pop('return_locals', True)

    print ('Recovering signal wiht n=%(n)i, k=%(k)i and m=%(m)i using OMP' %
           locals())

    if seed:
        np.random.seed(seed)
    x = get_sparse_x(n, k, dist=dist)
    if seed:
        np.random.seed(seed + 198)
    A = random_dict(m, n)
    y = np.dot(A, x)

    x_hat, residues, scores, Delta = omp(A, y, save_data=True)

    if plot:
        plt.figure()
        plt.stem(range(n), x, 'r-', 'ro', 'k:')
        plt.stem(range(n), x_hat, 'b:', 'bx', 'k:')
        plt.show()

    print 'error', norm(x - x_hat.reshape(n, 1))

    if return_locals:
        return locals()
コード例 #13
0
ファイル: statics.py プロジェクト: GeoZac/mechpy
def moment_ss_shear_bending(L,Pin,ain):
    '''
    Shear Bending plot of moment loads of a simply supported beam
    L = 4 # total length of beam
    Pin = [5]  # point moment load
    ain = [2]  # location of point load

    # or more multiple point moments
    L = 10
    Pin = [3,-15]
    ain = [2,6]
    '''

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.arange(0,L,L*0.02)
    V = np.zeros(len(x))
    M = np.zeros(len(x))
    
    for a, P in zip(ain, Pin):
        V += -P/L
        M[x<=a] += -P*x[x<=a]/L
        M[x>a] += P*(1-x[x>a]/L)    
    
    plt.figure()
    plt.title('Point Moment Loads')
    plt.subplot(2,1,1)    
    plt.stem(x,V)
    plt.ylabel('V,shear')
    plt.subplot(2,1,2)
    plt.stem(x,M)
    plt.ylabel('M,moment')    
コード例 #14
0
ファイル: filter.py プロジェクト: KasparSnashall/FIRfilter
	def graph(b,a=1):
			#make a graph
			w,h = signal.freqz(b,a)
			h_dB = 20 * np.log10 (abs(h))
			plt.figure()
			#plt.subplot(311)
			plt.plot(w/max(w),h_dB)
			plt.ylim(-150, 5)
			plt.ylabel('Magnitude (db)')
			plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
			plt.title(r'Frequency response')
			plt.show()
			plt.figure()
			l = len(b)
			impulse = np.repeat(0.,l); impulse[0] =1.
			x = arange(0,l)
			response = signal.lfilter(b,a,impulse)
			#plt.subplot(312)
			plt.stem(x, response)
			plt.ylabel('Amplitude')
			plt.xlabel(r'n (samples)')
			plt.title(r'Impulse response')
			plt.show()
			#plt.figure()
			#plt.subplot(313)
			#step = np.cumsum(response)
			#plt.stem(x, step)
			#plt.ylabel('Amplitude')
			#plt.xlabel(r'n (samples)')
			#plt.title(r'Step response')
			#plt.subplots_adjust(hspace=0.5)
			#plt.show()
			return 1
コード例 #15
0
ファイル: estimation.py プロジェクト: mattjj/py4sid
def viz_rank(Oi,k=None):
    if k is None:
        U, s, VT = np.linalg.svd(Oi)
    else:
        U, s, VT = thin_svd_randomized(Oi,k)

    plt.figure()
    plt.stem(np.arange(s.shape[0]),s)
コード例 #16
0
 def simple_plot(self, arr, filename, type='normal'):
     plt.figure()
     if type == 'normal':
         plt.plot(arr)
     elif type == 'stem':
         plt.stem(arr)
     plt.savefig('../images/{}.jpg'.format(filename))
     plt.close()
コード例 #17
0
ファイル: test_dsp.py プロジェクト: n8ohu/whitebox
def figure_binary_offset(title, axes, f_parent, signature, n, i):
    f = f_parent.add_subplot(*axes, title=title)
    plt.stem(n, i, linefmt='b-', markerfmt='b.', basefmt='b|')
    plt.axis([n[0], n[-1], signature.min, signature.max],
        figure=f)
    plt.xlabel('Time')
    plt.ylabel('Magnitude')
    return f
コード例 #18
0
def plotHistogram(fg):
   nSubBands = fg.getNumberOfSubBands()
   histogram = []
   for i in range(0,nSubBands):
      histogram.append(fg.getHistogram(i))
   plt.stem(range(0,nSubBands), histogram)
   plt.ylabel('Number of FA in a given sub-band')
   plt.xlabel('sub-band')
   plt.draw()
コード例 #19
0
ファイル: plots.py プロジェクト: rogalski/dsp-project
 def _make_channel_plots(self):
     plt.figure()
     channel = self._system.get_block(self._system.MULTI_PATH_CHANNEL)
     plt.stem(channel._impulse_response, basefmt='')
     plt.title(self._build_title("Odpowiedź impulsowa kanału"))
     plt.grid('on')
     length = len(channel._impulse_response)
     plt.xlim((-length / 20, length))
     self._save_plt("channel_impulse")
コード例 #20
0
ファイル: train.py プロジェクト: orchidas/Speaker-Recognition
def training(nfiltbank, orderLPC):
    nSpeaker = 8
    nCentroid = 16
    codebooks_mfcc = np.empty((nSpeaker,nfiltbank,nCentroid))
    codebooks_lpc = np.empty((nSpeaker, orderLPC, nCentroid))
    directory = os.getcwd() + '/train';
    fname = str()

    for i in range(nSpeaker):
        fname = '/s' + str(i+1) + '.wav'
        print('Now speaker ', str(i+1), 'features are being trained' )
        (fs,s) = read(directory + fname)
        mel_coeff = mfcc(s, fs, nfiltbank)
        lpc_coeff = lpc(s, fs, orderLPC)
        codebooks_mfcc[i,:,:] = lbg(mel_coeff, nCentroid)
        codebooks_lpc[i,:,:] = lbg(lpc_coeff, nCentroid)
        
        plt.figure(i)
        plt.title('Codebook for speaker ' + str(i+1) + ' with ' + str(nCentroid) +  ' centroids')
        for j in range(nCentroid):
            plt.subplot(211)
            plt.stem(codebooks_mfcc[i,:,j])
            plt.ylabel('MFCC')
            plt.subplot(212)
            markerline, stemlines, baseline = plt.stem(codebooks_lpc[i,:,j])
            plt.setp(markerline,'markerfacecolor','r')
            plt.setp(baseline,'color', 'k')
            plt.ylabel('LPC')
            plt.axis(ymin = -1, ymax = 1)
            plt.xlabel('Number of features')
    
    plt.show()
    print('Training complete')
    
    #plotting 5th and 6th dimension MFCC features on a 2D plane
    #comment lines 54 to 71 if you don't want to see codebook
    codebooks = np.empty((2, nfiltbank, nCentroid))
    mel_coeff = np.empty((2, nfiltbank, 68))
   
    for i in range(2):
        fname = '/s' + str(i+2) + '.wav'
        (fs,s) = read(directory + fname)
        mel_coeff[i,:,:] = mfcc(s, fs, nfiltbank)[:,0:68]
        codebooks[i,:,:] = lbg(mel_coeff[i,:,:], nCentroid)
        
    
    plt.figure(nSpeaker + 1)
    s1 = plt.scatter(mel_coeff[0,6,:], mel_coeff[0,4,:],s = 100,  color = 'r', marker = 'o')
    c1 = plt.scatter(codebooks[0,6,:], codebooks[0,4,:], s = 100, color = 'r', marker = '+')
    s2 = plt.scatter(mel_coeff[1,6,:], mel_coeff[1,4,:],s = 100,  color = 'b', marker = 'o')
    c2 = plt.scatter(codebooks[1,6,:], codebooks[1,4,:], s = 100, color = 'b', marker = '+')
    plt.grid()
    plt.legend((s1, s2, c1, c2), ('Sp1','Sp2','Sp1 centroids', 'Sp2 centroids'), scatterpoints = 1, loc = 'upper left')    
    plt.show()
   
    
    return (codebooks_mfcc, codebooks_lpc)
コード例 #21
0
ファイル: SARobot.py プロジェクト: understar/Stock-Science
def GenerateFigure(_open, _close, _items):
    # GenerateFigure(Open, Close, items)
    #==================Ignore Figure==========#
    Percent = RisingPercent(items)
    Rise = map(sub, Close , Open)
    rise_index = [i for i,per in enumerate(Rise) if per>=0]
    fall_index = [i for i,per in enumerate(Rise) if per<0]

    step = 5
    lookback = 55
    id_start = idx[-1]-lookback if idx[-1]>lookback else idx[0]
    plt.subplot(3, 1, 1)            
    
    # Draw K-fig 
    rise_index = [i for i,per in enumerate(Rise) if per>=0]
    fall_index = [i for i,per in enumerate(Rise) if per<0]
    plt.vlines(rise_index, GetPart(rise_index,Low), GetPart(rise_index,High), edgecolor='red', linewidth=1, label='_nolegend_') 
    plt.vlines(rise_index, GetPart(rise_index,Open), GetPart(rise_index,Close), edgecolor='red', linewidth=4, label='_nolegend_')
    plt.vlines(fall_index, GetPart(fall_index,Low), GetPart(fall_index,High), edgecolor='green', linewidth=1, label='_nolegend_') 
    plt.vlines(fall_index, GetPart(fall_index,Open), GetPart(fall_index,Close), edgecolor='green', linewidth=4, label='_nolegend_') 
    plt.title(stockname, fontproperties = FigureConf.Font)  
    
    plt.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2)      
    ax = plt.gca()      
    ax.autoscale(enable=True, axis='both', tight=True)
    ax.set_xticklabels( emp[0::step], rotation=75, fontsize='small')
    ax.set_xlim([id_start,idx[-1]])             
    ax.set_ylim(min(Close[id_start:]), max(Close[id_start:]))
    
    plt.subplot(3, 1, 2)
    plt.stem(idx, MACluster['VAR'], linefmt=VARclr, markerfmt=" ", basefmt=" ")
    plt.plot(idx,DDD, DDDclr, AMA, AMAclr ,DMA, DMAclr)
    plt.plot(zero_ndx[-3:], zero_pts[-3:], 'ro')            
    plt.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2)              
    ax = plt.gca()
    ax.autoscale(enable=True, axis='both', tight=True)          
    ax.set_xticklabels( emp[0::step], rotation=75, fontsize='small')
    ax.set_xlim([id_start,idx[-1]])             
    ax.set_ylim(min(DMA[id_start:] + AMA[id_start:] + DDD[id_start:]),\
    max(DMA[id_start:] + AMA[id_start:]+ DDD[id_start:]))
    
    plt.subplot(3, 1, 3)
    plt.bar(rise_index, GetPart(rise_index,Vol),bottom=-20,color='r',edgecolor='r',align="center")
    plt.bar(fall_index, GetPart(fall_index,Vol),bottom=-20,color='g',edgecolor='g',align="center")              
    plt.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2)      
    plt.xticks(np.arange(len(idx))[0::step], emp[0::step])
    ax = plt.gca()  
    ax.autoscale(enable=True, axis='both', tight=True)
    ax.set_xticklabels(datex[0::step], rotation=75, fontsize='small')
    ax.set_xlim([id_start,idx[-1]])             
    # # plt.show()
    try:
        plt.savefig('%s/%s/%s%s.png'%(baseFolder,RuleFolder,stockid+stockname,datex[zero_ndx[-1]]), dpi=100)
    except:
        plt.savefig('%s/%s/%s%s.png'%(baseFolder,RuleFolder,stockid+stockname[1:],datex[zero_ndx[-1]]), dpi=100)
    plt.clf()
コード例 #22
0
def main(streaming):
    modes, evals = streaming_dmd() if streaming else standard_dmd()
    fdmd = np.abs(np.angle(evals)) / (2 * np.pi * dt)
    n_modes = len(fdmd)
    ydmd = np.zeros(n_modes)
    for i in range(n_modes):
        ydmd[i] = np.linalg.norm(modes[:, i] * np.abs(evals[i]))
    ydmd /= max(ydmd)
    plt.stem(fdmd, ydmd)
    plt.show()
コード例 #23
0
ファイル: plot_json_events.py プロジェクト: robevans/minf
def plot_file(json_file):
    try:
        with open(json_file, 'r') as events_file:
            data = json.load(events_file)
            events = {int(index): int(type_) for index, type_ in data['event_annotations'].items()}
            indexes, types = zip(*events.items())
            plt.stem(indexes, types)
            plt.show()
    except Exception, e:
        print e
コード例 #24
0
ファイル: PS5_tests.py プロジェクト: keithw/onepingonly
def plot_USR(response,name):
    p.figure()
    p.stem(range(len(response)),response)
    smin = min(response)
    smax = max(response)
    ds = smax - smin
    p.axis([-.5,len(response)+.5,smin - 0.1*ds,smax + 0.1*ds])
    p.title('Response of channel %s' % name)
    p.xlabel('Sample number')
    p.ylabel('Voltage')
コード例 #25
0
ファイル: proc.py プロジェクト: anirudt/pipydenoiser
def graphify_stem(x, y, xlabel, ylabel, title, name, axis=None):
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    plt.stem(x, y)
    plt.grid = True
    plt.savefig(name+'stem.png')
    plt.show()
    if axis != None:
        plt.axis(axis)
コード例 #26
0
def plot_srcfun(mdl):
    sel = mdl.runner.wave[:,0].argsort()
    [pl.axvline(x=X,ymin = .85,ymax=.95,color='r') for X in tar.atom_data.lines.wavelength]
    pl.stem(1e8*mdl.runner.wave[sel],mdl.runner.att_S_ul)
    pl.title("Source function")
    pl.gca().set_yscale('log')
    pl.gca().set_xscale('log')
    pl.ylim(0,1e-3)    
    pl.xlabel("A")
    pl.show()
コード例 #27
0
ファイル: ex1.py プロジェクト: qiiyang/CS279CA
def plot_f(f, style="dots", color="b", ylabel="y", title="", xlim=50.):
    plt.xlabel("x")
    plt.ylabel(ylabel)
    plt.title(title)
    plt.xlim(-xlim, xlim)
    xs = np.arange(1000) - 500.
    if style == "dots":
        plt.plot(xs, f, color+".")
    elif style == "stem":
        plt.stem(xs, f, markerfmt=color+"o", linefmt=color+"--", basefmt="k-")
    plt.show()
コード例 #28
0
ファイル: estimation.py プロジェクト: mattjj/py4sid
def viz_rank2(y,i,k=None):
    Y = AR_striding(y,i-1).T
    l = Y.shape[0]//2

    if k is None:
        _, s, _ = np.linalg.svd(np.cov(Y)[:l,l:])
    else:
        _, s, _ = thin_svd_randomized(np.cov(Y)[:l,l:],k)

    plt.figure()
    plt.stem(np.arange(s.shape[0]),s)
コード例 #29
0
ファイル: ex1.py プロジェクト: qiiyang/CS279CA
def plot_overlap():
    f = two_spikes()
    g = cone()
    plt.xlabel("x")
    plt.ylabel("y")
    plt.xlim(-50, 50)
    xs = np.arange(1000) - 500.
    plt.plot(xs-20., g, "b.")
    plt.plot(xs+20., 2*g, "b.")
    plt.stem(xs, f, markerfmt="ro", linefmt="r--", basefmt="k-")
    plt.show()
コード例 #30
0
ファイル: dirHdpGenerative.py プロジェクト: jstraub/bnp
    def plotTopics(s, minSupport=None):
        D = s.state["D_tr"]
        ks = np.zeros(D)
        for d in range(0, D):

            # necessary since topics may be selected several times!
            c_u = np.unique(s.state["c"][d, :])
            sigPi_u = np.zeros(c_u.size)
            for i in range(0, c_u.size):
                # print('{}'.format(c_u[i] == s.c[d]))
                # print('{}'.format(s.sigPi[d]))
                sigPi_u[i] = np.sum(s.state["sigPi"][d, c_u[i] == s.state["c"][d, :]])
            k_max = c_u[sigPi_u == np.max(sigPi_u)]
            #      print('c={};'.format(s.c[d]))
            #      print('sigPi={};'.format(s.sigPi[d]))
            print("sigPi_u = {};\tc_u={};\tk_max={}".format(sigPi_u, c_u, k_max))

            #      t_max=np.nonzero(s.sigPi[d]==np.max(s.sigPi[d]))[0][0]
            #      print('d={}; D={}'.format(d,D))
            #      print('t_max={};'.format(np.nonzero(s.sigPi[d]==np.max(s.sigPi[d]))))
            #      print('sigPi={}; sum={}'.format(s.sigPi[d],np.sum(s.sigPi[d])))
            #      print('c[{}]={};'.format(d,s.c[d]))
            #      if t_max < s.c[d].size:
            #        k_max = s.c[d][t_max]
            #      else:
            #        k_max = np.nan # this means that we arre not selecting one of the estimated models!! (the last element in sigPi is 1-sum(sigPi(0:end-1)) and represents the "other" models
            ks[d] = k_max[0]
        ks_unique = np.unique(ks)
        ks_unique = ks_unique[~np.isnan(ks_unique)]
        if minSupport is not None:
            Np = ks_unique.size  # numer of subplots
            # print('D{0} Np{1}'.format(D,Np))
            sup = np.zeros(ks_unique.size)
            for d in range(0, D):
                sup[np.nonzero(ks_unique == ks[d])[0]] += 1
            # print('sup={0} sum(sup)={1}'.format(sup,np.sum(sup)))
            delete = np.zeros(ks_unique.size, dtype=np.bool)
            for i in range(0, Np):
                if sup[i] < minSupport:
                    delete[i] = True
            ks_unique = ks_unique[~delete]
        Np = ks_unique.size  # numer of subplots
        print("D{0} Np{1}".format(D, Np))
        Nrow = np.ceil(np.sqrt(Np))
        Ncol = np.ceil(np.sqrt(Np))
        fig = plt.figure()
        for i in range(0, Np):
            plt.subplot(Ncol, Nrow, i + 1)
            x = np.linspace(0, s.state["beta"][int(ks_unique[i])].size - 1, s.state["beta"][int(ks_unique[i])].size)
            plt.stem(x, s.state["beta"][int(ks_unique[i])])
            plt.ylim([0.0, 1.0])
            plt.xlabel("topic " + str(ks_unique[i]))
        return fig
コード例 #31
0
archivo = 'small.wav'
muestreo, sonido = waves.read(archivo)
print('frecuencia de muestreo: ', muestreo)
print('dimensiones de matriz: ', np.shape(sonido))
print('datos de sonido: ')
print(sonido)
# Toda la señal
inicia = 2000
termina = 3000

# Extraer el tiempo de muestreo
dt = 1 / muestreo
# Construir el intervalo de tiempo cada dt muestras
t = np.arange(inicia * dt, termina * dt, dt)
# Verificar la cantidad de muestras
muestras = len(t)
# Señal en dos canales, elegir uno
canal = 0
fragmento = sonido[inicia:inicia + muestras, canal]

# Gráfica analógica de sonido
plt.plot(t, fragmento)
plt.xlabel('t segundos')
plt.ylabel('sonido(t)')
plt.show()
# Gráfica discreta de sonido
n = np.arange(inicia, inicia + muestras, 1)
plt.stem(n, fragmento)
plt.xlabel('n')
plt.ylabel('sonido[n]')
plt.show()
コード例 #32
0
import numpy as np
import matplotlib.pyplot as plt

M = 31
n = np.linspace(0, M - 1)
whn = 0.5 - 0.5 * np.cos((2 * np.pi * n) / (M - 1))
plt.stem(n, whn)
plt.show()
コード例 #33
0
# Spacing in the frequency domain
f0 = 1 / T

# Signal creation
sigFreq = 250
w = 2 * pi * sigFreq
sig = np.sin(w * n)

plt.figure()
plt.plot(n, sig)

# Implementaion with calculating f myself
SIGf = np.fft.fftshift(np.fft.fft(sig)) / N
f = np.arange(-fs / 2, fs / 2, f0)
sig2 = np.fft.ifft(np.fft.fftshift(SIGf * N))

# Implementation with fftfreq
# SIGf = np.fft.fft(sig)/N
# f = np.fft.fftfreq(N,t0)
# sig2 = np.fft.ifft(SIGf*N)

# Correct quantization errors that will show up in phase
SIGf[np.abs(SIGf) < .0000000001] = 0

plt.figure()
plt.stem(f, np.abs(SIGf), use_line_collection=True)
plt.figure()
plt.stem(f, np.angle(SIGf), use_line_collection=True)
plt.figure()
plt.plot(n, np.real(sig2))
コード例 #34
0
import scipy.io
from matplotlib import pyplot as plt
from scipy.io import wavfile
import numpy as np
F = 100
Fs = 250
m = np.arange(1, 400)
x = np.random.rand(500)
w = np.arange(-np.pi, np.pi, 0.01 * np.pi)
l = len(x)
y = []
for i in range(0, len(w)):
    s = 0
    for n in range(0, l):
        s = s + x[n] * np.exp(-1 * 1j * w[i] * n)
    y.append(s)
plt.subplot(211)
plt.stem(w, np.abs(y))
plt.subplot(212)
plt.stem(w, np.angle(y))
plt.show()
コード例 #35
0
trials = int(1e5)
X = np.random.geometric(p=0.166, size=trials)
Pr_X = np.zeros((int(trials/2)))
for i in range(int(trials/2)):
    Pr_X[i] = np.count_nonzero(X == (i*2 + 1))
    Pr_X[i] = Pr_X[i]/trials

Pr_A_win = np.sum(Pr_X)
Pr_X_theo = [1/6, 22/216, 625/7776, 15625/279936]
trials = [1, 3, 5, 7]
print('Simulated Pr(On 1st trial die rolls a six by A) = ', Pr_X[0])
print('Mathematical Pr(On 1st trial die rolls a six by A) = ', 1/6)
print('\n')
print('Simulated Pr(On 3rd trial die rolls a six by A) = ', Pr_X[1])
print('Mathematical Pr(On 3rd trial die rolls a six by A) = ', 25/216)
print('\n')
print('Simulated Pr(On 5th trial die rolls a six by A) = ', Pr_X[2])
print('Mathematical Pr(On 5th trial die rolls a six by A) = ', 625/7776)
print('\n')
print('Simulated Pr(On 7th trial die rolls a six by A) = ', Pr_X[3])
print('Mathematical Pr(On 7th trial die rolls a six by A) = ', 15625/279936)
print('\n')
print('Simulated Pr(A = win) = ', Pr_A_win)
print('Mathematical Pr(A = win) = ', 6/11)
plt.stem(trials, Pr_X[0:4], linefmt='C1--', markerfmt='C1o', label='Sim')
plt.stem(trials, Pr_X_theo, linefmt='C2--', markerfmt='C2.', label='Math')
plt.legend()
plt.xlabel('Trial #')
plt.ylabel('Pr(A rolling six)')
plt.title('Math Vs Sim Pr(A winning the game on odd $k^{th}$ trial)')
plt.show()
コード例 #36
0
#plot_heat_map('R_human', R_human[::-1] )
#plot_heat_map('R_machine', R_machine[::-1] )
#plot_heat_map('R_total', R[::-1] )

#cal eigen value
eValue_h, eVector_h = eig(R_human)
eValue_m, eVector_m = eig(R_machine)
eValue_R, eVector_R = eig(R)
print('R_human eValue: ', eValue_h[0:2])
print('R_human percentage of variance: ',
      np.sum(eValue_h[0:2]) / np.sum(eValue_h))
print('R_machine eValue: ', eValue_m[0:2])
print('R_machine percentage of variance: ',
      np.sum(eValue_m[0:2]) / np.sum(eValue_m))
fig = plt.figure()
plt.stem(eValue_R, label='total', linefmt='tab:gray', markerfmt='ko')
axes = plt.gca()
axes.set_xlabel('index (k)')
axes.set_ylabel('eigen-vlaues of R matrix')

fig = plt.figure()
plt.stem(eValue_h, label='total', linefmt='tab:gray', markerfmt='ko')
axes = plt.gca()
axes.set_xlabel('index (k)')
axes.set_ylabel('eigen-vlaues of R-human matrix')

fig = plt.figure()
plt.stem(eValue_m, label='total', linefmt='tab:gray', markerfmt='ko')
axes = plt.gca()
axes.set_xlabel('index (k)')
axes.set_ylabel('eigen-vlaues of R-machine matrix')
コード例 #37
0
    return amplitude, time


def Squarer_System(x):  # Function to apply filter on a array
    """
	Applying Squarer System/Filter on an array
	"""
    n = x.shape[0]
    output = np.zeros(n)

    for i in range(n):
        output[i] = x[i] * x[i]

    return output


S, time = Sin_Discrete(0, 50, 32)

S_square = Squarer_System(S)

plt.figure(figsize=(13, 8))

ax = plt.subplot(1, 2, 1)
plt.stem(time, S, 'r')

ax = plt.subplot(1, 2, 2)
plt.stem(time, S_square, 'y')

plt.show()
コード例 #38
0
ファイル: interpretation.py プロジェクト: tzom/AHLF
#####################################################################

batch_size=64

model.load_weights("model/alpha_model_weights.hdf5")

from get_spectrum_as_numpy import get_spectrum
import shap 

spectrum = get_spectrum('example/example.mgf')
background_spectra = np.zeros((1,3600,2))
e = shap.DeepExplainer(model, background_spectra)

take_specific_spectrum=0
spectrum=spectrum[take_specific_spectrum,:,:]
spectrum=np.expand_dims(spectrum,0)

interpretation = np.squeeze(e.shap_values(spectrum))
spectrum = np.squeeze(spectrum)

import matplotlib.pyplot as plt

plt.title("Mirrorplot: demonstrating how SHAP values are used to interpret AHLF.")
plt.stem(spectrum[:,0]/np.max(spectrum[:,0]),linefmt='C0-',markerfmt=' ',basefmt=' ',use_line_collection=True,label='acquired peak')
plt.stem(- np.abs(interpretation[:,0])/np.max(np.abs(interpretation[:,0])),linefmt='C1-',markerfmt=' ',basefmt=' ',use_line_collection=True,label='abs. SHAP value')
plt.xlabel('feature')
plt.ylabel('Norm. abundance [a.u.]')
plt.legend()
plt.savefig('interpretation.png')

コード例 #39
0
M = 1

t = 0
x0 = np.linspace(0, 400, 400)
y0 = 0

surface = water.Surface(N=N, M=M, whitening=1)
k = surface.k
k0 = surface.k0
S = surface.spectrum(k)
plt.figure(figsize=[8, 6])
plt.loglog(k0, surface.spectrum(k0), '-', color='black')
plt.stem(surface.k_heights,
         surface.spectrum(surface.k_heights),
         use_line_collection=True,
         markerfmt=' ',
         linefmt='darkblue',
         label='Высоты',
         bottom=0)

plt.stem(surface.k_slopes,
         surface.spectrum(surface.k_slopes),
         use_line_collection=True,
         markerfmt=' ',
         linefmt='r',
         label='Наклоны',
         bottom=0)
plt.xlabel(r'$k, \text{ рад}\cdot\text{м}^{-1}$')
plt.ylabel(r'S,~\text{a.u.}')
plt.legend()
# plt.savefig('/home/kannab/documents/water/poster/nodes.pdf')
コード例 #40
0
# In[73]:

# first our usual bookkeeping
get_ipython().magic('pylab inline')
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Typically, we will take a vector of data points, compute the DFT and plot the magnitude of the result. For instance, consider the DFT of a linear ramp:

# In[74]:

x = np.arange(0, 1.02, 0.02) - 0.5
X = np.fft.fft(x)
plt.stem(abs(X))

# ## Positive and negative frequencies
#
# The coefficient number $k$ indicates the contribution (in amplitude and phase) of a sinusoidal component of frequency
#
# $$
#     \omega_k = \frac{2\pi}{N}k
# $$
#
# Because of the rotational symmetry of complex exponentials, a positive frequency $\omega$ between $\pi$ and $2\pi$ is equivalent to a negative frequency of $\omega - 2\pi$; this means that half of the DFT coefficients correspond to negative frequencies and when we concentrate on the physical properties  of the DFT it would probably make more sense to plot the coefficients centered around zero with positive frequencies on the right and negative frequencies on the left.
#
# The reason why this is not usuall done are many, including
#
#  * convenience
#  * since we are manipulating finite-length signals, the convention dictates that we start at index zero
コード例 #41
0
plt.ylabel('Mean Squared Error')
plt.show()

N_stem = max(y) * np.ones((np.shape(a)[0] + 1, ))
MMMI_stem = 0.9 * max(y) * np.ones((len(SSLS_seg), ))

MMI_stem = 0.8 * max(y) * np.ones((len(SSLS_seg_old), ))

MI_stem = 0.7 * max(y) * np.ones((len(seg), ))

plt.figure()
plt.plot(y, alpha=0.8, lw=0.5, label='switching AR process')

plt.stem(SSLS_seg,
         MMMI_stem,
         basefmt=" ",
         linefmt='b',
         markerfmt='+b',
         label='OSRLS (Linear Complexity)')
plt.stem(SSLS_seg_old,
         MMI_stem,
         basefmt=" ",
         linefmt='r',
         markerfmt='1r',
         label='OSRLS')
plt.stem(seg,
         MI_stem,
         basefmt=" ",
         linefmt='g',
         markerfmt='xg',
         label='segmented LS/RLS')
plt.stem(NN[0:np.shape(a)[0] + 1],
コード例 #42
0
      print("[Received] Topic: " + msg.topic + ", Message: " + str(msg.payload) + "\n")
      tilt[num] = int(msg.payload)
      num += 1

def on_subscribe(mosq, obj, mid, granted_qos):
      print("Subscribed OK")

def on_unsubscribe(mosq, obj, mid, granted_qos):
      print("Unsubscribed OK")

# Set callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_unsubscribe = on_unsubscribe

# Connect and subscribe
print("Connecting to " + host + "/" + topic)
mqttc.connect(host, port=1883, keepalive=60)
mqttc.subscribe(topic, 0)

# Publish messages from Python
while num < 20:
      mqttc.loop()
      time.sleep(1)

plt.stem(t, tilt)
plt.xlabel('time')
plt.ylabel('tilt')
plt.title('# tilt plot')
plt.show()
コード例 #43
0
triangles.  The `Triangle` class treats the development parameter as
optional. This example instantiates a 'premium' triangle as a single vector.
"""

import chainladder as cl
import pandas as pd
import matplotlib.pyplot as plt

# Raw premium data in pandas
premium_df = pd.DataFrame({
    'AccYear': [item for item in range(1977, 1988)],
    'premium': [3000000] * 11
})

# Create a premium 'triangle' with no development
premium = cl.Triangle(premium_df, origin='AccYear', columns='premium')

# Create some loss triangle
loss = cl.load_sample('abc')
ultimate = cl.Chainladder().fit(loss).ultimate_

loss_ratios = (ultimate / premium).to_frame()

# Plot
fig, ax = plt.subplots()
plt.stem(loss_ratios.index.astype(str), loss_ratios.iloc[:, 0])
ax.grid(axis='y')
for spine in ax.spines:
    ax.spines[spine].set_visible(False)
plt.show()
コード例 #44
0
        e += 1
        findBj(Tx, s, b, e)
        #to change the s and b values
        if i == 0 or i == 2:
            s += 1
        elif i == 1:
            s -= 1
            b += 1
#plotting the model
print("Delay Value: ", delay)
print("Impulse Response:", Hn)
print(len(Hn), " piece of data")
#plt.plot(delay, Hn)
plt.xlabel("time(s)")
plt.ylabel("Impulse Amplitude")
plt.stem(delay, Hn, '-')
plt.show()

#convolution
s1 = Hn
s2 = Txx
#print ('s1: ', s1)
#print ('s2: ', s2)
#s3 = np.flip(s2,0)
#length = len(s1)+len(s2)-1

#s1_zeros = length - len(s1)
#s3_zeros = length - len(s3)

#temp_s1 = np.concatenate((np.zeros(s1_zeros),s1))
#temp_s2 = np.concatenate((s3, np.zeros(s3_zeros)))
コード例 #45
0
x2 = list()
for i in range(0, 21):
    x2.append(i)
x1 = [
    -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17,
    -18, -19, -20
]
x = x1 + x2

# In[179]:

ADFWN1 = autocorrelation(W)[1:21]
ADFWN2 = autocorrelation(W)[0:21]
ADFWN = ADFWN1 + ADFWN2
plt.stem(x, ADFWN, use_line_collection=True)
plt.title('Autocorrelation formula for White noise', pad=20)
plt.ylabel('Autocorrelation')
plt.xlabel('Lag #')
plt.show()

# ### b. Plot both the generated WN in step 3 versus time and plot the histogram.
#

# In[180]:

plt.plot(W)
plt.title('White Noise through time', pad=40)
plt.xlabel('Time')
plt.ylabel('Generated White Noise')
plt.show()
コード例 #46
0
    def plot(self, dB=False, phase=False, stem=False, frange=(0, 10000)):
        '''
        Generate three subplots showing frequency-domain (both amplitude and
        phase) and time-domain representations of the given signal.
        If stem is True, stem plots will be used for both amplitude and phase
        If dB is True, the amplitude in the frequency domain plot will be shown
        with the log scale.
        If phase is True, the phase-shift plot will also be created.
        '''
        plt.subplots_adjust(hspace=.4)

        if phase:
            num_plots = 3
        else:
            num_plots = 2

        # plot time-domain signal
        plt.subplot(num_plots, 1, 1)
        plt.cla()
        x, y = self.get_time_domain()
        plt.grid(True)
        plt.xlabel(u'Time (s)')
        plt.ylabel('Value')
        plt.plot(x, y, 'g')

        # plot frequency vs. amplitude
        x, a, p = self.get_freq_domain()
        start_index = int(
            float(frange[0]) / self.sampling_rate * len(self.freqs))
        stop_index = int(
            float(frange[1]) / self.sampling_rate * len(self.freqs))
        x = x[start_index:stop_index]
        a = a[start_index:stop_index]
        p = p[start_index:stop_index]
        plt.subplot(num_plots, 1, 2)
        plt.cla()
        plt.grid(True)
        plt.xlabel(u'Frequency (Hz)')

        if dB:
            a = 10. * np.log10(a + 1e-10) + 100
            plt.ylabel(u'Amplitude (dB)')
        else:
            plt.ylabel(u'Amplitude')

        if stem:
            plt.stem(x, a, 'b')
        else:
            plt.plot(x, a, 'b')

        # plot frequency vs. phase-shift
        if phase:
            plt.subplot(num_plots, 1, 3)
            plt.cla()
            plt.grid(True)
            plt.xlabel(u'Frequency (Hz)')
            plt.ylabel(u'Phase (degree)')
            plt.ylim(-180, 180)
            if stem:
                plt.stem(x[start_index:stop_index], p[start_index:stop_index],
                         'r')
            else:
                plt.plot(x[start_index:stop_index], p[start_index:stop_index],
                         'r')

        plt.show()
コード例 #47
0
def main():
    # sine
    #sin = np.vectorize(sin_f)
    #series = sin(samples)

    # cos
    #cos = np.vectorize(cos_f)
    #series = cos(samples)

    # tan
    #tan = np.vectorize(tan_f)
    #series = tan(samples)

    # normal
    #series = np.random.normal(loc=6, scale=0.1, size=(N,1))
    # binomial
    #series = np.random.binomial(n=10, p=0.7, size=(N,1))
    # Poisson
    #series = np.random.poisson(lam=2, size=(N,1))
    # Uniform
    #series = np.random.uniform(size=(N, 1))
    # Logistic
    #series = np.random.logistic(loc=1, scale=2, size=(N, 1))
    # Multi
    series = np.random.multinomial(
        n=6, pvals=[1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6])
    # Exponential
    #series = np.random.exponential(scale=2, size=(N, 1))
    # Chi
    #series = np.random.chisquare(df=2, size=(N, 1))
    # Rayleigh
    #series = np.random.rayleigh(scale=2, size=(N, 1))
    # Pareto
    #series = np.random.pareto(a=2, size=(N, 1))
    # Zipf
    #series = np.random.zipf(a=2, size=(N, 1))

    g = visibility_graph(series)
    # Circular
    #pos = nx.circular_layout(g)
    # Bipartite
    #top = nx.bipartite.sets(g)[0]
    #pos = nx.bipartite_layout(g, top)
    # Kamada Kawai
    #pos = nx.kamada_kawai_layout(g)
    # Planar
    #pos = nx.planar_layout(g)
    # Random
    #pos = nx.random_layout(g)
    # Shell
    shells = [[0], list(np.arange(1, len(g), 1))]
    pos = nx.shell_layout(g, shells)
    # Spring
    #pos = nx.spring_layout(g)
    # Spectral
    #pos = nx.spectral_layout(g)
    # Spiral
    #pos = nx.spiral_layout(g)
    # Multipartite
    #pos = nx.multipartite_layout(g)

    print(g.nodes())
    print(g.edges())
    x = list(g.nodes())
    y = series
    e = list(g.edges())
    plt.stem(x, y)
    plt.figure(1)
    for edg in e:
        plt.plot(edg, [y[(edg[0])], y[(edg[1])]])
    plt.show()

    plt.figure(2)
    nx.draw(g, pos)
    #nx.draw_networkx_labels(g,pos,font_size=7,font_family='sans-serif')
    #nx.draw_networkx_edge_labels(g,pos,q_list,label_pos=0.3)
    plt.show()

    plt.figure(3)
    plt.hist(y)
    plt.show()
コード例 #48
0
ファイル: button3.py プロジェクト: suxas/suxas.github.io
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(0, 8, 10)
plt.subplot(111)
A = 2
a = 0.6
y = A * a**x
plt.grid(True)
plt.title('实指数信号')
plt.stem(x, y)

plt.show()
コード例 #49
0
        if iterations % 1 == 0:
            print("iteration:", iterations, "train_loss: ", '%.2f' % loss1, "test_loss: ", '%.2f' % test_loss, "test_corr: ", '%.2f' % cor, end='\n')

        iterations += 1
              
        
        
# Results



X1proj = sess.run(Fs_img,feed_dict={X1: train_X1 ,X2: train_X2})
plt.figure()
x = np.linspace(0,90,90)
markerline, stemlines, baseline = plt.stem(x,np.transpose(X1proj), '.-')


X2proj = sess.run(Fs_snp,feed_dict={X1: train_X1 ,X2: train_X2})

print('image')
plt.figure()
x = np.linspace(0,3365,3365)
markerline, stemlines, baseline = plt.stem(x,np.transpose(X2proj), '.-')






コード例 #50
0
    count = np.zeros(265)

    for j in range(0,x):
        for k in range(0,y):
            count[img[j,k]] = count[img[j,k]] + 1

    return count


img = cv.imread('image.png',cv.IMREAD_GRAYSCALE)

cv.imshow("Image",img)
k = cv.waitKey(100)
cv.imwrite('greyscale.png',img)

plt.figure(1)
histogram = compute_histogram(img)
plt.stem(histogram, markerfmt = ' ')
plt.xlabel("Grayscale Values")
plt.ylabel("No. Of Occurence")
plt.title("Using compute_histogram()")


plt.figure(2)
plt.hist(img.ravel(),256,[0,256])
plt.xlabel("Grayscale Values")
plt.ylabel("No. Of Occurence")
plt.title("Using In-Built Commands")
plt.show()
コード例 #51
0
    speed_out2.Update(s2[i])
    #speed_out3.Update(s3[i])
    i += 1

if ((speed_out0.Y() != s0).any()):
    print('Sensor-speedout: Fail in 1-1')
    raise AssertionError()

p1 = 0 * speed_out1.timespace() + 1
p2 = 0 * speed_out2.timespace() + 1

plt.figure()
plt.xlabel('t')
plt.ylabel('speedout')
plt.scatter(clock.timespace(), s1, c='r', s=0.5)
plt.stem(speed_out1.timespace(), p1, '-', use_line_collection=True)

plt.figure()
plt.xlabel('t')
plt.ylabel('speedout')
plt.scatter(clock.timespace(), s2, c='r', s=0.5)
plt.stem(speed_out2.timespace(), p2, '-', use_line_collection=True)
"""
plt.figure()
plt.xlabel('t')
plt.ylabel('speedout')
plt.scatter(clock.timespace(), s3, c='r', s=0.5)
plt.stem(clock.timespace(), speed_out3.Y(), '-', use_line_collection=True)
"""

plt.show()
コード例 #52
0
import cmath
import matplotlib.pyplot as plt
import numpy as np


def dft(f):
    F = []
    for k in range(len(f)):
        s = complex(0)  # s=0*j
        for n in range(len(f)):
            power = 2j * cmath.pi * n * k / len(f)
            s += f[n] * cmath.exp(-power)
        F.append(s)
    return F


N = 8
print(
    "Let N=8 and f(n)  where n = 0 ,.., N - 1 \nf(n) = 1 when n is even and f(n) = 0 when n is odd"
)
f = [1 if n % 2 == 0 else 0 for n in range(N)]
Dft = dft(f)
print("DFT of", f, " is :", Dft)
print("and F is real")

absl = [np.absolute(i) for i in Dft]

plt.suptitle("15.5.5")
plt.title("DFT")
plt.stem(absl)
plt.show()
コード例 #53
0
# calculate..
lkg = lk_gaussian(data, muHat, varHat)
llkg = llk_gaussian(data, muHat, varHat)

# generate output ..
print("Gaussian likelihood: " + str(lkg))
print("Gaussian loglikelihood: " + str(llkg))
print("exp(loglikelihood): " + str(np.exp(llkg)))

###############################################################################
### Subtask 8. Visualisation
###############################################################################

x = np.arange(0, max(data))

py = list(map(lambda d: lk_poisson([d], muHat), x))
gy = list(map(lambda d: lk_gaussian([d], muHat, varHat), x))

plt.plot(x, gy, label='Gaussian distribution', color='orange')
plt.stem(x, py, label='Poisson distribution')
plt.xlabel("samples")
plt.xticks(np.arange(0, 12, step=1))
plt.ylabel("$pdf(x=x_i)$")
plt.legend(loc='upper right')
plt.show()

###############################################################################
### END
###############################################################################
コード例 #54
0
array = np.zeros(com_list[1] + 1, dtype=int)
array2 = np.zeros(com_list[1] + 1, dtype=int)
counter = 4

for j in range(com_list[0], com_list[1] + 1):
    array[j] = com_list[counter]
    counter += 1

for k in range(com_list[2], com_list[3] + 1):
    array2[k] = com_list[counter]
    counter += 1

mean = sum(array) / len(array)
sd = np.std(array)

normalized_array = [(i - mean) / sd for i in array]

mean2 = sum(array2) / len(array2)
sd2 = np.std(array2)

normalized_array2 = [(i - mean2) / sd2 for i in array2]

convol = [
    normalized_array[k] * normalized_array2[com_list[1] - k]
    for k in range(0, com_list[1] + 1)
]

plt.title("Convolution of normalized")
plt.stem(convol, '--')
def RESON_dyProg_mat(GCI_relAmp,
                     GCI_N,
                     F0mean,
                     x,
                     fs,
                     trans_wgt,
                     relAmp_wgt,
                     plots=True):
    # Function to carry out dynamic programming method described in Ney (1989)
    # and used previously in the ESPS GCI detection algorithm. The method
    # considers target costs and transition costs which are accumulated in
    # order to select the `cheapest' path, considering previous context

    # USAGE: INPUT
    #        GCI_relAmp - target cost matrix with N rows (GCI candidates) by M
    #                     columns (mean based signal derived intervals).
    #        GCI_N      - matrix containing N by M candidate GCI locations (in
    #                     samples)
    #        F0_inter   - F0 values updated every sample point
    #        x          - speech signal
    #        fs         - sampling frequency
    #        trans_wgt  - transition cost weight
    #
    #        OUTPUT
    #        GCI        - estimated glottal closure instants (in samples)
    # =========================================================================
    # === FUNCTION CODED BY JOHN KANE AT THE PHONETICS LAB TRINITY COLLEGE ====
    # === DUBLIN. 25TH October 2011 ===========================================
    # =========================================================================

    # =========================================================================
    # === FUNCTION ADAPTED AND CODED IN PYTHON BY J. C. Vasquez-Correa
    #   AT THE PATTERN RECOGNITION LAB, UNIVERSITY OF ERLANGEN-NUREMBERG ====
    # === ERLANGEN, MAY, 2018 ===========================================
    # =========================================================================

    ## Initial settings

    GCI_relAmp = np.asarray(GCI_relAmp)
    relAmp_wgt = np.asarray(relAmp_wgt)
    cost = GCI_relAmp * relAmp_wgt
    #print(cost.shape)
    GCI_N = np.asarray(GCI_N)
    ncands = GCI_N.shape[1]
    nframe = GCI_N.shape[0]
    #print(ncands, nframe, cost.shape)
    prev = np.zeros((nframe, ncands))
    pulseLen = int(fs / F0mean)
    GCI_opt = np.zeros(nframe)

    for n in range(nframe):

        if n < 1:
            continue

        costm = np.zeros((ncands, ncands))

        for c in range(ncands):
            #Transitions TO states in current frame
            start = int(GCI_N[n, c] - pulseLen / 2)
            stop = int(GCI_N[n, c] + pulseLen / 2)
            if stop > len(x):
                stop = len(x)
            pulse_cur = x[start:stop]

            for p in range(ncands):
                #Transitions FROM states in previous frame
                start = int(GCI_N[n - 1, p] - pulseLen / 2)
                stop = int(GCI_N[n - 1, p] + pulseLen / 2)
                if start < 1:
                    start = 1
                if stop > len(x):
                    stop = len(x)
                pulse_prev = x[start:stop]
                if len(pulse_cur) == 0 or np.isnan(pulse_cur[0]) or np.isnan(
                        pulse_prev[0]):
                    costm[p, c] = 0
                else:
                    if len(pulse_cur) != len(pulse_prev):
                        cor_cur = 0
                    else:
                        cor_cur = pearsonr(pulse_cur, pulse_prev)[0]
                    costm[p, c] = (1 - np.abs(cor_cur)) * trans_wgt

        costm = costm + np.tile(cost[n - 1, 0:ncands], (ncands, 1))
        costm = np.asarray(costm)
        costi = np.min(costm, 0)
        previ = np.argmin(costm, 0)
        cost[n, 0:ncands] = cost[n, 0:ncands] + costi
        prev[n, 0:ncands] = previ

    best = np.zeros(n + 1)
    best[n] = np.argmin(cost[n, 0:ncands])
    for i in range(n - 1, 1, -1):

        best[i - 1] = prev[i, int(best[i])]

    for n in range(nframe):
        #print(n,int(best[n]))
        GCI_opt[n] = GCI_N[n, int(best[n])]

    if plots:
        GCI_norm = np.zeros((nframe, ncands))
        GCI_opt_norm = np.zeros((nframe, ncands))
        for n in range(nframe):
            GCI_norm[n, :] = GCI_N[n, :] - GCI_N[n, 0]
            GCI_opt_norm[n] = GCI_opt[n] - GCI_N[n, 0]

        plt.subplot(211)
        plt.plot(x)
        plt.stem(GCI_N[:, 0], -0.1 * np.ones(len(GCI_N[:, 0])), 'r')
        plt.stem(GCI_opt, -0.1 * np.ones(len(GCI_opt)), 'k')
        plt.subplot(212)
        #plt.plot(GCI_opt, GCI_norm)
        plt.plot(GCI_opt, GCI_opt_norm, 'bo')
        plt.show()
    return GCI_opt
コード例 #56
0
ファイル: program_4_3_2.py プロジェクト: simpleplanya/DSP
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5])
#h1 is unit step function
h1 = np.array([1, 1, 1, 1, 1])
y1 = np.convolve(x, h1)
plt.xlabel('Time index')
plt.ylabel('Amplitude')
plt.stem(np.arange(len(x)), x, label='$x[n]$')
plt.stem(np.arange(len(y1[0:5])), y1[0:5], label='$y_1[n]$', markerfmt='ro')
#自動調整子圖間的間距
plt.tight_layout()
plt.grid()
plt.legend()
plt.show()
コード例 #57
0
    for i in range(1, len(arr)):
        for k in range(0, size):
            arr[i] += arr[i - k] * filter[k]


# def Medfilt (x, k):
#     k2 = (k - 1) // 2
#     y = np.zeros((len (x), k))
#     y[:,k2] = x
#     for i in range (k2):
#         j = k2 - i
#         y[j:,i] = x[:-j]
#         y[:j,i] = x[0]
#         y[:-j,-(i+1)] = x[j:]
#         y[-j:,-(i+1)] = x[-1]
#     return np.median (y, axis=1)

arr = [1, 4, 6, 8, 0, 9, 4, 9, 9, 123]
arr1 = [1, 20, 40, 60, 0, 40, 60, 80, 123]
# Medfilt(arr,3)
arr1 = medfilt(arr1, 3)

print(arr)
print(arr1)
plt.subplot(2, 1, 1)
plt.stem(arr)

plt.subplot(2, 1, 2)
plt.stem(arr1)
plt.show()
コード例 #58
0
        x = new_x.copy()
        z = new_z.copy()

        this_pobj = 0.5 * linalg.norm(A.dot(x) - b)**2 + l * linalg.norm(x, 1)
        pobj.append((time.time() - time0, this_pobj))

    times, pobj = map(np.array, zip(*pobj))
    return x, pobj, times


maxit = 1000
x_ista, pobj_ista, times_ista = ista(A, b, l, maxit)

x_fista, pobj_fista, times_fista = fista(A, b, l, maxit)

import matplotlib.pyplot as plt

plt.close('all')

plt.figure()
plt.stem(x0, markerfmt='go')
plt.stem(x_ista, markerfmt='bo')
plt.stem(x_fista, markerfmt='ro')

plt.figure()
plt.plot(times_ista, pobj_ista, label='ista')
plt.plot(times_fista, pobj_fista, label='fista')
plt.xlabel('Time')
plt.ylabel('Primal')
plt.legend()
plt.show()
コード例 #59
0
p = 100  # Ambient dimension
n = 100  # Number of samples

# Generate a p-dimensional zero vector
x_star = np.random.randn(p)
# Normalize
x_star = (1 / la.norm(x_star, 2)) * x_star


# In[2]:


# Plot
xs = range(p)
markerline, stemlines, baseline = plt.stem(xs, x_star, '-.')
plt.setp(markerline, 'alpha', 0.3, 'ms', 6)
plt.setp(markerline, 'markerfacecolor', 'b')
plt.setp(baseline, 'color', 'r', 'linewidth', 1, 'alpha', 0.3)
plt.rc('text', usetex=True)
#plt.rc('font', family='serif')
plt.xlabel('Index')
plt.ylabel('Amplitude')
plt.show()


# <center> How would you solve this problem? </center>

# <center>Closed form solution using matrix inverse</center>
# 
# \begin{align}
コード例 #60
0
lg.DI_set_acquisition_mode('Record')

lg.DI_set_divider(500)  #divider factor

lg.DI_set_sample_bits(8)  #format:among 8, 16, 32
lg.cSamples = 5000
lg.DI_set_samples(5000)  #

lg.DI_trigsrc('detectdigital')
lg.DI_trig_position(lg.cSamples)
lg.DI_trig_set(1, 'fsRise')

#4.0 Excution
pttn.PCtrig()
lg.DI_start_acquisition()
lg.DI_read_record()

lg.CloseAll()
pttn.CloseAll()

# post processing
data = np.zeros(len(lg.rgwSamples))

for idx in range(len(data)):
    data[idx] = lg.rgwSamples[idx] & 0x0F

del lg, pttn

plt.stem(data[0:32])
plt.show()