示例#1
0
文件: scr.py 项目: gmatteo/abipy
    def plot_emacro(self, cplx_mode="re-im", ax=None, xlims=None, fontsize=12, **kwargs):
        r"""
        Plot the macroscopic dielectric function with local-field effects.

        Args:
            cplx_mode: string defining the data to print.
                Possible choices are (case-insensitive):
                "re" for the real part. "im" for the imaginary part.
                "abs" for the absolute value.
                "angle" will display the phase of the complex number in radians.
                Options can be concatenated with ``-`` e.g. ``re-im``.
            xlims: Set the data limits for the x-axis in eV. Accept tuple e.g. (left, right)
                or scalar e.g. left. If left (right) is None, default values are used.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: Legend and title fontsize.

        Returns:
            |matplotlib-Figure|
        """
        emlf = self.reader.read_emacro_lf()
        xx, yy = emlf.mesh * pmgu.Ha_to_eV, emlf.values

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        for c in cplx_mode.lower().split("-"):
            ax.plot(xx, data_from_cplx_mode(c, yy),
                    color=_COLOR_CMODE[c], linewidth=kwargs.get("linewidth", 2),
                    linestyle=kwargs.get("linestyle", "solid"),
                    label=_latex_symbol_cplxmode(r"\varepsilon_{M}", c))

        set_axlims(ax, xlims, "x")
        ax.grid(True)
        ax.set_xlabel(r"$\omega$ (eV)")
        ax.legend(loc="best", shadow=True, fontsize=fontsize)

        return fig
示例#2
0
文件: bse.py 项目: gmatteo/abipy
    def plot(self, ax=None, *args, **kwargs):
        """
        Plot all the components of the tensor.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.

        ==============  ==============================================================
        kwargs          Meaning
        ==============  ==============================================================
        red_coords      True to plot the reduced coordinate tensor (Default: True)
        ==============  ==============================================================

        Returns: |matplotlib-Figure|
        """
        red_coords = kwargs.pop("red_coords", True)
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        ax.set_xlabel('Frequency (eV)')
        ax.set_ylabel('Dielectric tensor')

        #if not kwargs:
        #    kwargs = {"color": "black", "linewidth": 2.0}

        # Plot the 6 independent components
        for icomponent in [0, 4, 8, 1, 2, 5]:
            self.plot_ax(ax, icomponent, red_coords, *args, **kwargs)

        return fig
示例#3
0
文件: bse.py 项目: gmatteo/abipy
    def plot(self, ax=None, **kwargs):
        """
        Plot the MDF.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.

        ==============  ==============================================================
        kwargs          Meaning
        ==============  ==============================================================
        only_mean       True if only the averaged spectrum is wanted (default True)
        ==============  ==============================================================

        Returns: |matplotlib-Figure|
        """
        only_mean = kwargs.pop("only_mean", True)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        ax.set_xlabel('Frequency (eV)')
        ax.set_ylabel('Macroscopic DF')

        #if not kwargs:
        #    kwargs = {"color": "black", "linewidth": 2.0}

        # Plot the average value
        self.plot_ax(ax, qpoint=None, **kwargs)

        if not only_mean:
            # Plot the q-points
            for iq, qpoint in enumerate(self.qpoints):
                self.plot_ax(ax, iq, **kwargs)

        return fig
示例#4
0
文件: scr.py 项目: gmatteo/abipy
    def plot_eelf(self, ax=None, xlims=None, fontsize=12, **kwargs):
        r"""
        Plot electron energy loss function.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            xlims: Set the data limits for the x-axis in eV. Accept tuple e.g. ``(left, right)``
                   or scalar e.g. ``left``. If left (right) is None, default values are used
            fontsize: Legend and label fontsize:

        Returns: |matplotlib-Figure|
        """
        eelf = self.reader.read_eelf()
        xx, yy = eelf.mesh * pmgu.Ha_to_eV, eelf.values

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.plot(xx, yy, linewidth=kwargs.get("linewidth", 2),
                linestyle=kwargs.get("linestyle", "solid"), label="EELF")

        set_axlims(ax, xlims, "x")
        ax.grid(True)
        ax.set_xlabel(r"$\omega$ (eV)")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#5
0
文件: optic.py 项目: gpetretto/abipy
    def plot_linear_epsilon(self, components="all", what="im", itemp=0,
                            ax=None, xlims=None, with_xlabel=True, label=None, fontsize=12, **kwargs):
        """
        Plot components of the linear dielectric function.

        Args:
            components: List of cartesian tensor components to plot e.g. ["xx", "xy"].
                "all" if all components available on file should be plotted on the same ax.
            what: quantity to plot. "re" for real part, "im" for imaginary. Accepts also "abs", "angle".
            itemp: Temperature index.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``
                   or scalar e.g. ``left``. If left (right) is None, default values are used.
            with_xlabel: True if x-label should be added.
            label: True to add legend label to each curve.
            fontsize: Legend and label fontsize.

        Returns: |matplotlib-Figure|
        """
        comp2eps = self.reader.read_lineps(components, itemp=itemp)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        for comp, eps in comp2eps.items():
            values = LINEPS_WHAT2EFUNC[what](eps)
            # Note: I'm skipping the first point at w=0 because optic does not compute it!
            # The same trick is used in the other plots.
            ax.plot(self.wmesh[1:], values[1:],
                    label=self.get_linopt_latex_label(what, comp) if label is None else label)

        ax.grid(True)
        if with_xlabel: ax.set_xlabel('Photon Energy (eV)')
        set_axlims(ax, xlims, "x")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#6
0
文件: qha.py 项目: gmatteo/abipy
    def plot_energies(self, tstart=0, tstop=800, num=10, ax=None, **kwargs):
        """
        Plots the energies as a function of volume at different temperatures.

        Args:
            tstart: The starting value (in Kelvin) of the temperature mesh.
            tstop: The end value (in Kelvin) of the mesh.
            num: int, optional Number of samples to generate. Default is 10.
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Returns: |matplotlib-Figure|
        """

        f = self.fit_energies(tstart, tstop, num)

        ax, fig, plt = get_ax_fig_plt(ax)
        xmin, xmax = np.floor(self.volumes.min() * 0.97), np.ceil(self.volumes.max() * 1.03)
        x = np.linspace(xmin, xmax, 100)

        for fit, e, t in zip(f.fits, f.tot_en.T - self.energies[self.iv0], f.temp):
            ax.scatter(self.volumes, e, label=t, color='b', marker='x', s=5)
            ax.plot(x, fit.func(x) - self.energies[self.iv0], color='b', lw=1)

        ax.plot(f.min_vol, f.min_en - self.energies[self.iv0] , color='r', lw=1, marker='x', ms=5)

        ax.set_xlabel(r'V (${\AA}^3$)')
        ax.set_ylabel('E (eV)')

        return fig
示例#7
0
文件: qha.py 项目: gmatteo/abipy
    def plot_vol_vs_t(self, tstart=0, tstop=800, num=100, ax=None, **kwargs):
        """
        Plots the volume as a function of the temperature.

        Args:
            tstart: The starting value (in Kelvin) of the temperature mesh.
            tstop: The end value (in Kelvin) of the mesh.
            num: int, optional Number of samples to generate. Default is 100.
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax)
        f = self.fit_energies(tstart, tstop, num)

        if 'linewidth' not in kwargs and 'lw' not in kwargs:
            kwargs['linewidth'] = 2

        if "color" not in kwargs:
            kwargs["color"] = "b"

        ax.plot(f.temp, f.min_vol, **kwargs)
        ax.set_xlabel('T (K)')
        ax.set_ylabel(r'V (${\AA}^3$)')

        ax.set_xlim(tstart, tstop)

        return fig
示例#8
0
文件: psps.py 项目: gmatteo/abipy
    def plot_tcore_rspace(self, ax=None, ders=(0, 1, 2, 3), rmax=3.0,  **kwargs):
        """
        Plot the model core and its derivatives in real space.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            ders: Tuple used to select the derivatives to be plotted.
            rmax: Max radius for plot in Bohr. None is full grid is wanted.

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        linewidth = kwargs.pop("linewidth", 2.0)
        rmeshes, coresd = self.reader.read_coresd(rmax=rmax)

        scale = None
        scale = 1.0
        for rmesh, mcores in zip(rmeshes, coresd):
            for der, values in enumerate(mcores):
                if der not in ders: continue
                yvals, fact, = rescale(values, scale=scale)
                ax.plot(rmesh, yvals, color=self.color_der[der], linewidth=linewidth,
                        linestyle=self.linestyles_der[der],
                        label=mklabel("\\tilde{n}_c", der, "r") + " x %.4f" % fact)

        ax.grid(True)
        ax.set_xlabel("r [Bohr]")
        ax.set_title("Model core in r-space")
        if kwargs.get("with_legend", False): ax.legend(loc="best")

        return fig
