Esempio n. 1
0
def plot_voltage_curve(hull_entries):
    """
    compute OCV between stable intermediate compositions
    see ref : https://www.nature.com/articles/npjcompumats20162
    """

    e_na = -2  # -1.47

    voltages = []
    voltage_coord = []
    for run_1, run_2 in zip(hull_entries[:-1], hull_entries[1:]):
        d_na = run_2.x_na - run_1.x_na
        d_e = run_2.energy_per_fu - run_1.energy_per_fu
        v_1_2 = -(d_e / d_na - e_na)
        voltages.append(v_1_2)
        voltage_coord.append([(run_1.x_na, v_1_2), (run_2.x_na, v_1_2)])

    plot_title = "Predicted Voltage Curve"
    fig = plt.figure(plot_title)
    axe = fig.add_subplot(1, 1, 1)
    axe.add_collection(LineCollection(voltages))
    axe.set_ylabel('V equilibrium')
    axe.set_xlabel('Na content')
    axe.set_ylim([min(voltages) - 1, max(voltages) + 1])

    # axe.legend()

    plt.show(block=False)

    generic_plot.save_fig(fig, plot_title)

    return fig
Esempio n. 2
0
def plot_DOS_graphs(sorted_entries):
    print("\n==== ELECTRONS IN RECIPROCAL SPACE (DOS) ======\n")

    if input("plot DOS  of some structures ? Y / N  : ") == "Y":
        # param['graph_type']="DOS"
        fig = plot_DOS(sorted_entries, spin_choice=None, DOS_choice=None)
        plt.show(block=False)
        generic_plot.save_fig(fig, "DOS", save_mode=None, folder=None)
Esempio n. 3
0
def plot_scatter_mesh_cell_shape(struct_list):
    colors = ['green', 'red', 'blue', 'black']
    marks = ['^', 'o', '*', '+']

    xtag = "disto"
    ytag = "x_na"
    XY = np.array([[d[xtag], d[ytag], d["eform"]] for d in struct_list])

    fig = plt.figure()
    ax = Axes3D(fig)

    # plot cell params  as a function of the distortion and x_na

    ZABC = np.array([
        list(d["structure"].lattice.lengths_and_angles[0]) for d in struct_list
    ])

    for i, direction in enumerate(["a", "b", "c"]):
        color = colors[i]
        mark = marks[i]
        ax.scatter(XY[:, 0],
                   XY[:, 1],
                   ZABC[:, i],
                   zdir='z',
                   c=color,
                   marker=mark,
                   label=direction,
                   s=100)
        for x, y, z, energy in zip(
                XY[:, 0], XY[:, 1], ZABC[:, i],
                XY[:, 2]):  # plot each point + it's index as text above
            ax.text(x,
                    y,
                    z,
                    "{:.3f}".format(energy),
                    size=10,
                    zorder=1,
                    color='k')

    ax.set_xlabel(ytag)
    ax.set_ylabel(ytag)
    ax.set_ylabel("cell parameter")
    fig.legend()

    # plot  V of the cell as a function of the distortion and x_na
    fig2 = plt.figure()
    ax2 = Axes3D(fig2)

    ZV = np.array([d["structure"].lattice.volume for d in struct_list])

    ax2.scatter(XY[:, 0], XY[:, 1], ZV, zdir='z', c=color, marker=mark, s=150)
    ax2.set_xlabel(xtag)
    ax2.set_ylabel(ytag)
    ax2.set_zlabel("Volume")
    #    fig2.legend()
    plt.show(block=False)
    generic_plot.save_fig(fig, "scatter surface", save_mode=None, folder=None)
Esempio n. 4
0
def plot_scatter_surface(sorted_entries,
                         xtag="disto",
                         ytag="x_na",
                         ztag="eform"):

    fig = plt.figure()
    ax = Axes3D(fig)

    for d in sorted_entries:
        d['disto'] = round(d["distortion"]["Mn"]["O:6"], 2)

    stacking_list = list(set([e["stacking"] for e in sorted_entries]))

    colors = ['green', 'red', 'blue', 'black']
    marks = ['^', 'o', '*', '+']

    for i, stacking in enumerate(stacking_list):
        color = colors[i]
        mark = marks[i]
        struct_list = [d for d in sorted_entries if d["stacking"] == stacking]

        XYZ = np.array([[d[xtag], d[ytag], d[ztag]] for d in struct_list])
        ax.scatter(XYZ[:, 0],
                   XYZ[:, 1],
                   XYZ[:, 2],
                   zdir='z',
                   c=color,
                   marker=mark,
                   label=stacking,
                   s=150)

    ax.set_xlabel(xtag)
    ax.set_ylabel(ytag)
    ax.set_zlabel(ztag)
    fig.legend()

    plt.show(block=False)

    generic_plot.save_fig(fig, "scatter surface", save_mode=None, folder=None)

    return (fig)
