def figure_problems_noise_correlations_histogram(noise_type, noise_info, filename_format=None):
    """Savepath should be a string with {noise_type} to fill in a lowercase name of the noise"""
    correlation_threshold = 0.05

    correlation = noise_info['correlations']
    title = noise_info['title']

    ratio = sum(abs(correlation) <= correlation_threshold) / len(correlation)

    print(f"Details about {noise_info['title']}:")
    print(f"n = {len(correlation)}")
    print(f"mean = {np.mean(correlation)}, var = {np.var(correlation)}")
    print(f"{ratio * 100}% of the correlations are below the threshold of {correlation_threshold}")

    num_bins = 400
    stepwidth = 2 / num_bins
    noise_histogram, bins = np.histogram(correlation, bins=num_bins, range=(-1, 1))

    fig, ax = plt.subplots(figsize=(5.0, 3.8))
    ax.bar(x=bins[:-1] + stepwidth, height=noise_histogram, width=stepwidth)

    ax.set_xlabel('Correlation')

    ax.set_ylabel('Count / 0.005')
    # ax.set_title(title)

    fig.show()

    if filename_format:
        filename = filename_format.format(noise_type=noise_type.lower())
        plu.save_figure(fig, filename, noise_type=noise_type,
                        samples=len(correlation),
                        correlation_threshold=correlation_threshold,
                        below_threshold=ratio,
                        correlation_source="FigureMethodsNoiseCorrelations.m")
def figure_methods_injected_currents_frequency(runnumber, l2, filename_currents=None, filename_frequency=None):
    ### Define injected currents
    num = 40
    i_inh = np.linspace(0.4, 2.0, num)
    i_exc = 0.4652 * i_inh ** 4 - 1.9860 * i_inh ** 3 + 3.2879 * i_inh ** 2 - 1.0623 * i_inh + 0.7546

    xaxis = range(1, 41)
    ### Plot curves of injected currents:
    fig_currents, ax = plt.subplots()
    sns.lineplot(xaxis, i_exc, ax=ax, label=r'$I_{inj}^{exc}$', color='red')
    sns.lineplot(xaxis, i_inh, ax=ax, label=r'$I_{inj}^{inh}$', color='blue')

    ax.set_ylabel('Injected current (${\mu A / cm^2}$)')
    ax.set_xlabel("Index of injected currents")

    # ax.set_title("Injected currents $I_{inj}^{inh}$ and $I_{inj}^{exc}$")
    fig_currents.show()

    plu.save_figure(fig_currents, filename_currents, runnumbers=[runnumber], l2=l2)

    # if savefigures:
    #     fig_currents.savefig(os.path.join(settings.py_figures_dir, f'figure_injected_currents_exc_inh.png'), bbox_inches='tight', pad_inches=0.1)

    ### Get frequency and PPC curve of runnumber
    analysis_standard_df_reg1, analysis_standard_df_reg2 = mlu.run_analysis_standard_to_df(runnumber=runnumber)
    freqe = analysis_standard_df_reg1['freqe'].loc[:, l2]
    avgmorfreq = analysis_standard_df_reg1['avgmorfreq'].loc[:, l2]
    phaselocke = analysis_standard_df_reg1['Phaselocke'].loc[:, l2]

    ### Plot curves of frequency and PPC (Phaselock)
    fig_frequency, ax_freq = plt.subplots()

    ax_phaselock = ax_freq.twinx()
    # ax_phaselock.axhline(y=0.1, color='black', alpha=0.9, linestyle='--')  # Threshold line for extremely low PPC (i.e., no real oscillations)
    sns.lineplot(y=phaselocke, x=xaxis, ax=ax_phaselock, label='PPC value', color='black')

    ax_phaselock.set_ylim([0, 0.8])
    ax_phaselock.set_ylabel("PPC value")

    sns.lineplot(y=avgmorfreq, x=xaxis, ax=ax_freq, label='Frequency (Morlet)')
    sns.lineplot(y=freqe, x=xaxis, ax=ax_freq, label='Frequency (Autocorrelation)')

    # ax_freq.set_xticklabels(np.linspace(1, 40, 41))
    ax_freq.set_xlim(left=0, right=41)
    ax_freq.set_xlabel("Index of injected currents")
    ax_freq.set_ylim([35, 75])
    ax_freq.set_ylabel("Frequency (Hz)")

    ax_freq.legend(loc='upper left')
    # ax_freq.set_title("Intrinsic frequency and PPC")

    fig_frequency.show()

    plu.save_figure(fig_frequency, filename_frequency, runnumbers=[runnumber], l2=l2)
