Exemplo n.º 1
0
def refine_and_resize_structure(struct, refine_cell=True, resize_volume=True):
    if resize_volume:
        dls = DLSVolumePredictor()
        struct = dls.get_predicted_structure(struct)
        struct.apply_strain(0.5)

    if refine_cell:
        sga = SpacegroupAnalyzer(struct)
        # SpacegroupAnalyzer.get_primitive_standard_structure may return incorrect structures
        # So we avoid to use SpacegroupAnalyzer.get_primitive_standard_structure
        struct = sga.get_refined_structure()

    return struct
Exemplo n.º 2
0
def get_symmetry_operations(structure):
    """
    find symmetry operations for a given structure

    Parameters
    ----------
    structure: pymatgen.core.Structure

    Returns
    -------
    rotations: array, (# of symmetry operations, 3, 3)
    translations: array, (# of symmetry operations, 3)
    """
    sym_dataset = SpacegroupAnalyzer(structure).get_symmetry_dataset()
    rotations = sym_dataset["rotations"]
    translations = sym_dataset["translations"]
    return rotations, translations
Exemplo n.º 3
0
def get_symmetry_operations(structure, symprec: float = 1e-2):
    """
    find symmetry operations for a given structure

    Parameters
    ----------
    structure: pymatgen.core.Structure
    symprec: precision parameter in spglib

    Returns
    -------
    rotations: array, (# of symmetry operations, 3, 3)
    translations: array, (# of symmetry operations, 3)
    """
    sym_dataset = SpacegroupAnalyzer(structure,
                                     symprec=symprec).get_symmetry_dataset()
    rotations = sym_dataset["rotations"]
    translations = sym_dataset["translations"]
    return rotations, translations
Exemplo n.º 4
0
def add_alt_projected_dispersion(ax,
                                 data,
                                 pdata,
                                 quantity,
                                 projected,
                                 bandmin=None,
                                 bandmax=None,
                                 temperature=300,
                                 direction='avg',
                                 poscar='POSCAR',
                                 main=True,
                                 log=False,
                                 interpolate=10000,
                                 smoothing=10,
                                 colour='viridis',
                                 cmin=None,
                                 cmax=None,
                                 cscale=None,
                                 unoccupied='grey',
                                 workers=32,
                                 xmarkkwargs={},
                                 **kwargs):
    """Plots a phono3py quantity on a high-symmetry path and projection.

    Just because you can, doesn't mean you should. A maxim I may fail to
    live up to, so I leave it to you, dear reader, to decide for
    yourself. Requires a POSCAR.

    Arguments
    ---------

        ax : axes
            axes to plot on.
        data : dict
            Phono3py-like data containing:

                qpoint : array-like
                    q-point locations.
                (quantities) : array-like
                    plotted and projected quantities.
                temperature : array-like, optional
                    temperature, if necessary for quantities.

        pdata : dict
            phonon dispersion data containing:

                q-point : array-like
                    qpoint locations.
                x : array-like
                    high-symmetry path.
                tick_position : array-like
                    x-tick positions.
                tick_label : array-like
                    x-tick labels.

        quantity : str
            quantity to plot.
        projected: str
            quantity to project.

        bandmin : int, optional
            Zero-indexed minimum band index to plot. Default: 0.
        bandmax : int, optional
            Zero-indexed maximum band index to plot. Default: max index.
        temperature : float, optional
            approximate temperature in K (finds closest). Default: 300.
        direction : str, optional
            direction from anisotropic data, accepts x-z/ a-c,
            average/ avg or normal/ norm. Default: average.

        poscar : str, optional
            VASP POSCAR filepath. Default: POSCAR.

        main : bool, optional
            set axis ticks, label, limits. Default: True.
        log : bool, optional
            log the y scale. Default: False.
        interpolate : int, optional
            number of points per line. Default: 10,000.
        smoothing : int, optional
            every n points to sample. Default: 10.

        colour : colormap or str, optional
            colourmap or colourmap name. Default: viridis.
        cmin : float, optional
            colour scale minimum. Default: display 99 % data.
        cmax : float, optional
            colour scale maximum. Default: display 99.9 % data.
        cscale : str, optional
            override colour scale (linear/ log). Default: None.
        unoccupied : str, optional
            if the colour variable is occuption, values below 1 are
            coloured in this colour. Id set to None, or cmin is set,
            this feature is turned off. Default: grey.

        workers : int, optional
            number of workers for paralellised section. Default: 32.

        xmarkkwargs : dict, optional
            keyword arguments for x markers passed to
            matplotlib.pyplot.axvline. Set color to None to turn off.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Defaults:

            color:      black
            linewidth:  axis line width
            rasterized: False

        kwargs
            keyword arguments passed to matplotlib.pyplot.scatter.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Defaults:

                marker:     .
                rasterized: True

    Returns
    -------

        colorbar
            colour bar for projected data.
    """

    from functools import partial
    from multiprocessing import Pool
    from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    import pymatgen.symmetry.analyzer as pmg
    from copy import copy
    from scipy.interpolate import interp1d

    # defaults

    defkwargs = {'marker': '.', 'rasterized': True}

    if conf is None or 'alt_projected_dispersion_kwargs' not in conf or \
       conf['alt_projected_dispersion_kwargs'] is None:
        kwargs = {**defkwargs, **kwargs}
    else:
        kwargs = {
            **defkwargs,
            **conf['alt_projected_dispersion_kwargs'],
            **kwargs
        }

    # check inputs

    for name, value in zip(['main', 'log'], [main, log]):
        assert isinstance(value, bool), '{} must be True or False'.format(name)

    # Phono3py data formatting

    tnames = tp.settings.to_tp()
    if quantity in tnames: quantity = tnames[quantity]
    if projected in tnames: projected = tnames[projected]
    if quantity == 'kappa': quantity = 'mode_kappa'
    if projected == 'kappa': projected = 'mode_kappa'
    qs = quantity if quantity == projected else [quantity, projected]

    data = tp.data.resolve.resolve(data, qs, temperature, direction)
    y = data[quantity]
    c = data[projected]
    if bandmin is None:
        bandmin = 0
    else:
        bandmin = np.amax([0, bandmin])
    if bandmax is None:
        bandmax = len(y[0])
    else:
        bandmax = np.amin([len(y[0]), bandmax])
    y = np.array(y)[:, bandmin:bandmax]
    c = np.array(c)[:, bandmin:bandmax]
    qk = data['qpoint']

    # Phonopy data formatting

    qp = pdata['qpoint']
    x = pdata['x']

    # map Phono3py to Phonopy

    struct = Poscar.from_file(poscar).structure
    sg = SpacegroupAnalyzer(struct)
    symops = sg.get_point_group_operations(cartesian=False)
    geq = partial(get_equivalent_qpoint, np.array(qk), symops)
    with Pool(processes=workers) as pool:
        min_id = pool.map(geq, qp)
    y2 = y[min_id, :]
    c2 = c[min_id, :]

    x, indices = np.unique(x, return_index=True)
    y2 = np.array(y2)[indices]
    c2 = np.array(c2)[indices]
    if len(x) > 100:
        xi = [x[i] for i in range(len(x)) if i % smoothing == 0]
        y2 = [y2[i] for i in range(len(y2)) if i % smoothing == 0]
    else:
        xi = x
        y2 = y2
    if xi[-1] != x[-1]:
        y2.append(y2[-1])
        xi.append(x[-1])

    # interpolate

    x2 = np.linspace(min(x), max(x), interpolate)
    yinterp = interp1d(xi, y2, kind='cubic', axis=0)
    y2 = np.abs(yinterp(x2))
    ysort = np.ravel(y2)
    ysort = ysort[ysort.argsort()]
    ymin = ysort[int(round(len(ysort) / 100 - 1, 0))]
    ymax = ysort[int(round(len(ysort) * 99.9 / 100 - 1, 0))]

    cinterp = interp1d(x, c2, kind='cubic', axis=0)
    c2 = np.abs(cinterp(x2))
    if isinstance(colour, str):
        cmap = copy(plt.cm.get_cmap(colour))
    else:
        cmap = copy(colour)
    cnorm, extend = tp.plot.utilities.colour_scale(c2, projected, cmap, cmin,
                                                   cmax, cscale, unoccupied)

    # plotting

    for n in range(len(y2[0])):
        line = ax.scatter(x2,
                          y2[:, n],
                          c=c2[:, n],
                          cmap=cmap,
                          norm=cnorm,
                          **kwargs)

    # axes formatting

    axlabels = tp.settings.labels()
    cbar = plt.colorbar(line, extend=extend)
    cbar.set_alpha(1)
    cbar.set_label(axlabels[projected])
    tp.plot.utilities.set_locators(cbar.ax, y=cbar.ax.yaxis.get_scale())
    cbar.draw_all()

    if main:
        ax.set_ylim(ymin, ymax)
        formatting(ax, pdata, quantity, log=log, **xmarkkwargs)

    return cbar