示例#9
0
文件: scissors.py 项目: gmatteo/abipy
    def plot_fit(self, ax=None, fontsize=8, **kwargs):
        """
        Compare fit functions with input quasi-particle corrections.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: fontsize for titles and legend.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        for spin in range(self.nsppol):
            qps = self._qps_spin[spin]
            e0mesh, qpcorrs = qps.get_e0mesh(), qps.get_qpeme0().real

            ax.scatter(e0mesh, qpcorrs, label="Input QP corrections, spin %s" % spin)
            scissors = self._scissors_spin[spin]
            intp_qpc = [scissors.apply(e0) for e0 in e0mesh]
            ax.plot(e0mesh, intp_qpc, label="Scissors operator, spin %s" % spin)

        ax.grid(True)
        ax.set_xlabel('KS energy (eV)')
        ax.set_ylabel('QP-KS (eV)')
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#10
0
文件: qha.py 项目: gmatteo/abipy
    def plot_thermal_expansion_coeff(self, tstart=0, tstop=800, num=100, ax=None, **kwargs):
        """
        Plots the thermal expansion coefficient as a function of the temperature.

        Args:
            tstart: The starting value (in Kelvin) of the temperature mesh.
            tstop: The end value (in Kelvin) of the mesh.
            num: int, optional Number of samples to generate. Default is 100.
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Returns: |matplotlib-Figure|
        """

        ax, fig, plt = get_ax_fig_plt(ax)

        if 'linewidth' not in kwargs and 'lw' not in kwargs:
            kwargs['linewidth'] = 2

        if "color" not in kwargs:
            kwargs["color"] = "b"

        alpha = self.get_thermal_expansion_coeff(tstart, tstop, num)

        ax.plot(alpha.mesh, alpha.values, **kwargs)
        ax.set_xlabel(r'T (K)')
        ax.set_ylabel(r'$\alpha$ (K$^{-1}$)')

        ax.set_xlim(tstart, tstop)

        ax.get_yaxis().get_major_formatter().set_powerlimits((0, 0))

        return fig
示例#11
0
    def plot_unfolded(self, kbounds, klabels, ylims=None, dist_tol=1e-12, verbose=0,
                      colormap="afmhot", facecolor="black", ax=None, fontsize=12, **kwargs):
        r"""
        Plot unfolded band structure with spectral weights.

        Args:
            klabels: dictionary whose keys are tuple with the reduced coordinates of the k-points.
                The values are the labels. e.g. ``klabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}``.
            ylims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``
                or scalar e.g. ``left``. If left (right) is None, default values are used
            dist_tol: A point is considered to be on the path if its distance from the line
                is less than dist_tol.
            verbose: Verbosity level.
            colormap: Have a look at the colormaps here and decide which one you like:
                http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html
            facecolor:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: Legend and title fontsize.

        Returns: |matplotlib-Figure|
	"""
        cart_bounds = [self.pc_lattice.reciprocal_lattice.get_cartesian_coords(c)
                       for c in np.reshape(kbounds, (-1, 3))]
        uf_cart = self.uf_kpoints.get_cart_coords()

        p = find_points_along_path(cart_bounds, uf_cart, dist_tol)
        if len(p.ikfound) == 0:
            cprint("Warning: find_points_along_path returned zero points along the path. Try to increase dist_tol.", "yellow")
            return None
        if verbose:
            uf_frac_coords = np.reshape([k.frac_coords for k in self.uf_kpoints], (-1, 3))
            fcoords = uf_frac_coords[p.ikfound]
            print("Found %d points along input k-path" % len(fcoords))
            print("k-points of path in reduced coordinates:")
            print(fcoords)

        fact = 8.0
        e0 = self.ebands.fermie
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.set_facecolor(facecolor)

        xs = np.tile(p.dist_list, self.nband)
        marker_spin = {0: "^", 1: "v"} if self.nss == 2 else {0: "o"}
        for spin in range(self.nss):
            ys = self.uf_eigens[spin, p.ikfound, :] - e0
            ws = self.uf_weights[spin, p.ikfound, :]
            s = ax.scatter(xs, ys.T, s=fact * ws.T, c=ws.T,
                           marker=marker_spin[spin], label=None if self.nss == 1 else "spin %s" % spin,
                           linewidth=1, edgecolors='none', cmap=plt.get_cmap(colormap))
            plt.colorbar(s, ax=ax, orientation='vertical')

        ax.set_xticks(p.path_ticks, minor=False)
        ax.set_xticklabels(klabels, fontdict=None, minor=False, size=kwargs.pop("klabel_size", "large"))
        ax.grid(True)
        ax.set_ylabel('Energy (eV)')
        set_axlims(ax, ylims, "y")
        if self.nss == 2: ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#12
0
 def plot_maxw(self, ax=None, **kwargs):
     ax, fig, plt = get_ax_fig_plt(ax=ax)
     for label, abifile in self.items():
         abifile.plot_maxw(ax=ax,
                           label=label,
                           with_title=False,
                           show=False,
                           **kwargs)
     return fig
示例#13
0
    def plot_unfolded(self, kbounds, klabels, ylims=None, dist_tol=1e-12, verbose=0,
                      colormap="afmhot", facecolor="black", ax=None, fontsize=12, **kwargs):
        r"""
        Plot unfolded band structure with spectral weights.

        Args:
            klabels: dictionary whose keys are tuple with the reduced coordinates of the k-points.
                The values are the labels. e.g. ``klabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}``.
            ylims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``
                or scalar e.g. ``left``. If left (right) is None, default values are used
            dist_tol: A point is considered to be on the path if its distance from the line
                is less than dist_tol.
            verbose: Verbosity level.
            colormap: Have a look at the colormaps here and decide which one you like:
                http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html
            facecolor:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: Legend and title fontsize.

        Returns: |matplotlib-Figure|
	"""
        cart_bounds = [self.pc_lattice.reciprocal_lattice.get_cartesian_coords(c)
                       for c in np.reshape(kbounds, (-1, 3))]
        uf_cart = self.uf_kpoints.get_cart_coords()

        klines, xs, ticks = find_points_along_path(cart_bounds, uf_cart, dist_tol)
        if len(klines) == 0: return None
        if verbose:
            uf_frac_coords = np.reshape([k.frac_coords for k in self.uf_kpoints], (-1, 3))
            fcoords = uf_frac_coords[klines]
            print("Found %d points along input k-path" % len(fcoords))
            print("k-points of path in reduced coordinates:")
            print(fcoords)

        fact = 8.0
        e0 = self.ebands.fermie
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.set_facecolor(facecolor)

        xs = np.tile(xs, self.nband)
        marker_spin = {0: "^", 1: "v"} if self.nss == 2 else {0: "o"}
        for spin in range(self.nss):
            ys = self.uf_eigens[spin, klines, :] - e0
            ws = self.uf_weights[spin, klines, :]
            s = ax.scatter(xs, ys.T, s=fact * ws.T, c=ws.T,
                           marker=marker_spin[spin], label=None if self.nss == 1 else "spin %s" % spin,
                           linewidth=1, edgecolors='none', cmap=plt.get_cmap(colormap))
            plt.colorbar(s, ax=ax, orientation='vertical')

        ax.set_xticks(ticks, minor=False)
        ax.set_xticklabels(klabels, fontdict=None, minor=False, size=kwargs.pop("klabel_size", "large"))
        ax.grid(True)
        ax.set_ylabel('Energy [eV]')
        set_axlims(ax, ylims, "y")
        if self.nss == 2: ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#14
0
文件: psps.py 项目: zbwang/abipy
    def plot_ffspl(self, ax=None, ecut_ffnl=None, ders=(0,), with_qn=0, with_fact=False, **kwargs):
        """
        Plot the nonlocal part of the pseudopotential in q-space.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            ecut_ffnl: Max cutoff energy for ffnl plot (optional)
            ders: Tuple used to select the derivatives to be plotted.
            with_qn:

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        color = kwargs.pop("color", "black")
        linewidth = kwargs.pop("linewidth", 2.0)

        color_l = {-1: "black", 0: "red", 1: "blue", 2: "green", 3: "orange"}
        linestyles_n = ["solid", '-', '--', '-.', ":"]
        scale = None
        l_seen = set()

        qmesh, vlspl = self.reader.read_vlspl()

        all_projs = self.reader.read_projectors()
        for itypat, projs_type in enumerate(all_projs):
            # Loop over the projectors for this atom type.
            for p in projs_type:
                for der, values in enumerate(p.data):
                    if der == 1: der = 2
                    if der not in ders: continue
                    #yvals, fact = rescale(values, scale=scale)
                    label = None
                    if p.l not in l_seen:
                        l_seen.add(p.l)
                        label = mklabel("v_{nl}", der, "q") + ", l=%d" % p.l

                    stop = len(p.ecuts)
                    if ecut_ffnl is not None:
                        stop = find_gt(p.ecuts, ecut_ffnl)

                    #values = p.ekb * p.values - vlspl[itypat, 0, :]
                    values = vlspl[itypat, 0, :] + p.sign_sqrtekb * p.values

                    #print(values.min(), values.max())
                    ax.plot(p.ecuts[:stop], values[:stop], color=color_l[p.l], linewidth=linewidth,
                            linestyle=linestyles_n[p.n], label=label)

        ax.grid(True)
        ax.set_xlabel("Ecut [Hartree]")
        ax.set_title("ffnl(q)")
        if kwargs.get("with_legend", False): ax.legend(loc="best")

        ax.axhline(y=0, linewidth=linewidth, color='k', linestyle="solid")
        fig.tight_layout()

        return fig
示例#15
0
    def plot_fit_freqs_dir(self,
                           idir,
                           ax=None,
                           units="eV",
                           fontsize=8,
                           **kwargs):
        """
        Plots the phonon frequencies, if available, along the specified direction.
        The line representing the fitted value will be shown as well.

        Args:
            idir: index of the direction.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            units: Units for phonon plots. Possible values in ("eV", "meV", "Ha", "cm-1", "Thz"). Case-insensitive.
            fontsize: fontsize for legends and titles

        Returns: |matplotlib-Figure|
        """
        if self.phfreqs is None or self.qpts is None:
            raise ValueError(
                "The plot requires phonon frequencies and qpoints.")

        ax, fig, plt = get_ax_fig_plt(ax=ax)

        ax.margins(x=0, y=0)
        rlatt = self.structure.lattice.reciprocal_lattice
        freqs = self.phfreqs[idir]
        qpt_cart_coords = np.array([
            np.linalg.norm(rlatt.get_cartesian_coords(c))
            for c in self.qpts[idir]
        ])
        slope = self.sound_velocities[
            idir] / abu.velocity_at_to_si * bohr_to_angstrom / eV_to_Ha

        units_factor = abu.phfactor_ev2units(units)

        title = "[{:.3f}, {:.3f}, {:.3f}]".format(*self.directions[idir])
        if self.labels:
            title += " - {}".format(self.labels[idir])

        for i, c in enumerate(["r", "b", "g"]):
            ax.scatter(qpt_cart_coords,
                       freqs[i] * units_factor,
                       color=c,
                       marker="x")
            ax.plot(qpt_cart_coords,
                    slope[i] * qpt_cart_coords * units_factor,
                    color=c,
                    ls="-")

        ax.set_title(title, fontsize=fontsize)
        ax.grid(True)
        ax.set_xlabel("Wave Vector")
        ax.set_ylabel(abu.wlabel_from_units(units))

        return fig
示例#16
0
    def plot_line(self,
                  point1,
                  point2,
                  num=200,
                  with_krphase=False,
                  cartesian=False,
                  ax=None,
                  fontsize=12,
                  **kwargs):
        """
        Plot (interpolated) wavefunction in real space along a line defined by ``point1`` and ``point2``.

        Args:
            point1: First point of the line. Accepts 3d vector or integer.
                The vector is in reduced coordinates unless ``cartesian`` is True.
                If integer, the first point of the line is given by the i-th site of the structure
                e.g. ``point1=0, point2=1`` gives the line passing through the first two atoms.
            point2: Second point of the line. Same API as ``point1``.
            num: Number of points sampled along the line.
            with_krphase: True to include the :math:`e^{ikr}` phase-factor.
            cartesian: By default, ``point1`` and ``point1`` are interpreted as points in fractional
                coordinates (if not integers). Use True to pass points in cartesian coordinates.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: legend and title fontsize.

        Return: |matplotlib-Figure|
        """
        # Interpolate along line.
        interpolator = self.get_interpolator()
        r = interpolator.eval_line(
            point1,
            point2,
            num=num,
            cartesian=cartesian,
            kpoint=None if not with_krphase else self.kpoint)
        # Plot data.
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        which = r"\psi(r)" if with_krphase else "u(r)"
        for ispinor in range(self.nspinor):
            spinor_label = latex_label_ispinor(ispinor, self.nspinor)
            ur = r.values[ispinor]
            ax.plot(r.dist,
                    ur.real,
                    label=r"$\Re %s$ %s" % (which, spinor_label))
            ax.plot(r.dist,
                    ur.imag,
                    label=r"$\Im %s$ %s" % (which, spinor_label))
            ax.plot(r.dist,
                    ur.real**2 + ur.imag**2,
                    label=r"$|\psi(r)|^2$ %s" % spinor_label)

        ax.grid(True)
        ax.set_xlabel("Distance from site1 [Angstrom]")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#17
