Esempio n. 1
0
def test_plot_instantaneous_measure(tsig_comb):

    times = create_times(N_SECONDS, FS)

    plot_instantaneous_measure(
        times,
        amp_by_time(tsig_comb, FS, F_RANGE),
        'amplitude',
        save_fig=True,
        file_path=TEST_PLOTS_PATH,
        file_name='test_plot_instantaneous_measure_amplitude.png')

    plot_instantaneous_measure(
        times,
        phase_by_time(tsig_comb, FS, F_RANGE),
        'phase',
        save_fig=True,
        file_path=TEST_PLOTS_PATH,
        file_name='test_plot_instantaneous_measure_phase.png')

    plot_instantaneous_measure(
        times,
        freq_by_time(tsig_comb, FS, F_RANGE),
        'frequency',
        save_fig=True,
        file_path=TEST_PLOTS_PATH,
        file_name='test_plot_instantaneous_measure_frequency.png')

    # Check the error for bad measure
    with raises(ValueError):
        plot_instantaneous_measure(times, tsig_comb, 'BAD')
Esempio n. 2
0
def test_plot_bursts(tsig_burst):

    times = create_times(N_SECONDS, FS)
    bursts = detect_bursts_dual_threshold(tsig_burst, FS, (0.75, 1.5), F_RANGE)

    plot_bursts(times,
                tsig_burst,
                bursts,
                save_fig=True,
                file_path=TEST_PLOTS_PATH,
                file_name='test_plot_bursts.png')
Esempio n. 3
0
def test_plot_timefrequency(tsig_comb):

    times = create_times(N_SECONDS, FS)
    freqs = np.array([5, 10, 15, 20, 25])
    mwt = compute_wavelet_transform(tsig_comb, FS, freqs)

    plot_timefrequency(times,
                       freqs,
                       mwt,
                       save_fig=True,
                       file_path=TEST_PLOTS_PATH,
                       file_name='test_plot_timefrequency1.png')

    plot_timefrequency(times,
                       freqs,
                       mwt,
                       x_ticks=[2.5, 7.5],
                       y_ticks=[5, 15],
                       save_fig=True,
                       file_path=TEST_PLOTS_PATH,
                       file_name='test_plot_timefrequency2.png')
Esempio n. 4
0
def test_plot_time_series(tsig_comb, tsig_burst):

    times = create_times(N_SECONDS, FS)

    # Check single time series plot
    plot_time_series(times,
                     tsig_comb,
                     save_fig=True,
                     file_path=TEST_PLOTS_PATH,
                     file_name='test_plot_time_series-1.png')

    # Check multi time series plot, labels
    plot_time_series(times, [tsig_comb, tsig_comb[::-1]],
                     labels=['signal', 'signal reversed'],
                     save_fig=True,
                     file_path=TEST_PLOTS_PATH,
                     file_name='test_plot_time_series-2.png')

    # Test 2D arrays
    plot_time_series(times,
                     np.array([tsig_comb, tsig_burst]),
                     save_fig=True,
                     file_path=TEST_PLOTS_PATH,
                     file_name='test_plot_time_series-2arr.png')
Esempio n. 5
0
# Often, we want to simulate noise that is comparable to what we see in neural recordings.
#
# Neural signals display 1/f-like activity, whereby power decreases linearly across
# increasing frequencies, when plotted in log-log.
#
# Let's start with a powerlaw signal, specifically a brown noise process, or a signal
# for which the power spectrum is distributed as 1/f^2.
#

###################################################################################################

# Setting for the simulation
exponent = -2

# Simulate powerlaw activity, specifically brown noise
times = create_times(n_seconds, fs)
br_noise = sim.sim_powerlaw(n_seconds, fs, exponent)

###################################################################################################

# Plot the simulated data, in the time domain
plot_time_series(times, br_noise)

###################################################################################################

# Plot the simulated data, in the frequency domain
freqs, psd = spectral.compute_spectrum(br_noise, fs)
plot_power_spectra(freqs, psd)

###################################################################################################
#
Esempio n. 6
0
###################################################################################################

# Simulation settings
fs = 1000
n_seconds = 5

