示例#1
0
def fig5():
    _, mask, _, networks, regions, brain_axis = get_template(tpt_name, space)

    tasks = task_order(True)
    df = acw.gen_long_data(tpt_name).groupby(["task", "region"]).mean().reset_index()
    df.metric *= 1000
    output = np.zeros((len(tasks), mask.size))
    for i, task in enumerate(tasks):
        values = and_filter(df, task=task).values
        for reg, pc in values:
            reg_index = np.argmax(regions == reg) + 1
            if reg_index == 0:
                print("0 reg_index in %s" % reg)
            output[i, np.argwhere(mask == reg_index)] = pc
    savemap("fig5.acw.map", output, brain_axis, cifti.Series(0, 1, output.shape[0]))

    tasks = task_order(True)
    df = acz.gen_long_data(tpt_name).groupby(["task", "region"]).mean().reset_index()
    df.metric *= 1000
    output = np.zeros((len(tasks), mask.size))
    for i, task in enumerate(tasks):
        values = and_filter(df, task=task).values
        for reg, pc in values:
            reg_index = np.argmax(regions == reg) + 1
            if reg_index == 0:
                print("0 reg_index in %s" % reg)
            output[i, np.argwhere(mask == reg_index)] = pc
    savemap("fig5.acz.map", output, brain_axis, cifti.Series(0, 1, output.shape[0]))
示例#2
0
def corr():
    df = add_net_meta(normalize(acw.gen_long_data(tpt_name), columns="metric"), get_net("pmc", tpt_name)) \
        .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()
    df1 = add_net_meta(normalize(acz.gen_long_data(tpt_name), columns="metric"), get_net("pmc", tpt_name)) \
        .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()

    correlations = []
    for task in task_order():
        dft = and_filter(df, task=task)
        subjects = dft.subject.unique()
        df_corr = np.zeros((len(subjects), len(subjects)))
        for i in range(len(subjects)):
            df_corr[i, i] = 1
            x = and_filter(dft, subject=subjects[i]).metric
            for j in range(i + 1, len(subjects)):
                y = and_filter(dft, subject=subjects[j]).metric
                df_corr[i, j] = df_corr[j, i] = pearsonr(x, y)[0]
        correlations.append(df_corr)

    correlations1 = []
    for task in task_order():
        dft = and_filter(df1, task=task)
        subjects = dft.subject.unique()
        df_corr = np.zeros((len(subjects), len(subjects)))
        for i in range(len(subjects)):
            df_corr[i, i] = 1
            x = and_filter(dft, subject=subjects[i]).metric
            for j in range(i + 1, len(subjects)):
                y = and_filter(dft, subject=subjects[j]).metric
                df_corr[i, j] = df_corr[j, i] = pearsonr(x, y)[0]
        correlations1.append(df_corr)

    min_val, max_val = 0, 1
    ticks = np.arange(min_val, max_val, 0.1)
    cmap = cm.get_cmap("jet")

    fig, axs = plt.subplots(2, 4, figsize=(20, 10))
    for i, task in enumerate(task_order()):
        ax = axs[0, i]
        isc = correlations[i]
        pp = ax.imshow(isc, interpolation="nearest", vmin=min_val, vmax=max_val, cmap=cmap)
        ax.xaxis.tick_top()
        down, up = sms.DescrStatsW(isc[np.triu_indices(len(isc), 1)]).tconfint_mean()
        ax.set_title(f"ACW-50 {task}: {down:.2f}:{up:.2f}")
    for i, task in enumerate(task_order()):
        ax = axs[1, i]
        isc = correlations1[i]
        pp = ax.imshow(isc, interpolation="nearest", vmin=min_val, vmax=max_val, cmap=cmap)
        ax.xaxis.tick_top()
        down, up = sms.DescrStatsW(isc[np.triu_indices(len(isc), 1)]).tconfint_mean()
        ax.set_title(f"ACW-0 {task}: {down:.2f}:{up:.2f}")

    cbar_ax = fig.add_axes([0.92, 0.125, 0.02, 0.755])
    cbar = fig.colorbar(pp, cax=cbar_ax, ticks=ticks, orientation="vertical")
    savefig(fig, "isc", low=True)