0
文件: wr.py 项目: jbouquiaux/abipy
    def plot_maxw(self, scale="semilogy", ax=None, fontsize=8, **kwargs):
        """
        Plot the decay of max_{r,idir,ipert} |W(R,r,idir,ipert)|
        for the long-range and the short-range part.

        Args:
            scale: "semilogy", "loglog" or "plot".
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: fontsize for legends and titles

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        f = {
            "plot": ax.plot,
            "semilogy": ax.semilogy,
            "loglog": ax.loglog
        }[scale]

        rmod = self.reader.read_value("rmod")

        # Plot short-range part.
        # normalize wrt the R=0 value
        # Fortran array: nctkarr_t("maxw_sr", "dp", "nrpt, natom3")
        maxw_sr = self.reader.read_value("maxw_sr")
        data = np.max(maxw_sr, axis=0)
        #data = data / data[0]
        f(rmod, data, marker="o", ls=":", lw=0, label="SR", **kwargs)

        # Plot long-range part.
        maxw_lr = self.reader.read_value("maxw_lr")
        data = np.max(maxw_lr, axis=0)
        #data = data / data[0]
        f(rmod, data, marker="x", ls="-", lw=0, label="LR", **kwargs)

        # Plot the ratio
        data = np.max(maxw_lr, axis=0) / np.max(maxw_sr, axis=0)
        #f(rmod, data, marker="x", ls="-", lw=0, label="LR/SR", **kwargs)

        #rmod = self.reader.read_value("rmod_lrmodel")
        #maxw = self.reader.read_value("maxw_lrmodel")
        #data = np.max(maxw, axis=0)
        #data = data / data[0]
        #f(rmod, data, marker="x", ls="-", lw=0, label="W_LR_only", **kwargs)

        ax.grid(True)
        ax.set_ylabel(
            r"$Max_{({\bf{r}}, idir, ipert)} \| W({\bf{r}}, {\bf{R}}, idir, ipert) \|$"
        )
        ax.set_xlabel(r"$\|{\bf{R}}\|$ (Bohr)")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        #if kwargs.pop("with_title", True):
        #    ax.set_title("dvdb_add_lr %d, qdamp: %s, symv1scf: %d" % (self.dvdb_add_lr, self.qdamp, self.symv1scf),
        #                 fontsize=fontsize)
        return fig
示例#18
0
文件: arpes.py 项目: xue-smile/abipy
    def plot_ekmap_itemp(self, itemp=0, spins=None, estep=0.02, ax=None, ylims=None, with_colorbar=True, **kwargs):
        """
        Plot (k, e) color map for given temperature.

        Args:
            e0: Option used to define the zero of energy in the band structure plot. Possible values:
                - ``fermie``: shift all eigenvalues to have zero energy at the Fermi energy (``self.fermie``).
                - Number e.g ``e0 = 0.5``: shift all eigenvalues to have zero energy at 0.5 eV
                - None: Don't shift energies, equivalent to ``e0 = 0``.
            spins: Selects the spin to be plotted, None if all spins.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            ylims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``
                or scalar e.g. ``left``. If left (right) is None, default values are used
            with_colorbar: True to add color bar.
            kwargs: options passed to ``ax.imshow``.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        a = self.get_data_nmtuple(itemp, estep, spins=spins)

        cmap = "jet"
        img = ax.imshow(a.data.T, origin="lower", extent=[0, a.nkpt, a.emin, a.emax],
                  cmap=cmap,
                  interpolation="bilinear",
                  #interpolation="spline36",
                  #interpolation="bicubic",
                  #vmin=0, vmax=np.abs(data).max()
                  )
        self.ebands.plot(ax=ax, e0=0, show=False, color="w", lw=1, ls="--")

        #ax.set_zlabel(r"$A(\omega)$")
        #self.ebands.plot(ax=ax, e0=0, color="r", lw=1)
        #ax.imshow(data, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None,
        #       origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None,
        #       url=None, hold=None, data=None, **kwargs)

        if with_colorbar:
            # Make a color bar
            #plt.colorbar(img, cmap=cmap)
            # https://stackoverflow.com/questions/13310594/positioning-the-colorbar
            from mpl_toolkits.axes_grid1 import make_axes_locatable
            divider = make_axes_locatable(ax)
            #cax = divider.new_vertical(size="5%", pad=0.1, pack_start=True)
            #cax = divider.new_horizontal(size="5%", pad=0.1, pack_start=True)

            # create an axes on the right side of ax. The width of cax will be 5%
            # of ax and the padding between cax and ax will be fixed at 0.05 inch.
            # https://matplotlib.org/2.0.2/mpl_toolkits/axes_grid/users/overview.html#axesdivider
            cax = divider.append_axes("right", size="5%", pad=0.05)

            #fig.add_axes(cax)
            #fig.colorbar(img, cax=cax, ax=ax, orientation="horizontal")
            fig.colorbar(img, cax=cax, ax=ax)

        return fig
示例#19
0
    def plot_mobility_conv(self, eh=0, component='xx', itemp=0, spin=0, fontsize=14, ax=None, **kwargs):
        """
        Plot the convergence of the mobility obtained in a list of files

        Args:
            eh: 0 for electrons, 1 for holes
            component: Component to plot ('xx', 'xy', ...)
            itemp: Index of the temperature.
            spin: Spin index.
            fontsize: fontsize for legends and titles
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)

        i, j = abu.s2itup(component)

        res = []
        for ncfile in self.abifiles:
            kptrlatt  = ncfile.reader.read_value('kptrlatt')
            kptrlattx = kptrlatt[0, 0]
            kptrlatty = kptrlatt[1, 1]
            kptrlattz = kptrlatt[2, 2]
            #nkpt      = ncfile.nkpt
            mobility  = ncfile.reader.read_value('mobility_mu')[itemp][i,j][spin][eh]
            res.append([kptrlattx, mobility])

        res.sort(key=lambda t: t[0])
        res = np.array(res)

        size = 14
        if eh == 0:
            ax.set_ylabel(r'Electron mobility (cm$^2$/(V$\cdot$s))', size=size)
        elif eh == 1:
            ax.set_ylabel(r'Hole mobility (cm$^2$/(V$\cdot$s))', size=size)
        else:
            raise ValueError("Invalid value for eh argument: %s" % eh)

        from fractions import Fraction
        ratio1 = Fraction(kptrlatty, kptrlattx)
        ratio2 = Fraction(kptrlattz, kptrlattx)
        text1  = '' if ratio1.numerator == ratio1.denominator else \
                 r'$\frac{{{0}}}{{{1}}}$'.format(ratio1.numerator, ratio1.denominator)
        text2  = '' if ratio2.numerator == ratio2.denominator else \
                 r'$\frac{{{0}}}{{{1}}}$'.format(ratio2.numerator, ratio2.denominator)

        ax.set_xlabel(r'Homogeneous $N_k \times$ '+ text1 + r'$N_k \times$ '+ text2 + r'$N_k$ $\mathbf{k}$-point grid',
                      size=size)

        ax.plot(res[:,0], res[:,1], **kwargs)

        ax.legend(loc="best", shadow=True, fontsize=fontsize)

        return fig
示例#20
0
    def plot_vlocq(self,
                   ax=None,
                   ders=(0, ),
                   with_qn=0,
                   with_fact=True,
                   **kwargs):
        """
        Plot the local part of the pseudopotential in q space.

        Args:
            ax: matplotlib :class:`Axes` or None if a new figure should be created.
            ders: Tuple used to select the derivatives to be plotted.
            with_qn:

        Returns:
            matplotlib figure.
        """
        ax, fig, plt = get_ax_fig_plt(ax)

        color = kwargs.pop("color", "black")
        linewidth = kwargs.pop("linewidth", 2.0)

        qmesh, vlspl = self.reader.read_vlspl()
        ecuts = 2 * (np.pi * qmesh)**2
        scale = 1.0
        scale = None
        for atype, vl_atype in enumerate(vlspl):
            for der, values in enumerate(vl_atype):
                if der == 1: der = 2
                if der not in ders: continue

                yvals, fact = rescale(values, scale=scale)
                label = mklabel("v_{loc}", der, "q")
                if with_fact: label += " x %.4f" % fact

                ax.plot(ecuts,
                        yvals,
                        color=color,
                        linewidth=linewidth,
                        linestyle=self.linestyles_der[der],
                        label=label)

                if with_qn and der == 0:
                    yvals, fact = rescale(qmesh * values, scale=scale)
                    ax.plot(ecuts,
                            yvals,
                            color=color,
                            linewidth=linewidth,
                            label="q*f(q) x %2.f" % fact)

        ax.grid(True)
        ax.set_xlabel("Ecut [Hartree]")
        ax.set_title("Vloc(q)")
        if kwargs.get("with_legend", False): ax.legend(loc="best")

        return fig
示例#21
0
文件: arpes.py 项目: gmatteo/abipy
    def plot_ekmap_itemp(self, itemp=0, spins=None, estep=0.02, ax=None, ylims=None, with_colorbar=True, **kwargs):
        """
        Plot (k, e) color map for given temperature.

        Args:
            e0: Option used to define the zero of energy in the band structure plot. Possible values:
                - ``fermie``: shift all eigenvalues to have zero energy at the Fermi energy (``self.fermie``).
                - Number e.g ``e0 = 0.5``: shift all eigenvalues to have zero energy at 0.5 eV
                - None: Don't shift energies, equivalent to ``e0 = 0``.
            spins: Selects the spin to be plotted, None if all spins.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            ylims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``
                or scalar e.g. ``left``. If left (right) is None, default values are used
            with_colorbar: True to add color bar.
            kwargs: options passed to ``ax.imshow``.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        a = self.get_data_nmtuple(itemp, estep, spins=spins)

        cmap = "jet"
        img = ax.imshow(a.data.T, origin="lower", extent=[0, a.nkpt, a.emin, a.emax],
                  cmap=cmap,
                  interpolation="bilinear",
                  #interpolation="spline36",
                  #interpolation="bicubic",
                  #vmin=0, vmax=np.abs(data).max()
                  )
        self.ebands.plot(ax=ax, e0=0, show=False, color="w", lw=1, ls="--")

        #ax.set_zlabel(r"$A(\omega)$")
        #self.ebands.plot(ax=ax, e0=0, color="r", lw=1)
        #ax.imshow(data, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None,
        #       origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None,
        #       url=None, hold=None, data=None, **kwargs)

        if with_colorbar:
            # Make a color bar
            #plt.colorbar(img, cmap=cmap)
            # https://stackoverflow.com/questions/13310594/positioning-the-colorbar
            from mpl_toolkits.axes_grid1 import make_axes_locatable
            divider = make_axes_locatable(ax)
            #cax = divider.new_vertical(size="5%", pad=0.1, pack_start=True)
            #cax = divider.new_horizontal(size="5%", pad=0.1, pack_start=True)

            # create an axes on the right side of ax. The width of cax will be 5%
            # of ax and the padding between cax and ax will be fixed at 0.05 inch.
            # https://matplotlib.org/2.0.2/mpl_toolkits/axes_grid/users/overview.html#axesdivider
            cax = divider.append_axes("right", size="5%", pad=0.05)

            #fig.add_axes(cax)
            #fig.colorbar(img, cax=cax, ax=ax, orientation="horizontal")
            fig.colorbar(img, cax=cax, ax=ax)

        return fig
示例#22
0
    def plot(self, ax=None, **kwargs):
        """
        Plot the histogram with matplotlib, returns `matplotlib` figure.
        """
        ax, fig, plt = get_ax_fig_plt(ax)

        yy = [len(v) for v in self.values]
        ax.plot(self.binvals, yy, **kwargs)

        return fig
