コード例 #1
0
def sfig1():
    df = pd.merge(
        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().rename(columns={"metric": "acw"}),
        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().rename(columns={"metric": "acz"}),
        on=["task", "subject", "region", "net_meta"], sort=False)

    fig, axs = plt.subplots(2, 2, figsize=(15, 10), sharex=True, sharey="col")

    ax = axs[0, 0]
    sns.distplot(df.groupby(["task", "subject"]).mean().reset_index().acw, ax=ax, rug=False, kde=True, hist=True)
    ax.set(xlabel=f"Normalized ACW-50 for subjects")
    ax.grid(False)

    ax = axs[1, 0]
    sns.distplot(df.groupby(["task", "region"]).mean().reset_index().acw, ax=ax, rug=False, kde=True, hist=True)
    ax.set(xlabel=f"Normalized ACW-50 for regions")
    ax.grid(False)

    ax = axs[0, 1]
    sns.distplot(df.groupby(["task", "subject"]).mean().reset_index().acz, ax=ax, rug=False, kde=True, hist=True)
    ax.grid(False)
    ax.set(xlabel=f"Normalized ACW-0 for subjects")

    ax = axs[1, 1]
    sns.distplot(df.groupby(["task", "region"]).mean().reset_index().acz, ax=ax, rug=False, kde=True, hist=True)
    ax.set(xlabel=f"Normalized ACW-0 for regions")
    ax.grid(False)

    fig.subplots_adjust(wspace=0.1, hspace=0.1)
    savefig(fig, "sfig1.dist.nolabel")
コード例 #2
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]))
コード例 #3
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)
コード例 #4
0
ファイル: ml.py プロジェクト: mehrshadg/acf_paper
def single():
    scaler = StandardScaler()

    df = pd.merge(
        acw.gen_long_data(tpt)
            .normalize(columns="metric")
            .add_net_meta(tpt.net_hierarchy(HierarchyName.RESTRICTED_PERIPHERY_CORE))
            .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()
            .rename(columns={"metric": "acw"}),
        acz.gen_long_data(tpt)
            .normalize(columns="metric")
            .add_net_meta(tpt.net_hierarchy(HierarchyName.RESTRICTED_PERIPHERY_CORE))
            .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()
            .rename(columns={"metric": "acz"}),
        on=["task", "subject", "region", "net_meta"], sort=False).and_filter(NOTnet_meta="M")

    X = df.iloc[:, -2:].values
    y = df.net_meta.map({"C": 0, "P": 1}).values
    X = scaler.fit_transform(X)

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

    logreg = LogisticRegression()
    logreg.fit(X_train, y_train)
    y_pred = logreg.predict(X_test)
    cnf_matrix = metrics.confusion_matrix(y_test, y_pred)
    print(cnf_matrix)

    class_names = ["Core", "Periphery"]
    fig, ax = plt.subplots(1, 1, figsize=(5, 5))
    tick_marks = np.arange(len(class_names))
    ax.set_xticks(tick_marks, class_names)
    ax.set_yticks(tick_marks, class_names)
    sns.heatmap(pd.DataFrame(cnf_matrix), annot=True, cmap="YlGnBu", fmt='g', ax=ax)
    ax.xaxis.set_label_position("top")
    ax.set(title="Confusion matrix", xlabel="Predicted label", ylabel="Actual label")
    savefig(fig, "ml4.conf", low=True)

    y_pred_proba = logreg.predict_proba(X_test)[::, 1]
    fpr, tpr, _ = metrics.roc_curve(y_test, y_pred_proba)
    auc = metrics.roc_auc_score(y_test, y_pred_proba)
    fig, ax = plt.subplots(1, 1, figsize=(5, 5))
    ax.plot(fpr, tpr, label="data 1, auc=" + str(auc))
    ax.legend(loc=4)
    savefig(fig, "ml4.roc", low=True)

    print("Accuracy:", metrics.accuracy_score(y_test, y_pred))
    print("Precision:", metrics.precision_score(y_test, y_pred))
    print("Recall:", metrics.recall_score(y_test, y_pred))
コード例 #5
0
def feature_selection():
    df = pd.merge(
        acw.gen_long_data(tpt_sh).normalize(columns="metric").add_net_meta(
            tpt_sh.net_hierarchy(HierarchyName.PERIPHERY_CORE)).groupby([
                "task", "subject", "region", "net_meta"
            ]).mean().reset_index().rename(columns={"metric": "acw"}),
        acz.gen_long_data(tpt_sh).normalize(columns="metric").add_net_meta(
            tpt_sh.net_hierarchy(HierarchyName.PERIPHERY_CORE)).groupby([
                "task", "subject", "region", "net_meta"
            ]).mean().reset_index().rename(columns={"metric": "acz"}),
        on=["task", "subject", "region", "net_meta"],
        sort=False)
    x = df.iloc[:, -2:].values
    y = df.net_meta.map({"C": 0, "P": 1}).values
    model = SelectKBest(mutual_info_classif, k=1).fit(x, y)
    print(f"ACW-50: score = {model.scores_[0]}\n"
          f"ACW-0: score = {model.scores_[1]}")