# Define simulation components
components = {'sim_synaptic_current' : {'n_neurons':1000, 'firing_rate':2,
                                        't_ker':1.0, 'tau_r':0.002, 'tau_d':0.02},
              'sim_bursty_oscillation' : {'freq' : 10,
                                          'prob_enter_burst' : .2, 'prob_leave_burst' : .2}}

# Simulate a signal with a bursty oscillation with an aperiodic component & a time vector
sig = sim_combined(n_seconds, fs, components)
times = create_times(n_seconds, fs)

###################################################################################################

# Plot the simulated data
plot_time_series(times, sig, 'Simulated EEG')

###################################################################################################
#
# In the simulated signal above, we can see some bursty 10 Hz oscillations.
#

###################################################################################################
# Dual Amplitude Threshold Algorithm
# ----------------------------------
#
###################################################################################################
# Load example neural signal
# --------------------------
#
# First, we will load an example neural signal to use for our time-frequency measures.
#

###################################################################################################

# Load a neural signal, as well as a filtered version of the same signal
sig = load_ndsp_data('sample_data_1.npy', folder='data')
sig_filt_true = load_ndsp_data('sample_data_1_filt.npy', folder='data')

# Set sampling rate, and create a times vector for plotting
fs = 1000
times = create_times(len(sig) / fs, fs)

# Set the frequency range to be used
f_range = (13, 30)

###################################################################################################
#
# Throughout this example, we will use
# :func:`~neurodsp.plts.time_series.plot_time_series` to plot time series, and
# :func:`~neurodsp.plts.time_series.plot_instantaneous_measure`
# to plot instantaneous measures.
#

###################################################################################################

# Plot signal
# Simulate an Example Signal
# --------------------------
#
# First, we'll simulate an example signal that starts with a burst of alpha activity, followed
# by a period of only aperiodic activity.
#

###################################################################################################

# Set time and sampling rate
n_seconds_burst = 1
n_seconds_noise = 2
fs = 1000

# Create a times vector
times = create_times(n_seconds_burst + n_seconds_noise, fs)

# Simulate a signal component with an oscillation
components = {'sim_powerlaw': {'exponent': 0}, 'sim_oscillation': {'freq': 10}}
s1 = sim_combined(n_seconds_burst, fs, components, [0.1, 1])

# Simulate a signal component with just noise
s2 = sim_powerlaw(n_seconds_noise, fs, 0, variance=0.1)

# Join signals together to approximate a 'burst'
sig = np.append(s1, s2)

###################################################################################################

# Plot example signal
plot_time_series(times, sig)
Esempio n. 9
0
# Set the random seed, for consistency simulating data
np.random.seed(0)

###################################################################################################
#
# 1. Bandpass filter
# ------------------
#
# Extract signal within a specific frequency range (e.g. theta, 4-8 Hz).
#

###################################################################################################

# Generate an oscillation with noise
fs = 1000
times = create_times(4, 1000)
sig = np.random.randn(len(times)) + 5 * np.sin(times * 2 * np.pi * 6)

###################################################################################################

# Filter the data, across a frequency band of interest
f_range = (4, 8)
sig_filt = filt.filter_signal(sig, fs, 'bandpass', f_range)

###################################################################################################

# Plot filtered signal
plot_time_series(times, [sig, sig_filt], ['Raw', 'Filtered'])

###################################################################################################
#
#

###################################################################################################

# Parameters for simulated signal
n_samples = 5000
fs = 1000
burst_freq = 10
burst_starts = [0, 3000]
burst_seconds = 1
burst_samples = burst_seconds*fs

###################################################################################################

# Design burst kernel
burst_kernel_t = create_times(burst_seconds, fs)
burst_kernel = 2*np.sin(burst_kernel_t*2*np.pi*burst_freq)

# Generate random signal with bursts
times = create_times(n_samples/fs, fs)
sig = np.random.randn(n_samples)
for ind in burst_starts:
    sig[ind:ind+burst_samples] += burst_kernel

###################################################################################################

# Plot example signal
plot_time_series(times, sig)