示例#23
0
    def plot_fit_energies(self, fit_function=None, min_fit_eta=None, max_fit_eta=None, freq=None,
                          ax=None, **kwargs):
        """
        Fits the displacements etas to the energies. See fit_to_frequency() for more details.

        Args:
            fit_function: a function that will be used to fit the data. The first parameter should be the coefficient
                of the quadratic term. If None a simple quadratic fit will be used.
            min_fit_eta: if not None represents minimum value allowed for the (signed) eta to be used in the fit.
            max_fit_eta: if not None represents maximum value allowed for the (signed) eta to be used in the fit.
            freq: if not None the quadratic function with this frequency as a coefficient will be added to the plot.
                freq in eV. Requires the 0 displacement to be present in the list of etas.
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Returns:
            |matplotlib-Figure|
        """

        if fit_function is None:
            fit_function = quadratic_fit_function

        fit_data = self.fit_to_frequency(fit_function, min_fit_eta=min_fit_eta, max_fit_eta=max_fit_eta)

        ax, fig, plt = get_ax_fig_plt(ax=ax)

        if "color" not in kwargs and "c" not in kwargs:
            kwargs["color"] = "blue"

        kwargs_points = dict(kwargs)
        kwargs_points["linestyle"] = "None"
        if "markersize" not in kwargs_points and "ms" not in kwargs_points:
            kwargs_points["markersize"] = 10
        if "marker" not in kwargs_points and "m" not in kwargs_points:
            kwargs_points["marker"] = "o"

        ax.plot(self.etas, self.energies, **kwargs_points)

        if "linewidth" not in kwargs and "lw" not in kwargs:
            kwargs["linewidth"] = 2
        kwargs["linestyle"] = "-"

        etas_plot = np.linspace(self.etas.min(), self.etas.max(), 100)
        ax.plot(etas_plot, fit_function(etas_plot, *fit_data.fit_params), **kwargs)

        if freq is not None:
            kwargs["linestyle"] = "--"
            e0 = self.energies[self.ieta0]
            en_freq = quadratic_fit_function(etas_plot, self._freq_to_quad_coeff(freq), e0)
            ax.plot(etas_plot, en_freq, **kwargs)

        ax.set_xlabel("Displacements (Ang)")
        ax.set_ylabel("Energy (eV)")

        return fig
示例#24
0
文件: scr.py 项目: Npikeulg/abipy
    def plot_with_ppmodels(self,
                           gvec1,
                           gvec2=None,
                           waxis="real",
                           cplx_mode="re",
                           zcut=0.1 / Ha_to_eV,
                           **kwargs):
        """
        Args:
            gvec1, gvec2:
            waxis: "real" to plot along the real axis, "imag" for the imaginary axis.
            cplx_mode: string defining the data to print.
                       Possible choices are (case-insensitive): `re` for the real part
                       "im" for the imaginary part, "abs" for the absolute value.
                       "angle" will display the phase of the complex number in radians.
                       Options can be concatenated with "-" e.g. "re-im"
            zcut: Small shift along the imaginary axis to avoid poles. 0.1 eV is the Abinit default.
            ax: matplotlib :class:`Axes` or None if a new figure should be created.

        Returns:
            matplotlib figure.
        """
        # Select the (G,G') indices to plot.
        ig1 = self.gindex(gvec1)
        ig2 = ig1 if gvec2 is None else self.gindex(gvec2)

        ax, fig, plt = get_ax_fig_plt(None)

        self.plot_w(gvec1,
                    gvec2=gvec2,
                    waxis=waxis,
                    cplx_mode=cplx_mode,
                    ax=ax,
                    show=False)

        # Compute em1 from the ppmodel on the same grid used for self.
        omegas = {"real": self.real_wpts, "imag": self.imag_wpts}[waxis]

        # Get y-limits of the ab-initio em1 to zoom-in the interesting region
        ymin_em1, ymax_em1 = ax.get_ylim()

        for ppm in self.ppmodels:
            em1_ppm = ppm.eval_em1(omegas, zcut)
            em1_ppm.plot_w(ig1,
                           gvec2=ig2,
                           waxis=waxis,
                           cplx_mode=cplx_mode,
                           ax=ax,
                           linestyle="--",
                           show=False)

        ax.set_ylim(ymin_em1, ymax_em1)

        return fig
示例#25
0
文件: optic.py 项目: zbwang/abipy
    def plot_chi2(self,
                  key,
                  components="all",
                  what="abs",
                  itemp=0,
                  decompose=False,
                  ax=None,
                  xlims=None,
                  with_xlabel=True,
                  label=None,
                  fontsize=12,
                  **kwargs):
        """
        Low-level function to plot chi2 tensor.

        Args:
            key:
            components: List of cartesian tensor components to plot e.g. ["xxx", "xyz"].
                "all" if all components available on file should be plotted on the same ax.
            what: quantity to plot. "re" for real part, "im" for imaginary, Accepts also "abs", "angle".
            itemp: Temperature index.
            decompose: True to plot individual contributions.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``
                   or scalar e.g. ``left``. If left (right) is None, default values are used.
            with_xlabel: True to add x-label.
            label: True to add legend label to each curve.
            fontsize: Legend and label fontsize.

        Returns: |matplotlib-Figure|
        """
        if not self.reader.computed_components[key]: return None
        comp2terms = self.reader.read_tensor3_terms(key,
                                                    components,
                                                    itemp=itemp)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        for comp, terms in comp2terms.items():
            for name, values in terms.items():
                if not decompose and not name.endswith("tot"): continue
                values = data_from_cplx_mode(what, values)
                ax.plot(
                    self.wmesh[1:],
                    values[1:],
                    label=self.get_chi2_latex_label(key, what, comp)
                    if label is None else label,
                )

        ax.grid(True)
        if with_xlabel: ax.set_xlabel('Photon Energy [eV]')
        set_axlims(ax, xlims, "x")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#26
0
    def plot_anharmonic_contribution(self,
                                     freq,
                                     relative=False,
                                     ax=None,
                                     **kwargs):
        """
        Plots the the absolute relative difference between the energies extracted from the frequency as
        quadratic coefficient and the calculated energies, giving an estimate of the anharmonic contribution
        Requires the 0 displacement to be present in the list of etas.

        Args:
            freq: phonon frequncy in eV
            relative: if True the plot will represent the relative difference with respect to the expected value
                obtained from the frequency, rather than the absolute difference.
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Returns:
            |matplotlib-Figure|
        """

        if self.energies is None:
            raise ValueError("The energies are required to calculate the fit")

        self._freq_to_quad_coeff(freq)

        if "color" not in kwargs and "c" not in kwargs:
            kwargs["color"] = "blue"
        if "linewidth" not in kwargs and "lw" not in kwargs:
            kwargs["linewidth"] = 2

        e0 = self.energies[self.ieta0]
        en_freq = quadratic_fit_function(self.etas,
                                         self._freq_to_quad_coeff(freq), e0)

        diff = np.abs(en_freq - np.array(self.energies))

        if relative:
            diff = [
                d / (e - e0) * 100 if e != 0 else 0
                for d, e in zip(diff, en_freq)
            ]

        ax, fig, plt = get_ax_fig_plt(ax=ax)

        ax.plot(self.etas, diff, **kwargs)

        ax.set_xlabel("Displacements (Ang)")
        if relative:
            ax.set_ylabel("Relative energy difference (%)")
        else:
            ax.set_ylabel("Energy difference (eV)")

        return fig
示例#27
0
    def plot_hints(self, with_soc=False, **kwargs):
        # Build pandas dataframe with results.
        rows = []
        for p in self:
            if not p.has_dojo_report:
                cprint("Cannot find dojo_report in %s" % p.basename, "magenta")
                continue
            report = p.dojo_report
            row = {att: getattr(p, att) for att in ("basename", "symbol", "Z", "Z_val", "l_max")}

            # Get deltafactor data with/without SOC
            df_dict = report.get_last_df_results(with_soc=with_soc)
            row.update(df_dict)
            for struct_type in ["fcc", "bcc"]:
                gbrv_dict = report.get_last_gbrv_results(struct_type, with_soc=with_soc)
            row.update(gbrv_dict)

            # Get the hints
            hint = p.hint_for_accuracy(accuracy="normal")
            row.update(dict(ecut=hint.ecut, pawecutdg=hint.pawecutdg))

            rows.append(row)

        import pandas as pd
        frame = pd.DataFrame(rows)

        def print_frame(x):
            import pandas as pd
            with pd.option_context('display.max_rows', len(x),
                                   'display.max_columns', len(list(x.keys()))):
                print(x)

        print_frame(frame)
        # Create axes
        #import matplotlib.pyplot as plt

        import seaborn as sns
        ax, fig, plt = get_ax_fig_plt(ax=None)

        #order = sort_symbols_by_Z(set(frame["element"]))

        # Box plot
        ax = sns.boxplot(x="symbol", y="ecut", data=frame, ax=ax, #order=order,
                         whis=np.inf, color="c")
        # Add in points to show each observation
        sns.stripplot(x="symbol", y="ecut", data=frame, ax=ax, #order=order,
                      jitter=True, size=5, color=".3", linewidth=0)

        sns.despine(left=True)
        ax.set_ylabel("Relative error %")
        ax.grid(True)

        return fig