Esempio n. 3
0
def figure_results_correlation_boxplots_compare_thresholds(
        runnumbers_sett, filename_format, analysis_info2_name,
        compare_thresholds):
    """

    :param runnumbers_sett:
    :param filename_format: Needs {analysis_info2_name}!
    :param analysis_info2_name:
    :param compare_thresholds:
    :return:
    """

    corr_df2 = __figure_results_correlation_boxplots_prepare_df(
        runnumbers_sett)

    fig, ax = plt.subplots(ncols=2, sharey=True, figsize=figsize)

    for i, threshold in enumerate(compare_thresholds):
        sns.violinplot(x='feedback',
                       y=analysis_info2_name,
                       hue='Noiseseed',
                       split=True,
                       data=corr_df2[corr_df2['coh'] >= threshold],
                       ax=ax[i],
                       scale='count',
                       inner='box',
                       cut=0,
                       linewidth=1.5)
        if threshold == 0:
            ax[i].set_title("All conditions")
            pass
        else:
            ax[i].set_title(f"Threshold $\geq$ {threshold}")
            pass
        ax[i].set_xlabel(r"Feedback $g_{{2 \to 1}}^{{e \to i}}$ in $mS/cm^2$")

    # fig.suptitle(mlu.derive_analysis_info2_title(analysis_info2_name))

    ax[0].set_ybound(None, 1)
    ax[0].set_ylabel('Correlation')
    ax[0].get_legend().remove()
    fig.show()

    if filename_format:
        filename = filename_format.format(
            analysis_info2_name=analysis_info2_name)
        plu.save_figure(fig, filename=filename, runnumbers=runnumbers_sett)
Esempio n. 4
0
def plot_3_ts(dates,
              data_1,
              data_2,
              data_3,
              x_label,
              y1_label,
              y2_label,
              y3_label,
              title,
              save=False):
    fig, axarr = plt.subplots(3, sharex=True, sharey=False)
    axarr[0].plot(dates, data_1)
    axarr[1].plot(dates, data_2)
    axarr[2].plot(dates, data_3)
    axarr[0].set_ylabel(y1_label)
    axarr[1].set_ylabel(y2_label)
    axarr[2].set_ylabel(y3_label)
    axarr[2].set_title(title, y=-0.75, fontsize=16)
    if save: pu.save_figure(plt, title, 'compare', lgd=None)
Esempio n. 5
0
def figure_results_correlation_boxplots_compare_signals(
        runnumbers_sett, filename_format, compare_signals):
    """

    :param filename_format: Needs {compare_signal0} and {compare_signal1}!
    :param runnumbers_sett:
    :param compare_signals:
    :return:
    """
    corr_df2 = __figure_results_correlation_boxplots_prepare_df(
        runnumbers_sett)

    fig, ax = plt.subplots(ncols=2, sharey=True, figsize=figsize)

    for i, analysis_info2_name in enumerate(compare_signals):
        means = corr_df2.groupby(['feedback', 'Noiseseed'],
                                 as_index=False).mean()[analysis_info2_name]
        print(means)
        sns.violinplot(x='feedback',
                       y=analysis_info2_name,
                       hue='Noiseseed',
                       split=True,
                       data=corr_df2,
                       ax=ax[i],
                       scale='count',
                       inner='box',
                       cut=0,
                       linewidth=1.5)
        ax[i].set_ylabel('')
        ax[i].set_title(mlu.derive_analysis_info2_title(analysis_info2_name))
        ax[i].set_xlabel(r"Feedback $g_{{2 \to 1}}^{{e \to i}}$ in $mS/cm^2$")

    ax[0].set_ybound(None, 1.1)
    ax[0].set_ylabel('Correlation')
    ax[0].get_legend().remove()
    fig.show()

    if filename_format:
        filename = filename_format.format(compare_signal0=compare_signals[0],
                                          compare_signal1=compare_signals[1])
        plu.save_figure(fig, filename=filename, runnumbers=runnumbers_sett)
Esempio n. 6
0
def methods_coherence_slepian_sequences(T, TW, filename=None):
    # Generate the slepian sequences, here using the time-halfbandwith-product
    [w, eigens] = spectrum.dpss(T, TW / 2, 4)

    # fig, ax = plt.subplots(figsize=(8, 5))
    fig, ax = plt.subplots(figsize=(6, 4.4))
    # ax.canvas(200, 350)

    sns.lineplot(data=w, ax=ax)

    ax.set_xlim([100, 900])
    ax.set_xlabel(r"Time t in $ms$")

    ax.set_ylim([-0.12, 0.12])

    ax.legend(['1st sequence', '2nd sequence', '3rd sequence', '4th sequence'])
    # ax.set_title(f"Slepian sequences for T={T}, TW={TW}")

    fig.show()

    plu.save_figure(fig, filename, T=T, TW=TW)