###################################################################################################
#
Esempio n. 11
0
# Set the sampling rate
fs = 1000

# Set time for each segment of the simulated signal, in seconds
t_osc = 1  # oscillation
t_ap = 2  # aperiodic

# Set the frequency of the oscillation
freq = 10

# Set the exponent value for the aperiodic activity
exp = -1

# Create a times vector
times = create_times(t_osc + t_ap, fs)

###################################################################################################
# Create the simulated data
# ~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Next, we will create our simulated data, by concatenating simulated segments of data
# with and without a rhythm.
#

###################################################################################################

# Simulate a signal component with an oscillation
components = {
    'sim_oscillation': {
        'freq': freq
               'high_gamma' : [50, 150]})

###################################################################################################
# Simulating Data
# ~~~~~~~~~~~~~~~
#
# We will use simulated data for this example, to create some example aperiodic signals,
# that we can then apply filters to. First, let's simulate some data.
#

###################################################################################################

# Simulation settings
s_rate = 1000
n_seconds = 4
times = create_times(n_seconds, s_rate)

# Set random seed, for consistency generating simulated data
set_random_seed(21)

###################################################################################################

# Simulate a signal of aperiodic activity: pink noise
sig = sim_powerlaw(n_seconds, s_rate, exponent=-1)

###################################################################################################

# Plot our simulated time series
plot_time_series(times, sig)

###################################################################################################
Esempio n. 13
0
import matplotlib.pyplot as plt
from neurodsp.sim import sim_oscillation, sim_bursty_oscillation
from neurodsp.utils import set_random_seed
from neurodsp.utils import create_times
from neurodsp.plts.time_series import plot_time_series

time = 1.5
sampling_rate = 100
oscillation_freq = 1
set_random_seed(0)
oscillation_sine = sim_oscillation(time,
                                   sampling_rate,
                                   oscillation_freq,
                                   cycle='sine')
