Exemplo n.º 1
0
def test_plot_dis():
    spp = kpath.SpecialPointsPath(ks=np.array([[0,0,0], [.5,0,0], [.7,0,0]]),
                                  ks_frac=np.array([[0,0,0], [.55,0,0], [.77,0,0]]),  
                                  symbols=['A','B', 'C'])
    path_norm = np.linspace(0,1,100)
    nfreq = 5
    freqs = np.random.rand(100, nfreq) 
    try:
        print os.environ['DISPLAY']
        fig1,ax1,axdos1 = kpath.plot_dis(path_norm, freqs, spp,
                                         show_coords='cart')
        assert axdos1 is None
        fig2,ax2 = mpl.fig_ax()
        kpath.plot_dis(path_norm, freqs, spp, ax=ax2, show_coords='frac')
        lines1 = ax1.get_lines()
        lines2 = ax2.get_lines()
        for idx in range(nfreq):
            x1 = lines1[idx].get_xdata()
            x2 = lines2[idx].get_xdata()
            y1 = lines1[idx].get_ydata()
            y2 = lines2[idx].get_ydata()
            assert (x1 == x2).all()
            assert (y1 == y2).all()
        faxis = np.linspace(freqs.min(), freqs.max(), 30)                
        dos = np.array([faxis, np.random.rand(len(faxis))]).T            
        fig3,ax3,ax3dos = kpath.plot_dis(path_norm, freqs, spp, dos=dos,
                                         show_coords=None)
        # plot 90 rotated -> x and y swapped
        assert (ax3dos.get_lines()[0].get_xdata() == dos[:,1]).all()
        assert (ax3dos.get_lines()[0].get_ydata() == dos[:,0]).all()
    except KeyError:
        tools.skip("no DISPLAY environment variable, skipping test")
Exemplo n.º 2
0
def plot_pl(*pls):
    # A `pl` is an instance of Plot(). Plot the RPDF and the number integral
    # with the same color and marker. This can be done b/c they look quite
    # different. 
    fig, ax = mpl.fig_ax()
    for pl in pls:
        pl.line1, = ax.plot(pl.rad, 
                            pl.hist, 
                            pl.color + pl.marker + '-',
                            )
        pl.line2, = ax.plot(pl.rad, 
                            pl.num_int, 
                            pl.color + pl.marker + '-', 
                            )
    ax.legend((pl.line1 for pl in pls), (pl.leg_label for pl in pls),
              loc='upper left')
    xlo, xhi = ax.get_xlim()
    ax.hlines(1, xlo, xhi, color='k', lw=2)
    return fig,ax
Exemplo n.º 3
0
def plot_pl(*pls):
    # A `pl` is an instance of Plot(). Plot the RPDF and the number integral
    # with the same color and marker. This can be done b/c they look quite
    # different. 
    fig, ax = mpl.fig_ax()
    for pl in pls:
        pl.line1, = ax.plot(pl.rad, 
                            pl.hist, 
                            pl.color + pl.marker + '-',
                            )
        pl.line2, = ax.plot(pl.rad, 
                            pl.num_int, 
                            pl.color + pl.marker + '-', 
                            )
    ax.legend((pl.line1 for pl in pls), (pl.leg_label for pl in pls),
              loc='upper left')
    xlo, xhi = ax.get_xlim()
    ax.hlines(1, xlo, xhi, color='k', lw=2)
    return fig,ax
Exemplo n.º 4
0
def test_mpl():
    try:
        from pwtools import mpl
        try:
            import os
            print(os.environ['DISPLAY'])
            fig,ax = mpl.fig_ax(dpi=15,num=20)
            assert fig.dpi == 15
            assert fig.number == 20
            
            pl = mpl.Plot(dpi=15,num=20)
            assert pl.fig.dpi == 15
            assert pl.fig.number == 20
            
            dct = mpl.prepare_plots(['test'], dpi=15,num=20)
            assert dct['test'].fig.dpi == 15
            assert dct['test'].fig.number == 20
        except KeyError:
            tools.skip("no DISPLAY environment variable, skipping test")
    except ImportError:
        tools.skipping("couldn't import matplotlib, skipping test")