Esempio n. 5
0
def plot_COOP_OO(RunDict_list, sorting="oxidation"):
    override_sorting = True
    try:
        bond_choice = input(
            "[M]-O // [O]-O // [s]pecific pair // [A]ll: Bond choice ?")
        if bond_choice in ["O", "o"]:
            bonds = ["O_O"]  # , "O_O" "M_O"
        elif bond_choice in ["M", "m"]:
            bonds = ["M_O"]
        elif bond_choice in ["S", "s"]:
            bonds = ["specific_pair"]
        elif bond_choice in ["A", "a"]:
            bonds = ["M_O", "O_O", "specific_pair"]
    except Exception:
        print('bond = M-O')
        bonds = ["M_O"]

# ========= getting the COOP data
    for v in RunDict_list:
        v.coop_dict = {}
        for bond in bonds:
            v.coop_dict[bond] = get_COOP_from_folder(v.job_folder, bond=bond)

    plot_dos = True
    dos_ax = 1 if plot_dos else 0

    Emin = -10
    Emax = 3

    # ========= plotting all bond_COOP per run
    for v in RunDict_list:
        valid_coops = {
            bond: v.coop_dict[bond]
            for bond in bonds if v.coop_dict[bond] is not None
        }
        nb_axes = len(valid_coops)
        if nb_axes == 0:
            print("no valid COOP runs for {}".format(v.str_id))
            return ([])

        nb_axes += dos_ax

        fig = plt.figure("COOP", figsize=(20, 10))
        if nb_axes == 1:
            axes = [fig.add_subplot(111)]
        else:
            axes = fig.subplots(nb_axes, 1, sharex="col")
            fig.subplots_adjust(hspace=0)

        bottom_COOP, top_COOP = [0, 0]
        i = dos_ax
        for (bond, coop) in valid_coops.items():
            plot_coop(axes[i],
                      coop,
                      Emin,
                      Emax,
                      pmg_efermi=v.data['efermi'],
                      sorting="all",
                      override_sorting=True,
                      title=bond)
            bottom_COOP = min(axes[i].get_ylim()[0], bottom_COOP)
            top_COOP = max(axes[i].get_ylim()[1], top_COOP)
            i += 1

        # for ax in axes[dos_ax:]:
        #     ax.set_ylim([bottom_COOP, top_COOP])

        if plot_dos:
            ax_dos = axes[0]
            pre_defined_colors = {
                "O": "xkcd:light red",
                "Mn": "xkcd:bluish",
                "Mg": "#20c073",
                "Na": "xkcd:dandelion"
            }
            DOS.plot_DOS_on_axe(
                ax_dos,
                v,
                Emin,
                Emax,
                DOS_choice="perElt",
                spin_choice=0,  # 0 = Up & dpwn
                pre_defined_colors=pre_defined_colors)
            ax_dos.legend()
            # (bottom_DOS, top_DOS) = ax_dos.get_ylim()
            # ax_dos.set_ylim([top_DOS * (bottom_COOP / top_COOP), top_DOS])

            # axes[-1].text(-0.05 , 0.5 , "Na {} \nEf={:.4f}".format(v["x_na"],v["vaspRun"].efermi),
            #      weight='bold',size='large',
            #     horizontalalignment='right', verticalalignment='center',
            #     multialignment='right', transform=axes[-1].transAxes)

        plt.show(block=False)
        generic_plot.save_fig(fig,
                              "COOP_{}".format(v.job_folder.split("/")[-2]))


# # =========================
#     # for bond in bonds:
#     #     # plot each bond_coop of all runs
#     for bond in bonds:
#         fig = plt.figure("COOP by bonds", figsize=(20, 10))
#         if len(complete_coop_list) == 1:
#             axes = [fig.add_subplot(111)]
#         else:
#             axes = fig.subplots(len(complete_coop_list), 1, sharex="col")
#             fig.subplots_adjust(hspace=0)

#         runList = COOP_from_runListDict(rundict_list, bond=bond)
#         valid_coop_runs = [v for v in runList if v.complete_coop is not None]

# def plot_coop_list(complete_coop_list, axes=None):
#     if len(complete_coop_list) == 0:
#         print("no valid COOP runs to show")
#         return([])