示例#3
0
def fig4():
    unique_networks = net_order(tpt_name)
    dfs = [[], []]
    for i, lib in enumerate([acw, acz]):
        for avg in ["net_meta", "network"]:
            df = add_net_meta(
                and_filter(lib.gen_long_data(tpt_name), subject=lib.find_shared_subjects(tpt_name, task_order())) \
                    .groupby(["task", "subject", "network", "region"]).mean().reset_index() \
                    .groupby(["subject", "network", "region"]).apply(calc_pchange).reset_index().drop("level_3", 1),
                get_net("pmc", tpt_name)).groupby(["task", "subject", avg]).mean().reset_index()
            df.pchange *= -1
            dfs[i].append(df)

    fig = plt.figure(figsize=(20, 15))
    gs = fig.add_gridspec(2, 2, width_ratios=[0.7, 1.9], hspace=0.1, wspace=0.2)
    for row, ((df1, df2), label, (min_val, max_val)) in enumerate(
            zip(dfs, ["ACW-50", "ACW-0"], [(None, None), (None, None)])):
        ax = fig.add_subplot(gs[row, 0])
        sns.barplot(data=df1, x="task", y="pchange", hue="net_meta",
                    order=task_order(False), hue_order=["P", "M", "C"], ax=ax)
        ax.set(xlabel="", ylabel=f"Mean \u00B1 %95 CI (% change)", ylim=[min_val, max_val])
        if row == 0:
            h, l = ax.get_legend_handles_labels()
            ax.legend(h, PMC_labels, loc=3, ncol=3, mode="expand", borderaxespad=0, bbox_to_anchor=(0., 1.08, 1, 0.),
                      handletextpad=0.1)
        else:
            ax.get_legend().remove()
        ax.set_xticklabels(ax.get_xticklabels() if row == 1 else [], rotation=45)

        ax = fig.add_subplot(gs[row, 1])
        sns.barplot(data=df2, x="network", y="pchange", hue="task", palette=task_colors,
                    hue_order=task_order(False), order=unique_networks, ax=ax)
        ax.set(xlabel="", ylabel="", ylim=[min_val, max_val], yticklabels=[])
        if row == 0:
            lgn = ax.legend(loc=3, ncol=6, mode="expand", borderaxespad=0, bbox_to_anchor=(0., 1.08, 1, 0.))
        else:
            ax.get_legend().remove()
        ax.set_xticklabels(ax.get_xticklabels() if row == 1 else [], rotation=45)
        ax.set_title(label, ha="center", loc="left", x=0.3)

    savefig(fig, "fig4.bar", extra_artists=(lgn,))