def figure_problemns_noise_compare(noise_type, filename_format):
    """
    Savepath should be a string with {noise_type} to fill a lowercase name of the noise in
    :param savepath:
    :return:
    """
    noise_examples = mlu.loadmat('./mat/noise_examples.mat')

    Fs = 20  # Sampling rate: samples/millisecond
    T = 1000  # plot T seconds of noise

    noise_example = noise_examples[noise_type]

    n = len(noise_example)  # Number of points

    x = np.linspace(0, T, T*Fs)


    fig, ax = plt.subplots()
    for region in [0, 1]:
        y = noise_example[region][0:T * Fs]
        sns.lineplot(x, y, ax=ax, label=f"Noise to region {region+1}")

    ax.set_ylim([-1.2, 1.2])
    ax.legend(loc='upper left')

    # ax.set_title(f"{noise_type} noise")

    ax.set_xlabel("Time t in $ms$")
    ax.set_ylabel("$I_{noise}$ in $\mu A/cm^2$")

    fig.show()

    if filename_format:
        filename = filename_format.format(noise_type=noise_type.lower())
        plu.save_figure(fig, filename, noise_type=noise_type, source='FigureMethodsNoiseExamples.m')
def methods_analysis_spike_density_histogram(runnumber,
                                             l1,
                                             l2,
                                             region,
                                             start,
                                             stop,
                                             filename=None):
    sett = mlu.get_clean_settings(runnumber)['sett']
    spikes_excitatory, spikes_inhibitory = mlu.get_spiketrains_df(
        runnumber, l1, l2)

    spikes_excitatory[
        'neuron_idx'] = spikes_excitatory['neuron_idx'] + sett['Ni']

    # Filter for region
    spikes_excitatory = spikes_excitatory[spikes_excitatory['region'] ==
                                          region]
    spikes_inhibitory = spikes_inhibitory[spikes_inhibitory['region'] ==
                                          region]

    # Filter for start <= t <= end
    spikes_excitatory = spikes_excitatory[spikes_excitatory['t'] >= start]
    spikes_excitatory = spikes_excitatory[spikes_excitatory['t'] <= stop]

    spikes_inhibitory = spikes_inhibitory[spikes_inhibitory['t'] >= start]
    spikes_inhibitory = spikes_inhibitory[spikes_inhibitory['t'] <= stop]

    # Bin the spikes for histograms
    bins = np.linspace(start=start,
                       stop=stop,
                       num=int((stop - start) / sett['dthist'] + 1),
                       endpoint=True)
    excitatory_spikes_binned, _ = np.histogram(spikes_excitatory['t'],
                                               bins=bins)
    inhibitory_spikes_binned, _ = np.histogram(spikes_inhibitory['t'],
                                               bins=bins)

    excitatory_spikes_density = 1000 * 1 / (
        sett['dthist'] * sett['Ne']) * excitatory_spikes_binned
    inhibitory_spikes_density = 1000 * 1 / (
        sett['dthist'] * sett['Ni']) * inhibitory_spikes_binned

    fig, ax = plt.subplots(nrows=2, sharex=True, figsize=(10, 4.5))

    ax[0].bar(x=bins[:-1],
              height=excitatory_spikes_density,
              color='red',
              label='Pyramidal cells')
    ax[1].bar(x=bins[:-1],
              height=inhibitory_spikes_density,
              color='blue',
              label='Interneurons')

    handles = [
        mpatches.Patch(color='red', label='Pyramidal cells'),
        mpatches.Patch(color='blue', label='Interneurons')
    ]

    ax[0].legend(handles=handles, loc='upper right')

    ax[1].invert_yaxis()
    fig.subplots_adjust(wspace=0, hspace=0)

    ax[1].set_xlabel('Time t ($ms$)')
    ax[0].set_ylabel('Spikes/s')
    ax[1].set_ylabel('Spikes/s')

    # ax[0].set_title(
    #     f"Pyramidal cell (upper) and interneuron (lower) spike density plots")

    fig.show()

    ppc_value = mlu.run_analysis_standard_to_df(runnumber)[
        region - 1]['Phaselocke'][l1 - 1, l2 - 1]

    plu.save_figure(fig,
                    filename,
                    runnumbers=[runnumber],
                    l1=l1,
                    l2=l2,
                    region=region,
                    start=start,
                    stop=stop,
                    ppc_value=ppc_value)