Exemplo n.º 5
0
def add_projected_dispersion(ax,
                             data,
                             pdata,
                             quantity,
                             bandmin=None,
                             bandmax=None,
                             temperature=300,
                             direction='avg',
                             poscar='POSCAR',
                             main=True,
                             interpolate=500,
                             colour='viridis_r',
                             cmin=None,
                             cmax=None,
                             cscale=None,
                             unoccupied='grey',
                             workers=32,
                             xmarkkwargs={},
                             **kwargs):
    """Plots a phonon dispersion with projected colour.

    Plots a phonon dispersion, and projects a quantity onto the colour
    axis. Requires a POSCAR.

    Arguments
    ---------

        ax : axes
            axes to plot on.
        data : dict
            Phono3py-like data containing:

                qpoint : array-like
                    q-point locations.
                (quantity) : array-like
                    projected quantity.
                temperature : array-like, optional
                    temperature, if necessary for quantity.

        pdata : dict
            phonon dispersion data containing:

                q-point : array-like
                    qpoint locations.
                x : array-like
                    high-symmetry path.
                frequency : array-like
                    phonon frequencies.
                tick_position : array-like
                    x-tick positions.
                tick_label : array-like
                    x-tick labels.

        quantity : str
            quantity to project.

        bandmin : int, optional
            Zero-indexed minimum band index to plot. Default: 0.
        bandmax : int, optional
            Zero-indexed maximum band index to plot. Default: max index.
        temperature : float, optional
            approximate temperature in K (finds closest). Default: 300.
        direction : str, optional
            direction from anisotropic data, accepts x-z/ a-c,
            average/ avg or normal/ norm. Default: average.

        poscar : str, optional
            VASP POSCAR filepath. Default: POSCAR.

        main : bool, optional
            set axis ticks, label, limits. Default: True.
        interpolate : int, optional
            number of points per path (e.g. gamma -> X) per line.
            Default: 500.

        colour : colormap or str, optional
            colourmap or colourmap name. Default: viridis_r.
        cmin : float, optional
            colour scale minimum. Default: display 99 % data.
        cmax : float, optional
            colour scale maximum. Default: display 99.9 % data.
        cscale : str, optional
            override colour scale (linear/ log). Default: None.
        unoccupied : str or array-like, optional
            if the colour variable is occuption, values below 1 are
            coloured in this colour. If set to None, or cmin is set,
            this feature is turned off. Default: grey.

        workers : int, optional
            number of workers for paralellised section. Default: 32.

        xmarkkwargs : dict, optional
            keyword arguments for x markers passed to
            matplotlib.pyplot.axvline. Set color to None to turn off.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Default

            color:      black
            linewidth:  axis line width
            rasterized: False

        kwargs
            keyword arguments passed to matplotlib.pyplot.scatter.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Defaults:

            marker:     .
            rasterized: True

    Returns
    -------

        colorbar
            colour bar for projected data.
    """

    from functools import partial
    from multiprocessing import Pool
    from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    import pymatgen.symmetry.analyzer as pmg
    from copy import copy
    from scipy.interpolate import interp1d

    # defaults

    defkwargs = {'marker': '.', 'rasterized': True}

    if conf is None or 'projected_dispersion_kwargs' not in conf or \
       conf['projected_dispersion_kwargs'] is None:
        kwargs = {**defkwargs, **kwargs}
    else:
        kwargs = {**defkwargs, **conf['projected_dispersion_kwargs'], **kwargs}

    # check inputs

    assert isinstance(main, bool), 'main must be True or False'

    # Phono3py data formatting

    tnames = tp.settings.to_tp()
    quantity = tnames[quantity] if quantity in tnames else quantity
    if quantity == 'kappa': quantity = 'mode_kappa'

    data = tp.data.resolve.resolve(data, quantity, temperature, direction)
    c = data[quantity]
    if bandmin is None:
        bandmin = 0
    else:
        bandmin = np.amax([0, bandmin])
    if bandmax is None:
        bandmax = len(c[0])
    else:
        bandmax = np.amin([len(c[0]), bandmax])
    c = np.array(c)[:, bandmin:bandmax]
    qk = data['qpoint']

    # Phonopy data formatting

    qp = pdata['qpoint']
    x = pdata['x']
    f = np.array(pdata['frequency'])[:, bandmin:bandmax]

    # map Phono3py to Phonopy

    struct = Poscar.from_file(poscar).structure
    sg = SpacegroupAnalyzer(struct)
    symops = sg.get_point_group_operations(cartesian=False)
    geq = partial(get_equivalent_qpoint, np.array(qk), symops)
    with Pool(processes=workers) as pool:
        min_id = pool.map(geq, qp)
    c = c[min_id, :]

    x, indices = np.unique(x, return_index=True)
    f = np.array(f)[indices]
    c = np.array(c)[indices]

    # interpolate

    index = [0, 0]
    x2, f2, c2 = [], [], []
    for d in pdata['tick_position'][1:]:
        index[0] = index[1] + 1
        index[1] = next(i[0] for i in enumerate(x) if i[1] == d)
        xtemp = np.linspace(x[index[0]], x[index[1]], interpolate)
        finterp = interp1d(x[index[0]:index[1]],
                           f[index[0]:index[1]],
                           kind='cubic',
                           axis=0,
                           fill_value='extrapolate')
        x2.append(xtemp)
        f2.append(finterp(xtemp))

        cinterp = interp1d(x[index[0]:index[1]],
                           c[index[0]:index[1]],
                           kind='cubic',
                           axis=0,
                           fill_value='extrapolate')
        c2.append(np.abs(cinterp(xtemp)))

    if isinstance(colour, str):
        cmap = copy(plt.cm.get_cmap(colour))
    else:
        cmap = copy(colour)
    cnorm, extend = tp.plot.utilities.colour_scale(c2, quantity, cmap, cmin,
                                                   cmax, cscale, unoccupied)

    # plotting

    for n in range(len(f2[0][0])):
        for i in range(len(x2)):
            line = ax.scatter(x2[i],
                              np.array(f2[i])[:, n],
                              c=np.array(c2[i])[:, n],
                              cmap=cmap,
                              norm=cnorm,
                              **kwargs)

    # axes formatting

    axlabels = tp.settings.labels()
    cbar = plt.colorbar(line, extend=extend)
    cbar.set_alpha(1)
    cbar.set_label(axlabels[quantity])
    tp.plot.utilities.set_locators(cbar.ax, y=cbar.ax.yaxis.get_scale())
    cbar.draw_all()

    if main:
        if round(np.amin(f), 1) == 0:
            ax.set_ylim(bottom=0)
        formatting(ax, pdata, 'frequency', **xmarkkwargs)

    return cbar