示例#28
0
    def plot_emass(self,
                   acc=4,
                   ax=None,
                   fontsize=8,
                   colormap="viridis",
                   **kwargs):
        """

        Args:
            acc:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: legend and title fontsize.
            colormap: matplotlib colormap

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        cmap = plt.get_cmap(colormap)

        for ib, enes_kline in enumerate(self.energies_bk):
            # Plot KS-DFT points.
            xs = range(len(enes_kline))
            ax.scatter(xs,
                       enes_kline,
                       marker="o",
                       color=cmap(float(ib) / self.nb))

            # Compute effective masses
            try:
                emass, d2 = self.get_fd_emass_d2(enes_kline, acc)
            except Exception as exc:
                cprint("Eception for segment: %s" % str(self), "red")
                raise exc

            ys = (
                (self.kmk0_2 * units.bohr_to_ang**2) /
                (2 * emass)) * units.Ha_to_eV + self.energies_bk[ib, self.kpos]
            label = r"$m^*$ = %.3f, %d-pts %s finite-diff" % (emass, d2.npts,
                                                              d2.mode)
            ax.plot(xs,
                    ys,
                    linestyle="--",
                    color=cmap(float(ib) / self.nb),
                    label=label)

        ax.legend(loc="best", fontsize=fontsize, shadow=True)
        title = r"${\bf k}_0$: %s, direction: %s" % (repr(
            self.k0), self.kdir.tos(m="fracart"))
        ax.set_title(title, fontsize=fontsize)
        ax.set_ylabel('Energy (eV)')

        return fig
示例#29
0
    def plot_gruns_scatter(self, values="gruns", ax=None, units="eV", cmap="rainbow", **kwargs):
        """
        A scatter plot of the values of the Gruneisen parameters or group velocities as a function
        of the phonon frequencies.

        Args:
            values: Define the plotted quantity. "gruns" for Grunesein parameters, "gruns_fd" for Grunesein
                parameters calculated with finite differences,  "groupv" for phonon group velocities.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            units: Units for phonon frequencies. Possible values in ("eV", "meV", "Ha", "cm-1", "Thz").
                Case-insensitive.
            cmap: matplotlib colormap. If not None, points are colored according to the branch index.
            **kwargs: kwargs passed to the matplotlib function 'scatter'. Size defaults to 10.

        Returns: |matplotlib-Figure|
        """

        if values == "gruns":
            y = self.gvals_qibz
        elif values == "groupv":
            # TODO: units?
            y = np.linalg.norm(self.reader.read_value("gruns_dwdq_qibz"), axis=-1)
        elif values == "gruns_fd":
            y = self.gvals_qibz_finite_differences(match_eigv=True)
        else:
            raise ValueError("Unsupported values: `%s`" % values)

        w = self.wvols_qibz[:, self.iv0, :] * abu.phfactor_ev2units(units)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)

        if 's' not in kwargs:
            kwargs['s'] = 10

        if cmap is None:
            ax.scatter(w.flatten(), y.flatten(), **kwargs)
        else:
            cmap = plt.get_cmap(cmap)
            natom3 = 3 * len(self.structure)
            for nu in range(natom3):
                color = cmap(float(nu) / natom3)
                ax.scatter(w[:, nu], y[:, nu], color=color, **kwargs)

        ax.set_xlabel('Frequency %s' % abu.phunit_tag(units))

        if values.startswith("gruns"):
            ax.set_ylabel('Gruneisen')
        elif values == "groupv":
            ax.set_ylabel('|v|')

        return fig
示例#30
0
文件: bse.py 项目: gmatteo/abipy
    def plot_mdftype_cplx(self, mdf_type, cplx_mode, qpoint=None, ax=None, xlims=None, ylims=None,
                          with_legend=True, with_xlabel=True, with_ylabel=True, fontsize=8, **kwargs):
        """
        Helper function to plot data corresponds to ``mdf_type``, ``cplx_mode``, ``qpoint``.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            mdf_type:
            cplx_mode: string defining the data to print (case-insensitive).
                Possible choices are `re` for the real part, `im` for imaginary part only. `abs` for the absolute value.
            qpoint: index of the q-point or :class:`Kpoint` object or None to plot emacro_avg.
            xlims: Set the data limits for the y-axis. Accept tuple e.g. `(left, right)`
                  or scalar e.g. `left`. If left (right) is None, default values are used
            ylims: Same meaning as `ylims` but for the y-axis
            with_legend: True if legend should be added
            with_xlabel:
            with_ylabel:
            fontsize: Legend and label fontsize.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)

        if with_xlabel: ax.set_xlabel("Frequency (eV)")
        if with_ylabel: ax.set_ylabel(self.MDF_TYPECPLX2TEX[mdf_type][cplx_mode.lower()])

        can_use_basename = self._can_use_basenames_as_labels()
        qtag = "avg" if qpoint is None else repr(qpoint)

        lines, legends = [], []
        for label, mdf_dict in self._mdfs.items():
            mdf = mdf_dict[mdf_type]
            # Plot the average value
            l = mdf.plot_ax(ax, qpoint, cplx_mode=cplx_mode, **kwargs)[0]
            lines.append(l)
            if can_use_basename:
                label = os.path.basename(label)
            else:
                # Use relative paths if label is a file.
                if os.path.isfile(label): label = os.path.relpath(label)

            legends.append(r"%s: %s, %s $\varepsilon$" % (cplx_mode, qtag, label))

        set_axlims(ax, xlims, "x")
        set_axlims(ax, ylims, "y")

        # Set legends.
        if with_legend:
            ax.legend(lines, legends, loc='best', fontsize=fontsize, shadow=True)

        return fig
示例#31
0
    def plot_gruns_scatter(self, values="gruns", ax=None, units="eV", cmap="rainbow", **kwargs):
        """
        A scatter plot of the values of the Gruneisen parameters or group velocities as a function
        of the phonon frequencies.

        Args:
            values: Define the plotted quantity. "gruns" for Grunesein parameters, "gruns_fd" for Grunesein
                parameters calculated with finite differences,  "groupv" for phonon group velocities.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            units: Units for phonon frequencies. Possible values in ("eV", "meV", "Ha", "cm-1", "Thz").
                Case-insensitive.
            cmap: matplotlib colormap. If not None, points are colored according to the branch index.
            **kwargs: kwargs passed to the matplotlib function 'scatter'. Size defaults to 10.

        Returns: |matplotlib-Figure|
        """

        if values == "gruns":
            y = self.gvals_qibz
        elif values == "groupv":
            # TODO: units?
            y = np.linalg.norm(self.reader.read_value("gruns_dwdq_qibz"), axis=-1)
        elif values == "gruns_fd":
            y = self.gvals_qibz_finite_differences(match_eigv=True)
        else:
            raise ValueError("Unsupported values: `%s`" % values)

        w = self.wvols_qibz[:, self.iv0, :] * abu.phfactor_ev2units(units)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)

        if 's' not in kwargs:
            kwargs['s'] = 10

        if cmap is None:
            ax.scatter(w.flatten(), y.flatten(), **kwargs)
        else:
            cmap = plt.get_cmap(cmap)
            natom3 = 3 * len(self.structure)
            for nu in range(natom3):
                color = cmap(float(nu) / natom3)
                ax.scatter(w[:, nu], y[:, nu], color=color, **kwargs)

        ax.set_xlabel('Frequency %s' % abu.phunit_tag(units))

        if values.startswith("gruns"):
            ax.set_ylabel('Gruneisen')
        elif values == "groupv":
            ax.set_ylabel('|v|')

        return fig
示例#32
0
    def plot_freq(self, gvec1, gvec2=None, waxis="real", cplx_mode="re-im", ax=None, fontsize=12, **kwargs):
        r"""
        Plot the frequency dependence of :math:`W_{G1, G2}(\omega)`

        Args:
            gvec1, gvec2:
            waxis: ``real`` to plot along the real axis, ``imag`` for the imaginary axis.
            cplx_mode: string defining the data to print.
                Possible choices are (case-insensitive): ``re`` for the real part
                ``im`` for the imaginary part, ``abs`` for the absolute value.
                ``angle`` will display the phase of the complex number in radians.
                Options can be concatenated with ``-`` e.g. ``re-im``.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: legend and label fontsize.

        Returns: |matplotlib-Figure|
        """
        # Select data to plot
        ig1 = self.gindex(gvec1)
        ig2 = ig1 if gvec2 is None else self.gindex(gvec2)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        if waxis == "real":
            if self.nrew == 0: return fig
            xx = self.real_wpoints.real * pmgu.Ha_to_eV
            yy = self.wggmat_realw[:, ig1, ig2]

        elif waxis == "imag":
            if self.nimw == 0: return fig
            xx = self.imag_wpoints.imag * pmgu.Ha_to_eV
            yy = self.wggmat_imagw[:, ig1, ig2]

        else:
            raise ValueError("Wrong value for waxis: %s" % str(waxis))

        linewidth = kwargs.pop("linewidth", 2)
        linestyle = kwargs.pop("linestyle", "solid")

        lines = []
        for c in cplx_mode.lower().split("-"):
            l, = ax.plot(xx, data_from_cplx_mode(c, yy),
                         color=_COLOR_CMODE[c], linewidth=linewidth, linestyle=linestyle,
                         label=self.latex_label(c))
            lines.append(l)

        ax.grid(True)
        ax.set_xlabel(r"$\omega$ (eV)")
        ax.set_title("%s, kpoint: %s" % (self.netcdf_name, self.kpoint), fontsize=fontsize)
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#33
0
文件: scr.py 项目: gmatteo/abipy
    def plot_freq(self, gvec1, gvec2=None, waxis="real", cplx_mode="re-im", ax=None, fontsize=12, **kwargs):
        r"""
        Plot the frequency dependence of :math:`W_{G1, G2}(\omega)`

        Args:
            gvec1, gvec2:
            waxis: ``real`` to plot along the real axis, ``imag`` for the imaginary axis.
            cplx_mode: string defining the data to print.
                Possible choices are (case-insensitive): ``re`` for the real part
                ``im`` for the imaginary part, ``abs`` for the absolute value.
                ``angle`` will display the phase of the complex number in radians.
                Options can be concatenated with ``-`` e.g. ``re-im``.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: legend and label fontsize.

        Returns: |matplotlib-Figure|
        """
        # Select data to plot
        ig1 = self.gindex(gvec1)
        ig2 = ig1 if gvec2 is None else self.gindex(gvec2)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        if waxis == "real":
            if self.nrew == 0: return fig
            xx = self.real_wpoints.real * pmgu.Ha_to_eV
            yy = self.wggmat_realw[:, ig1, ig2]

        elif waxis == "imag":
            if self.nimw == 0: return fig
            xx = self.imag_wpoints.imag * pmgu.Ha_to_eV
            yy = self.wggmat_imagw[:, ig1, ig2]

        else:
            raise ValueError("Wrong value for waxis: %s" % str(waxis))

        linewidth = kwargs.pop("linewidth", 2)
        linestyle = kwargs.pop("linestyle", "solid")

        lines = []
        for c in cplx_mode.lower().split("-"):
            l, = ax.plot(xx, data_from_cplx_mode(c, yy),
                         color=_COLOR_CMODE[c], linewidth=linewidth, linestyle=linestyle,
                         label=self.latex_label(c))
            lines.append(l)

        ax.grid(True)
        ax.set_xlabel(r"$\omega$ (eV)")
        ax.set_title("%s, kpoint: %s" % (self.netcdf_name, self.kpoint), fontsize=fontsize)
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#34
0
    def plot(self, ax=None, fontsize=12, yscale="log", **kwargs):
        """
        Plot the matrix elements of the KS Hamiltonian in real space in the Wannier Gauge.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: fontsize for legends and titles
            yscale: Define scale for y-axis. Passed to ax.set_yscale
            kwargs: options passed to ``ax.plot``.

        Return: |matplotlib-Figure|
        """
        # Sort R-points by length and build sortmap.
        irs = [ir for ir in enumerate(self.structure.lattice.norm(self.irvec))]
        items = sorted(irs, key=lambda t: t[1])
        sortmap = np.array([item[0] for item in items])
        rvals = np.array([item[1] for item in items])

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        ax.set_xlabel(r"$|R|$ (Ang)")
        ax.set_ylabel(r"$Max |H^W_{ij}(R)|$")

        marker_spin = {0: "^", 1: "v"}
        needs_legend = False
        for spin in range(self.nsppol):
            amax_r = [
                np.abs(self.spin_rmn[spin][ir]).max()
                for ir in range(self.nrpts)
            ]
            amax_r = [amax_r[i] for i in sortmap]
            label = kwargs.get("label", None)
            if label is not None:
                label = "spin: %d" % spin if self.nsppol == 2 else None
            if label: needs_legend = True
            ax.plot(rvals,
                    amax_r,
                    marker=marker_spin[spin],
                    lw=kwargs.get("lw", 2),
                    color=kwargs.get("color", "k"),
                    markeredgecolor="r",
                    markerfacecolor="r",
                    label=label)

            ax.set_yscale(yscale)

        if needs_legend:
            ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#35