def methods_analysis_spikes_scatterplot(runnumber,
                                        l1,
                                        l2,
                                        region,
                                        start,
                                        stop,
                                        filename=None):
    sett = mlu.get_clean_settings(runnumber)['sett']
    spikes_excitatory, spikes_inhibitory = mlu.get_spiketrains_df(
        runnumber, l1, l2)

    spikes_excitatory[
        'neuron_idx'] = spikes_excitatory['neuron_idx'] + sett['Ni']

    # Filter for region
    spikes_excitatory = spikes_excitatory[spikes_excitatory['region'] ==
                                          region]
    spikes_inhibitory = spikes_inhibitory[spikes_inhibitory['region'] ==
                                          region]

    # Filter for start <= t <= end
    spikes_excitatory = spikes_excitatory[spikes_excitatory['t'] >= start]
    spikes_excitatory = spikes_excitatory[spikes_excitatory['t'] <= stop]

    spikes_inhibitory = spikes_inhibitory[spikes_inhibitory['t'] >= start]
    spikes_inhibitory = spikes_inhibitory[spikes_inhibitory['t'] <= stop]

    # Plot spikes in scatterplot
    fig, ax = plt.subplots(figsize=(10, 4))

    sns.scatterplot(x='t',
                    y='neuron_idx',
                    color='red',
                    s=6,
                    data=spikes_excitatory,
                    ax=ax,
                    label='Pyramidal Cells')
    sns.scatterplot(x='t',
                    y='neuron_idx',
                    color='blue',
                    s=6,
                    data=spikes_inhibitory,
                    ax=ax,
                    label='Interneurons')
    ax.set_ylim(ymin=-20)
    ax.set_ylabel('Neuron index')
    ax.set_xlabel('Time t ($ms$)')
    ax.legend(loc='upper left')

    # ax.set_title('Pyramidal cell (red) and interneuron (blue) spiketrains')

    # Create dummy Line2D objects for legend
    h1 = Line2D([0], [0],
                marker='o',
                markersize=np.sqrt(30),
                color='red',
                linestyle='None')
    h2 = Line2D([0], [0],
                marker='o',
                markersize=np.sqrt(30),
                color='blue',
                linestyle='None')

    ax.legend([h1, h2], ['Pyramidal cells', 'Interneurons'], loc='upper right')

    fig.show()

    ppc_value = mlu.run_analysis_standard_to_df(runnumber)[
        region - 1]['Phaselocke'][l1 - 1, l2 - 1]
    print('ppc_value: ', ppc_value)

    plu.save_figure(fig,
                    filename,
                    runnumbers=[runnumber],
                    l1=l1,
                    l2=l2,
                    region=region,
                    start=start,
                    stop=stop,
                    ppc_value=ppc_value)
Esempio n. 10
0
def figure_problems_noise_to_region_correlation_vs_frequency(
        region_to, filename=None):
    noise_types = {
        'brown10': {
            'runnumbers': [117, 118, 122],
            'title': "Strong Brown noise",
            'color': '#572b0c',  # Saddle Brown
            'style': '-',
        },
        'brown05': {
            'runnumbers': [140, 134, 141],
            'title': "Weak Brown noise",
            'color': '#9c4e15',  # Saddle Brown
            'style': '--',
        },
        'pink': {
            'runnumbers': [112, 115, 114],
            'title': "Pink noise",
            'color': '#FF1493',  # Deep Pink
            'style': '-.'
        },
        'white': {
            'runnumbers': [123, 156, 157],
            'title': "White noise",
            'color': '#808080',  # Web Gray
            'style': ':'
        },
    }

    analysis_info2_name = f'rhos_fper_noise1_reg{region_to}'
    # analysis_info2_lag = f'{analysis_info2_name}_lag0'
    method = mlu.METHOD_CORRELATION_MAX

    fig, ax = plt.subplots()

    for noise_type, noise_details in noise_types.items():
        runnumbers = noise_details['runnumbers']

        correlation_dfs = [
            mlu.get_run_correlations(
                runnumber, method, [analysis_info2_name])[analysis_info2_name]
            for runnumber in runnumbers
        ]

        correlation_mean_line = pd.concat(correlation_dfs).groupby(
            level=[0]).mean()

        print(f"Details about {noise_details['title']}:")
        print(f"Mean {np.mean(correlation_mean_line)}")

        noise_details['correlation_mean'] = np.mean(correlation_mean_line)

        ax.plot(correlation_mean_line,
                color=noise_details['color'],
                label=noise_details['title'],
                linestyle=noise_details['style'])

    ax.set_xlabel("Intrinsic frequency of region 1 ($Hz$)")
    ax.set_xticks(np.linspace(0, 39, 7))
    xticklabels = np.linspace(35, 65, 7)
    ax.set_xticklabels(xticklabels)

    ax.set_ylabel("Correlation")
    ax.set_ylim(-0.08, 1.02)

    # ax.set_title(f"Mean correlation between noise$_1$ and firing rate of region {region_to}")
    ax.legend(loc='upper right', bbox_to_anchor=(1, 0.92))

    fig.show()

    plu.save_figure(fig,
                    filename,
                    region_to=region_to,
                    noise_types=noise_types)