Exemplo n.º 6
0
def add_alt_dispersion(
        ax,
        data,
        pdata,
        quantity,
        bandmin=None,
        bandmax=None,
        temperature=300,
        direction='avg',
        label=['Longitudinal', 'Transverse_1', 'Transverse_2', 'Optic'],
        poscar='POSCAR',
        main=True,
        log=False,
        interpolate=10000,
        smoothing=5,
        colour=['#44ffff', '#ff8044', '#ff4444', '#00000010'],
        linestyle='-',
        workers=32,
        xmarkkwargs={},
        **kwargs):
    """Plots a phono3py quantity on a high-symmetry path.

    Labels, colours and linestyles can be given one for the whole
    dispersion, or one for each band, with the last entry filling all
    remaining bands. Requires a POSCAR.

    Arguments
    ---------

        ax : axes
            axes to plot on.
        data : dict
            Phono3py-like data containing:

                qpoint : array-like
                    q-point locations.
                (quantity) : array-like
                    plotted quantity.
                temperature : array-like, optional
                    temperature, if necessary for quantity.

        pdata : dict
            phonon dispersion data containing:

                q-point : array-like
                    qpoint locations.
                x : array-like
                    high-symmetry path.
                tick_position : array-like
                    x-tick positions.
                tick_label : array-like
                    x-tick labels.

        quantity : str
            quantity to plot.

        bandmin : int, optional
            Zero-indexed minimum band index to plot. Default: 0.
        bandmax : int, optional
            Zero-indexed maximum band index to plot. Default: max index.
        temperature : float, optional
            approximate temperature in K (finds closest). Default: 300.
        direction : str, optional
            direction from anisotropic data, accepts x-z/ a-c,
            average/ avg or normal/ norm. Default: average.
        label : array-like, optional
            labels per line. A single dataset could have a single label,
            or the default labels the lines by type. You'll want to
            change this if a minimum band index is set.
            Default: ['Longitudinal', 'Transverse_1', 'Transverse_2',
            'Optic'].

        poscar : str, optional
            VASP POSCAR filepath. Default: POSCAR.

        main : bool, optional
            set axis ticks, label, limits. Default: True.
        log : bool, optional
            log the y scale. Default: False.
        interpolate : int, optional
            number of points per line. Default: 10,000.
        smoothing : int, optional
            every n points to sample. Default: 5.

        colour : str or array-like, optional
            line colour(s). Note if retrieved from a colourmap or in
            [r,g,b] notation, the colour should be enclosed in [], e.g.
            colour = plt.get_cmap('winter_r')(linspace(0, 1, len(files)))
            tp.plot.phonons.add_dispersion(..., colour=[colour[0]], ...)
            Default: ['#44ffff', '#ff8044', '#ff4444', '#00000010'].
        linestyle : str or array-like, optional
            linestyle(s) ('-', '--', '.-', ':'). Default: solid.

        workers : int, optional
            number of workers for paralellised section. Default: 32.

        xmarkkwargs : dict, optional
            keyword arguments for x markers passed to
            matplotlib.pyplot.axvline. Set color to None to turn off.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Defaults:

                color:      black
                linewidth:  axis line width
                rasterized: False

        kwargs
            keyword arguments passed to matplotlib.pyplot.plot.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Defaults:

                rasterized: False

    Returns
    -------

        None
            adds plot directly to ax.
    """

    from functools import partial
    from multiprocessing import Pool
    from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    import pymatgen.symmetry.analyzer as pmg
    from scipy.interpolate import interp1d

    # defaults

    defkwargs = {'rasterized': False}

    if conf is None or 'alt_dispersion_kwargs' not in conf or \
       conf['alt_dispersion_kwargs'] is None:
        kwargs = {**defkwargs, **kwargs}
    else:
        kwargs = {**defkwargs, **conf['alt_dispersion_kwargs'], **kwargs}

    # check inputs

    for name, value in zip(['main', 'log'], [main, log]):
        assert isinstance(value, bool), '{} must be True or False'.format(name)

    # Phono3py data formatting

    tnames = tp.settings.to_tp()
    if quantity in tnames: quantity = tnames[quantity]
    if quantity == 'kappa': quantity = 'mode_kappa'

    data = tp.data.resolve.resolve(data, quantity, temperature, direction)
    y = data[quantity]
    if bandmin is None:
        bandmin = 0
    else:
        bandmin = np.amax([0, bandmin])
    if bandmax is None:
        bandmax = len(y[0])
    else:
        bandmax = np.amin([len(y[0]), bandmax])
    y = np.array(y)[:, bandmin:bandmax]
    qk = data['qpoint']

    # Phonopy data formatting

    qp = pdata['qpoint']
    x = pdata['x']

    if len(x) > 100:
        xi = [x[i] for i in range(len(x)) if i % smoothing == 0]
        qpi = [qp[i] for i in range(len(qp)) if i % smoothing == 0]
    else:
        xi = x
        qpi = qp
    if xi[-1] != x[-1]:
        qpi.append(qp[-1])
        xi.append(x[-1])

    # map Phono3py to Phonopy

    struct = Poscar.from_file(poscar).structure
    sg = SpacegroupAnalyzer(struct)
    symops = sg.get_point_group_operations(cartesian=False)
    geq = partial(get_equivalent_qpoint, np.array(qk), symops)
    with Pool(processes=workers) as pool:
        min_id = pool.map(geq, qpi)
    y2 = y[min_id, :]

    x, indices = np.unique(xi, return_index=True)
    y2 = np.array(y2)[indices]

    # interpolate

    x2 = np.linspace(min(x), max(x), interpolate)
    yinterp = interp1d(x, y2, kind='cubic', axis=0)
    y2 = np.abs(yinterp(x2))
    ysort = np.ravel(y2)
    ysort = ysort[ysort.argsort()]
    ymin = ysort[int(round(len(ysort) / 100, 0))]
    ymax = ysort[-1]

    # line appearance

    colour = tile_properties(colour, bandmin, bandmax)
    linestyle = tile_properties(linestyle, bandmin, bandmax)

    # prevents unintentionally repeated legend entries

    label2 = []
    if isinstance(label, str):
        label2.extend(['$\mathregular{{{}}}$'.format(label)])
    else:
        try:
            label = ['$\mathregular{{{}}}$'.format(l) for l in label]
            label2.extend(label)
        except Exception:
            label2.extend([label])
    label2.append(None)
    label2 = tile_properties(label2, bandmin, bandmax)

    # plotting

    for n in range(len(y2[0])):
        ax.plot(x2,
                y2[:, n],
                color=colour[n],
                linestyle=linestyle[n],
                label=label2[n],
                **kwargs)

    # axes formatting

    if main:
        ax.set_ylim(ymin, ymax)
        formatting(ax, pdata, quantity, log=log, **xmarkkwargs)

    return
