Beispiel #1
0
 def plot_coherence_fft(self, s1, s2, chan_a, chan_b):
     plt.figure()
     plt.ylabel("Coherence")
     plt.xlabel("Frequency (Hz)")
     plt.title(self.plot_title("Coherence between channels "+chan_a+" and " +chan_b +" in the "+str(config['band'][0])+"-"+str(config['band'][1])+" Hz band"))
     plt.grid(True)
     plt.xlim(config['band'][0],config['band'][1])
     cxy, f = plt.cohere(s1, s2, NFFT, fs_Hz)
     self.plotit(plt)
Beispiel #2
0
 def plot_coherence_fft(self, s1, s2, chan_a, chan_b):
     plt.figure()
     plt.ylabel("Coherence")
     plt.xlabel("Frequency (Hz)")
     plt.title(self.plot_title("Coherence between channels "+chan_a+" and " +chan_b +" in the "+str(config['band'][0])+"-"+str(config['band'][1])+" Hz band"))
     plt.grid(True)
     plt.xlim(config['band'][0],config['band'][1])
     cxy, f = plt.cohere(s1, s2, NFFT, fs_Hz)
     self.plotit(plt)
def coherence_over_time(west, north, name):
    west = np.array(west)
    north = np.array(north)
    to_plot = zip(west, north) #let's have transform
    cxy, f = plt.cohere(west, north) #for freqs first
    with open("./coherence_stats/" + name, "w") as stats_file:
        stats_file.write(",".join(map(str, f)))
        stats_file.write("\n")
        stats_file.write(",".join(map(str, cxy)))
Beispiel #4
0
    def plot_coherence(self, sensor_1: str, sensor_2: str):
        """
        Plot Coherence between two sensors.

        :param sensor_1: The value of the column name from the loaded files where the desired information is. [SENSOR 1 NAME]
        :param sensor_2: The value of the column name from the loaded files where the desired information is. [SENSOR 2 NAME]
        :param sampling_freq : The signal sampling frequency.

        :return Return Instance so that it can be linearly written in code.
        """

        # Get Columns as Series.
        s1 = self.data_read[sensor_1]  # each row is a list
        s2 = self.data_read[sensor_2]  # each row is a list

        plt.cohere(s1, s2, self.sampling_rate)

        # Setup Plot Parameters.
        plt.title('Coherence Function between  ' + sensor_1 + '  and  ' +
                  sensor_2)
        plt.show()

        return self  # Return Instance so that it can be linearly written in code.
def coherences_over_time(wests, norths):
    plt.close()
    coherences = []
    for west, north in zip(wests, norths):
        curr_coherences = []
        for x in xrange(0, 100): ######## use np.roll
            curr_coherences.append(plt.cohere(west, north)[0])
        #get freqs and cxy, must plot according to those
        plt.plot(curr_coherences[-1], color="blue", alpha=0.1)
        coherences.append(curr_coherences)
    plt.ylabel("coherence synchrony score")
    plt.xlabel("offset")
    plt.title("simultaneous coherence plot")
    plt.savefig("./wholes/coherence_mc")
    plt.close()
    """
Beispiel #6
0
def coherences_over_time(wests, norths):
    plt.close()
    coherences = []
    for west, north in zip(wests, norths):
        curr_coherences = []
        for x in xrange(0, 100):  ######## use np.roll
            curr_coherences.append(plt.cohere(west, north)[0])
        #get freqs and cxy, must plot according to those
        plt.plot(curr_coherences[-1], color="blue", alpha=0.1)
        coherences.append(curr_coherences)
    plt.ylabel("coherence synchrony score")
    plt.xlabel("offset")
    plt.title("simultaneous coherence plot")
    plt.savefig("./wholes/coherence_mc")
    plt.close()
    """
Beispiel #7
0
def acrossCoherence():
        # https://pythontic.com/visualization/signals/coherence

        data1 = request.json.get('data1', [])
        data2 = request.json.get('data2', [])

        # print(request.json.get('name', ""))
        # Create sine wave1
        # time        = np.arange(0, 100, 0.1)
        # sinewave1   = np.sin(time)


        # Create sine wave2 as replica of sine wave1
        # time1        = np.arange(0, 100, 0.1)
        # sinewave2    = np.sin(time1)

        # Plot the sine waves - subplot 1
        # plot.title('Two sine waves with coherence as 1')
        # plot.subplot(211)
        # plot.grid(True, which='both')
        # plot.xlabel('time')
        # plot.ylabel('amplitude')
        # plot.plot(time, sinewave1, time1, sinewave2)

        # Plot the coherence - subplot 2
        # plot.subplot(212)
        # coh, f = plot.cohere(sinewave1, sinewave2, 256, 1./.01)
        # print("Coherence between two signals:")
        # print(coh)
        # plot.ylabel('coherence')

        # plot.show()
        # print(sinewave1)
        # print(sinewave2)
        print(len(data1))
        coh, f = plot.cohere(data1, data2, 64, 256)

        output = {}
        output['code'] = 20000
        output['data'] = {}
        output['data']['coherence'] = coh.tolist()
        output['data']['frequency'] = f.tolist()
        return Response(json.dumps(output), mimetype='application/json')