def figure_results_feedforward_conductance_frequency(runnumber, l1,
                                                     filename_format):
    """
    Plots the change in region 2 frequency in dependence on the total synaptic conductance from region 1 to region 2
    :param runnumber:
    :param l1:
    :param filename_format:
    :return:
    """

    sett = mlu.get_clean_settings(runnumber)['sett']
    feedback_conductance_ei = sett['g_syn_ei_r'][0, 1]

    run_settings_loops = mlu.get_run_loops(runnumber)
    analysis_standard_reg1_df, analysis_standard_reg2_df = mlu.run_analysis_standard_to_df(
        runnumber)

    avgmorfreqs1 = analysis_standard_reg1_df['avgmorfreq'][l1]
    avgmorfreqs2 = analysis_standard_reg2_df['avgmorfreq'][l1]

    i_inj_exc = run_settings_loops[1]['values_excitatory'][l1].round(2)
    i_inj_inh = run_settings_loops[1]['values_inhibitory'][l1].round(2)

    synaptic_conductances = run_settings_loops[2]['values'].round(2)

    print(f"Frequency of region 1: {avgmorfreqs1[0]}")
    print(f"Starting frequency of region 2: {avgmorfreqs2[0]}")
    print(f"Ending frequency of region 2: {list(avgmorfreqs2)[-1]}")

    fig, ax = plt.subplots(figsize=(6.4, 4.4))

    sns.scatterplot(x=synaptic_conductances,
                    y=avgmorfreqs1,
                    s=30,
                    ax=ax,
                    label="Region 1")
    sns.scatterplot(x=synaptic_conductances,
                    y=avgmorfreqs2,
                    s=30,
                    ax=ax,
                    label="Region 2")

    ax.set_xlabel(
        r"Total synaptic conductance $g_{1 \to 2}^{e \to e, i}$ ($mS/cm^2$)")
    ax.set_ylim([39, 71])

    ax.set_ylabel('Frequency ($Hz$)')

    # ax.set_title(f"Frequency modulation through synaptic conductance")
    ax.legend(loc='upper left')

    if feedback_conductance_ei != 0:
        text = mlu.get_infobox_text(
            feedback_conductance_ee=None,
            feedback_conductance_ei=feedback_conductance_ei)
        # text = f"$reg_{2}^{{exc}} \\rightarrow reg_{1}^{{inh}}={feedback_conductance_ei} mS/cm^2$"
        plu.set_textbox(ax, text, loc='upper right')

    fig.show()

    if filename_format:
        filename = filename_format.format(runnumber=runnumber, l1=l1)
        plu.save_figure(fig,
                        filename,
                        runnumbers=[runnumber],
                        l1=l1,
                        i_inj_exc=i_inj_exc,
                        i_inj_inh=i_inj_inh,
                        reg1_freq=avgmorfreqs1[0],
                        reg2_freq_start=avgmorfreqs2[0],
                        reg2_freq_end=list(avgmorfreqs2)[-1])