Exemplo n.º 7
0
def add_wideband(ax,
                 kdata,
                 pdata,
                 temperature=300,
                 poscar='POSCAR',
                 main=True,
                 smoothing=5,
                 colour='viridis',
                 workers=32,
                 xmarkkwargs={},
                 **kwargs):
    """Plots a phonon dispersion with broadened bands.

    Requires a POSCAR.

    Arguments
    ---------

        ax : axes
            axes to plot on.
        kdata : dict
            Phono3py-like data containing:

                qpoint : array-like
                    q-point locations.
                gamma : array-like
                    imaginary component of the self-energy.
                temperature : array-like
                    temperature.

        pdata : dict
            phonon dispersion data containing:

                q-point : array-like
                    qpoint locations.
                x : array-like
                    high-symmetry path.
                frequency : array-like
                    phonon frequencies.
                tick_position : array-like
                    x-tick positions.
                tick_label : array-like
                    x-tick labels.

        temperature : float, optional
            approximate temperature in K (finds closest). Default: 300.

        poscar : str, optional
            VASP POSCAR filepath. Default: POSCAR.

        main : bool, optional
            set axis ticks, label, limits. Default: True.
        smoothing : int, optional
            every n points to sample. Default: 5.

        colour : colormap or str or list, optional
            colourmap or colourmap name or max #RRGGBB colour (fades to
            white) or min and max #RRGGBB colours. Default: viridis.

        workers : int, optional
            number of workers for paralellised section. Default: 32.

        xmarkkwargs : dict, optional
            keyword arguments for x markers passed to
            matplotlib.pyplot.axvline. Set color to None to turn off.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Defaults:

                color:      None
                linewidth:  axis line width
                rasterized: False

        kwargs
            keyword arguments passed to matplotlib.pyplot.pcolormesh.
            Defaults are defined below, which are overridden by those in
            ``~/.config/tprc.yaml``, both of which are overridden by
            arguments passed to this function.
            Defaults:

                rasterized: True
                shading:    auto

    Returns
    -------

        None
            adds plot directly to ax.
    """

    from functools import partial
    from multiprocessing import Pool
    from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    import pymatgen.symmetry.analyzer as pmg
    from scipy.interpolate import interp1d
    from tp.calculate import lorentzian

    # defaults

    defkwargs = {'rasterized': True, 'shading': 'auto'}

    if conf is None or 'wideband_kwargs' not in conf or \
       conf['wideband_kwargs'] is None:
        kwargs = {**defkwargs, **kwargs}
    else:
        kwargs = {**defkwargs, **conf['wideband_kwargs'], **kwargs}

    defxmarkkwargs = {'color': None}
    xmarkkwargs = {**defxmarkkwargs, **xmarkkwargs}

    # check inputs

    assert isinstance(main, bool), 'main must be True or False'

    # Phono3py data formatting

    kdata = tp.data.resolve.resolve(kdata, 'gamma', temperature)
    c = np.array(kdata['gamma'])
    qk = kdata['qpoint']

    # Phonopy data formatting

    qp = pdata['qpoint']
    x = pdata['x']

    qpi = [qp[i] for i in range(len(qp)) if i % smoothing == 0]
    xi = [x[i] for i in range(len(x)) if i % smoothing == 0]
    if xi[-1] != x[-1]:
        qpi.append(qp[-1])
        xi.append(x[-1])

    # map Phono3py to Phonopy

    struct = Poscar.from_file(poscar).structure
    sg = SpacegroupAnalyzer(struct)
    symops = sg.get_point_group_operations(cartesian=False)
    geq = partial(get_equivalent_qpoint, np.array(qk), symops)
    with Pool(processes=workers) as pool:
        min_id = pool.map(geq, qpi)
    c2 = c[min_id, :]

    x, indices = np.unique(x, return_index=True)
    f = np.array(pdata['frequency'])[indices]
    where = np.where(c2 == np.amax(c2))

    # interpolate

    x2 = np.linspace(min(x), max(x), 2500)
    finterp = interp1d(x, f, kind='cubic', axis=0)
    f = finterp(x2)

    cinterp = interp1d(xi, c2, kind='cubic', axis=0)
    c2 = np.abs(cinterp(x2))
    fmax = np.amax(np.add(f, c2))
    fmin = np.amin(np.subtract(f, c2))
    f2 = np.linspace(fmin, fmax, 2500)

    # broadening

    area = np.zeros((len(x2), len(f2)))
    for q in range(len(area)):
        for b in range(len(c2[q])):
            area[q] = np.add(area[q], lorentzian(f2, f[q][b], c2[q][b]))

    cnorm = mpl.colors.LogNorm(vmin=np.nanmin(area), vmax=np.nanmax(area))

    # colours
    # Tries colourmap name or colourmap object, then tries a single
    # colour as the max of a linear colourmap, then tries two colours as
    # the min and max values.

    try:
        colours = mpl.cm.get_cmap(colour)
    except Exception:
        if isinstance(colour, mpl.colors.ListedColormap):
            colours = colour
        else:
            try:
                colours = tp.plot.colour.linear(colour)
            except Exception:
                colours = tp.plot.colour.linear(colour[1], colour[0])

    # plotting

    ax.pcolormesh(x2,
                  f2,
                  np.transpose(area),
                  cmap=colours,
                  norm=cnorm,
                  **kwargs)

    # axes formatting

    if main:
        if round(np.amin(f), 1) == 0:
            ax.set_ylim(bottom=0)
        formatting(ax, pdata, 'frequency', **xmarkkwargs)

    return