Exemplo n.º 5
0
def test_mpl():
    try:
        from pwtools import mpl
        try:
            import os
            print os.environ['DISPLAY']
            fig,ax = mpl.fig_ax(dpi=15,num=20)
            assert fig.dpi == 15
            assert fig.number == 20
            
            pl = mpl.Plot(dpi=15,num=20)
            assert pl.fig.dpi == 15
            assert pl.fig.number == 20
            
            dct = mpl.prepare_plots(['test'], dpi=15,num=20)
            assert dct['test'].fig.dpi == 15
            assert dct['test'].fig.number == 20
        except KeyError:
            tools.skip("no DISPLAY environment variable, skipping test")
    except ImportError:
        tools.skipping("couldn't import matplotlib, skipping test")
Exemplo n.º 6
0
def test_plot_dis():
    spp = kpath.SpecialPointsPath(ks=np.array([[0, 0, 0], [.5, 0, 0],
                                               [.7, 0, 0]]),
                                  ks_frac=np.array([[0, 0, 0], [.55, 0, 0],
                                                    [.77, 0, 0]]),
                                  symbols=['A', 'B', 'C'])
    path_norm = np.linspace(0, 1, 100)
    nfreq = 5
    freqs = np.random.rand(100, nfreq)
    try:
        print(os.environ['DISPLAY'])
        fig1, ax1, axdos1 = kpath.plot_dis(path_norm,
                                           freqs,
                                           spp,
                                           show_coords='cart')
        assert axdos1 is None
        fig2, ax2 = mpl.fig_ax()
        kpath.plot_dis(path_norm, freqs, spp, ax=ax2, show_coords='frac')
        lines1 = ax1.get_lines()
        lines2 = ax2.get_lines()
        for idx in range(nfreq):
            x1 = lines1[idx].get_xdata()
            x2 = lines2[idx].get_xdata()
            y1 = lines1[idx].get_ydata()
            y2 = lines2[idx].get_ydata()
            assert (x1 == x2).all()
            assert (y1 == y2).all()
        faxis = np.linspace(freqs.min(), freqs.max(), 30)
        dos = np.array([faxis, np.random.rand(len(faxis))]).T
        fig3, ax3, ax3dos = kpath.plot_dis(path_norm,
                                           freqs,
                                           spp,
                                           dos=dos,
                                           show_coords=None)
        # plot 90 rotated -> x and y swapped
        assert (ax3dos.get_lines()[0].get_xdata() == dos[:, 1]).all()
        assert (ax3dos.get_lines()[0].get_ydata() == dos[:, 0]).all()
    except KeyError:
        tools.skip("no DISPLAY environment variable, skipping test")
