コード例 #1
0
    def plot_levelvar(self, title: str = None, outdir: Path = None) -> None:
        # label is always g1_v_g2, we want "attention" to be orange, "nonattend"
        # to be black
        if self.label in ["rest_v_task", "nopain_v_pain", "control_v_control_pre", "park_pre_v_parkinsons"]:
            c1, c2 = "#000000", "#FD8208"
        elif self.label in [
            "allpain_v_nopain",
            "allpain_v_duloxetine",
            "high_v_low",
            "control_pre_v_park_pre",
            "control_v_parkinsons",
        ]:
            c1, c2 = "#FD8208", "#000000"
        else:
            c1, c2 = "#EA00FF", "#FD8208"
        df1 = pd.read_pickle(self.levelvar[0]).set_index("L")
        df2 = pd.read_pickle(self.levelvar[1]).set_index("L")
        L = np.array(df1.index)
        _configure_sbn_style()
        fig: plt.Figure
        ax: plt.Axes
        fig, ax = plt.subplots()

        # plot curves for each group
        for col in df1:
            sbn.lineplot(x=L, y=df1[col], color=c1, alpha=0.05, ax=ax)
        for col in df2:
            sbn.lineplot(x=L, y=df2[col], color=c2, alpha=0.05, ax=ax)

        # plot bootstrapped means and CIs for each group
        boots = _percentile_boot(df1)
        sbn.lineplot(x=L, y=boots["mean"], color=c1, label=self.subgroup1, ax=ax)
        ax.fill_between(x=L, y1=boots["low"], y2=boots["high"], color=c1, alpha=0.3)

        boots = _percentile_boot(df2)
        sbn.lineplot(x=L, y=boots["mean"], color=c2, label=self.subgroup2, ax=ax)
        ax.fill_between(x=L, y1=boots["low"], y2=boots["high"], color=c2, alpha=0.3)

        # plot theoretically-expected curves
        # sbn.lineplot(x=L, y=Poisson.level_variance(L=L), color="#08FD4F", label="Poisson", ax=ax)
        sbn.lineplot(x=L, y=GOE.level_variance(L=L), color="#0066FF", label="GOE", ax=ax)

        ax.legend().set_visible(True)
        ax.set_title(f"{self.label}: Level Variance" if title is None else title)
        ax.set_xlabel("L")
        ax.set_ylabel("Σ²(L)", fontname="DejaVu Sans")
        fig.set_size_inches(w=8, h=8)
        if outdir is None:
            plt.show()
            plt.close()
        else:
            os.makedirs(outdir, exist_ok=True)
            outfile = outdir / f"{self.levelvar[0].stem}_{self.label}.png"
            plt.savefig(outfile, dpi=300)
            plt.close()
            print(f"Pooled levelvar plots saved to {relpath(outfile)}")
コード例 #2
0
def plot_pred_rigidity(
    args: Any,
    dataset_name: str,
    comparison: str,
    unfold: List[int] = [5, 7, 9, 11, 13],
    ensembles: bool = True,
    silent: bool = False,
    force: bool = False,
) -> None:
    global ARGS
    # ARGS.fullpre = True
    for trim_idx in ["(1,-1)", "(1,-20)"]:
        ARGS.trim = trim_idx
        all_pairs = []
        for normalize in [False]:
            args.normalize = normalize
            for degree in unfold:
                ARGS.unfold["degree"] = degree
                pairings = Pairings(args, dataset_name)
                pairing = list(filter(lambda p: p.label == comparison, pairings.pairs))
                if len(pairing) != 1:
                    raise ValueError("Too many pairings, something is wrong.")
                all_pairs.append(pairing[0])
        g1, _, g2 = all_pairs[0].label.split("_")  # groupnames
        fig: plt.Figure
        fig, axes = plt.subplots(nrows=1, ncols=len(all_pairs), sharex=True)
        for i, pair in enumerate(all_pairs):
            ax: plt.Axes = axes.flat[i]
            df1 = pd.read_pickle(pair.rigidity[0]).set_index("L")
            df2 = pd.read_pickle(pair.rigidity[1]).set_index("L")
            boots1 = _percentile_boot(df1)
            boots2 = _percentile_boot(df2)
            sbn.lineplot(x=df1.index, y=boots1["mean"], color="#FD8208", label=g1, ax=ax)
            ax.fill_between(x=df1.index, y1=boots1["low"], y2=boots1["high"], color="#FD8208", alpha=0.3)
            sbn.lineplot(x=df2.index, y=boots2["mean"], color="#000000", label=g2, ax=ax)
            ax.fill_between(x=df2.index, y1=boots2["low"], y2=boots2["high"], color="#000000", alpha=0.3)
            if ensembles:
                L = df1.index
                poisson = GDE.spectral_rigidity(L=L)
                goe = GOE.spectral_rigidity(L=L)
                sbn.lineplot(x=L, y=poisson, color="#08FD4F", label="Poisson", ax=ax)
                sbn.lineplot(x=L, y=goe, color="#0066FF", label="GOE", ax=ax)
            ax.legend().set_visible(False)
            ax.set_title(f"Unfolding Degree {unfold[i]}")
            ax.set_xlabel("")
            ax.set_ylabel("")
        axes.flat[-1].legend().set_visible(True)
        fig.text(0.5, 0.04, "L", ha="center", va="center")  # xlabel
        fig.text(
            0.03, 0.5, "∆₃(L)", ha="center", va="center", rotation="vertical", fontdict={"fontname": "DejaVu Sans"}
        )  # ylabel
        fig.set_size_inches(w=12, h=3)
        fig.subplots_adjust(top=0.83, bottom=0.14, left=0.085, right=0.955, hspace=0.2, wspace=0.2)
        plt.suptitle(f"{dataset_name} {ARGS.trim} - Spectral Rigidity")
        plt.show(block=False)