Exemplo n.º 8
0
def add_wideband(ax,
                 data,
                 pdata,
                 temperature=300,
                 poscar='POSCAR',
                 main=True,
                 interpolate=5,
                 colour='viridis',
                 workers=32,
                 xmarkkwargs={},
                 **kwargs):
    """Plots a phonon dispersion with broadened bands.

    Arguments:
        ax : axes
            axes to plot on.
        data : dict
            Phono3py-like data containing:
                qpoint : array-like
                    q-point locations.
                gamma : array-like
                    imaginary component of the self-energy.
                temperature : array-like
                    temperature.
        pdata : dict
            phonon dispersion data containing:
                q-point : array-like
                    qpoint locations.
                x : array-like
                    high-symmetry path.
                frequency : array-like
                    phonon frequencies.
                tick_position : array-like
                    x-tick positions.
                tick_label : array-like
                    x-tick labels.

        temperature : float, optional
            approximate temperature in K (finds closest). Default: 300.

        poscar : str, optional
            VASP POSCAR filepath. Default: POSCAR.

        main : bool, optional
            set axis ticks, label, limits. Default: True.
        interpolate : int, optional
            every n points to sample. Default: 5.

        colour : colormap or str, optional
            colourmap or colourmap name. Default: viridis.

        workers : int, optional
            number of workers for paralellised section. Default: 32.

        xmarkkwargs : dict, optional
            keyword arguments for x markers passed to
            matplotlib.pyplot.axvline. Set color to None to turn off.
            Defaults: {'color':      None,
                       'linewidth':  axis line width,
                       'rasterized': False}
        **kwargs : dict, optional
            keyword arguments passed to matplotlib.pyplot.pcolormesh.
            Defaults: {'rasterized': True}
    """

    from functools import partial
    from multiprocessing import Pool
    from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    import pymatgen.symmetry.analyzer as pmg
    from scipy.interpolate import interp1d
    from tp.calculate import lorentzian

    # defaults

    defkwargs = {'rasterized': True}
    for key in defkwargs:
        if key not in kwargs:
            kwargs[key] = defkwargs[key]

    defxmarkkwargs = {'color': None}
    for key in defxmarkkwargs:
        if key not in xmarkkwargs:
            xmarkkwargs[key] = defxmarkkwargs[key]

    # Phono3py data formatting

    data = tp.data.resolve.resolve(data, 'gamma', temperature)
    c = np.array(data['gamma'])
    qk = data['qpoint']

    # Phonopy data formatting

    qp = pdata['qpoint']
    x = pdata['x']

    qpi = [qp[i] for i in range(len(qp)) if i % interpolate == 0]
    xi = [x[i] for i in range(len(x)) if i % interpolate == 0]
    if xi[-1] != x[-1]:
        qpi.append(qp[-1])
        xi.append(x[-1])

    # map Phono3py to Phonopy

    struct = Poscar.from_file(poscar).structure
    sg = SpacegroupAnalyzer(struct)
    symops = sg.get_point_group_operations(cartesian=False)
    geq = partial(get_equivalent_qpoint, np.array(qk), symops)
    with Pool(processes=workers) as pool:
        min_id = pool.map(geq, qpi)
    c2 = c[min_id, :]

    x, indices = np.unique(x, return_index=True)
    f = np.array(pdata['frequency'])[indices]

    # interpolate

    x2 = np.linspace(min(x), max(x), 2500)
    finterp = interp1d(x, f, kind='cubic', axis=0)
    f = finterp(x2)

    cinterp = interp1d(xi, c2, kind='cubic', axis=0)
    c2 = np.abs(cinterp(x2))
    fmax = np.amax(np.add(f, c2))
    fmin = np.amin(np.subtract(f, c2))
    f2 = np.linspace(fmin, fmax, 2500)

    # broadening

    area = np.zeros((len(x2), len(f)))
    for q in range(len(area)):
        for b in range(len(c2[q])):
            area[q] = np.add(area[q], lorentzian(f2, f[q][b], c2[q][b]))

    cnorm = mpl.colors.LogNorm(vmin=np.amin(area), vmax=np.amax(area))

    # plotting

    ax.pcolormesh(x2,
                  f2,
                  np.transpose(area),
                  cmap=colour,
                  norm=cnorm,
                  **kwargs)

    # axes formatting

    if main:
        if round(np.amin(f), 1) == 0:
            ax.set_ylim(bottom=0)
        formatting(ax, pdata, 'frequency', **xmarkkwargs)

    return