示例#4
0
def isc():
    df = and_filter(add_net_meta(normalize(acw.gen_long_data(tpt_name), columns="metric"), get_net("pmc", tpt_name)) \
                    .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index(), NOTnet_meta="M")
    df1 = and_filter(add_net_meta(normalize(acz.gen_long_data(tpt_name), columns="metric"), get_net("pmc", tpt_name)) \
                     .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index(), NOTnet_meta="M")

    correlations = []
    for task in task_order():
        temp = []
        for meta in ["C", "P"]:
            dft = and_filter(df, task=task, net_meta=meta)
            subjects = dft.subject.unique()
            df_corr = np.zeros((len(subjects), len(subjects)))
            for i in range(len(subjects)):
                df_corr[i, i] = 1
                x = and_filter(dft, subject=subjects[i]).metric
                for j in range(i + 1, len(subjects)):
                    y = and_filter(dft, subject=subjects[j]).metric
                    df_corr[i, j] = df_corr[j, i] = pearsonr(x, y)[0]
            temp.append(df_corr)
        correlations.append(temp)

    correlations1 = []
    for task in task_order():
        temp = []
        for meta in ["C", "P"]:
            dft = and_filter(df1, task=task, net_meta=meta)
            subjects = dft.subject.unique()
            df_corr = np.zeros((len(subjects), len(subjects)))
            for i in range(len(subjects)):
                df_corr[i, i] = 1
                x = and_filter(dft, subject=subjects[i]).metric
                for j in range(i + 1, len(subjects)):
                    y = and_filter(dft, subject=subjects[j]).metric
                    df_corr[i, j] = df_corr[j, i] = pearsonr(x, y)[0]
            temp.append(df_corr)
        correlations1.append(temp)

    min_val, max_val = 0, 1
    ticks = np.arange(min_val, max_val + 0.01, 0.1)
    cmap = cm.get_cmap("jet")

    fig, axs = plt.subplots(4, 4, figsize=(20, 20))
    cbar_ax = fig.add_axes([0.92, 0.125, 0.02, 0.755])
    for i, task in enumerate(task_order()):
        for j, meta in enumerate(["Core", "Periphery"]):
            ax = axs[j, i]
            isc = correlations[i][j]
            xy_ticks = np.linspace(1, len(isc), 10, dtype=np.int)
            pp = ax.imshow(isc, interpolation="nearest", vmin=min_val, vmax=max_val, cmap=cmap)
            ax.set(xticks=xy_ticks, yticks=xy_ticks)
            ax.xaxis.tick_top()
            down, up = sms.DescrStatsW(isc[np.triu_indices(len(isc), 1)]).tconfint_mean()

            if j == 0:
                ax.set_title(task, fontsize=18)
            else:
                ax.set_xticks([])
            if i == 0:
                ax.set_ylabel(meta, fontsize=18)
            else:
                ax.set_yticks([])
            # ax.set_title(f"ACW-50: {down:.2f}:{up:.2f}")
    for i, task in enumerate(task_order()):
        for j, meta in enumerate(["Core", "Periphery"]):
            ax = axs[j + 2, i]
            isc = correlations1[i][j]
            xy_ticks = np.linspace(1, len(isc), 10, dtype=np.int)
            pp = ax.imshow(isc, interpolation="nearest", vmin=min_val, vmax=max_val, cmap=cmap)
            ax.set(xticks=[], yticks=xy_ticks)
            ax.xaxis.tick_top()
            down, up = sms.DescrStatsW(isc[np.triu_indices(len(isc), 1)]).tconfint_mean()

            if i == 0:
                ax.set_ylabel(meta, fontsize=18)
            else:
                ax.set_yticks([])
            # ax.set_title(f"ACW-0: {down:.2f}:{up:.2f}")

    cbar = fig.colorbar(pp, cax=cbar_ax, ticks=ticks, orientation="vertical")
    txt1 = fig.text(0.06, 0.67, "ACW-50", rotation=90, fontsize=18)
    txt2 = fig.text(0.06, 0.27, "ACW-0", rotation=90, fontsize=18)
    savefig(fig, "isc1", extra_artists=(txt1, txt2))