0
文件: rta.py 项目: jbouquiaux/abipy
    def plot_vvtau_dos(self, component="xx", spin=0, ax=None, colormap="jet", fontsize=8, **kwargs):
        r"""
        Plot (v_i * v_j * tau) DOS.

            $\frac{1}{N_k} \sum_{nk} v_i v_j \delta(\epsilon - \epsilon_{nk})$

        Args:
            component: Cartesian component to plot: "xx", "yy" "xy" ...
            ax: |matplotlib-Axes| or None if a new figure should be created.
            colormap: matplotlib colormap.
            fontsize (int): fontsize for titles and legend

        Return: |matplotlib-Figure|
        """
        i, j = abu.s2itup(component)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        cmap = plt.get_cmap(colormap)

        for irta in range(self.nrta):
            # nctkarr_t('vvtau_dos', "dp", "edos_nw, three, three, ntemp, nsppol, nrta")
            var = self.reader.read_variable("vvtau_dos")
            for itemp, temp in enumerate(self.tmesh):
                vvtau_dos = var[irta, spin, itemp, j, i, :] / (2 * abu.Ha_s)
                label = "T = %dK" % temp
                if (itemp == 0): label = "%s (%s)" % (label, irta2s(irta))
                if (irta == 0 and itemp > 0): label = None
                ax.plot(self.edos_mesh_eV, vvtau_dos, c=cmap(itemp / self.ntemp), label=label, **style_for_irta(irta))

                # This to plot the vv dos along without tau
                #if itemp == 1:
                #    # nctkarr_t('vv_dos', "dp", "edos_nw, three, three, nsppol"), &
                #    vv_dos_var = self.reader.read_variable("vv_dos")
                #    vv_dos = vv_dos_var[spin, j, i] # / (2 * abu.Ha_s)
                #    ax.plot(self.edos_mesh_eV, vv_dos, c=cmap(itemp / self.ntemp), label='VVDOS' % temp)

        self._add_vline_at_bandedge(ax, spin, "both")

        ax.grid(True)
        ax.set_xlabel('Energy (eV)')
        ax.set_ylabel(r'$v_{%s} v_{%s} \tau$ DOS' % (component[0], component[1]))
        ax.set_yscale('log')
        ax.legend(loc="best", shadow=True, fontsize=fontsize)

        if "title" not in kwargs:
            vvt = r'v_{%s} v_{%s} \tau' % (component[0], component[1])
            title = r"$\frac{1}{N_k} \sum_{nk} %s\,\delta(\epsilon - \epsilon_{nk})$" % vvt
            fig.suptitle(title, fontsize=fontsize)

        return fig
示例#36
0
文件: rta.py 项目: vishankkumar/abipy
    def plot_edos(self, ax=None, fontsize=8, **kwargs):
        """
        Plot the electronic DOS

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        # Total DOS, spin up and spin down components in nsppol_plus1.
        # nctkarr_t("edos_dos", "dp", "edos_nw, nsppol_plus1")
        dos = self.reader.read_value("edos_dos") / abu.Ha_to_eV

        # Plot total DOS.
        ax.plot(self.edos_mesh_eV,
                dos[0],
                label="Total DOS",
                color="black",
                linewidth=1.0)

        #idos = self.reader.read_value("edos_idos")
        #ax.plot(self.edos_mesh_eV, idos[0], label="Total IDOS", color="black", linewidth=1.0)

        if self.nsppol == 2:
            ax.plot(self.edos_mesh_eV,
                    +dos[1],
                    color="red",
                    linewidth=1,
                    label="up")
            ax.plot(self.edos_mesh_eV,
                    -dos[2],
                    color="blue",
                    linewidth=1,
                    label="down")

        for spin in range(self.nsppol):
            self._add_vline_at_bandedge(ax, spin, "both")

        ax.grid(True)
        ax.set_xlabel('Energy (eV)')
        ax.set_ylabel('States/eV p.u.c')
        ax.legend(loc="best", shadow=True, fontsize=fontsize)

        if "title" not in kwargs:
            title = r"$\frac{1}{N_k} \sum_{nk} \delta(\epsilon - \epsilon_{nk})$"
            fig.suptitle(title, fontsize=fontsize)

        return fig
示例#37
0
文件: rta.py 项目: vishankkumar/abipy
    def plot_mobility(self,
                      eh=0,
                      irta=0,
                      component='xx',
                      spin=0,
                      ax=None,
                      colormap='jet',
                      fontsize=8,
                      yscale="log",
                      **kwargs):
        """
        Read the mobility from the netcdf file and plot it

        Args:
            component: Component to plot: "xx", "yy" "xy" ...
            ax: |matplotlib-Axes| or None if a new figure should be created.
            colormap: matplotlib colormap.
            fontsize (int): fontsize for titles and legend

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        cmap = plt.get_cmap(colormap)

        # nctkarr_t('mobility',"dp", "three, three, edos_nw, ntemp, two, nsppol, nrta")
        mu_var = self.reader.read_variable("mobility")
        i, j = abu.s2itup(component)

        for irta in range(self.nrta):
            for itemp, temp in enumerate(self.tmesh):
                mu = mu_var[irta, spin, eh, itemp, :, j, i]
                label = "T = %dK" % temp
                if (itemp == 0): label = "%s (%s)" % (label, irta2s(irta))
                if (irta == 0 and itemp > 0): label = None
                ax.plot(self.edos_mesh_eV,
                        mu,
                        c=cmap(itemp / self.ntemp),
                        label=label,
                        **style_for_irta(irta))

        self._add_vline_at_bandedge(ax, spin, "cbm" if eh == 0 else "vbm")

        ax.grid(True)
        ax.set_xlabel('Fermi level (eV)')
        ax.set_ylabel(r'%s-mobility $\mu_{%s}(\epsilon_F)$ (cm$^2$/Vs)' %
                      (eh2s(eh), component))
        ax.set_yscale(yscale)
        ax.legend(loc="best", shadow=True, fontsize=fontsize)

        return fig
示例#38
0
文件: bse.py 项目: Npikeulg/abipy
    def plot(self, ax=None, cplx_mode="Im", qpoint=None, **kwargs):
        """
        Get a matplotlib plot showing the MDFs.

        Args:
            ax: matplotlib :class:`Axes` or None if a new figure should be created.
            cplx_mode: string defining the data to print (case-insensitive).
                Possible choices are `re` for the real part, `im` for imaginary part only. `abs` for the absolute value.
                Options can be concated with "-".
            qpoint: index of the q-point or :class:`Kpoint` object or None to plot emacro_avg.

        ==============  ==============================================================
        kwargs          Meaning
        ==============  ==============================================================
        xlim            x-axis limits. None (Default) for automatic determination.
        ylim            y-axis limits. None (Default) for automatic determination.
        ==============  ==============================================================
        """
        ax, fig, plt = get_ax_fig_plt(ax)
        ax.grid(True)

        xlim = kwargs.pop("xlim", None)
        if xlim is not None: ax.set_xlim(xlim)

        ylim = kwargs.pop("ylim", None)
        if ylim is not None: ax.set_ylim(ylim)

        ax.set_xlabel('Frequency [eV]')
        ax.set_ylabel('Macroscopic DF')

        cmodes = cplx_mode.split("-")
        qtag = "avg" if qpoint is None else repr(qpoint)

        lines, legends = [], []
        for label, mdf in self._mdfs.items():
            # Plot the q-points
            #for (iq, qpoint) in enumerate(self.qpoints):
            #    self.plot_ax(ax, iq, **kwargs)

            for cmode in cmodes:
                # Plot the average value
                l = mdf.plot_ax(ax, qpoint, cplx_mode=cmode, **kwargs)[0]
                lines.append(l)
                legends.append(r"%s: %s, %s $\,\\varepsilon$" %
                               (cmode, qtag, label))

        # Set legends.
        ax.legend(lines, legends, loc='best', shadow=False)
        return fig
示例#39
0
    def plot_v1qnu_vs_lr(self, ax=None, fontsize=8, **kwargs):
        """
        Plot the difference between the ab-initio v1_qnu and the potential obtained with Verdi's model

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: Label and title fontsize.

        Return: |matplotlib-Figure|
        """
        # Fortran array nctkarr_t("v1_qnu", "dp", "two, nfft, nspden, natom3, nqlist")])
        v1_qnu = self.reader.read_value("v1_qnu", cmode="c")
        v1lr_qnu = self.reader.read_value("v1lr_qnu", cmode="c")

        stats = OrderedDict([
            ("min", []),
            ("max", []),
            ("mean", []),
            ("std", []),
        ])

        qnorms = []
        for iq, qpt in enumerate(self.qpoints):
            qnorms.append(qpt.norm)
            abs_diff = np.abs(v1_qnu[iq] - v1lr_qnu[iq])
            for key in stats.keys():
                stats[key].append(getattr(abs_diff, key)())

        # Sort values by |q|.
        qindex = np.arange(len(qnorms))
        items = sorted(list(zip(qnorms, qindex)),  key=lambda t: t[0])
        qnorm = np.array([t[0] for t in items])
        qindex = np.array([t[1] for t in items])
        #print(qnorm, "\n", qindex)
        for key in stats.keys():
            stats[key] = np.array(stats[key])[qindex]

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        for key, values in stats.items():
            ax.plot(values, label=key)

        ax.grid(True)
        ax.set_xlabel(r"$|\bf{q}|$ 1/Ang")
        #ax.set_ylabel(r"$|g_{\bf q}|$ (meV)")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)
        #title = "band_kq: %s, band_k: %s, kpoint: %s" % (band_kq, band_k, repr(kpoint))
        #ax.set_title(title, fontsize=fontsize)

        return fig
示例#40
0
文件: psps.py 项目: zbwang/abipy
    def plot_tcore_qspace(self, ax=None, ders=(0,), with_fact=True, with_qn=0, **kwargs):
        """
        Plot the model core in q space

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            ders: Tuple used to select the derivatives to be plotted.
            with_qn:

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        color = kwargs.pop("color", "black")
        linewidth = kwargs.pop("linewidth", 2.0)

        qmesh, tcore_spl = self.reader.read_tcorespl()
        #print(qmesh, tcore_spl)
        ecuts = 2 * (np.pi * qmesh)**2
        lines = []
        scale = 1.0
        scale = None
        for atype, tcore_atype in enumerate(tcore_spl):
            for der, values in enumerate(tcore_atype):
                if der == 1: der = 2
                if der not in ders: continue
                yvals, fact = rescale(values, scale=scale)

                label = mklabel("\\tilde{n}_{c}", der, "q")
                if with_fact: label += " x %.4f" % fact

                line, = ax.plot(ecuts, yvals, color=color, linewidth=linewidth,
                                linestyle=self.linestyles_der[der], label=label)
                lines.append(line)

                if with_qn and der == 0:
                    yvals, fact = rescale(qmesh * values, scale=scale)
                    line, ax.plot(ecuts, yvals, color=color, linewidth=linewidth,
                                  label=mklabel("q f", der, "q") + " x %.4f" % fact)

                    lines.append(line)

        ax.grid(True)
        ax.set_xlabel("Ecut [Hartree]")
        ax.set_title("Model core in q-space")
        if kwargs.get("with_legend", False): ax.legend(loc="best")

        return fig
示例#41
0
    def plot_dos(self, ax=None, **kwargs):
        """
        Plot the density of states

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        wmesh, dos, idos = self.reader.read_dos()
        ax.plot(wmesh, dos, **kwargs)
        ax.grid(True)
        ax.set_xlabel('Fermi level (eV)')
        ax.set_ylabel('DOS')
        return fig
示例#42
0
 def plot_vol_vs_t(self, **kwargs):
     """
     Plot the volume as a function of the temperature.
     kwargs are propagated to the analogous method of QHA.
     """
     self._consistency_check()
     ax, fig, plt = get_ax_fig_plt(None)
     cmap = plt.get_cmap(self.colormap)
     for iq, (qha, ngqpt) in enumerate(zip(self.qha_list, self.ngqpt_list)):
         qha.plot_vol_vs_t(ax=ax,
                           color=cmap(float(iq) / self.num_qmeshes),
                           label="ngqpt: %s" % str(ngqpt),
                           show=False,
                           **kwargs)
     ax.legend(loc="best", fontsize=self.fontsize, shadow=True)
     return fig