Exemplo n.º 9
0
def add_projected_dispersion(ax,
                             data,
                             pdata,
                             quantity,
                             bandrange=None,
                             temperature=300,
                             direction='avg',
                             poscar='POSCAR',
                             main=True,
                             interpolate=2500,
                             colour='viridis_r',
                             cmin=None,
                             cmax=None,
                             cscale=None,
                             unoccupied='grey',
                             workers=32,
                             xmarkkwargs={},
                             **kwargs):
    """Plots a phonon dispersion with projected colour.

    Plots a phonon dispersion, and projects a quantity onto the colour
    axis.

    Arguments:
        ax : axes
            axes to plot on.
        data : dict
            Phono3py-like data containing:
                qpoint : array-like
                    q-point locations.
                (quantity) : array-like
                    projected quantity.
                temperature : array-like, optional
                    temperature, if necessary for quantity.
        pdata : dict
            phonon dispersion data containing:
                q-point : array-like
                    qpoint locations.
                x : array-like
                    high-symmetry path.
                frequency : array-like
                    phonon frequencies.
                tick_position : array-like
                    x-tick positions.
                tick_label : array-like
                    x-tick labels.
        quantity : str
            quantity to project.

        bandrange : array-like, optional
            minumum and maximum band indices to plot. Default: None.
        temperature : float, optional
            approximate temperature in K (finds closest). Default: 300.
        direction : str, optional
            direction from anisotropic data, accepts x-z/ a-c,
            average/ avg or normal/ norm. Default: average.

        poscar : str, optional
            VASP POSCAR filepath. Default: POSCAR.

        main : bool, optional
            set axis ticks, label, limits. Default: True.
        interpolate : int, optional
            number of points per line. Default: 2,500.

        colour : colormap or str, optional
            colourmap or colourmap name. Default: viridis_r.
        cmin : float, optional
            colour scale minimum. Default: display 99 % data.
        cmax : float, optional
            colour scale maximum. Default: display 99.9 % data.
        cscale : str, optional
            override colour scale (linear/ log). Default: None.
        unoccupied : str, optional
            if the colour variable is occuption, values below 1 are
            coloured in this colour. Id set to None, or cmin is set,
            this feature is turned off. Default: grey.

        workers : int, optional
            number of workers for paralellised section. Default: 32.

        xmarkkwargs : dict, optional
            keyword arguments for x markers passed to
            matplotlib.pyplot.axvline. Set color to None to turn off.
            Defaults: {'color':      'black',
                       'linewidth':  axis line width,
                       'rasterized': False}
        **kwargs : dict, optional
            keyword arguments passed to matplotlib.pyplot.scatter.
            Defaults: {'marker':     '.',
                       'rasterized': True,
                       's':          1}

    Returns:
        colorbar
            colour bar for projected data.
    """

    from functools import partial
    from multiprocessing import Pool
    from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    import pymatgen.symmetry.analyzer as pmg
    from scipy.interpolate import interp1d

    # defaults

    defkwargs = {'marker': '.', 'rasterized': True, 's': 1}
    for key in defkwargs:
        if key not in kwargs:
            kwargs[key] = defkwargs[key]

    # Phono3py data formatting

    tnames = tp.settings.to_tp()
    quantity = tnames[quantity] if quantity in tnames else quantity
    data = tp.data.resolve.resolve(data, quantity, temperature, direction)
    c = data[quantity]
    if bandrange is None:
        bmin = 0
        bmax = len(c[0])
    else:
        bmin = np.amax([0, bandrange[0]])
        bmax = np.amin([len(c[0]), bandrange[1]])
    bdiff = bmax - bmin
    c = np.array(c)[:, bmin:bmax]
    qk = data['qpoint']

    # Phonopy data formatting

    qp = pdata['qpoint']
    x = pdata['x']
    f = np.array(pdata['frequency'])[:, bmin:bmax]

    # map Phono3py to Phonopy

    struct = Poscar.from_file(poscar).structure
    sg = SpacegroupAnalyzer(struct)
    symops = sg.get_point_group_operations(cartesian=False)
    geq = partial(get_equivalent_qpoint, np.array(qk), symops)
    with Pool(processes=workers) as pool:
        min_id = pool.map(geq, qp)
    c2 = c[min_id, :]

    x, indices = np.unique(x, return_index=True)
    f = np.array(f)[indices]
    c2 = np.array(c2)[indices]

    # interpolate

    x2 = np.linspace(min(x), max(x), interpolate)
    finterp = interp1d(x, f, kind='cubic', axis=0)
    f = finterp(x2)

    cinterp = interp1d(x, c2, kind='cubic', axis=0)
    c2 = np.abs(cinterp(x2))
    if isinstance(colour, str):
        cmap = plt.cm.get_cmap(colour)
    else:
        cmap = colour
    cnorm, extend = tp.plot.utilities.colour_scale(c2, quantity, cmap, cmin,
                                                   cmax, cscale, unoccupied)

    # plotting

    for n in range(bdiff):
        line = ax.scatter(x2,
                          f[:, n],
                          c=c2[:, n],
                          cmap=cmap,
                          norm=cnorm,
                          **kwargs)

    # axes formatting

    axlabels = tp.settings.labels()
    cbar = plt.colorbar(line, extend=extend)
    cbar.set_alpha(1)
    cbar.set_label(axlabels[quantity])
    cbar.draw_all()

    if main:
        if round(np.amin(f), 1) == 0:
            ax.set_ylim(bottom=0)
        formatting(ax, pdata, 'frequency', **xmarkkwargs)

    return cbar