示例#5
0
def fig6():
    tasks = task_order(with_rest=False)
    unique_networks = net_order(tpt_name)
    palette = make_net_palette(unique_networks)
    _, mask, _, _, regions, brain_axis = get_template(tpt_name, space)

    df = acw.gen_long_data(tpt_name).groupby(["task", "subject", "network", "region"]).mean().reset_index() \
        .groupby(["subject", "network", "region"]).apply(split, "task", "metric").reset_index().drop("level_3", 1) \
        .sort_values("subject")

    output = np.zeros((len(tasks), mask.size))
    for ti, task in enumerate(tasks):
        shared_subj = acw.find_shared_subjects(tpt_name, ["Rest", task])
        for ri, region in enumerate(regions):
            mask_reg_ind = np.argwhere(mask == ri + 1)
            df_rgn = and_filter(df, region=region, subject=shared_subj)
            output[ti, mask_reg_ind] = stats.pearsonr(df_rgn.task_Rest, df_rgn[f"task_{task}"])[0]
    savemap("fig6.acw", output, brain_axis, cifti.Series(0, 1, output.shape[0]))

    df_fig = df.groupby(["network", "region"]).mean().reset_index()
    for task in task_order(True):
        df_fig[f"task_{task}"] *= 1000

    fig, axs = plt.subplots(1, 3, figsize=(16, 5))
    for ti, task in enumerate(tasks):
        ax = axs[ti]
        sns.scatterplot(data=df_fig, x="task_Rest", y=f"task_{task}", hue="network", hue_order=unique_networks, ax=ax,
                        palette=palette)
        slope, intercept, r_value, _, _ = stats.linregress(df_fig.task_Rest, df_fig[f"task_{task}"])
        sns.lineplot(df_fig.task_Rest, slope * df_fig.task_Rest + intercept, ax=ax, color='black')
        ax.text(30, 80, f"$r^2$={r_value ** 2:.2f}", ha='center', va='center')
        ax.set(xlabel=f"Rest ACW-50", ylabel=f"{task} ACW-50", xlim=[25, 60], ylim=[25, 90])
        ax.get_legend().remove()

    # fig.subplots_adjust(wspace=0.22)
    legend_handles = []
    for net, color in zip(unique_networks, palette):
        legend_handles.append(Line2D([], [], color=color, marker='o', linestyle='None', markersize=5, label=net))
    fig.legend(handles=legend_handles, loc=2, ncol=6, handletextpad=0.1, mode="expand",
               bbox_to_anchor=(0.037, 0.05, 0.785, 1))
    txt = fig.text(0.1, 1, "test", color="white")
    savefig(fig, "fig6.acw.scatter", extra_artists=(txt,))

    df = acz.gen_long_data(tpt_name).groupby(["task", "subject", "network", "region"]).mean().reset_index() \
        .groupby(["subject", "network", "region"]).apply(split, "task", "metric").reset_index().drop("level_3", 1) \
        .sort_values("subject")

    output = np.zeros((len(tasks), mask.size))
    for ti, task in enumerate(tasks):
        shared_subj = acz.find_shared_subjects(tpt_name, ["Rest", task])
        for ri, region in enumerate(regions):
            mask_reg_ind = np.argwhere(mask == ri + 1)
            df_rgn = and_filter(df, region=region, subject=shared_subj)
            output[ti, mask_reg_ind] = stats.pearsonr(df_rgn.task_Rest, df_rgn[f"task_{task}"])[0]
    savemap("fig6.acz", output, brain_axis, cifti.Series(0, 1, output.shape[0]))

    df_fig = df.groupby(["network", "region"]).mean().reset_index()
    for task in task_order(True):
        df_fig[f"task_{task}"] *= 1000

    fig, axs = plt.subplots(1, 3, figsize=(16, 5))
    for ti, task in enumerate(tasks):
        ax = axs[ti]
        sns.scatterplot(data=df_fig, x="task_Rest", y=f"task_{task}", hue="network", hue_order=unique_networks, ax=ax,
                        palette=palette)
        slope, intercept, r_value, _, _ = stats.linregress(df_fig.task_Rest, df_fig[f"task_{task}"])
        sns.lineplot(df_fig.task_Rest, slope * df_fig.task_Rest + intercept, ax=ax, color='black')
        ax.text(200, 500, f"$r^2$={r_value ** 2:.2f}", ha='center', va='center')
        ax.set(xlabel=f"Rest ACW-0", ylabel=f"{task} ACW-0", xlim=[130, 510], ylim=[40, 550])
        ax.get_legend().remove()

    # fig.subplots_adjust(wspace=0.22)
    legend_handles = []
    for net, color in zip(unique_networks, palette):
        legend_handles.append(Line2D([], [], color=color, marker='o', linestyle='None', markersize=5, label=net))
    fig.legend(handles=legend_handles, loc=2, ncol=6, handletextpad=0.1, mode="expand",
               bbox_to_anchor=(0.045, 0.05, 0.785, 1))
    txt = fig.text(0.1, 1, "test", color="white")
    savefig(fig, "fig6.acz.scatter", extra_artists=(txt,))