示例#43
0
    def plot(self,
             ax=None,
             cplx_mode="Im",
             qpoint=None,
             xlims=None,
             ylims=None,
             fontsize=12,
             **kwargs):
        """
        Get a matplotlib plot showing the MDFs.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            cplx_mode: string defining the data to print (case-insensitive).
                Possible choices are ``re`` for the real part, ``im`` for imaginary part only. ``abs`` for the absolute value.
                Options can be concated with "-".
            qpoint: index of the q-point or :class:`Kpoint` object or None to plot emacro_avg.
            xlims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``
                or scalar e.g. ``left``. If left (right) is None, default values are used
            ylims: Same meaning as ``ylims`` but for the y-axis
            fontsize: Legend and label fontsize.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        ax.set_xlabel('Frequency (eV)')
        ax.set_ylabel('Macroscopic DF')

        cmodes = cplx_mode.split("-")
        qtag = "avg" if qpoint is None else repr(qpoint)

        lines, legends = [], []
        for label, mdf in self._mdfs.items():
            for cmode in cmodes:
                # Plot the average value
                l = mdf.plot_ax(ax, qpoint, cplx_mode=cmode, **kwargs)[0]
                lines.append(l)
                legends.append(r"%s: %s, %s $\varepsilon$" %
                               (cmode, qtag, label))

        # Set legends.
        ax.legend(lines, legends, loc='best', fontsize=fontsize, shadow=True)
        set_axlims(ax, xlims, "x")
        set_axlims(ax, ylims, "y")

        return fig
示例#44
0
文件: ifc.py 项目: jbouquiaux/abipy
    def get_plot_ifc(self,
                     ifc,
                     atom_indices=None,
                     atom_element=None,
                     neighbour_element=None,
                     min_dist=None,
                     max_dist=None,
                     ax=None,
                     **kwargs):
        """
        Plots the specified ifcs, filtered according to the optional arguments.
        An array with shape number_of_atoms*number_of_neighbours, so only one of the components of the ifc matrix can
        be plotted at a time.

        Args:
            ifc: an array with shape number_of_atoms * number_of_neighbours of the ifc that should be plotted
            atom_indices: a list of atom indices in the structure. Only neighbours of these atoms will be considered.
            atom_element: symbol of an element in the structure. Only neighbours of these atoms will be considered.
            neighbour_element: symbol of an element in the structure. Only neighbours of this specie will be considered.
            min_dist: minimum distance between atoms and neighbours.
            max_dist: maximum distance between atoms and neighbours.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to blue, symbol to 'o' and lw to 0

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        ind = self._filter_ifc_indices(atom_indices=atom_indices,
                                       atom_element=atom_element,
                                       neighbour_element=neighbour_element,
                                       min_dist=min_dist,
                                       max_dist=max_dist)

        dist, filtered_ifc = self.distances[ind], ifc[ind]

        if 'color' not in kwargs: kwargs['color'] = 'blue'
        if 'marker' not in kwargs: kwargs['marker'] = 'o'
        if 'linewidth' not in kwargs and 'lw' not in kwargs: kwargs['lw'] = 0

        ax.set_xlabel('Distance (Bohr)')
        ax.set_ylabel(r'IFC (Ha/Bohr$^2$)')
        ax.grid(True)
        ax.plot(dist, filtered_ifc, **kwargs)

        return fig
示例#45
0
    def plot_edos(self, ax=None, **kwargs):
        """
        Plot the electronic density of states

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        wmesh, dos, idos = self.reader.read_dos()
        ax.plot(wmesh, dos[0], **kwargs)
        ax.grid(True)
        ax.set_xlabel('Energy (eV)')
        ax.set_ylabel('States/eV')

        return fig
示例#46
0
文件: abiwan.py 项目: gmatteo/abipy
    def plot(self, ax=None, fontsize=12, yscale="log", **kwargs):
        """
        Plot the matrix elements of the KS Hamiltonian in real space in the Wannier Gauge.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: fontsize for legends and titles
            yscale: Define scale for y-axis. Passed to ax.set_yscale
            kwargs: options passed to ``ax.plot``.

        Return: |matplotlib-Figure|
        """
        # Sort R-points by length and build sortmap.
        irs = [ir for ir in enumerate(self.structure.lattice.norm(self.irvec))]
        items = sorted(irs, key=lambda t: t[1])
        sortmap = np.array([item[0] for item in items])
        rvals = np.array([item[1] for item in items])

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        ax.set_xlabel(r"$|R|$ (Ang)")
        ax.set_ylabel(r"$Max |H^W_{ij}(R)|$")

        marker_spin = {0: "^", 1: "v"}
        needs_legend = False
        for spin in range(self.nsppol):
            amax_r = [np.abs(self.spin_rmn[spin][ir]).max() for ir in range(self.nrpts)]
            amax_r = [amax_r[i] for i in sortmap]
            label = kwargs.get("label", None)
            if label is not None:
                label = "spin: %d" % spin if self.nsppol == 2 else None
            if label: needs_legend = True
            ax.plot(rvals, amax_r, marker=marker_spin[spin],
                    lw=kwargs.get("lw", 2),
                    color=kwargs.get("color", "k"),
                    markeredgecolor="r",
                    markerfacecolor="r",
                    label=label)

            ax.set_yscale(yscale)

        if needs_legend:
            ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#47
0
文件: abiwan.py 项目: gmatteo/abipy
    def plot_hwanr(self, ax=None, colormap="jet", fontsize=8, **kwargs):
        """
        Plot the matrix elements of the KS Hamiltonian in real space in the Wannier Gauge.
        on the same Axes.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            colormap: matplotlib color map.
            fontsize: fontsize for legends and titles

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        cmap = plt.get_cmap(colormap)
        for i, abiwan in enumerate(self.abifiles):
            abiwan.hwan.plot(ax=ax, fontsize=fontsize, color=cmap(i / len(self)), show=False)

        return fig
示例#48
0
文件: psps.py 项目: gmatteo/abipy
    def plot_vlocq(self, ax=None, ders=(0,), with_qn=0, with_fact=True, **kwargs):
        """
        Plot the local part of the pseudopotential in q space.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            ders: Tuple used to select the derivatives to be plotted.
            with_qn:

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        color = kwargs.pop("color", "black")
        linewidth = kwargs.pop("linewidth", 2.0)

        qmesh, vlspl = self.reader.read_vlspl()
        ecuts = 2 * (np.pi * qmesh)**2
        scale = 1.0
        scale = None
        for atype, vl_atype in enumerate(vlspl):
            for der, values in enumerate(vl_atype):
                if der == 1: der = 2
                if der not in ders: continue

                yvals, fact = rescale(values, scale=scale)
                label = mklabel("v_{loc}", der, "q")
                if with_fact: label += " x %.4f" % fact

                ax.plot(ecuts, yvals, color=color, linewidth=linewidth,
                        linestyle=self.linestyles_der[der], label=label)

                if with_qn and der == 0:
                    yvals, fact = rescale(qmesh * values, scale=scale)
                    ax.plot(ecuts, yvals, color=color, linewidth=linewidth,
                            label="q*f(q) x %2.f" % fact)

        ax.grid(True)
        ax.set_xlabel("Ecut [Hartree]")
        ax.set_title("Vloc(q)")
        if kwargs.get("with_legend", False): ax.legend(loc="best")

        return fig
示例#49
0
文件: func1d.py 项目: gmatteo/abipy
    def plot(self, ax=None, **kwargs):
        """
        Plot the function.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.

        ==============  ===============================================================
        kwargs          Meaning
        ==============  ===============================================================
        exchange_xy     True to exchange x- and y-axis (default: False)
        ==============  ===============================================================

        Returns: |matplotlib-Figure|.
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        exchange_xy = kwargs.pop("exchange_xy", False)
        self.plot_ax(ax, exchange_xy=exchange_xy, **kwargs)

        return fig
示例#50
0
    def plot_gruns_scatter(self, values="gruns", ax=None, units="eV", **kwargs):
        """
        A scatter plot of the values of the Gruneisen parameters or group velocities as a function
        of the phonon frequencies.

        Args:
            values:  Define the plotted quantity. "gruns" for Grunesein parameters,
                "groupv" for phonon group velocities.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            units: Units for phonon frequencies. Possible values in ("eV", "meV", "Ha", "cm-1", "Thz").
                Case-insensitive.
            **kwargs: kwargs passed to the matplotlib function 'scatter'. Size defaults to 10.

        Returns: |matplotlib-Figure|
        """

        if values == "gruns":
            y = self.gvals_qibz
        elif values == "groupv":
            # TODO: units?
            y = np.linalg.norm(self.reader.read_value("gruns_dwdq_qibz"), axis=-1)
        else:
            raise ValueError("Unsupported values: `%s`" % values)

        w = self.wvols_qibz[:, self.iv0, :] * abu.phfactor_ev2units(units)

        ax, fig, plt = get_ax_fig_plt(ax=ax)

        if 's' not in kwargs:
            kwargs['s'] = 10

        ax.scatter(w.flatten(), y.flatten(), **kwargs)
        ax.set_xlabel('Frequency %s' % abu.phunit_tag(units))
        if values == "gruns":
            ax.set_ylabel('Gruneisen')
        elif values == "groupv":
            ax.set_ylabel('|v|')

        return fig