Exemplo n.º 10
0
def add_alt_dispersion(
        ax,
        data,
        pdata,
        quantity,
        bandrange=None,
        temperature=300,
        direction='avg',
        label=['Longitudinal', 'Transverse_1', 'Transverse_2', 'Optic'],
        poscar='POSCAR',
        main=True,
        log=False,
        interpolate=10000,
        colour=['#44ffff', '#ff8044', '#ff4444', '#00000010'],
        linestyle='-',
        workers=32,
        xmarkkwargs={},
        **kwargs):
    """Plots a phono3py quantity on a high-symmetry path.

    Arguments:
        ax : axes
            axes to plot on.
        data : dict
            Phono3py-like data containing:
                qpoint : array-like
                    q-point locations.
                (quantity) : array-like
                    plotted quantity.
                temperature : array-like, optional
                    temperature, if necessary for quantity.
        pdata : dict
            phonon dispersion data containing:
                q-point : array-like
                    qpoint locations.
                x : array-like
                    high-symmetry path.
                tick_position : array-like
                    x-tick positions.
                tick_label : array-like
                    x-tick labels.
        quantity : str
            quantity to plot.

        bandrange : array-like, optional
            minumum and maximum band indices to plot. Default: None.
        temperature : float, optional
            approximate temperature in K (finds closest). Default: 300.
        direction : str, optional
            direction from anisotropic data, accepts x-z/ a-c,
            average/ avg or normal/ norm. Default: average.
        label : array-like, optional
            labels per line. A single dataset could have a single label,
            or the default labels the lines by type. You'll want to
            change this if a minimum band index is set.
            Default: ['Longitudinal', 'Transverse_1', 'Transverse_2',
            'Optic'].

        poscar : str, optional
            VASP POSCAR filepath. Default: POSCAR.

        main : bool, optional
            set axis ticks, label, limits. Default: True.
        log : bool, optional
            log the y scale. Default: False.
        interpolate : int, optional
            number of points per line. Default: 10,000.

        colour : str or array-like, optional
            line colour(s). If too few colours are selected, the last
            one is repeated for the rest of the bands. Note if retrieved
            from a colourmap or in [r,g,b] notation, the colour should
            be enclosed in [], e.g.
            colour = plt.get_cmap('winter_r')(linspace(0, 1, len(files)))
            tp.plot.phonons.add_dispersion(..., colour=[colour[0]], ...)
            Default: ['#44ffff', '#ff8044', '#ff4444', '#00000010'].
        linestyle : str or array-like, optional
            linestyle(s) ('-', '--', '.-', ':'). Default: solid.

        workers : int, optional
            number of workers for paralellised section. Default: 32.

        xmarkkwargs : dict, optional
            keyword arguments for x markers passed to
            matplotlib.pyplot.axvline. Set color to None to turn off.
            Defaults: {'color':      'black',
                       'linewidth':  axis line width,
                       'rasterized': False}
        **kwargs : dict, optional
            keyword arguments passed to matplotlib.pyplot.plot.
            Defaults: {'rasterized': False}
    """

    from functools import partial
    from multiprocessing import Pool
    from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    import pymatgen.symmetry.analyzer as pmg
    from scipy.interpolate import interp1d

    # defaults

    defkwargs = {'rasterized': False}
    for key in defkwargs:
        if key not in kwargs:
            kwargs[key] = defkwargs[key]

    # Phono3py data formatting

    tnames = tp.settings.to_tp()
    if quantity in tnames: quantity = tnames[quantity]
    data = tp.data.resolve.resolve(data, quantity, temperature, direction)
    y = data[quantity]
    if bandrange is None:
        bmin = 0
        bmax = len(y[0])
    else:
        bmin = np.amax([0, bandrange[0]])
        bmax = np.amin([len(y[0]), bandrange[1]])
    y = np.array(y)[:, bmin:bmax]
    qk = data['qpoint']

    # Phonopy data formatting

    qp = pdata['qpoint']
    x = pdata['x']

    qpi = [qp[i] for i in range(len(qp))
           if i % 5 == 0] if len(qp) > 100 else qp
    xi = [x[i] for i in range(len(x)) if i % 5 == 0] if len(x) > 100 else x
    if xi[-1] != x[-1]:
        qpi.append(qp[-1])
        xi.append(x[-1])

    # map Phono3py to Phonopy

    struct = Poscar.from_file(poscar).structure
    sg = SpacegroupAnalyzer(struct)
    symops = sg.get_point_group_operations(cartesian=False)
    geq = partial(get_equivalent_qpoint, np.array(qk), symops)
    with Pool(processes=workers) as pool:
        min_id = pool.map(geq, qpi)
    y2 = y[min_id, :]

    x, indices = np.unique(xi, return_index=True)
    y2 = np.array(y2)[indices]

    # interpolate

    x2 = np.linspace(min(x), max(x), interpolate)
    yinterp = interp1d(x, y2, kind='cubic', axis=0)
    y2 = np.abs(yinterp(x2))
    ysort = np.ravel(y2)
    ysort = ysort[ysort.argsort()]
    ymin = ysort[int(round(len(ysort) / 100, 0))]
    ymax = ysort[-1]

    # line appearance

    colour = tile_properties(colour, bmin, bmax)
    linestyle = tile_properties(linestyle, bmin, bmax)

    # plotting

    # ensures only one legend entry
    bdiff = bmax - bmin
    if bdiff == 1:
        ax.plot(x2,
                y2,
                label=label,
                color=colour[0],
                linestyle=linestyle[0],
                **kwargs)
    else:
        for i in range(len(label)):
            ax.plot(x2,
                    y2[:, i],
                    label='$\mathregular{{{}}}$'.format(label[i]),
                    color=colour[i],
                    linestyle=linestyle[i],
                    **kwargs)
        if len(label) < bdiff:
            for n in range(len(label), bdiff):
                ax.plot(x2,
                        y2[:, n],
                        color=colour[n],
                        linestyle=linestyle[n],
                        **kwargs)

    # axes formatting

    if main:
        ax.set_ylim(ymin, ymax)
        formatting(ax, pdata, quantity, log=log, **xmarkkwargs)

    return