コード例 #3
0
def plot_subject_levelvar(summaries: Dict[str, Dict[Observable, Path]],
                          args: Any,
                          outfile: Path = None) -> None:
    sbn.set_context("paper")
    sbn.set_style("ticks", {"ytick.left": False})
    c1 = "#000000"
    fig, axes = plt.subplots(ncols=6, nrows=4, sharex=True, sharey=True)
    top = []
    for i, (subj_id, summary) in enumerate(summaries.items()):
        ax: Axes = axes.flat[i]
        label = f"subj-{subj_id}"
        levelvars = pd.read_pickle(summary["levelvar"]).set_index("L")
        rename_columns(levelvars)
        L = levelvars.index.to_numpy(dtype=float).ravel()
        for col in levelvars:
            sbn.lineplot(x=L,
                         y=levelvars[col],
                         color=c1,
                         alpha=1.0 / 8.0,
                         ax=ax)
            # sbn.lineplot(x=L, y=levelvars[col], label=f"run-{col}", color=c1, alpha=1.0/8.0, ax=ax)

        boots = _percentile_boot(levelvars, B=2000)
        top.append(np.max(boots["mean"]))
        # sbn.lineplot(x=L, y=boots["mean"], color=c1, label=label)
        sbn.lineplot(x=L, y=boots["mean"], color=c1, ax=ax)
        ax.fill_between(x=L,
                        y1=boots["low"],
                        y2=boots["high"],
                        color=c1,
                        alpha=0.3)
        # plot theoretically-expected curves
        sbn.lineplot(x=L,
                     y=Poisson.level_variance(L=L),
                     color="#08FD4F",
                     label="Poisson",
                     ax=ax)
        sbn.lineplot(x=L,
                     y=GOE.level_variance(L=L),
                     color="#0066FF",
                     label="GOE",
                     ax=ax)

        ax.set_ylabel("")
        ax.set_title(label)
        ax.legend(frameon=False, framealpha=0)
        plt.setp(ax.get_legend().get_texts(), fontsize="6")
        if i != 0:
            handle, labels = ax.get_legend_handles_labels()
            ax._remove_legend(handle)
        ticks = [1, 5, 10]
        ax.set_xticks(ticks)
        ax.set_xticklabels(ticks, rotation=45, horizontalalignment="right")
    plt.setp(axes, ylim=(0.0, np.percentile(top, 90)))  # better use of space
    fig.suptitle("Per-Subject Task Level Number Variances")
    fig.set_size_inches(10, 6)
    fig.subplots_adjust(left=0.13, bottom=0.15, wspace=0.1, hspace=0.35)
    fig.text(0.5, 0.04, "L", ha="center", va="center")  # xlabel
    fig.text(0.05,
             0.5,
             "Σ²(L)",
             ha="center",
             va="center",
             rotation="vertical",
             fontname="DejaVu Sans")  # ylabel
    if outfile is None:
        plt.show()
    else:
        fig.savefig(str(outfile.resolve()), dpi=300)
        print(f"Saved levelvar plot to {str(outfile.relative_to(DATA_ROOT))}")
    plt.close()