示例#51
0
文件: bse.py 项目: gmatteo/abipy
    def plot(self, ax=None, cplx_mode="Im", qpoint=None, xlims=None, ylims=None, fontsize=12, **kwargs):
        """
        Get a matplotlib plot showing the MDFs.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            cplx_mode: string defining the data to print (case-insensitive).
                Possible choices are ``re`` for the real part, ``im`` for imaginary part only. ``abs`` for the absolute value.
                Options can be concated with "-".
            qpoint: index of the q-point or :class:`Kpoint` object or None to plot emacro_avg.
            xlims: Set the data limits for the y-axis. Accept tuple e.g. ``(left, right)``
                or scalar e.g. ``left``. If left (right) is None, default values are used
            ylims: Same meaning as ``ylims`` but for the y-axis
            fontsize: Legend and label fontsize.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        ax.set_xlabel('Frequency (eV)')
        ax.set_ylabel('Macroscopic DF')

        cmodes = cplx_mode.split("-")
        qtag = "avg" if qpoint is None else repr(qpoint)

        lines, legends = [], []
        for label, mdf in self._mdfs.items():
            for cmode in cmodes:
                # Plot the average value
                l = mdf.plot_ax(ax, qpoint, cplx_mode=cmode, **kwargs)[0]
                lines.append(l)
                legends.append(r"%s: %s, %s $\varepsilon$" % (cmode, qtag, label))

        # Set legends.
        ax.legend(lines, legends, loc='best', fontsize=fontsize, shadow=True)
        set_axlims(ax, xlims, "x")
        set_axlims(ax, ylims, "y")

        return fig
示例#52
0
文件: pwwave.py 项目: gmatteo/abipy
    def plot_line(self, point1, point2, num=200, with_krphase=False, cartesian=False,
                  ax=None, fontsize=12, **kwargs):
        """
        Plot (interpolated) wavefunction in real space along a line defined by ``point1`` and ``point2``.

        Args:
            point1: First point of the line. Accepts 3d vector or integer.
                The vector is in reduced coordinates unless ``cartesian`` is True.
                If integer, the first point of the line is given by the i-th site of the structure
                e.g. ``point1=0, point2=1`` gives the line passing through the first two atoms.
            point2: Second point of the line. Same API as ``point1``.
            num: Number of points sampled along the line.
            with_krphase: True to include the :math:`e^{ikr}` phase-factor.
            cartesian: By default, ``point1`` and ``point1`` are interpreted as points in fractional
                coordinates (if not integers). Use True to pass points in cartesian coordinates.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: legend and title fontsize.

        Return: |matplotlib-Figure|
        """
        # Interpolate along line.
        interpolator = self.get_interpolator()
        r = interpolator.eval_line(point1, point2, num=num, cartesian=cartesian,
                                   kpoint=None if not with_krphase else self.kpoint)
        # Plot data.
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        which = r"\psi(r)" if with_krphase else "u(r)"
        for ispinor in range(self.nspinor):
            spinor_label = latex_label_ispinor(ispinor, self.nspinor)
            ur = r.values[ispinor]
            ax.plot(r.dist, ur.real, label=r"$\Re %s$ %s" % (which, spinor_label))
            ax.plot(r.dist, ur.imag, label=r"$\Im %s$ %s" % (which, spinor_label))
            ax.plot(r.dist, ur.real**2 + ur.imag**2, label=r"$|\psi(r)|^2$ %s" % spinor_label)

        ax.grid(True)
        ax.set_xlabel("Distance from site1 [Angstrom]")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#53
0
文件: optic.py 项目: gpetretto/abipy
    def plot_chi2(self, key, components="all", what="abs", itemp=0, decompose=False,
                  ax=None, xlims=None, with_xlabel=True, label=None, fontsize=12, **kwargs):
        """
        Low-level function to plot chi2 tensor.

        Args:
            key:
            components: List of cartesian tensor components to plot e.g. ["xxx", "xyz"].
                "all" if all components available on file should be plotted on the same ax.
            what: quantity to plot. "re" for real part, "im" for imaginary, Accepts also "abs", "angle".
            itemp: Temperature index.
            decompose: True to plot individual contributions.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``
                   or scalar e.g. ``left``. If left (right) is None, default values are used.
            with_xlabel: True to add x-label.
            label: True to add legend label to each curve.
            fontsize: Legend and label fontsize.

        Returns: |matplotlib-Figure|
        """
        if not self.reader.computed_components[key]: return None
        comp2terms = self.reader.read_tensor3_terms(key, components, itemp=itemp)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        for comp, terms in comp2terms.items():
            for name, values in terms.items():
                if not decompose and not name.endswith("tot"): continue
                values = data_from_cplx_mode(what, values)
                ax.plot(self.wmesh[1:], values[1:],
                        label=self.get_chi2_latex_label(key, what, comp) if label is None else label,
                )

        ax.grid(True)
        if with_xlabel: ax.set_xlabel('Photon Energy (eV)')
        set_axlims(ax, xlims, "x")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#54
0
文件: abicomp.py 项目: gmatteo/abipy
def abicomp_getattr(options):
    """
    Extract attribute from Abipy object for all files listed on the command line and print them.
    Use `--list` option to list the attributes available (in the first file).
    """
    files = []
    attr_name = options.paths[0]
    values = []
    for p in options.paths[1:]:
        with abilab.abiopen(p) as abifile:
            if options.list:
                print("List of attributes available in %s" % p)
                pprint(dir(abifile))
                return 0

            v = getattr(abifile, attr_name)
            print(v, "   # File: ", p)
            if options.plot:
                try:
                    values.append(float(v))
                except TypeError as exc:
                    print("Cannot plot data. Exception:\n", str(exc))

    if options.plot and len(values) == len(options.paths[1:]):
        # Plot values.

        ax, fig, plt = get_ax_fig_plt()
        xs = np.arange(len(options.paths[1:]))
        ax.plot(xs, values)
        ax.set_ylabel(attr_name)
        ax.set_xticks(xs)
        xlabels = options.paths[1:]
        s = set((os.path.basename(s) for s in xlabels))
        if len(s) == len(xlabels): xlabels = s
        ax.set_xticklabels(xlabels) #, rotation='vertical')
        plt.show()

    return 0
示例#55
0
文件: fields.py 项目: gmatteo/abipy
    def plot_line(self, point1, point2, num=200, cartesian=False, ax=None, fontsize=12, **kwargs):
        """
        Plot (interpolated) density/potential in real space along a line defined by ``point1`` and ``point2``.

        Args:
            point1: First point of the line. Accepts 3d vector or integer.
                The vector is in reduced coordinates unless ``cartesian`` is True.
                If integer, the first point of the line is given by the i-th site of the structure
                e.g. ``point1=0, point2=1`` gives the line passing through the first two atoms.
            point2: Second point of the line. Same API as ``point1``.
            num: Number of points sampled along the line.
            cartesian: By default, ``point1`` and ``point1`` are interpreted as points in fractional
                coordinates (if not integers). Use True to pass points in cartesian coordinates.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: legend and title fontsize.

        Return: |matplotlib-Figure|
        """
        # Interpolate along line.
        r = self.get_interpolator().eval_line(point1, point2, num=num, cartesian=cartesian)

        # Plot data.
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        for ispden in range(self.nspden):
            ax.plot(r.dist, r.values[ispden], label=latexlabel_ispden(ispden, self.nspden))

        ax.grid(True)
        if r.site1 is None:
            ax.set_xlabel("Distance from point %s [Angstrom]" % str(point1))
        else:
            cs = "[%+.5f, %+.5f, %+.5f]" % tuple(r.site1.frac_coords)
            ax.set_xlabel("Distance in Angstrom from %s at %s" % (r.site1.specie.symbol, cs))
        ax.set_ylabel(self.latex_label)
        if self.nspden > 1:
            ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
示例#56
0
文件: hist.py 项目: gmatteo/abipy
    def plot_energies(self, ax=None, fontsize=12, **kwargs):
        """
        Plot the total energies as function of the iteration step.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: Legend and title fontsize.

        Returns: |matplotlib-Figure|
        """
        # TODO max force and pressure
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        terms = self.reader.read_eterms()
        for key, values in terms.items():
            if np.all(values == 0.0): continue
            ax.plot(self.steps, values, marker="o", label=key)

        ax.set_xlabel('Step')
        ax.set_ylabel('Energies (eV)')
        ax.grid(True)
        ax.legend(loc='best', fontsize=fontsize, shadow=True)

        return fig
示例#57
0
    def plot_gruns_bs(self, values="gruns", ax=None, branch_range=None, qlabels=None, match_bands=False, **kwargs):
        """
        A plot of the values of the Gruneisen parameters or group velocities along the
        high symmetry path.
        By default only the calculated points will be displayed. If lines are required set a positive value for lw
        and match_bands=True to obtained reasonable paths.

        Args:
            values:  Define the plotted quantity. "gruns" for Grunesein parameters, "gruns_fd" for Grunesein
                parameters calculated with finite differences,  "groupv" for phonon group velocities.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            branch_range: Tuple specifying the minimum and maximum branch index to plot (default: all
                branches are plotted).
            qlabels: dictionary whose keys are tuples with the reduced coordinates of the q-points.
                The values are the labels. e.g. ``qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}``.
            match_bands: if True the bands will be matched based on the scalar product between the eigenvectors.
            **kwargs: kwargs passed to the matplotlib function 'plot'. Marker size defaults to 4, line width to 0,
                marker to 'o', color to black.

        Returns: |matplotlib-Figure|
        """

        if values == "gruns":
            y = self.split_gruns
        elif values == "groupv":
            # TODO: units?
            y = np.linalg.norm(self.split_dwdq, axis=-1)
        elif values == "gruns_fd":
            y = self.split_gruns_finite_differences(match_eigv=True)
        else:
            raise ValueError("Unsupported values: `%s`" % values)

        phbands = self.phbands_qpath_vol[self.iv0]

        # Select the band range.
        if branch_range is None:
            branch_range = range(phbands.num_branches)
        else:
            branch_range = range(branch_range[0], branch_range[1], 1)

        ax, fig, plt = get_ax_fig_plt(ax=ax)

        phbands.decorate_ax(ax, units=None, qlabels=qlabels)
        if values in ("gruns", "gruns_fd"):
            ax.set_ylabel('Gruneisen')
        elif values == "groupv":
            ax.set_ylabel('|v|')

        if 'marker' not in kwargs and 'm' not in kwargs:
            kwargs['marker'] = 'o'

        if 'markersize' not in kwargs and 'ms' not in kwargs:
            kwargs['markersize'] = 4

        if 'linewidth' not in kwargs and 'lw' not in kwargs:
            kwargs['linewidth'] = 0

        if "color" not in kwargs:
            kwargs["color"] = "black"

        first_xx = 0

        for i, yy in enumerate(y):
            if match_bands:
                ind = phbands.split_matched_indices[i]
                yy = yy[np.arange(len(yy))[:, None], ind]
            xx = list(range(first_xx, first_xx + len(yy)))
            for branch in branch_range:
                ax.plot(xx, yy[:, branch], **kwargs)
            first_xx = xx[-1]

        return fig
示例#58
0
文件: robots.py 项目: gmatteo/abipy
    def plot_convergence(self, item, sortby=None, hue=None, ax=None, fontsize=12, **kwargs):
        """
        Plot the convergence of ``item`` wrt the ``sortby`` parameter.
        Values can optionally be grouped by ``hue``.

        Args:
            item: Define the quantity to plot. Accepts callable or string
                If string, it's assumed that the abifile has an attribute with the same name and `getattr` is invoked.
                Dot notation is also supported e.g. hue="structure.formula" --> abifile.structure.formula
                If callable, the output of item(abifile) is used.
            sortby: Define the convergence parameter, sort files and produce plot labels.
                Can be None, string or function. If None, no sorting is performed.
                If string and not empty it's assumed that the abifile has an attribute
                with the same name and `getattr` is invoked.
                If callable, the output of sortby(abifile) is used.
            hue: Variable that define subsets of the data, which will be drawn on separate lines.
                Accepts callable or string
                If string, it's assumed that the abifile has an attribute with the same name and getattr is invoked.
                If callable, the output of hue(abifile) is used.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: legend and label fontsize.
            kwargs: keyword arguments passed to matplotlib plot method.

        Returns: |matplotlib-Figure|

        Example:

             robot.plot_convergence("energy")

             robot.plot_convergence("energy", sortby="nkpt")

             robot.plot_convergence("pressure", sortby="nkpt", hue="tsmear")
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        if "marker" not in kwargs:
            kwargs["marker"] = "o"

        def get_yvalues(abifiles):
            if callable(item):
                return [float(item(a)) for a in abifiles]
            else:
                return [float(getattr(a, item)) for a in abifiles]

        if hue is None:
            labels, abifiles, params = self.sortby(sortby, unpack=True)
            yvals = get_yvalues(abifiles)
            #print("params", params, "\nyvals", yvals)
            ax.plot(params, yvals, **kwargs)
        else:
            groups = self.group_and_sortby(hue, sortby)
            for g in groups:
                yvals = get_yvalues(g.abifiles)
                label = "%s: %s" % (self._get_label(hue), g.hvalue)
                ax.plot(g.xvalues, yvals, label=label, **kwargs)

        ax.grid(True)
        ax.set_xlabel("%s" % self._get_label(sortby))
        if sortby is None: rotate_ticklabels(ax, 15)
        ax.set_ylabel("%s" % self._get_label(item))

        if hue is not None:
            ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig