def plot_had(ax, feaname, atoms):
    abc, new_xyzs = get_structure_from_contcar('./cons/h_ad_suf.con', 11)
    hab3 = Atoms('H1O6Ir3Ge', positions=new_xyzs, cell=abc, pbc=[0, 0, 0])

    plot_atoms(hab3, ax, rotation=('30x,-30y,90z'))

    ax.text(2, 6, feaname, fontsize=16)

    ax.set_xlim(0, 8)
    ax.set_ylim(0, 8)

    # plot dots and lines
    xs, ys = [], []
    for atom in atoms:
        xs.append(atom[0])
        ys.append(atom[1])

    ax.plot(xs, ys, 'k-.', lw=2)
    ax.scatter(xs, ys, color='k', zorder=10)

    ax.set_axis_off()

    if len(atoms) in [3]:
        ax.arrow(atoms[0][0], atoms[0][1], \
                0.15*(atoms[2][0]-atoms[0][0]), \
                0.15*(atoms[2][1]-atoms[0][1]), \
                head_width=0.15, fc='k')

        ax.arrow(atoms[2][0], atoms[2][1], \
                0.15*(atoms[0][0]-atoms[2][0]), \
                0.15*(atoms[0][1]-atoms[2][1]), \
                head_width=0.15, fc='k')
def test_matplotlib_plot(plt):
    slab = FaceCenteredCubic('Au', size=(2, 2, 2))

    fig, ax = plt.subplots()
    plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'), show_unit_cell=0)

    assert len(ax.patches) == len(slab)
Exemple #3
0
    def inspect_sample(self,
                       path: str = '',
                       extension: str = '',
                       mode: str = 'ase'):
        """
        Helps to quickly inspect the samples by plotting them (work great in e.g. jupyter notebooks,
        here you'll have to call %matplotlib inline).

        It assumes that the identifier the sampler returned are file-names, -stems or -paths.

        Args:
            path (str): path to the structure directory
            extension (str): extension (without the leading dot, e.g. 'cif')
            mode (str): visualization mode for the structures

        Returns:

        """
        if mode == 'ase':
            if self.selection:
                for item in self.selection:
                    fig, axarr = plt.subplots(1, 1, figsize=(15, 15))
                    plt.title(item)
                    plot_atoms(
                        read(os.path.join(path, '.'.join([item, extension]))),
                        axarr)
def plot_structural_descriptors():
    """"""
    # figure general setting
    fig, axarr = plt.subplots(2, 3, figsize=(16, 9))

    plt.tight_layout(pad=2.0, w_pad=2.0, h_pad=2.0)
    plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95, \
            wspace=0.1, hspace=0.1)

    plt.suptitle('Selected Structural Descriptors for the Surface-stabilized Pathway', \
            fontsize=20, fontweight='bold')

    M_cus = [5, 2]
    O_br = [2, 3.5]
    H_ch3 = [4, 4.2]
    H_h = [2.5, 4.0]
    C = [4.8, 4.0]

    # 1 angle
    plot_ch3ad(axarr[0][0], '(a) $A_{O_{br}-M_{cus}-C}^{CH_3^*}$ (0.41)', \
            [O_br, M_cus, C])

    # 2 distance
    plot_ch3ad(axarr[0][1], '(b) $D_{H-C}^{CH_3^*}$ (-0.32)', \
            [H_ch3, C])

    # 3 dihedral
    plot_ch3ad(axarr[0][2], '(c) $H_{O_{br}-C-M_{cus}-H}^{CH_3^*}$ (0.30)', \
            [O_br, H_ch3, C, M_cus]) # 1423, 431

    # 4 dihedral
    plot_ch3ad(axarr[1][0], '(d) $H_{O_{br}-H-M_{cus}-C}^{CH_3^*}$ (-0.29)', \
            [O_br, C, H_ch3, M_cus])

    # 5 angle
    plot_had(axarr[1][1], '(e) $A_{O_{br}-M_{cus}-H}^{H^*}$ (-0.24)', \
            [O_br, M_cus, H_h])

    # 6
    ax6 = axarr[1][2]
    ax6.set_axis_off()

    # plot symbols
    symbols = ['C', 'H', 'O', 'Ir', 'Ge']
    names = ['Carbon', 'Hydrogen', 'Oxygen', 'Base', 'Dopant']
    lefts = np.arange(0.7, 0.9, 0.05)
    for i, left in enumerate(lefts):
        # set subfigure location
        ax = fig.add_axes([left, 0.2, 0.04,
                           0.04])  # left, bottom, width, height
        atom = Atoms(symbols[i], positions=[[0, 0, 0]])

        # plot atoms
        plot_atoms(atom, ax, rotation=('0x,0y,0z'))

        ax.set_title(names[i], fontsize=12)
        ax.set_axis_off()

    fig.savefig("fig6.png")
Exemple #5
0
def plot(name):
    assert name in ("ZnVO", "CoVO")
    data, atoms = read_cube_data(cube_file(name))

    lattice = atoms.cell
    na, nb, nc = data.shape
    layer = data[:, :, nc // 2].T
    print(layer.max(), layer.min())
    x_ = numpy.linspace(0, 1, na)
    y_ = numpy.linspace(0, 1, nb)
    xx_s, yy_s = numpy.meshgrid(x_, y_)
    xx_fine, yy_fine = numpy.meshgrid(numpy.linspace(0, 1, 256),
                                      numpy.linspace(0, 1, 256))

    xy_flat = numpy.vstack([xx_s.flat, yy_s.flat]).T
    print(xy_flat.shape)
    c_fine = griddata(xy_flat, layer.flat, (xx_fine, yy_fine), method="cubic")
    zz_fine = numpy.ones_like(yy_fine) * 0.5
    xx, yy, zz = numpy.tensordot(lattice.T,
                                 numpy.array([xx_fine, yy_fine, zz_fine]),
                                 axes=1)
    # print(xx, yy)
    fig = plt.figure(figsize=(3.5, 3.0))
    ax = fig.add_subplot(111)
    # layer = layer.T
    ax.pcolor(
        xx,
        yy,
        c_fine,
        cmap="rainbow_r",
        vmin=-10,
        # antialiased=True,
        # interpolate="bicubic",
        rasterized=True)
    sc = make_supercell(atoms, numpy.diag([2, 2, 1]))
    idx = [p.index for p in sc if (p.z > atoms.cell[-1, -1]*0.43) \
                                   and (p.z < atoms.cell[-1, -1] * 0.58)]
    # and (p.x < atoms.cell[0, 0] * 1.1) \
    # and (p.y < atoms.cell[1, 1] * 1.2)]
    new_atoms = sc[idx]
    rot = {"ZnVO": (-0.4, 1.30, 0.02), "CoVO": (0.00, 1.89, 0.00)}
    off = {"ZnVO": (-1.40, -1.15), "CoVO": (-0.9, -1.2)}
    plot_atoms(new_atoms,
               ax=ax,
               rotation="{0}x,{1}y,{2}z".format(*rot[name]),
               radii=0.6,
               offset=off[name])
    # show_unit_cell=True)
    # offset=(-1.1, -0.8),
    # show_unit_cell=True)
    # plt.show()
    ax.set_aspect("equal")
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_axis_off()
    # ax.set_axis_off()
    fig.savefig(join(img_path, "{}_half.svg".format(name)))
def show_atoms_grid(data, rotation = '-0x,0y,0z', save= False, filename = 'grid_configs'):
    '''
    Where data is list of Atoms objects
    '''
    dim = int(np.ceil(np.sqrt(len(data))))
    fig, axarr = plt.subplots(dim, dim, figsize=(25, 25))
    for i, config in enumerate(data):
        plot_atoms(config, axarr[i%dim,i//dim], rotation = rotation)
    if save:
        fig.savefig(filename + ".png")
Exemple #7
0
def test_matplotlib_plot(plt):
    from ase.visualize.plot import plot_atoms
    from ase.lattice.cubic import FaceCenteredCubic

    slab = FaceCenteredCubic('Au', size=(2, 2, 2))

    fig, ax = plt.subplots()
    plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'),
               show_unit_cell=0)

    assert len(ax.patches) == len(slab)
    print(ax)
Exemple #8
0
def plot_cell_ase(cell, title):
    """Use ase in-built function to create 2D plot
    NOTE: Not very nice for visualising a 3D structure and appears to always set cell vectors to positive values

    Args:
        cell (ase Atoms object): Ase atoms object for structure to visualise
        title (str): Set a title for the plot

    Returns:
        Produces figure of plot, originally used in development notebook with '%matplotlib inline'
    """
    fig, ax = plt.subplots()
    plt.title(title)
    plot_atoms(cell, ax, radii=0.3, rotation=('0x,0y,0z'))
    def __plot_stack(self, stack, fig, axes, scdata):
        from ase.visualize.plot import plot_atoms

        canvas = fig.canvas
        axes.clear()
        axes.set_yticks([])
        axes.set_xticks([])
        axes.set_xlabel("")
        axes.set_ylabel("")
        scdata = "#{:d}, {:d} atoms, twist angle of {:.2f}°".format(
            scdata[-1], len(stack), scdata[-2])
        axes.set_title(scdata)
        plot_atoms(stack, axes, radii=0.3)
        axes.set_frame_on(False)
        canvas.draw()
Exemple #10
0
def graphene_nanotube():

    from ase.build.tube import nanotube
    from ase.visualize.plot import plot_atoms

    n = 10
    m = 10

    atoms = nanotube(n, m)
    atoms.wrap()

    period = np.array([list(atoms.get_cell()[2])])
    period[:, [1, 2]] = period[:, [2, 1]]
    coord = atoms.get_positions()
    coord[:, [1, 2]] = coord[:, [2, 1]]
    coords = []
    coords.append(str(len(coord)))
    coords.append('Nanoribbon')

    for j, item in enumerate(coord):
        coords.append('C' + str(j + 1) + ' ' + str(item[0]) + ' ' + str(item[1]) + ' ' + str(item[2]))

    coords = '\n'.join(coords)

    # --------------------------- Basis set --------------------------

    s_orb = tb.Orbitals('C')
    s_orb.add_orbital("pz", energy=0, orbital=1, magnetic=0, spin=0)
    # s_orb.add_orbital("py", energy=0, orbital=1, magnetic=1, spin=0)
    # s_orb.add_orbital("px", energy=0, orbital=1, magnetic=-1, spin=0)

    # ------------------------ set TB parameters----------------------

    t = 2.8
    tb.set_tb_params(PARAMS_C_C={'pp_pi': t})

    # --------------------------- Hamiltonian -------------------------

    h = tb.Hamiltonian(xyz=coords, nn_distance=1.7, comp_angular_dep=False)
    h.initialize()
    h.set_periodic_bc(period)

    k_points = np.linspace(0.0, np.pi/period[0][1], 20)
    band_structure = np.zeros((len(k_points), h.h_matrix.shape[0]))

    for jj, item in enumerate(k_points):
        band_structure[jj, :], _ = h.diagonalize_periodic_bc([0.0, item, 0.0])

    # visualize
    ax = plt.axes()
    ax.set_title('Band structure of carbon nanotube, ({0}, {1}) \n 1st nearest neighbour approximation'.format(n, m))
    ax.set_ylabel('Energy (eV)')
    ax.set_xlabel(r'Wave vector ($\frac{\pi}{a}$)')
    ax.plot(k_points, np.sort(band_structure), 'k')
    ax.xaxis.grid()
    plt.show()

    ax1 = plot_atoms(atoms, show_unit_cell=2, rotation='10x,50y,30z')
    ax1.axis('off')
    plt.show()
def update(val):
    RelaxStep = relaxatiostep.val

    Step = int(RelaxStep)

    ax[0, 0].imshow(hes_series.loc[str(Step)].values, vmin=MIN, vmax=MAX)
    ax[0, 1].cla()
    plot_atoms(atoms=traj[Step],
               ax=ax[0, 1],
               rotation=('0x,0y,0z'),
               offset=(0, 0))
    ax[1, 0].scatter(list(range(len(traj))), energies, c='k')
    ax[1, 1].scatter(range(len(traj)), forces, c='k')
    ax[1, 0].scatter(Step, traj[Step].get_potential_energy(), c='r')
    ax[1, 1].scatter(Step, fmax(traj[Step]), c='r')
    fig.canvas.draw_idle()
 def inspect_duplicates(self, mode: str = "ase"):
     if mode == "ase":
         if self.pairs:
             for items in self.pairs:
                 fig, axarr = plt.subplots(1, 2, figsize=(15, 5))
                 plot_atoms(
                     read(
                         self.scalar_feature_matrix.iloc[items[0]]["name"]),
                     axarr[0],
                 )
                 plot_atoms(
                     read(
                         self.scalar_feature_matrix.iloc[items[1]]["name"]),
                     axarr[1],
                 )
         else:
             logger.info("no duplicates to plot")
Exemple #13
0
def plot_stack(stack: "ase.atoms.Atoms" = None,
               supercell_data: "namedtuple" = None):
    """Wrapper of the :func:~`ase.visualize.plot.plot_atoms` function."""
    fig = plt.gcf()
    axes = plt.gca()
    canvas = fig.canvas
    axes.clear()
    axes.set_yticks([])
    axes.set_xticks([])
    axes.set_xlabel("")
    axes.set_ylabel("")
    description = r"#{:d}, {:d} atoms, {:.1f} % stress, $\theta=${:.2f}°".format(
        supercell_data.index,
        supercell_data.natoms,
        supercell_data.stress,
        supercell_data.angle,
    )
    axes.set_title(description, fontsize=12)
    plot_atoms(stack, axes, radii=0.3)
    axes.set_frame_on(False)
    canvas.draw()
def plot_surface():
    """paper fig 1"""
    abc, new_xyzs = get_structure_from_contcar('./cons/surface_model.con', 48)

    rutile = Atoms('O32Ir15Ge', positions=new_xyzs, cell=abc, pbc=[0, 0, 0])

    fig, axarr = plt.subplots(1, 2, figsize=(12, 6))
    plt.suptitle('(110) Surface Model of Rutile-type Metal Oxides', \
            fontsize=20, fontweight='bold')

    # fig a
    axarr[0].set_title('(a) Over View', fontsize=16, fontweight='normal')
    axarr[0].set_axis_off()

    plot_atoms(rutile, axarr[0], rotation=('0x,0y,270z'))
    axarr[0].text(1.5, 3, '$O_{br}$', fontsize=16)
    axarr[0].text(4.5, 3, '$M_{cus}$', fontsize=16)

    # fig b
    axarr[1].set_title('(b) Side View', fontsize=16, fontweight='normal')
    axarr[1].set_axis_off()

    plot_atoms(rutile, axarr[1], rotation=('0x,270y,270z'))

    # plot symbols
    symbols = ['Ir', 'O', 'Ge']
    names = ['Base', 'Oxygen', 'Dopant']
    lefts = [0.40, 0.50, 0.60]
    for i, left in enumerate(lefts):
        # set subfigure location
        ax3 = fig.add_axes([left, 0.05, 0.05, 0.05])
        atom = Atoms(symbols[i], positions=[[0, 0, 0]])
        # plot atoms
        plot_atoms(atom, ax3, rotation=('0x,0y,0z'))

        ax3.set_title(names[i], fontsize=12)
        ax3.set_axis_off()

    fig.savefig("fig1.png")
Exemple #15
0
# creates: matplotlib_plot_atoms1.png, matplotlib_plot_atoms2.png
# creates: matplotlib_plot_atoms3.png

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from ase.visualize.plot import plot_atoms
from ase.lattice.cubic import FaceCenteredCubic
from ase.spacegroup import crystal

slab = FaceCenteredCubic('Au', size=(2, 2, 2))
fig, ax = plt.subplots()
plot_atoms(slab, ax, radii=0.3, rotation=('90x,45y,0z'))
fig.savefig('matplotlib_plot_atoms1.png')

slab = FaceCenteredCubic('Au', size=(2, 2, 2))
fig, axarr = plt.subplots(1, 4, figsize=(15, 5))
plot_atoms(slab, axarr[0], radii=0.3, rotation=('0x,0y,0z'))
plot_atoms(slab,
           axarr[1],
           scale=0.7,
           offset=(3, 4),
           radii=0.3,
           rotation=('0x,0y,0z'))
plot_atoms(slab, axarr[2], radii=0.3, rotation=('45x,45y,0z'))
plot_atoms(slab, axarr[3], radii=0.3, rotation=('0x,0y,0z'))
axarr[0].set_title('No rotation')
axarr[1].set_xlabel(r'X-axis, [$\mathrm{\AA}$]')
axarr[1].set_ylabel(r'Y-axis, [$\mathrm{\AA}$]')
axarr[2].set_axis_off()
axarr[3].set_xlim(2, 6)
axarr[3].set_ylim(2, 6)
Exemple #16
0
import unittest
import matplotlib.pyplot as plt

from ase.gui.ui import tk

try:
    plt.figure()
except (tk.TclError, RuntimeError) as err:
    # "RuntimeError: Invalid DISPLAY variable" may happen in conda tests
    raise unittest.SkipTest(err)

from ase.visualize.plot import plot_atoms
from ase.lattice.cubic import FaceCenteredCubic

slab = FaceCenteredCubic('Au', size=(2, 2, 2))

fig, ax = plt.subplots()
plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'), show_unit_cell=0)

assert len(ax.patches) == len(slab)
print(ax)
def plot_adsorptions():
    """paper fig 2"""
    # read H contcars
    abc, new_xyzs = get_structure_from_contcar('./cons/Hab2.con', 49)
    hab2 = Atoms('HO32Ir15Ge', positions=new_xyzs, cell=abc, pbc=[0, 0, 0])

    abc, new_xyzs = get_structure_from_contcar('./cons/Hab3.con', 49)
    hab3 = Atoms('HO32Ir15Ge', positions=new_xyzs, cell=abc, pbc=[0, 0, 0])

    # read CH3 contcars
    abc, new_xyzs = get_structure_from_contcar('./cons/CH3ab.con', 52)
    ch3ab = Atoms('H3CO32Ir15Ge', positions=new_xyzs, cell=abc, pbc=[0, 0, 0])

    abc, new_xyzs = get_structure_from_contcar('./cons/CH3ab2.con', 52)
    ch3ab2 = Atoms('H3CO32Ir15Ge', positions=new_xyzs, cell=abc, pbc=[0, 0, 0])

    # figure general setting
    fig, axarr = plt.subplots(2, 4, figsize=(16, 8))
    plt.tight_layout(pad=2.0, w_pad=2.0, h_pad=2.0)
    plt.subplots_adjust(left=None, bottom=None, right=None, top=0.85, \
            wspace=None, hspace=0.2)

    plt.suptitle(r'Adsorption Conformations of H and $\bf{CH_3}$', \
            fontsize=20, fontweight='bold')

    plt.text(-50,
             35,
             r'(a) Adsorption of ${H}$',
             fontsize=16,
             fontweight='normal')
    plt.text(-15,
             35,
             r'(b) Adsorption of ${CH_3}$',
             fontsize=16,
             fontweight='normal')

    # plot H atoms
    plot_atoms(hab2, axarr[0][0], rotation=('0x,0y,270z'))
    axarr[0][0].set_title(' Over View of On-Top Position ($sp^2$) ',
                          fontsize=12)
    axarr[0][0].set_axis_off()

    plot_atoms(hab2, axarr[0][1], rotation=('0x,270y,270z'))
    axarr[0][1].set_title(' Side View of On-Top Position ($sp^2$) ',
                          fontsize=12)
    axarr[0][1].set_axis_off()

    plot_atoms(hab3, axarr[1][0], rotation=('0x,0y,270z'))
    axarr[1][0].set_title(' Side View of Inclined Position ($sp^3$) ',
                          fontsize=12)
    axarr[1][0].set_axis_off()

    plot_atoms(hab3, axarr[1][1], rotation=('0x,270y,270z'))
    axarr[1][1].set_title(' Side View of Inclined Position ($sp^3$) ',
                          fontsize=12)
    axarr[1][1].set_axis_off()

    # plot CH3 atoms
    plot_atoms(ch3ab, axarr[0][2], rotation=('0x,270y,135z'))
    axarr[0][2].set_title(' Over View of Vertical Position ', fontsize=12)
    axarr[0][2].set_axis_off()

    plot_atoms(ch3ab, axarr[0][3], rotation=('45x,0y,90z'))
    axarr[0][3].set_title(' Side View of Vertical Position ', fontsize=12)
    axarr[0][3].set_axis_off()

    plot_atoms(ch3ab2, axarr[1][2], rotation=('0x,0y,270z'))
    axarr[1][2].set_title(' Side View of Parallel Position ', fontsize=12)
    axarr[1][2].set_axis_off()

    plot_atoms(ch3ab2, axarr[1][3], rotation=('0x,270y,270z'))
    axarr[1][3].set_title(' Side View of Parallel Position ', fontsize=12)
    axarr[1][3].set_axis_off()

    # plot symbols
    symbols = ['C', 'H', 'O', 'Ir', 'Ge']
    names = ['Carbon', 'Hydrogen', 'Oxygen', 'Base', 'Dopant']
    lefts = [0.30, 0.40, 0.50, 0.60, 0.70]
    for i, left in enumerate(lefts):
        # set subfigure location
        ax3 = fig.add_axes([left, -0.00, 0.04, 0.04])
        atom = Atoms(symbols[i], positions=[[0, 0, 0]])
        # plot atoms
        plot_atoms(atom, ax3, rotation=('0x,0y,0z'))

        ax3.set_title(names[i], fontsize=12)
        ax3.set_axis_off()

    #plt.show()
    plt.savefig('../figures/fig2.png')
Exemple #18
0
pos = initial.get_positions()
ucell = initial.get_cell()
type = initial.get_chemical_symbols()
atoms = Atoms(positions=pos, symbols=type, cell=ucell, pbc=[True,True,True])

#c = FixAtoms(indices=[atom.index for atom in atoms if atom.symbol == 'Hf'])

#                """Constrain an atom index *a* to move in a given plane only.
#for atom in atoms:
#	c.append( FixedPlane(atom.index, ( 0, 0, 1)) )
c = [ FixedPlane( atom.index, ( 0, 0, 1) )  for atom in atoms ]
atoms.set_constraint(c)

write_vasp("OUT.vasp", atoms=atoms, vasp5=True, ignore_constraints=False)
#print (c)
fig = plt.figure()
ax = fig.add_subplot(111)
#ax.set_aspect("auto")
ax.set(xlim=(-1, 1), ylim = (-1, 1) )
a_circle = plt.Circle((23, 11.7), 2.7, alpha = 0.5,fill=False, ec='red')
a1_circle = plt.Circle((23, 11.7), 0.2,fill=False, ec='red')
ax.add_artist(a_circle)
ax.add_artist(a1_circle)
plot_atoms(atoms, ax, radii=0.5, rotation=('0x,0y,00z'))
plt.savefig("test.eps", format="eps", dpi=600)
plt.show()




Exemple #19
0
#
#
#

import ase.spacegroup
import matplotlib.pyplot as plt
from ase.visualize.plot import plot_atoms

quartz = ase.spacegroup.crystal(symbols=['O', 'Si'],
                                basis=[[0.413, 0.2711, 0.2172],
                                       [0.4673, 0, 0.3333]],
                                spacegroup=152,
                                cellpar=[4.9019, 4.9019, 5.3988, 90, 90, 120])
fig, ax = plt.subplots()
plot_atoms(quartz)


 def update_plot_atoms(num):
     cur_rotation = rotation_list[num]
     ax.cla()
     ax.set_axis_off()
     plot_atoms(atoms, ax=ax, radii=radii, rotation=cur_rotation)
     return ax,
Exemple #21
0
def graphene_nanoribbons_armchair():

    from ase.build.ribbon import graphene_nanoribbon
    from ase.visualize.plot import plot_atoms

    atoms = graphene_nanoribbon(11, 1, type='armchair')

    period = np.array([list(atoms.get_cell()[2])])
    period[:, [1, 2]] = period[:, [2, 1]]
    coord = atoms.get_positions()
    coord[:, [1, 2]] = coord[:, [2, 1]]
    coords = []
    coords.append(str(len(coord)))
    coords.append('Nanoribbon')

    for j, item in enumerate(coord):
        coords.append('C' + str(j+1) + ' ' + str(item[0]) + ' ' + str(item[1]) + ' ' + str(item[2]))

    coords = '\n'.join(coords)

    s_orb = tb.Orbitals('C')
    s_orb.add_orbital("pz", energy=-0.28, orbital=1, magnetic=0, spin=0)

    # ------------------------ set TB parameters----------------------

    gamma0 = -2.97
    gamma1 = -0.073
    gamma2 = -0.33
    s0 = 0.073
    s1 = 0.018
    s2 = 0.026

    tb.set_tb_params(PARAMS_C_C1={'pp_pi': gamma0},
                     PARAMS_C_C2={'pp_pi': gamma1},
                     PARAMS_C_C3={'pp_pi': gamma2},
                     OV_C_C1={'pp_pi': s0},
                     OV_C_C2={'pp_pi': s1},
                     OV_C_C3={'pp_pi': s2})

    # --------------------------- Hamiltonian -------------------------

    h = tb.Hamiltonian(xyz=coords, nn_distance=3.1, comp_overlap=True)
    h.initialize(radial_dep)
    h.set_periodic_bc(period)

    k_points = np.linspace(0.0, np.pi/period[0][1], 20)
    band_structure = np.zeros((len(k_points), h.h_matrix.shape[0]))

    for jj, item in enumerate(k_points):
        band_structure[jj, :], _ = h.diagonalize_periodic_bc([0.0, item, 0.0])

    # visualize
    ax = plt.axes()
    ax.set_title('Graphene nanoribbon, armchair 11')
    ax.set_ylabel('Energy (eV)')
    ax.set_xlabel(r'Wave vector ($\frac{\pi}{a}$)')
    ax.plot(k_points, np.sort(band_structure), 'k')
    ax.xaxis.grid()
    plt.show()

    ax1 = plot_atoms(atoms, show_unit_cell=2, rotation='90x,0y,00z')
    ax1.axis('off')
    plt.show()
Exemple #22
0
#!/home/lineng/software/python36/bin/python3.6


# https://wiki.fysik.dtu.dk/ase/ase/visualize/visualize.html

from ase.io import write
from ase.io import read
from ase.calculators.vasp import Vasp
from ase import Atoms
import matplotlib.pyplot as plt
from ase.visualize.plot import plot_atoms

slab = read("./CONTCAR")


#write("image.png", atoms, rotation="10z,-80x")
#write("0.pov", atoms,format="pov", ,run_povray=True,rotation="10z,-80x")
fig, axarr = plt.subplots(1, 4, figsize=(15, 5))
plot_atoms(slab, axarr[0], radii=0.3, rotation=('0x,0y,0z'))
plot_atoms(slab, axarr[1], scale=0.7, offset=(3, 4), radii=0.3, rotation=('0x,0y,0z'))
plot_atoms(slab, axarr[2], radii=0.3, rotation=('45x,45y,0z'))
plot_atoms(slab, axarr[3], radii=0.3, rotation=('0x,0y,0z'))
#write('slab.png',slab, rotation='10z,-80x')
fig.savefig("ase_slab_multiple.png")


Exemple #23
0
def visualize2(hc, field, size_x_min, size_y_min, size_z_min, eps):
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    from matplotlib import cm

    if not isinstance(field, list):
        field = [field]
        eps = [eps]

    # ----------------------------------------------------------------------------

    slab = read('./SiNW/SiNW2/SiNW2f.xyz', format='xyz')

    # ----------------------------------------------------------------------------

    x = np.linspace(-14, 26, 100)
    y = np.linspace(-3, 30, 100)
    z = np.linspace(-20, 20, 100)

    X = np.meshgrid(x, y, z, indexing='ij')

    data = []

    for j, fl in enumerate(field):
        data.append(fl.get_values(np.vstack((X[0].flatten(),
                                             X[1].flatten(),
                                             X[2].flatten())).T).reshape(X[0].shape) / eps[j])

        cut_level = 0.01 * 20
        data[j][data[j] > cut_level] = cut_level
        data[j][data[j] < -cut_level] = -cut_level

    # ----------------------------------------------------------------------------

    n_contours = 21

    norm = cm.colors.Normalize(vmax=cut_level, vmin=-cut_level)
    # cmap = cm.PRGn
    # cmap = cm.seismic
    cmap = cm.coolwarm
    levels = np.arange(-cut_level * 1.1, cut_level * 1.1, 2 * cut_level / n_contours)

    # ----------------------------------------------------------------------------

    x = (x, y, z)

    mins = [max(np.min(hc.coords[:, j]), np.min(x[j])) for j in range(3)]
    sizes = [min(np.max(hc.coords[:, j]) - mins[j], np.max(x[j]) - mins[j]) for j in range(3)]
    # inds = [np.argmin(np.abs(x + field._origin_shift[j])) for j in range(3)]
    inds = [np.argmin(np.abs(x[j] - mins[j] - 0.5 * sizes[j])) for j in range(3)]

    # ----------------------------------------------------------------------------

    set_ind = {0, 1, 2}

    shift = 100

    for j1 in range(3):
        for j2 in range(3):
            if j1 != j2 and j2 > j1:

                if j1 == 1:
                    jj2 = j1
                    jj1 = j2
                else:
                    jj1 = j1
                    jj2 = j2

                j = (set_ind - {j1, j2}).pop()

                fig, ax = plt.subplots(figsize=(10, 10))

                for jjj, dt in enumerate(data):

                    if jjj == 0:
                        ax.contourf(np.take(X[jj1], inds[j], j) + shift,
                                    np.take(X[jj2], inds[j], j) + shift,
                                    np.take(dt, inds[j], j),
                                    levels,
                                    norm=norm,
                                    cmap=cm.get_cmap(cmap, len(levels) - 1))

                        ax.contour(np.take(X[jj1], inds[j], j) + shift,
                                   np.take(X[jj2], inds[j], j) + shift,
                                   np.take(dt, inds[j], j),
                                   levels,
                                   norm=norm,
                                   colors='k',
                                   linewidths=1)
                    else:
                        ax.contour(np.take(X[jj1], inds[j], j) + shift,
                                   np.take(X[jj2], inds[j], j) + shift,
                                   np.take(dt, inds[j], j),
                                   levels,
                                   norm=norm,
                                   colors='r',
                                   linewidths=2,
                                   linestyles=':')

                # ax[max(j2 - j1 - 1, 0), j1].add_patch(Rectangle((mins[jj1]+shift, mins[jj2]+shift),
                #                                                 sizes[jj1],
                #                                                 sizes[jj2],
                #                                                 alpha=1,
                #                                                 fill=None))

                radii = 0.5

                if j == 0:
                    rotation = ('0x,90y,0z')
                    offsets = (size_z_min + shift + radii - 5, size_y_min + shift - radii)
                elif j == 1:
                    rotation = ('90x,0y,0z')
                    offsets = (size_x_min + shift - radii, size_z_min + shift + radii - 5)
                else:
                    rotation = ('0x,0y,0z')
                    offsets = (size_x_min + shift - radii, size_y_min + shift - radii)

                plot_atoms(slab, ax=ax, radii=radii, offset=offsets, rotation=rotation)

                ax.axis('off')
                ax.set_ylim(np.min(x[jj2]) + shift, np.max(x[jj2]) + shift)

                if j1 != jj1:
                    ax.set_xlim(np.max(x[jj1]) + shift, np.min(x[jj1]) + shift)
                else:
                    ax.set_xlim(np.min(x[jj1]) + shift, np.max(x[jj1]) + shift)

                plt.tight_layout()
                plt.show()
Exemple #24
0
import matplotlib.pyplot as plt
from ase.test.testsuite import NotAvailable
from ase.gui.ui import tk

try:
    plt.figure()
except tk.TclError as err:
    raise NotAvailable(err)

from ase.visualize.plot import plot_atoms
from ase.lattice.cubic import FaceCenteredCubic

slab = FaceCenteredCubic('Au', size=(2, 2, 2))

fig, ax = plt.subplots()
plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'))

assert len(ax.patches) == len(slab)
print(ax)
def test_matplotlib_plot_info_occupancies(plt):
    slab = FaceCenteredCubic('Au')
    slab.info['occupancy'] = {'0': {'Au': 1}}
    fig, ax = plt.subplots()
    plot_atoms(slab, ax, show_unit_cell=0)
    assert len(ax.patches) == len(slab)
Exemple #26
0
    weights=np.ones(np.shape(energies)),
    lamb_for_labels=1.0)
space = np.linspace(0, len(energyLabels), len(energyLabels))
plt.plot(space, [e[1] for e in energyLabels])
plt.show()
print(energyLabels)
energyLabels = energyClassifier.get_energy_labels(
    clusterCountVectors=clusterCounts, energies=energies, lamb_for_labels=1.0)

np.save("Energy_Labels", energyLabels)
colors = [
    jmol_colors[kmeans.predict(np.array(e).reshape(1, -1))].flatten()
    for e in atomFeatures
]
fig, ax = plt.subplots()
plot_atoms(atomS, ax, radii=0.3, rotation=('45x, 45y, 45z'), colors=colors)
plt.show()
plot_atoms(atomS, ax, radii=0.3, rotation=('90x, 90y, 0z'), colors=colors)
plt.show()
# space = np.linspace(0, len(energies), len(energies))
# emin = np.amin(energies)
# plt.plot(space, [e - emin for e in energies])
# print(emin)
# plt.show()

# ksis = [1, 2, 4]
# lambs = [1, -1]
# etas = [0.05, 2, 4, 8, 20, 40, 80]
# rss = [0]
# rc = 1
# print(features())