Exemplo n.º 7
0
def plot_dis(path_norm,
             freqs,
             special_points_path=None,
             show_coords=None,
             dos=None,
             ax=None,
             ylim=None,
             **kwargs):
    """Plot dispersion. 
    
    See ``bin/plot_dispersion.py`` for a usage example. This lives here (and not in
    :mod:`~pwtools.pwscf`) b/c it is not PWscf-specific. It can be used for any
    dispersion data (band structure).
    
    See :func:`~pwtools.pwscf.read_matdyn_freq` for how to get `freqs` in the
    case of phonon dispersions.

    This function is a convenience function, which can even plot the DOS as
    well. We do not expose many matplotlib parameters here. If you want to tweak
    your plot much, then operate on the returned `fig`, `ax` (dispersion) and
    `axdos` (dos), or copy and hack the function, which might be actually the easiest
    way.
    
    Parameters
    ----------
    path_norm : array (nks,)
        x-axis with cumulative norms of points along the k-path, see
        :func:`get_path_norm`
    freqs : array (nks, nbnd)
        `nbnd` frequencies for each band at each k-point
    special_points_path : optional, :class:`SpecialPointsPath` instance
        used for pretty-printing the x-axis (set special point labels)
    show_coords : 'cart', 'frac', None
        Show the cartesian or fractional coordinates of special points in the
        x-axis label, on neither if None.
    dos : array (N,2) or None
        array with phonon dos to plot: ``dos[:,0]=freq``, ``dos[:,1]=phdos``
    ax : matplotlib AxesSubplot (e.g. from ``fig,ax=pwtools.mpl.fig_ax()``)
        automatically created if None
    ylim : tuple (2,)
        frequency axis limits
    **kwargs : keywords
        passed to plot()
    
    Returns
    -------
    fig, ax, axdos
    fig : matplotlib Figure to ax
    ax : matplotlib AxesSubplot with dispersion
    axdos : matplotlib AxesSubplot with dos, or None if `dos=None` 

    Examples
    --------
    >>> spp = kpath.SpecialPointsPath(ks=np.array([[0,0,0], [1.5,0,0], [2.3,0,0]]),
                                      symbols=['A', 'B', 'C'])
    >>> path_norm = np.linspace(0,2.5,100)
    >>> freqs = np.random.rand(100,5)*500 
    >>> # create fig,ax inside, returned axdos=None
    >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp)
    >>> # pass ax from outside, returns fig,ax but we don't use that b/c ax
    >>> # is in-place modified
    >>> fig,ax = mpl.fig_ax()
    >>> kpath.plot_dis(path_norm, freqs, spp, ax=ax)
    >>> # plot also DOS
    >>> dos = np.empty((30,2)); dos[:,0]=np.linspace(0,500,30); dos[:,1]=rand(30)
    >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp, dos=dos)

    See Also
    --------
    :func:`get_path_norm`
    :func:`pwtools.pwscf.read_matdyn_freq`
    :ref:`dispersion_example`
    """
    if ax is None:
        fig, ax = mpl.fig_ax()
    else:
        fig = ax.get_figure()
    # Plot columns of `freq` against q points (path_norm)
    ax.plot(path_norm, freqs, **kwargs)
    if special_points_path is not None:
        ylim = ax.get_ylim() if ylim is None else ylim
        ks, ks_frac, nrm, symbols = \
            special_points_path.ks, \
            special_points_path.ks_frac, \
            special_points_path.path_norm, \
            special_points_path.symbols
        ax.vlines(nrm, ylim[0], ylim[1])
        fmtfunc = lambda x: "%.2g" % x
        if show_coords is None:
            labels = symbols
        else:
            if show_coords == 'cart':
                ks_plot = ks
            elif show_coords == 'frac':
                ks_plot = ks_frac
            else:
                raise Exception("show_coords = 'cart', 'frac' or "
                                "None needed")
            labels = ['%s\n[%s]' %(sym, common.seq2str(kk, func=fmtfunc,sep=','))\
                      for sym,kk in zip(symbols, ks_plot)]
        ax.set_xticks(nrm)
        ax.set_xticklabels(labels)
        ax.set_xlim(path_norm[0], path_norm[-1])
        ax.set_ylabel("frequency (cm$^{-1}$)")
        if dos is not None:
            # http://matplotlib.org/examples/axes_grid/scatter_hist.html
            from mpl_toolkits.axes_grid1 import make_axes_locatable
            divider = make_axes_locatable(ax)
            axdos = divider.append_axes("right", 1.2, pad=0.1, sharey=ax)
            axdos.plot(dos[:, 1], dos[:, 0], 'b')
            mpl.plt.setp(axdos.get_yticklabels(), visible=False)
            mpl.plt.setp(axdos.get_xticklabels(), visible=False)
            axdos.xaxis.set_tick_params(size=0)
        else:
            axdos = None
    return fig, ax, axdos
Exemplo n.º 8
0
#!/usr/bin/python

# Plot E(V) curve.

from pwtools import sql, mpl, io

db = sql.SQLiteDB('calc.db')
data = db.get_array("select volume,etot from calc order by volume")
natoms = io.cpickle_load('results/0/traj.pk').natoms

# plotting
fig,ax = mpl.fig_ax()
ax.plot(data[:,0]/float(natoms), data[:,1]/float(natoms))
ax.set_ylabel('energy/atom [eV]')
ax.set_xlabel('volume/atom [Ang^3]')

mpl.plt.show()
Exemplo n.º 9
0
#!/usr/bin/python

# Print result of convergence study: differences of etot, pressure

from pwtools import sql, batch, mpl

db = sql.SQLiteDB('calc.db')
etot_fac = 1000.0 / 4  # eV -> meV/atom, 4 atoms
data = db.get_array("select ecutwfc,etot,pressure from calc order by ecutwfc")
print("ecutwfc, diff(etot) [meV/atom], diff(pressure) [GPa]")
print(
    batch.conv_table(data[:, 0], [data[:, 1] * etot_fac, data[:, 2]],
                     mode='last',
                     orig=False))

# plotting
fig, ax = mpl.fig_ax()
ax.plot(data[:, 0], (data[:, 1] - data[-1, 1]) * etot_fac,
        label='etot',
        color='b')
ax.set_ylabel('diff(etot) [meV/atom]')
ax.set_xlabel('ecutwfc [Ry]')
ax.legend()