def figure_appendix_analysis_standard_heatmap_with_feedback(
        runnumbers,
        region,
        analysis_standard_name,
        filename_format,
        debug=False):
    """
    :param runnumbers: All runnumbers need to have the same settings except seed!
    :param filename: needs {analysis_standard_name} {feedback_conductance_ee} and {feedback_conductance_ei} and {region}
    :return:
    """

    sett = mlu.get_clean_settings(runnumbers[0])['sett']
    feedback_conductance_ee = sett['g_syn_ee_r'][0, 1]
    feedback_conductance_ei = sett['g_syn_ei_r'][0, 1]

    # Compute the means for standard analyses
    analyses_standard = {}

    group_analyses_standard_reg = [
        mlu.run_analysis_standard_to_df(runnumber)[region]
        for runnumber in runnumbers
    ]
    analyses_standard[region] = pd.concat(group_analyses_standard_reg).groupby(
        level=[0, 1]).mean()

    # # Compute the mean over all runnumbers for standard2 analysis
    # analyses_standard2_dfs = [mlu.run_analysis_standard2_to_df(runnumber) for runnumber in runnumbers]
    # analysis_standard2_mean = pd.concat(analyses_standard2_dfs).groupby(level=[0, 1]).mean()

    if analysis_standard_name in ['Phaselocke', 'Phaselocki']:
        vmin = 0
        vmax = 1
    elif analysis_standard_name in [
            'freqe', 'freqi', 'avgmorfreq', 'avgmorfreqi'
    ]:
        vmin = 35
        vmax = 80
    elif analysis_standard_name in ['re', 'ri']:
        vmin = 10
        vmax = 100
    else:
        vmin = None
        vmax = None

    ## Plotting coherence
    fig, ax = plt.subplots()

    sns.heatmap(analyses_standard[region]
                [analysis_standard_name].unstack().transpose(),
                ax=ax,
                vmin=vmin,
                vmax=vmax,
                cmap='inferno')

    ax.invert_yaxis()
    plu.set_heatmap_axes(ax)
    analysis_title = mlu.analysis_standard_names[
        analysis_standard_name] if not mlu.analysis_standard_names[
            analysis_standard_name] == "" else analysis_standard_name
    ax.set_title(f'{analysis_title} of region {region+1}')

    text = mlu.get_infobox_text(
        feedback_conductance_ei=feedback_conductance_ei,
        feedback_conductance_ee=feedback_conductance_ee,
        runnumbers=runnumbers,
        debug=debug,
        show_info_fb_inh=True)

    plu.set_textbox(ax, text)

    fig.show()

    if filename_format:
        # Convert the float into a string. We are always <1, so cut off everything in front of decimal
        feedback_conductance_ee_str = "{:4.3f}".format(
            feedback_conductance_ee).replace(".", "_")[2:]
        feedback_conductance_ei_str = "{:4.3f}".format(
            feedback_conductance_ei).replace(".", "_")[2:]

        filename = filename_format.format(
            feedback_conductance_ee=feedback_conductance_ee_str,
            feedback_conductance_ei=feedback_conductance_ei_str,
            region=region,
            analysis_standard_name=analysis_standard_name.lower())

        plu.save_figure(fig,
                        filename,
                        runnumbers=runnumbers,
                        feedback_conductance_ee=feedback_conductance_ee,
                        feedback_conductance_ei=feedback_conductance_ei)
def figure_results_correlation_heatmap(runnumbers,
                                       analysis_info2_name,
                                       coherence_threshold,
                                       filename_format,
                                       debug=False,
                                       show_info_fb_inh=True):
    analysis_info2_title = mlu.derive_analysis_info2_title(analysis_info2_name)

    sett = mlu.get_clean_settings(runnumbers[0])['sett']
    feedback_conductance_ee = sett['g_syn_ee_r'][0, 1]
    feedback_conductance_ei = sett['g_syn_ei_r'][0, 1]
    noise_title = mlu.get_noise_title(sett['noiseamp'], sett['noisetype'])

    analysis_standard2_df = mlu.run_analysis_standard2_to_df(runnumbers[0])
    coherences_all = [
        mlu.run_analysis_standard2_to_df(runnumber) for runnumber in runnumbers
    ]
    coherences = pd.concat(coherences_all).groupby(level=[0, 1]).mean()['coh']

    # print(analysis_standard2_df[analysis_standard2_df['coh'] >= coherence_threshold])

    correlations_all = [
        mlu.get_max_correlations(runnumber) for runnumber in runnumbers
    ]
    correlations = pd.concat(correlations_all).groupby(level=[0, 1]).mean()
    correlations = correlations[analysis_info2_name]

    correlations[coherences < coherence_threshold] = np.nan

    print(
        f"{analysis_info2_name}, feedback {feedback_conductance_ei} mS/cm^2. Correlation limits (min, max): ({correlations.min()},{correlations.max()})"
    )

    fig, ax = plt.subplots()

    sns.heatmap(correlations.unstack().transpose(),
                cmap='coolwarm',
                vmin=-0.3,
                vmax=1,
                center=0,
                ax=ax)
    ax.invert_yaxis()

    plu.set_heatmap_axes(ax)

    # Insert a textbox listing the feedback conductance
    text = mlu.get_infobox_text(
        feedback_conductance_ee=feedback_conductance_ee,
        feedback_conductance_ei=feedback_conductance_ei,
        runnumbers=runnumbers,
        debug=debug,
        show_info_fb_inh=True)

    plu.set_textbox(ax, text, loc='lower right')

    # ax.set_title(f"{analysis_info2_title}")

    ax.legend(loc='lower right')

    fig.show()

    if filename_format:
        # Convert the float into a string. We are always <1, so cut off everything in front of decimal
        feedback_conductance_ee_str = "{:4.3f}".format(
            feedback_conductance_ee).replace(".", "_")[2:]
        feedback_conductance_ei_str = "{:4.3f}".format(
            feedback_conductance_ei).replace(".", "_")[2:]
        coherence_threshold_str = "{:3.2f}".format(
            coherence_threshold).replace('.', "")

        filename = filename_format.format(
            analysis_info2_name=analysis_info2_name,
            feedback_conductance_ee=feedback_conductance_ee_str,
            feedback_conductance_ei=feedback_conductance_ei_str,
            coherence_threshold=coherence_threshold_str)

        plu.save_figure(fig,
                        filename,
                        runnumbers=runnumbers,
                        feedback_conductance_ee=feedback_conductance_ee,
                        feedback_conductance_ei=feedback_conductance_ei,
                        analysis_info2_name=analysis_info2_name,
                        coherence_threshold=coherence_threshold)