timeSequenceMatrix = create_times(time, sampling_rate)
print("TIME : " + str(len(timeSequenceMatrix)))
print(timeSequenceMatrix)
print("OSCILACION : " + str(len(oscillation_sine)))
print(oscillation_sine)
plt.scatter(timeSequenceMatrix, oscillation_sine)
plt.show()
plot_time_series(timeSequenceMatrix, oscillation_sine)
Esempio n. 14
0
def predict_and_plot_sstaging(data_path, data_file):
    print("I am here", os.getcwd())
    model = keras.models.load_model('flaskapp/model')

    data_path = Path(data_path)
    record = data_file

    annotation_dict = defaultdict(lambda: 5, {
        '1': 0,
        '2': 1,
        '3': 2,
        '4': 2,
        'R': 3
    })

    classes = defaultdict(lambda: '6', {
        '1000': '1',
        '0100': '2',
        '0010': '3',
        '0001': '4',
        '0000': '5'
    })

    class_count = defaultdict(lambda: 0, {
        '1000': 0,
        '0100': 0,
        '0010': 0,
        '0001': 0,
        '0000': 0
    })

    annsamp = wfdb.rdann(str(data_path / record),
                         extension='st', summarize_labels=True)

    signal = wfdb.rdrecord(str(data_path / record), channels=[2])
    physical_signal = signal.p_signal
    physical_signal = preprocessing.scale(physical_signal)

    number_annotations = len(annsamp.aux_note)

    starting_index = int((len(physical_signal) / 7500) -
                         number_annotations)*7500
    physical_signal = physical_signal[starting_index:]
    inputs = np.split(physical_signal, number_annotations)
    annots = list()
    target = [[0]*4 for _ in range(number_annotations)]

    for annotation_index in range(number_annotations):

        labels = annsamp.aux_note[annotation_index].split(' ')
        labels = [_l.strip('\x00') if type(_l) == str else str(_l)
                  for _l in labels]
        for label in labels:
            if annotation_dict[label] != 5:
                target[annotation_index][annotation_dict[label]] = 1

        event_class = ''.join([str(v) for v in target[annotation_index]])
        event_class = classes[event_class]

        annots.append(event_class)
    annots_c = to_categorical(annots)
    inputs = np.array(inputs)
    y_pred = model.predict(inputs)

    y_pred_c = y_pred.argmax(axis=1)

    y_pred_c = y_pred_c.tolist()

    S1 = 0
    S2 = 0
    S3 = 0
    R = 0
    W = 0
    for i in y_pred_c:
        if i == 1:
            S1 += 1
        elif i == 2:
            S2 += 1
        elif i == 3:
            S3 += 1
        elif i == 4:
            R += 1
        else:
            W += 1
    annots = np.array(annots).astype(np.int)

    annotation_dict1 = defaultdict(
        lambda: 5, {
            'S1': 1,
            'S2': 2,
            'S3': 3,
            'R': 4,
            'W': 5
        }
    )

    matplotlib.rcParams['agg.path.chunksize'] = 10000

    fig, ax = plt.subplots(figsize=(50, 20))
    plt.rcParams["axes.linewidth"] = 3
    plt.xticks(fontsize=50)
    plt.yticks(fontsize=50)
    plt.title('Hypno Çizimi', fontsize=50)

    plt.tick_params(axis='both', pad=30)
    plt.yticks(range(1, len(annotation_dict1.keys())+1),
               annotation_dict1.keys())

    plt.plot(y_pred_c, color='blue', linewidth=5)

    figfile = BytesIO()
    plt.savefig(figfile, format='png')
    figfile.seek(0)
    print(figfile)
    global figure
    figure = base64.b64encode(figfile.getvalue()).decode('ascii')
    plt.savefig("./flaskapp/static/images"+"/" +
                record+"_hypno.png", format='png')

    plt.clf()
    plt.cla()
    gc.collect()

    fs = 250

    times = create_times(len(physical_signal)/fs, fs)

    plt.rcParams['axes.linewidth'] = 5
    plt.rcParams["figure.figsize"] = (40, 50)
    plt.title('Epoch Çizimi', fontsize=50)

    plt.tick_params(axis='both', pad=45)

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

    # plt.xlabel('time (s)', fontsize=100, labelpad=50)
    # plt.ylabel('Voltage (mV)', fontsize=100, labelpad=50)

    plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower'))

    plt.plot(times, physical_signal, linewidth=6)

    figfile1 = BytesIO()
    plt.savefig(figfile1, format='png')
    figfile1.seek(0)
    global figure2
    figure2 = base64.b64encode(figfile1.getvalue()).decode('ascii')
    plt.savefig("./flaskapp/static/images"+"/" +
                record + "_epochs.png", format='png')

    plt.clf()
    plt.cla()
    gc.collect()

    total = len(annots)
    eq = 0
    for i in range(len(annots)):
        if annots[i] == y_pred_c[i]:
            eq += 1

    f = open("./flaskapp/"+data_file + ".txt", "w")
    f.write("Toplam uyku süresi:" + str(total/2) + " dakika\n")
    f.write("S1:" + str(S1) + " dakika\n")
    f.write("S2:" + str(S2) + " dakika\n")
    f.write("S3:" + str(S3) + " dakika\n")
    f.write("R:" + str(R) + " dakika\n")
    f.write("W:" + str(W) + " dakika\n")
    f.close()
    global read_file
    read = open("./flaskapp/"+data_file + ".txt")

    global info
    info = read.read()
    read_file = read.readlines()

    ss_labels = ["S1", "S2", "S3", "R", "W"]
    ss_values = [S1, S2, S3, R, W]
    ss_explode = (0, 0, 0.1, 0, 0)

    fig1, ax1 = plt.subplots(figsize=(40, 30))

    ax1.pie(ss_values, explode=ss_explode, labels=ss_labels, autopct='%1.1f%%',
            shadow=False, startangle=90, textprops={'fontsize': 60})
    ax1.axis('equal')
    figfile2 = BytesIO()
    plt.savefig(figfile2, format='png')
    figfile2.seek(0)
    global figure3
    figure3 = base64.b64encode(figfile2.getvalue()).decode('ascii')

    plt.savefig("./flaskapp/static/images"+"/" +
                record + "_pie.png", format='png')

    plt.clf()
    plt.cla()
    gc.collect()