Beispiel #8
0
plt.subplots_adjust(wspace=0.5)

dt = 0.01
t = np.arange(0, 30, dt)
nse1 = np.random.randn(len(t))                 # white noise 1
nse2 = np.random.randn(len(t))                 # white noise 2
r = np.exp(-t/0.05)

cnse1 = np.convolve(nse1, r, mode='same')*dt   # colored noise 1
cnse2 = np.convolve(nse2, r, mode='same')*dt   # colored noise 2

# two signals with a coherent part and a random part
s1 = 0.01*np.sin(2*np.pi*10*t) + cnse1
s2 = 0.01*np.sin(2*np.pi*10*t) + cnse2

plt.subplot(211)
plt.plot(t, s1, 'b-', t, s2, 'g-')
plt.xlim(0, 5)
plt.xlabel('time')
plt.ylabel('s1 and s2')
plt.grid(True)

plt.subplot(212)
cxy, f = plt.cohere(s1, s2, 256, 1./dt)
plt.ylabel('coherence')
file = 'fig2_py.pdf'  # Nombre del fichero
plt.savefig(file)  # Salva la imagen en PDF
os.system('pdfcrop ' + file + ' ' + file)  # Recorta el fichero PDF para ajustar el BB
# plt.savefig('tex_demo')  # Salva la imagen en png
plt.show()
Beispiel #9
0
import numpy as np
import matplotlib.pyplot as plt

# make a little extra space between the subplots
plt.subplots_adjust(wspace=0.5)

dt = 0.01
t = np.arange(0, 30, dt)
nse1 = np.random.randn(len(t))                 # white noise 1
nse2 = np.random.randn(len(t))                 # white noise 2
r = np.exp(-t/0.05)

cnse1 = np.convolve(nse1, r, mode='same')*dt   # colored noise 1
cnse2 = np.convolve(nse2, r, mode='same')*dt   # colored noise 2

# two signals with a coherent part and a random part
s1 = 0.01*np.sin(2*np.pi*10*t) + cnse1
s2 = 0.01*np.sin(2*np.pi*10*t) + cnse2

plt.subplot(211)
plt.plot(t, s1, 'b-', t, s2, 'g-')
plt.xlim(0, 5)
plt.xlabel('time')
plt.ylabel('s1 and s2')
plt.grid(True)

plt.subplot(212)
cxy, f = plt.cohere(s1, s2, 256, 1./dt)
plt.ylabel('coherence')
plt.show()
Beispiel #10
0
c1 = np.convolve(n1, r, mode='same') * dt
c2 = np.convolve(n2, r, mode='same') * dt

s1 = 0.01 * np.sin(2 * np.pi * 10 * t) + c1
s2 = 0.01 * np.sin(2 * np.pi * 10 * t) + c2

plt.subplot(211)
plt.plot(t, s1, t, s2)
plt.xlim(0, 5)
plt.xlabel('time')
plt.ylabel('s1&s2')
plt.grid(True)

plt.subplot(212)
plt.cohere(s1, s2, 256, 1. / dt)
plt.ylabel('coherernece')

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:
    plt.title(titleText)
else:  #对特定通道进行分析
    channelN = pressuresData.getColumnData(CHANNEL_NUM)[0:dataSize]
    plt.subplots_adjust(wspace=0.5)
    x = czySignal.getXByFs(dataSize, fs)
    print('进行%d通道相关分析' % (CHANNEL_NUM))
    plt.subplot(211)
    plt.plot(x, channelN, 'r')
    plt.plot(x, channelEnd, 'b')
    if SHOW_AXIS_TEXT:
        plt.xlabel('times(s)')
        plt.ylabel('amplitude')
    if SHOW_TITLE:
        plt.title(titleText)

    plt.subplot(212)
    cxy, f = plt.cohere(channelN,
                        channelEnd,
                        NFFT=cohereNFFTSize,
                        Fs=fs,
                        detrend='mean')
    if MARK_MAX:
        index = np.argmax(cxy)
        plt.plot(f[index], cxy[index], 'o')
    if SHOW_AXIS_TEXT:
        plt.xlabel('frequency(Hz)')
        plt.ylabel('coherence')