def figure_results_lag_vs_correlation_lines(runnumber, signal_type, signal_from, region_from, region_to,
                                            coherence_threshold, filename_format=None):
    if region_from == region_to:
        coherence_threshold = 0

    coherences = mlu.run_analysis_standard2_to_df(runnumber)['coh']

    correlations, lags = mlu.run_analysis_info2_to_df(runnumber)
    analysis_info2_name = f'rhos_{signal_type}_{signal_from}{region_from}_reg{region_to}'

    correlations = correlations[analysis_info2_name][coherences >= coherence_threshold]

    maximum_correlations_lags = []
    min_lag = -35
    max_lag = 30  # in ms

    title = mlu.derive_analysis_info2_title(analysis_info2_name)

    fig, ax = plt.subplots(figsize=(10, 5))

    for index_condition in correlations.unstack(2).index:
        condition_correlations = correlations.loc[index_condition]
        condition_lags = lags

        sns.lineplot(x=condition_lags, y=condition_correlations, zorder=10)

        #### Filtering:
        condition_correlations[condition_lags > mlu.CORRELATION_TMAX] = 0
        condition_correlations[condition_lags < mlu.CORRELATION_TMIN] = 0


        condition_idx_of_max_correlation = condition_correlations.idxmax()
        filtered_lag = condition_lags[condition_idx_of_max_correlation]
        maximum_correlations_lags.append(filtered_lag)

    maximum_correlation_histogram, _ = np.histogram(maximum_correlations_lags, bins=lags)

    ax.axvline(mlu.CORRELATION_TMIN, linestyle='--', c='grey')
    ax.axvline(mlu.CORRELATION_TMAX, linestyle='--', c='grey')


    ax.set_xlim([mlu.CORRELATION_TMIN - 5, mlu.CORRELATION_TMAX + 5])
    ax.set_xlabel('Lag $\Delta t$ in ms')

    ax.set_ylabel('Correlation')
    ax.set_ylim([-0.1, 1])

    ax2 = ax.twinx()
    ax2.bar(x=lags[:-1], height=maximum_correlation_histogram, width=0.5, zorder=1, alpha=0.6)

    # ax2.set_yticks(np.arange(0, max(maximum_correlation_histogram)+1), 5)
    ax2.set_ylabel("Count")

    # ax.set_title(
    #     f'{title} vs Lag')

    fig.show()

    if filename_format:
        filename = filename_format.format(runnumber=runnumber, analysis_info2_name=analysis_info2_name)
        plu.save_figure(fig, filename, analysis_info2_name=analysis_info2_name, coherence_threshold=coherence_threshold)
Esempio n. 15
0
def figure_results_coherence_heatmap_with_feedback(runnumbers,
                                                   filename_format,
                                                   show_info_fb_inh=True,
                                                   debug=False):
    """
    :param runnumbers: All runnumbers need to have the same settings except seed!
    :param filename: needs {feedback_conductance_ee} and {feedback_conductance_ei}
    :return:
    """
    sett = mlu.get_clean_settings(runnumbers[0])['sett']
    feedback_conductance_ee = sett['g_syn_ee_r'][0, 1]
    feedback_conductance_ei = sett['g_syn_ei_r'][0, 1]

    # Compute the mean over all runnumbers for standard2 analysis
    analyses_standard2_dfs = [
        mlu.run_analysis_standard2_to_df(runnumber) for runnumber in runnumbers
    ]
    analysis_standard2_mean = pd.concat(analyses_standard2_dfs).groupby(
        level=[0, 1]).mean()

    coherence_mean = analysis_standard2_mean['coh']

    print(
        f"Runs {runnumbers} coherence >= {coherence_threshold}: {sum(coherence_mean >= coherence_threshold)}"
    )

    ## Plotting coherence
    fig, ax = plt.subplots()

    sns.heatmap(coherence_mean.unstack().transpose(),
                cmap='inferno',
                ax=ax,
                vmin=0,
                vmax=1)
    ax.invert_yaxis()

    plu.set_heatmap_axes(ax)

    # ax.set_title(f'Coherence - pyramidal neurons')

    # Insert a textbox listing the feedback conductance
    text = mlu.get_infobox_text(
        feedback_conductance_ee=feedback_conductance_ee,
        feedback_conductance_ei=feedback_conductance_ei,
        debug=debug,
        show_info_fb_inh=show_info_fb_inh)

    plu.set_textbox(ax, text)

    fig.show()

    if filename_format:
        # Convert the float into a string. We are always <1, so cut off everything in front of decimal
        feedback_conductance_ee_str = "{:4.3f}".format(
            feedback_conductance_ee).replace(".", "_")[2:]
        feedback_conductance_ei_str = "{:4.3f}".format(
            feedback_conductance_ei).replace(".", "_")[2:]

        filename = filename_format.format(
            feedback_conductance_ee=feedback_conductance_ee_str,
            feedback_conductance_ei=feedback_conductance_ei_str)

        plu.save_figure(fig,
                        filename,
                        runnumbers=runnumbers,
                        feedback_conductance_ee=feedback_conductance_ee,
                        feedback_conductance_ei=feedback_conductance_ei)