mpl.plt.show()
Exemplo n.º 10
0
def plot_dis(path_norm, freqs, special_points_path=None, show_coords=None, dos=None, ax=None, ylim=None, **kwargs):
    """Plot dispersion. 
    
    See ``bin/plot_dispersion.py`` for a usage example. This lives here (and not in
    :mod:`~pwtools.pwscf`) b/c it is not PWscf-specific. It can be used for any
    dispersion data (band structure).
    
    See :func:`~pwtools.pwscf.read_matdyn_freq` for how to get `freqs` in the
    case of phonon dispersions.

    This function is a convenience function, which can even plot the DOS as
    well. We do not expose many matplotlib parameters here. If you want to tweak
    your plot much, then operate on the returned `fig`, `ax` (dispersion) and
    `axdos` (dos), or copy and hack the function, which might be actually the easiest
    way.
    
    Parameters
    ----------
    path_norm : array (nks,)
        x-axis with cumulative norms of points along the k-path, see
        :func:`get_path_norm`
    freqs : array (nks, nbnd)
        `nbnd` frequencies for each band at each k-point
    special_points_path : optional, :class:`SpecialPointsPath` instance
        used for pretty-printing the x-axis (set special point labels)
    show_coords : 'cart', 'frac', None
        Show the cartesian or fractional coordinates of special points in the
        x-axis label, on neither if None.
    dos : array (N,2) or None
        array with phonon dos to plot: ``dos[:,0]=freq``, ``dos[:,1]=phdos``
    ax : matplotlib AxesSubplot (e.g. from ``fig,ax=pwtools.mpl.fig_ax()``)
        automatically created if None
    ylim : tuple (2,)
        frequency axis limits
    **kwargs : keywords
        passed to plot()
    
    Returns
    -------
    fig, ax, axdos
    fig : matplotlib Figure to ax
    ax : matplotlib AxesSubplot with dispersion
    axdos : matplotlib AxesSubplot with dos, or None if `dos=None` 

    Examples
    --------
    >>> spp = kpath.SpecialPointsPath(ks=np.array([[0,0,0], [1.5,0,0], [2.3,0,0]]),
                                      symbols=['A', 'B', 'C'])
    >>> path_norm = np.linspace(0,2.5,100)
    >>> freqs = np.random.rand(100,5)*500 
    >>> # create fig,ax inside, returned axdos=None
    >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp)
    >>> # pass ax from outside, returns fig,ax but we don't use that b/c ax
    >>> # is in-place modified
    >>> fig,ax = mpl.fig_ax()
    >>> kpath.plot_dis(path_norm, freqs, spp, ax=ax)
    >>> # plot also DOS
    >>> dos = np.empty((30,2)); dos[:,0]=np.linspace(0,500,30); dos[:,1]=rand(30)
    >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp, dos=dos)

    See Also
    --------
    :func:`get_path_norm`
    :func:`pwtools.pwscf.read_matdyn_freq`
    :ref:`dispersion_example`
    """
    if ax is None:
        fig, ax = mpl.fig_ax()
    else:
        fig = ax.get_figure()
    # Plot columns of `freq` against q points (path_norm)
    ax.plot(path_norm, freqs, **kwargs)
    if special_points_path is not None:
        ylim = ax.get_ylim() if ylim is None else ylim
        ks, ks_frac, nrm, symbols = (
            special_points_path.ks,
            special_points_path.ks_frac,
            special_points_path.path_norm,
            special_points_path.symbols,
        )
        ax.vlines(nrm, ylim[0], ylim[1])
        fmtfunc = lambda x: "%.2g" % x
        if show_coords is None:
            labels = symbols
        else:
            if show_coords == "cart":
                ks_plot = ks
            elif show_coords == "frac":
                ks_plot = ks_frac
            else:
                raise StandardError("show_coords = 'cart', 'frac' or " "None needed")
            labels = [
                "%s\n[%s]" % (sym, common.seq2str(kk, func=fmtfunc, sep=",")) for sym, kk in zip(symbols, ks_plot)
            ]
        ax.set_xticks(nrm)
        ax.set_xticklabels(labels)
        ax.set_xlim(path_norm[0], path_norm[-1])
        ax.set_ylabel("frequency (cm$^{-1}$)")
        if dos is not None:
            # http://matplotlib.org/examples/axes_grid/scatter_hist.html
            from mpl_toolkits.axes_grid1 import make_axes_locatable

            divider = make_axes_locatable(ax)
            axdos = divider.append_axes("right", 1.2, pad=0.1, sharey=ax)
            axdos.plot(dos[:, 1], dos[:, 0], "b")
            mpl.plt.setp(axdos.get_yticklabels(), visible=False)
            mpl.plt.setp(axdos.get_xticklabels(), visible=False)
            axdos.xaxis.set_tick_params(size=0)
        else:
            axdos = None
    return fig, ax, axdos