Exemplo n.º 11
0
    def from_tasks(
        cls,
        task_group: List[TaskDocument],
        quality_scores=SETTINGS.VASP_QUALITY_SCORES,
        use_statics: bool = False,
    ) -> "MaterialsDoc":
        """
        Converts a group of tasks into one material

        Args:
            task_group: List of task document
            quality_scores: quality scores for various calculation types
            use_statics: Use statics to define a material
        """
        if len(task_group) == 0:
            raise Exception("Must have more than one task in the group.")

        # Material ID
        possible_mat_ids = [task.task_id for task in task_group]
        material_id = min(possible_mat_ids)

        # Metadata
        last_updated = max(task.last_updated for task in task_group)
        created_at = min(task.completed_at for task in task_group)
        task_ids = list({task.task_id for task in task_group})

        deprecated_tasks = {task.task_id for task in task_group if not task.is_valid}
        run_types = {task.task_id: task.run_type for task in task_group}
        task_types = {task.task_id: task.task_type for task in task_group}
        calc_types = {task.task_id: task.calc_type for task in task_group}

        structure_optimizations = [
            task
            for task in task_group
            if task.task_type == TaskType.Structure_Optimization  # type: ignore
        ]
        statics = [task for task in task_group if task.task_type == TaskType.Static]  # type: ignore
        structure_calcs = (
            structure_optimizations + statics
            if use_statics
            else structure_optimizations
        )

        def _structure_eval(task: TaskDocument):
            """
            Helper function to order structures optimziation and statics calcs by
            - Functional Type
            - Spin polarization
            - Special Tags
            - Energy
            """

            task_run_type = task.run_type

            is_valid = task.task_id in deprecated_tasks

            return (
                -1 * is_valid,
                -1 * quality_scores.get(task_run_type.value, 0),
                -1 * task.input.parameters.get("ISPIN", 1),
                -1 * task.input.parameters.get("LASPH", False),
                task.output.energy_per_atom,
            )

        best_structure_calc = sorted(structure_calcs, key=_structure_eval)[0]
        structure = SpacegroupAnalyzer(
            best_structure_calc.output.structure, symprec=0.1
        ).get_conventional_standard_structure()

        # Initial Structures
        initial_structures = [task.input.structure for task in task_group]
        sm = StructureMatcher(
            ltol=0.1, stol=0.1, angle_tol=0.1, scale=False, attempt_supercell=False
        )
        initial_structures = [
            group[0] for group in sm.group_structures(initial_structures)
        ]

        # Deprecated
        deprecated = all(task.task_id in deprecated_tasks for task in structure_calcs)

        # Origins
        origins = [
            PropertyOrigin(
                name="structure",
                task_id=best_structure_calc.task_id,
                last_updated=best_structure_calc.last_updated,
            )
        ]

        # entries
        entries = {}
        all_run_types = set(run_types.values())
        for rt in all_run_types:
            relevant_calcs = sorted(
                [doc for doc in structure_calcs if doc.run_type == rt and doc.is_valid],
                key=_structure_eval,
            )

            if len(relevant_calcs) > 0:
                best_task_doc = relevant_calcs[0]
                entry = best_task_doc.structure_entry
                entry.data["task_id"] = entry.entry_id
                entry.entry_id = material_id
                entries[rt] = entry

        return cls.from_structure(
            structure=structure,
            material_id=material_id,
            last_updated=last_updated,
            created_at=created_at,
            task_ids=task_ids,
            calc_types=calc_types,
            run_types=run_types,
            task_types=task_types,
            initial_structures=initial_structures,
            deprecated=deprecated,
            deprecated_tasks=deprecated_tasks,
            origins=origins,
            entries=entries,
        )
Exemplo n.º 12
0
    # identify and remove duplicates from the list of equivalent q-points:
    for i in range(len(points) - 1):
        for j in range(i + 1, len(points)):
            if np.allclose(pbc_diff(points[i], points[j]), [0, 0, 0], tol):
                rm_list.append(i)
                break
    return np.delete(points, rm_list, axis=0)


import numpy as np
import pymatgen.symmetry.analyzer as pmg
from pymatgen.io.vasp.inputs import Poscar
from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer

struct = Poscar.from_file('POSCAR').structure
sg = SpacegroupAnalyzer(struct)
symmops = sg.get_point_group_operations(cartesian=False)

new_qpoints = []
for q in qpoints:
    equiv_qpoints = get_symmetry_equivalent_qpoints(symmops, q)
    all_dists = [
        np.min(np.sum(np.power(k - equiv_qpoints, 2), axis=1))
        for k in file_qpoints
    ]
    min_id = all_dists.index(np.min(all_dists))
    new_qpoints.append(file_qpoints[min_id])

print(new_qpoints)

freq_near_G = []
Exemplo n.º 13
0
#!/usr/bin/env python3

from pymatgen.io import vasp
import numpy as np
from pymatgen.analysis.structure_analyzer import SpacegroupAnalyzer
import pymatgen

run = vasp.Vasprun('vasprun.xml')
outcar = vasp.Outcar('OUTCAR')
st = run.final_structure
symbols = np.array([x.value for x in st.species])
sa = SpacegroupAnalyzer(st)
print('**************')
print("conventional cell")
print(sa.get_conventional_standard_structure())
print(sa.get_conventional_standard_structure().volume)
print(sa.get_space_group_symbol(), sa.get_space_group_number())
print("******************")
print("Final structure")
print(run.final_structure)
print("vol={}".format(run.final_structure.volume))
print("******************")
print("Bandgap information")
print(run.get_band_structure().get_band_gap())
print("******************")
print("Magnetzation per site")
for ielement in range(len(symbols)):
    print("{}-{} {}".format(symbols[ielement], ielement,
                            outcar.magnetization[ielement]['tot']))
print("******************")
print("Magnetzation per species")