Esempio n. 16
0
def figure_problems_shifting_windows_noise_signal(runnumber, l1, l2, run_frequency, data_source, filename):
    noise_signal_dataset = mlu.loadmat(data_source)

    dthist = 0.5

    t_start = 0
    t_stop = 500

    noise_shift = int(1000 / (run_frequency * dthist))

    idx_stop = int(t_stop / dthist) + noise_shift

    sig_noise = noise_signal_dataset['sig_noise']
    sig_fper = noise_signal_dataset['sigfper']
    sig_freq = noise_signal_dataset['sigfreq']

    sig_noise1_norm = norm_signal(sig_noise[0, :idx_stop])
    sig_fper1_norm = norm_signal(sig_fper[:idx_stop, 0])
    sig_fper2_norm = norm_signal(sig_fper[:idx_stop, 1])
    sig_freq1_norm = norm_signal(sig_freq[:idx_stop, 0])
    sig_freq2_norm = norm_signal(sig_freq[:idx_stop, 1])

    n = len(sig_noise1_norm) - noise_shift
    t = n * dthist  # in ms

    x = np.linspace(0, t, n)

    factor = 3.5/6.5
    width = 8
    height = 8*factor
    fig, ax = plt.subplots(figsize=(10, 4.4))

    ax.plot(x, sig_noise1_norm[noise_shift:], color='#9c4e15', label=r'$\rm{Noise}_1$')
    ax.plot(x, sig_fper1_norm[noise_shift:], label='Region 1 Firing rate')
    ax.plot(x, sig_fper1_norm[:-noise_shift], label='Region 1 Firing rate after shift')
    # ax.plot(x, sig_freq1_norm[noise_shift:], label='Region 1 Frequency')
    # ax.plot(x, sig_fper2_norm[noise_shift:], label='Region 2 Firing rate')
    # ax.plot(x, sig_freq2_norm[noise_shift:], label='Region 2 Frequency')


    for arrow_x in [50, 170, 234, 330, 433]:
        # arrow_x = (200)
        arrow_y = sig_fper1_norm[int(arrow_x / dthist) + noise_shift]
        arrow_dx = noise_shift * dthist - 1
        arrow_dy = 0

        ax.arrow(arrow_x, arrow_y, arrow_dx, arrow_dy, head_width=0.015, head_length=5, length_includes_head=True,
                 fc='black')
    # ax.plot(x, sig_freq1_norm[noise_shift:], label='Region 1 Frequency before shift')
    # ax.plot(x, sig_freq1_norm[:-noise_shift], label='Region 1 Frequency')

    # ax.plot(x, sig_fper2_norm[:-noise_shift], label='Region 2 Firing rate')

    ax.legend(loc='upper right')
    ax.set_xlim(t_start, t_stop)
    ax.set_xlabel("Time t ($ms$)")

    ax.set_ylim(-0.1, 1.05)

    ax.set_yticks([])
    ax.set_yticklabels([])

    # ax.set_title("Noise and region signals after shift")

    fig.show()
    print(f"Frequency of the circuit: {run_frequency} Hz")

    plu.save_figure(fig, filename, runnumbers=[runnumber], l1=l1, l2=l2, run_frequency=run_frequency,
                    data_source=data_source)
Esempio n. 17
0
def plot_array(dates, array, title, save=False):
    plt.figure()
    for plot_item in array:
        plt.plot(dates, plot_item)
    plt.title(title, fontsize=16)
    if save: pu.save_figure(plt, title, 'array', lgd=None)