#     if axes is not None:

#         # for i, v in enumerate(valid_coop_runs):
#         #     COOP = v.complete_coop
#         #     if sorting == "all" or override_sorting:
#         #         key_list = [k for k in COOP.bonds.keys()]
#         #     elif sorting == "distance":
#         #         key_list = sort_key_by_dist(COOP, bond_length_max=3)[0]
#         #     elif sorting == "oxidation":
#         #         key_list = sort_key_by_oxidation(v, COOP, nb_sites=1)[0]
#         #     elif sorting == "OO_pairs":
#         #         key_list = get_OO_pair_keys(v, COOP)

    return (RunDict_list)
Esempio n. 6
0
def plot_convex_hull(sorted_entries, coord='x_na'):

    clean_entries = [d for d in sorted_entries if d.status >= 4]
    hull_entries = [d for d in sorted_entries if d.status >= 5]

    #  int => stacking string
    stacking_list = list({e.stacking for e in sorted_entries})
    print("stacking set : ", stacking_list)

    # stacking string => int
    stacking_index = {s: i for i, s in enumerate(stacking_list)}
    print("stacking index : ", stacking_index)

    colors = ['green', 'red', 'blue', 'black']

    # stacking string => color
    color_dict = {}
    for i, stacking in enumerate(stacking_list):
        color_dict[stacking] = colors[i]
    print(color_dict)
    color_dict.update({"P3": "#b700ffff", "O3": "#00baffff"})

    plot_title = "Convex Hull"

    fig = plt.figure(plot_title)

    # fig.suptitle(hull_entries[-1]["folder"]+"\n"
    #              +hull_entries[-1]["formula"]+"\n"
    #              +plotTitle,
    #              fontsize="large")
    # plotting
    dot_size = 40

    axe = fig.add_subplot(1, 1, 1)

    # Plot error bar on energies of structures with lowest energy at given x_na
    # symmetric or not depending if they are (or not) on the convex hull

    if True:  # input("add error bars for ambient temp ? [Y/N] ")=="Y" :
        thermal_error = 25  # in meV
        x_e_1 = np.array([[getattr(e, coord), e.eform] for e in clean_entries])
        # print(XE1)
        x_clean = x_e_1[:, 0]
        e_clean = x_e_1[:, 1]
        yerr_down = [(thermal_error if (e.status < 4) else 0)
                     for e in clean_entries]
        yerr_up = thermal_error * np.ones_like(e_clean)
        # print([yerr_down, yerr_up])
        axe.errorbar(x_clean,
                     e_clean,
                     yerr=[yerr_down, yerr_up],
                     fmt='',
                     linestyle="None")

    # # Plot all entries (hollow circles) [sorted_entries]
    for entry in sorted_entries:
        try:
            print(entry.eform)
        except Exception as ex:
            print("Exception raised for {} : {}".format(entry.name_tag, ex))
    for stacking in stacking_list:
        print("current stacking", stacking)
        x_e = np.array([[getattr(entry, coord), entry.eform]
                        for entry in sorted_entries
                        if entry.stacking == stacking])

        print(x_e)
        axe.scatter(x_e[:, 0],
                    x_e[:, 1],
                    s=dot_size,
                    facecolors='none',
                    edgecolor=color_dict[stacking],
                    label=stacking)

    # Plot entries with lowest energies (filled circles) [clean_entries]

    x_e_c = np.array(
        [[getattr(entry, coord), entry.eform, stacking_index[entry.stacking]]
         for entry in clean_entries])
    print(x_e_c)
    axe.scatter(
        x_e_c[:, 0],
        x_e_c[:, 1],
        s=dot_size,
        color=[color_dict[stacking_list[int(index)]] for index in x_e_c[:, 2]],
        edgecolor='face')

    # link entries on the convex hull (black line) [hull_entries]
    x_e = np.array([[getattr(entry, coord), entry.eform]
                    for entry in hull_entries])
    print(x_e)
    axe.plot(x_e[:, 0], x_e[:, 1], "k-")

    axe.legend()
    axe.set_ylabel('E total (meV)')
    axe.set_xlabel('Na content')
    # X = [getattr(entry, coord) for entry in sorted_entries]
    if coord == "x_na":
        axe.invert_xaxis()
    # axe.tick_params(axis='x', which='minor', bottom=True)
    axe.xaxis.set_minor_locator(AutoMinorLocator(n=2))
    # xlim(max(X), min(X))

    plt.show(block=False)
    generic_plot.save_fig(fig, plot_title)

    return fig