plt.gcf().set_facecolor('w')
plt.show()
Beispiel #12
0
y = np.random.randn(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)

plt.scatter(x, y, c = colors, s = sizes, alpha = 0.3, cmap = 'magma')
plt.colorbar()
plt.show()
print()

# x와 y의 일관성 차트

# 2개의 일관성 출력
print('2개의 일관성 출력')
dt = 0.01
t = np.arange(0, 30, dt)
n1 = np.random.randn(len(t))
n2 = np.random.randn(len(t))

s1 = 1.5 * np.sin(2 * np.pi * 10 * t) + n1
s2 = np.cos(np.pi * t) + n2
plt.cohere(s1, s2 ** 2, 128, 1./dt)
plt.xlabel('time')
plt.ylabel('coherence')
plt.show()
print()


# =============================================================================


        ax.set_zlabel('coherence')
    plt.subplots_adjust(hspace=0.31)#水平间距
    plt.title(titleText)
else:#对特定通道进行分析
    channelN = pressuresData.getColumnData(CHANNEL_NUM)[0:dataSize]
    plt.subplots_adjust(wspace=0.5)
    x = czySignal.getXByFs(dataSize,fs)
    print('进行%d通道相关分析'%(CHANNEL_NUM))
    plt.subplot(211)
    plt.plot(x,channelN,'r')
    plt.plot(x,channelEnd,'b')
    if SHOW_AXIS_TEXT:
        plt.xlabel('times(s)')
        plt.ylabel('amplitude')
    if SHOW_TITLE:
        plt.title(titleText)

    plt.subplot(212)
    cxy,f = plt.cohere(channelN,channelEnd,NFFT = cohereNFFTSize,Fs = fs,detrend='mean')
    if MARK_MAX:
        index = np.argmax(cxy)
        plt.plot(f[index],cxy[index],'o')
    if SHOW_AXIS_TEXT:
        plt.xlabel('frequency(Hz)')
        plt.ylabel('coherence')
    

plt.gcf().set_facecolor('w')
plt.show()

Beispiel #14
0
from sys import exit


x = np.genfromtxt("x.csv",delimiter=';')
y = np.genfromtxt("y.csv",delimiter=';')
coh = np.genfromtxt("coh.csv",delimiter=';')
fr  = np.genfromtxt("f.csv",delimiter=";")

SN = 256

w = [1.]*SN
hann = [0.0]*SN
for i in range(SN):
#	hann[i] = 0.5*(1-np.cos(2*np.pi*i/SN))
	hann[i] = 1.0
c,f = plt.cohere(x,y,NFFT=SN,Fs=1,window=hann)


plt.subplot(2,2,1)
plt.plot(x)
plt.title("x")

plt.subplot(2,2,2)
plt.plot(y)
plt.title("y")

plt.subplot(2,2,3)
plt.plot(fr,coh)
plt.title("coh")

plt.subplot(2,2,4)
Beispiel #15
0
def cohere(*args, **kwargs):
    r"""starkplot wrapper for cohere"""
    return _pyplot.cohere(*args, **kwargs)
Beispiel #16
0
plot.title('Two sine waves with coherence as 1')

plot.subplot(211)

plot.grid(True, which='both')

plot.xlabel('time')

plot.ylabel('amplitude')

plot.plot(time, sinewave1, time1, sinewave2)

# Plot the coherence - subplot 2

plot.subplot(212)

coh, f = plot.cohere(sinewave1, sinewave2, 256, 1. / .01)

print("Coherence between two signals:")

print(coh)

print("Frequncies of the coherence vector:")

print(f)

plot.ylabel('coherence')

plot.show()
plt.show()

##更复杂的子绘图区域: gridspec子类
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(3, 3) # 设定3x3网格

ax1 = plt.subplot(gs[0, :]) # 选中网格,确定选中的行列网格数
ax2 = plt.subplot(gs[1, :-1]

# 常用绘图函数
plt.boxplot(data, notch, position)  # 在图形中增加带箭头的注解
plt.bar(left, height, width, bottom)  # 横向条形图
plt.barh(width, bottom, left, height) #条形图
plt.hist(x,bins,normed) # 直方图
plt.scatter(x,y)        # 散点图
plt.cohere(x,y,NFFT=256, Fs) # X-Y 的相关性函数
plt.vlines()            # 垂线图
plt.plot_date()         # 数据日期
plt.polar(theta, r)
plt.pie(data, explode)  # 饼图

# 例1 饼图:
labels = 'Frogs', 'Hogs', 'Dogs','Logs'
sizes = [15, 30, 45, 10]  # 占比
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels,
        autopct='%1.1f%%',shadow=False, startangle=90)  # 饼图
plt.axis('equal')

# 例2 直方图:
np.random.seed(0)