コード例 #6
0
def regression():
    df = pd.merge(
        normalize(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().rename(
            columns={"metric": "acw"}), "acw"),
        normalize(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().rename(
            columns={"metric": "acz"}), "acz"),
        on=["task", "subject", "region", "net_meta"], sort=False)

    df = and_filter(df, NOTnet_meta="M")
    X = df.iloc[:, -2:].values
    y = df.net_meta.map({"C": 0, "P": 1}).values
    X = sm.add_constant(X)
    model = sm.Logit(y, X)
    result = model.fit()
    print(result.summary())
    mfx = result.get_margeff()
    print(mfx.summary())
コード例 #7
0
ファイル: ml.py プロジェクト: mehrshadg/acf_paper
def kfold():
    scaler = StandardScaler()
    random_state = 10
    K = 2

    df = pd.merge(
        acw.gen_long_data(tpt)
            .normalize(columns="metric")
            .add_net_meta(tpt.net_hierarchy(HierarchyName.RESTRICTED_PERIPHERY_CORE))
            .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()
            .rename(columns={"metric": "acw"}),
        acz.gen_long_data(tpt)
            .normalize(columns="metric")
            .add_net_meta(tpt.net_hierarchy(HierarchyName.RESTRICTED_PERIPHERY_CORE))
            .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()
            .rename(columns={"metric": "acz"}),
        on=["task", "subject", "region", "net_meta"], sort=False).and_filter(NOTnet_meta="M")

    Xraw = df.iloc[:, -2:].values
    y = df.net_meta.map({"C": 0, "P": 1}).values

    logreg = LogisticRegression()
    svc = svm.SVC(probability=True)
    output = {}

    lbl = "svm_both"
    print(lbl)
    X = scaler.fit_transform(Xraw)
    output[lbl] = do_kfold(lbl, svc, X, y, K, random_state)

    lbl = "svm_acw"
    print(lbl)
    X = scaler.fit_transform(Xraw[:, 0].reshape(-1, 1))
    output[lbl] = do_kfold(lbl, svc, X, y, K, random_state)

    lbl = "svm_acz"
    print(lbl)
    X = scaler.fit_transform(Xraw[:, 1].reshape(-1, 1))
    output[lbl] = do_kfold(lbl, svc, X, y, K, random_state)

    np.save("svm.npy", output)
コード例 #8
0
def scale_relation():
    sns.set(style="whitegrid", font_scale=1)
    tpt = tpt_cole
    df = pd.merge(
        acw.gen_long_data(tpt).groupby(["task", "subject", "region"]).mean().reset_index().normalize("metric"),
        acz.gen_long_data(tpt).groupby(["task", "subject", "region"]).mean().reset_index().normalize("metric"),
        on=["task", "subject", "region"]
    )
    df1 = df.groupby(["task", "subject"]).mean().reset_index()
    df2 = df.groupby(["task", "region"]).mean().reset_index()

    # noinspection PyTypeChecker
    fig, axs = plt.subplots(1, 3, figsize=(18, 5), sharey=True, sharex=True)
    ax = axs[0]
    sns.kdeplot(df.metric_x, ax=ax, bw_adjust=1.5, clip=(0, None), label="ACW-50", fill=True, color='#2B72C3')
    sns.kdeplot(df.metric_y, ax=ax, clip=(0, None), label="ACW-0", fill=True, color='#F0744E')
    ax.legend()
    ax.set(xlabel="No label", ylabel="Probability", yticklabels=[])
    txt1 = ax.text(-0.05, 0.02, "0", transform=ax.transAxes, va='center', ha='center')
    txt2 = ax.text(-0.05, 0.98, "1", transform=ax.transAxes, va='center', ha='center')
    ax.grid(False)

    ax = axs[1]
    sns.kdeplot(df1.metric_x, ax=ax, bw_adjust=1, clip=(0, None), label="ACW-50", fill=True, color='#2B72C3')
    sns.kdeplot(df1.metric_y, ax=ax, clip=(0, None), label="ACW-0", fill=True, color='#F0744E')
    ax.legend()
    ax.set(xlabel="Averaged over regions", ylabel="Probability")
    ax.grid(False)

    ax = axs[2]
    sns.kdeplot(df2.metric_x, ax=ax, bw_adjust=1, clip=(0, None), label="ACW-50", fill=True, color='#2B72C3')
    sns.kdeplot(df2.metric_y, ax=ax, clip=(0, None), label="ACW-0", fill=True, color='#F0744E')
    ax.legend()
    ax.set(xlabel="Averaged over subjects", ylabel="Probability")
    ax.grid(False)

    fig.subplots_adjust(wspace=0.05)
    savefig(fig, "relation.dist", extra_artists=(txt1, txt2))
