Handling/CompAlgSystemsTopics/CrossCorrs/0419SergKulk/cross_corr.py

# =============================================================================
# A couple of functions to compute a cross-correlation between the signals from
# pins of double rake probe and then plot the result
# =============================================================================
import numpy as np
from matplotlib import pyplot as plt
from urllib.request import urlopen
plt.ion()
# =============================================================================
# A function for data collection from the pins of the double rake probe
# =============================================================================
def collect(shot, pin):
    print('Data from shot %i, pin %s' % (shot, pin))
    url = f'http://golem.fjfi.cvut.cz/utils/data/{shot}/drppin{pin}'
    ourl = urlopen(url)
    data_all = np.loadtxt(ourl)
    data = np.array([row[1] for row in data_all])
    ourl.close()
    return data


# =============================================================================
# The function will compute cross-correlation between the signals from two pins
# of the double rake probe. 'left' and 'right' are points on x-axis (time)
# that should be taken from 'U_loop' diagnostics and are points indicating a
# plato. Data from that interval gives better results.
# =============================================================================
def cross_corr(shot, pin1, pin2, left, right):
    dt = 1e-6
    data1 = collect(shot, pin1)
    data2 = collect(shot, pin2)
    time_axis = np.arange(data1.size)*dt
    mask_ft = (left < time_axis) & (time_axis < right)
    data1 = data1[mask_ft]
    data2 = data2[mask_ft]
    norm = np.sqrt(np.sum(np.correlate(data1, data1)) * np.sum(np.correlate(data2, data2)))
    corr = np.correlate(data1, data2, 'same') / norm 
    N = len(corr)
    time_lag = (np.arange(N) - N//2) * dt  # time lag between two pins
    return time_lag, corr


# =============================================================================
# A function for plotting a close-up of the cross-correlation around the peak
# =============================================================================
def plot(lag, corr):
    plt.figure(); plt.clf()
    plt.title('Cross-correlation of pins %s and %s, shot %i' % (pin1, pin2, shot))
    plt.xlabel('time lag, [us]')
    plt.ylabel('cross-correlation coeficient, [-]')
    mask = (-20e-6 < lag) & (lag < 20e-6)
    plt.plot(lag[mask]*1e6, corr[mask])
    plt.axvline(c='k')
    plt.show()
    
# =============================================================================
# Example: plot and results
# =============================================================================
shot, pin1, pin2 = 30141, '15', '12'
lag, corr = cross_corr(shot, pin1, pin2, 10e-3, 12e-3)

plot(lag, corr)
print("Time shift between the pins:", lag[np.argmax(corr)]*1e6, "[us]")
print("Poloidal velocity:", round(2.5e-3 / lag[np.argmax(corr)], 3), "[m/s]")