コード例 #9
0
ファイル: ml.py プロジェクト: mehrshadg/acf_paper
def select_best():
    df = pd.merge(
        acw.gen_long_data(tpt)
            .normalize(columns="metric")
            .add_net_meta(tpt.net_hierarchy(HierarchyName.RESTRICTED_PERIPHERY_CORE))
            .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()
            .rename(columns={"metric": "acw"}),
        acz.gen_long_data(tpt)
            .normalize(columns="metric")
            .add_net_meta(tpt.net_hierarchy(HierarchyName.RESTRICTED_PERIPHERY_CORE))
            .groupby(["task", "subject", "region", "net_meta"]).mean().reset_index()
            .rename(columns={"metric": "acz"}),
        on=["task", "subject", "region", "net_meta"], sort=False).and_filter(NOTnet_meta="M")

    X = df.iloc[:, -2:].values
    y = df.net_meta.map({"C": 0, "P": 1}).values

    functions = [fs.mutual_info_classif, fs.f_classif, fs.chi2]
    for func in functions:
        for method in [fs.SelectKBest(func, k=1), fs.SelectPercentile(func), fs.SelectFdr(func), fs.SelectFpr(func),
                       fs.SelectFwe(func)]:
            method.fit(X, y)
            print(f'{str(method).split("(")[0]} {func.__name__}: {np.argmax(method.scores_) + 1}')
コード例 #10
0
def fig7():
    df = pd.merge(
        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().rename(columns={"metric": "acw"}),
        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().rename(columns={"metric": "acz"}),
        on=["task", "subject", "region", "net_meta"], sort=False)

    fig, axs = plt.subplots(1, 2, figsize=(15, 10), sharex=True, sharey="col")

    ax = axs[0, 0]
    sns.distplot(df.acw, ax=ax, rug=False, kde=True, hist=True, kde_kws={"bw": 0.02})
    ax.set(xlabel=f"Normalized ACW-50")
    ax.grid(False)

    ax = axs[1, 0]
    for meta, label, color in zip(["P", "M", "C"], PMC_labels, PMC_colors):
        sns.distplot(and_filter(df, net_meta=meta).acw, ax=ax, rug=False, kde=True, hist=False,
                     kde_kws={"bw": 0.02}, label=label, color=color)
    ax.set(xlabel=f"Normalized ACW-50")
    ax.grid(False)

    ax = axs[0, 1]
    sns.distplot(df.acz, ax=ax, rug=False, kde=True, hist=True, )
    ax.grid(False)
    ax.set(xlabel=f"Normalized ACW-0")

    ax = axs[1, 1]
    for meta, label, color in zip(["P", "M", "C"], PMC_labels, PMC_colors):
        sns.distplot(and_filter(df, net_meta=meta).acz, ax=ax, rug=False, kde=True, hist=False,
                     label=label, color=color)
    ax.set(xlabel=f"Normalized ACW-0")
    ax.grid(False)

    fig.subplots_adjust(wspace=0.1, hspace=0.1)
    savefig(fig, "fig7.dist.nolabel")
コード例 #11
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))
コード例 #12
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,))
コード例 #13
0
ファイル: cp_ap.py プロジェクト: mehrshadg/acf_paper
from neuro_helper.abstract.map import Space
from neuro_helper.map import SchaeferTemplateMap, MarguliesGradientTopo, AntPostTopo
from neuro_helper import dataframe
import hcp_acf_window as acw
import hcp_acf_zero as acz
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

tpt = SchaeferTemplateMap(Space.K32_CORTEX, 200, 7)()
cp = MarguliesGradientTopo(tpt)
ap = AntPostTopo(tpt)

df = pd.merge(acw.gen_long_data(tpt).groupby(
    ["task", "region", "network"]).mean().reset_index().convert_column(
        metric=lambda x: x * 1000).rename(columns={"metric": "acw"}),
              acz.gen_long_data(tpt).groupby([
                  "task", "region", "network"
              ]).mean().reset_index().convert_column(
                  metric=lambda x: x * 1000).rename(columns={"metric": "acz"}),
              on=["task", "region",
                  "network"]).normalize(["acw", "acz"]).add_topo(ap, cp)

df["ratio"] = df.gradient / df.coord_y

ax = sns.catplot(data=df, x="ratio", y="acw", hue="network", col="")
ax.set(xlim=[-1, 1])
plt.show()