Пример #1
0
def test_gen_diamond_lattice():
    """
    Create a conventional cell of diamond from lattice information.
    """
    from structure import generate_structure

    diamond = generate_structure(
        lattice='cubic',  # cubic tetragonal orthorhombic rhombohedral
        # hexagonal triclinic monoclinic
        cell='conventional',  # primitive, conventional
        centering='F',  # P A B C I R F
        constants=3.57,  # a,b,c,alpha,beta,gamma
        units='A',  # A or B
        atoms='C',  # species in primitive cell
        basis=[
            [0, 0, 0],  # basis vectors (optional)
            [.25, .25, .25]
        ],
    )

    ref = generate_structure(
        units='A',
        axes=[[3.57, 0.00, 0.00], [0.00, 3.57, 0.00], [0.00, 0.00, 3.57]],
        elem=8 * ['C'],
        posu=[[0.00, 0.00, 0.00], [0.25, 0.25, 0.25], [0.00, 0.50, 0.50],
              [0.25, 0.75, 0.75], [0.50, 0.00, 0.50], [0.75, 0.25, 0.75],
              [0.50, 0.50, 0.00], [0.75, 0.75, 0.25]],
    )

    assert (structure_same(diamond, ref))
Пример #2
0
    def test_embed():
        """
        Embed a "relaxed" structure in a larger pristine cell.
        """
        import numpy as np
        from structure import generate_structure

        center = (0, 0, 0)

        g = generate_structure(
            structure='graphene',
            cell='prim',
            tiling=(4, 4, 1),
        )
        g.recenter(center)

        # Represent the "relaxed" cell
        gr = g.copy()
        npos = len(gr.pos)
        dr = gr.min_image_vectors(center)
        dr.shape = npos, 3
        r = np.linalg.norm(dr, axis=1)
        dilation = 2 * r * np.exp(-r)
        for i in range(npos):
            gr.pos[i] += dilation[i] / r[i] * dr[i]
        #end for

        # Represent the unrelaxed large cell
        gl = generate_structure(
            structure='graphene',
            cell='rect',
            tiling=(8, 4, 1),
        )
        gl.recenter(center)

        # Embed the relaxed cell in the large unrelaxed cell
        ge = gl.copy()
        ge.embed(gr)

        assert (len(ge.elem) == len(gl.elem))
        assert (len(ge.pos) == len(gl.pos))

        # check that the large local distortion made in the small cell
        # is present in the large cell after embedding
        rnn_max_ref = 2.1076122431022664
        rnn_max = np.linalg.norm(gr.pos[1] - gr.pos[30])
        assert (value_eq(rnn_max, rnn_max_ref))
        rnn_max = np.linalg.norm(ge.pos[1] - ge.pos[28])
        assert (value_eq(rnn_max, rnn_max_ref))
Пример #3
0
def demo_opt_tiling():
    """
    Search for the "best" tiling matrix for a graphene supercell.
    """

    g11 = generate_structure(
        structure='graphene',
        cell='prim',
    )

    # Look for an optimal cell 20x larger than the primitive cell
    gopt = g11.tile_opt(20)

    print('\nOptimal(?) tiling matrix between primitive and supercell:')
    print(gopt.tilematrix(g11))

    # Plot the tiled structure
    plt.figure(tight_layout=True)
    gopt.plot2d_ax(0, 1, 'k', lw=2)
    g11.plot2d_ax(0, 1, 'r', lw=2)
    gopt.plot2d_pos(0, 1, 'bo')
    plt.axis('equal')
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo tiling: optimally tiled graphene')
    plt.show()
Пример #4
0
def demo_matrix_tiling():
    """
    Make a matrix tiled cell of graphene and plot it.
    """

    g11 = generate_structure(
        structure='graphene',
        cell='prim',
    )

    tmat = [[3, 0, 0], [3, 6, 0], [0, 0, 1]]

    gmat = g11.tile(tmat)

    # For any two structures related by tiling, tiling matrix can be found:
    print('\nTiling matrix between primitive and supercell:')
    print(gmat.tilematrix(g11))

    # Plot the tiled structure
    plt.figure(tight_layout=True)
    gmat.plot2d_ax(0, 1, 'k', lw=2)
    g11.plot2d_ax(0, 1, 'r', lw=2)
    gmat.plot2d_pos(0, 1, 'bo')
    plt.axis('equal')
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo tiling: matrix tiled graphene')
    plt.show()
Пример #5
0
def demo_write():
    """
    Write conventional diamond cell to XYZ, XSF, and POSCAR formats.
    """

    d8 = generate_structure(
        structure='diamond',
        cell='conv',
    )

    # Write an XYZ file
    d8.write('diamond8.xyz')  # loses cell info, appropriate for molecules

    # Write an XSF file
    d8.write('diamond8.xsf')

    # Write a POSCAR file
    d8.write('diamond8.POSCAR')

    # Print the contents of each file
    print('\nXYZ file:')
    os.system('cat diamond8.xyz')

    print('\nXSF file:')
    os.system('cat diamond8.xsf')

    print('\nPOSCAR file:')
    os.system('cat diamond8.POSCAR')
Пример #6
0
def demo_primitive_search():
    """
    Find the primitive cell given a supercell.
    """

    # Note: this demo requires SeeKpath

    d2 = generate_structure(
        structure='diamond',
        cell='prim',
    )

    # Construct the cubic 64 atom supercell
    d64 = d2.tile_opt(32)

    # Remove all traces of the 2 atom cell, supercell is all that remains
    d64.remove_folded()
    del d2

    # Find the primitive cell from the supercell
    dprim = d64.primitive()

    # Print the supercell axes
    print('\nSupercell axes:\n{}'.format(d64.axes))

    # Print the primitive cell axes
    print('\nPrimitive cell axes:\n{}'.format(dprim.axes))

    # Print the tiling matrix
    print('\nTiling matrix:\n{}'.format(d64.tilematrix(dprim)))
Пример #7
0
def test_unit_coords():
    """
    Get atomic positions in unit coordinates.
    """
    import numpy as np
    from structure import generate_structure

    s = generate_structure(
        structure='diamond',
        cell='prim',
        tiling=(2, 2, 2),
    )

    upos_ref = np.array([[0.000, 0.000, 0.000], [0.125, 0.125, 0.125],
                         [0.500, 0.000, 0.000], [0.625, 0.125, 0.125],
                         [0.000, 0.500, 0.000], [0.125, 0.625, 0.125],
                         [0.500, 0.500, 0.000], [0.625, 0.625, 0.125],
                         [0.000, 0.000, 0.500], [0.125, 0.125, 0.625],
                         [0.500, 0.000, 0.500], [0.625, 0.125, 0.625],
                         [0.000, 0.500, 0.500], [0.125, 0.625, 0.625],
                         [0.500, 0.500, 0.500], [0.625, 0.625, 0.625]])

    upos = s.pos_unit()

    upos[np.abs(upos - 1.0) < 1e-10] = 0.0

    assert (value_eq(upos, upos_ref))
Пример #8
0
def test_gen_diamond_direct():
    """
    Create a conventional cell of diamond directly.
    """
    import numpy as np
    from structure import generate_structure

    diamond = generate_structure(
        units='A',
        axes=[[3.57, 0.00, 0.00], [0.00, 3.57, 0.00], [0.00, 0.00, 3.57]],
        elem=8 * ['C'],
        posu=[[0.00, 0.00, 0.00], [0.25, 0.25, 0.25], [0.00, 0.50, 0.50],
              [0.25, 0.75, 0.75], [0.50, 0.00, 0.50], [0.75, 0.25, 0.75],
              [0.50, 0.50, 0.00], [0.75, 0.75, 0.25]],
    )

    assert (diamond.units == 'A')
    assert (tuple(diamond.bconds) == tuple('ppp'))
    assert (value_eq(diamond.axes, 3.57 * np.eye(3)))
    assert (value_eq(list(diamond.center), 3 * [1.785]))
    assert (value_eq(diamond.kaxes, 1.75999588 * np.eye(3)))
    assert (list(diamond.elem) == 8 * ['C'])
    assert (value_eq(tuple(diamond.pos[-1]), (2.6775, 2.6775, 0.8925)))
    assert (len(diamond.kpoints) == 0)
    assert (len(diamond.kweights) == 0)
    assert (diamond.frozen is None)
    assert (diamond.folded_structure is None)
Пример #9
0
    def test_read_cif():
        """
        Read La2CuO4 structure from a CIF file.
        """
        from structure import read_structure, generate_structure

        files = get_files()

        # Read from CIF file
        s = read_structure(files['La2CuO4_ICSD69312.cif'])

        ref = generate_structure(
            units='A',
            axes=[[2.665, 0., -6.5525], [0., 5.4126, 0.], [2.665, 0., 6.5525]],
            elem='La La La La Cu Cu O O O O O O O O'.split(),
            pos=[[2.665, 5.37038172,
                  -1.8071795], [2.665, 2.74851828, 4.7453205],
                 [2.665, 2.66408172, -4.7453205],
                 [2.665, 0.04221828, 1.8071795], [0., 0., 0.],
                 [2.665, 2.7063, 0.], [1.3325, 1.35315, -0.128429],
                 [3.9975, 4.05945, 0.128429], [3.9975, 1.35315, -0.128429],
                 [1.3325, 4.05945, 0.128429], [2.665, 0.23490684, -4.1398695],
                 [2.665, 2.47139316,
                  2.4126305], [2.665, 2.94120684, -2.4126305],
                 [2.665, 5.17769316, 4.1398695]],
        )

        assert (structure_same(s, ref))
Пример #10
0
def demo_freeze():
    """
    Freeze sets of atoms to prevent relaxation.
    """

    g = generate_structure(
        structure='graphene',
        cell='prim',
        tiling=(6, 6, 1),
    )
    g.recenter((0, 0, 0))

    # Select atoms to be frozen
    outer_atoms = np.sqrt((g.pos**2).sum(1)) > 3.2

    # Freeze the atoms
    g.freeze(outer_atoms)

    # Get a mask array identifying the frozen atoms
    frozen = g.is_frozen()

    # Plot the frozen and movable atoms
    plt.figure(tight_layout=True)
    g.plot2d_ax(0, 1, 'k', lw=2)
    t = 2 * np.pi * np.linspace(0, 1, 400)
    plt.plot(3.2 * np.cos(t), 3.2 * np.sin(t), 'g--')
    plt.plot(g.pos[frozen, 0], g.pos[frozen, 1], 'bo', label='frozen')
    plt.plot(g.pos[~frozen, 0], g.pos[~frozen, 1], 'ro', label='movable')
    plt.axis('equal')
    plt.legend()
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo freeze: prevent atoms from relaxing')
    plt.show()
Пример #11
0
def test_bounding_box():
    import numpy as np
    from structure import generate_structure, read_structure

    files = get_files()

    h2o = generate_structure(
        elem=['O', 'H', 'H'],
        pos=[[0.000000, 0.000000, 0.000000], [0.000000, -0.757160, 0.586260],
             [0.000000, 0.757160, 0.586260]],
        units='A',  # Angstroms
    )

    # add a box by hand to the water molecule
    h2o_diy = h2o.copy()
    h2o_diy.set_axes(8.0 * np.eye(3))
    assert (value_eq(h2o_diy.axes, 8. * np.eye(3)))

    # automatically add a bounding box to the water molecule
    h2o_auto = h2o.copy()
    h2o_auto.bounding_box(box='cubic', minsize=8.0)
    assert (value_eq(h2o_auto.axes, 8. * np.eye(3)))
    assert (value_eq(tuple(h2o_auto.pos[-1]), (4., 4.75716, 4.29313)))

    s = read_structure(files['coronene.xyz'])

    # make a bounding box that is at least 5 A from the nearest atom
    s.bounding_box(mindist=5.0)

    ref_axes = np.array([[16.4035, 0., 0.], [0., 16.3786, 0.], [0., 0., 10.]])

    assert (value_eq(s.axes, ref_axes))
    assert (value_eq(s.pos[:, 2].min(), 5.0))
    assert (value_eq(s.pos[:, 2].max(), 5.0))
Пример #12
0
    def test_primitive_search():
        """
        Find the primitive cell given a supercell.
        """

        from structure import generate_structure

        d2 = generate_structure(
            structure='diamond',
            cell='prim',
        )

        tmatrix = [[2, -2, 2], [2, 2, -2], [-2, 2, 2]]

        d64 = d2.tile(tmatrix)

        # Remove all traces of the 2 atom cell, supercell is all that remains
        d64.remove_folded()
        del d2

        # Find the primitive cell from the supercell
        dprim = d64.primitive()

        tmatrix = d64.tilematrix(dprim)

        axes_ref = np.array([[0., 1.785, 1.785], [1.785, 0., 1.785],
                             [1.785, 1.785, 0.]])
        tmatrix_ref = np.array([[-2, 2, 2], [2, -2, 2], [2, 2, -2]])

        assert (value_eq(dprim.axes, axes_ref))
        assert (value_eq(tmatrix, tmatrix_ref))
Пример #13
0
def demo_cell_constants():
    """
    Compute the cell volume, Madelung constant, and Makov Payne correction
    """

    d2 = generate_structure(
        structure='diamond',
        cell='prim',
    )

    # Construct the cubic 64 atom supercell
    d64 = d2.tile_opt(32)

    # Print the volume
    print('\nVolume of 64 atom cell (A): {}'.format(d64.volume()))

    # Print the Madelung constant
    #   ( see equation 7 in PRB 78 125106 (2008) )
    print('\nMadelung constant (Ha): {}'.format(d64.madelung()))

    # Print Makov-Payne corrections
    mp_q1 = d64.makov_payne(q=1, eps=5.68)
    mp_q2 = d64.makov_payne(q=2, eps=5.68)
    print(
        '\nMakov-Payne corr. (Ha) for charged defect (q=1): {}'.format(mp_q1))
    print(
        '\nMakov-Payne corr. (Ha) for charged defect (q=2): {}'.format(mp_q2))
Пример #14
0
def demo_symm_kpoints():
    """
    Add symmetrized Monkhorst-Pack kpoints.
    """

    # Note: this demo requires spglib

    g44 = generate_structure(
        structure='graphene',
        cell='prim',
        tiling=(4, 4, 1),
        kgrid=(4, 4, 1),
        kshift=(0, 0, 0),
        symm_kgrid=True,
    )

    g11 = g44.folded_structure

    # Print the symmtrized kpoints
    print('Symmetrized k-points:\n{}'.format(g44.kpoints_unit()))
    print('Symmetrized weights:\n{}'.format(g44.kweights))

    # Plot the symmetrized kpoints
    plt.figure(tight_layout=True)
    g11.plot2d_kax(0, 1, 'r', lw=2, label='primcell')
    g44.plot2d_kax(0, 1, 'k', lw=2, label='supercell')
    g11.plot2d_kp(0, 1, 'g.')
    g44.plot2d_kp(0, 1, 'bo')
    plt.legend()
    plt.axis('equal')
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo kpoints: symmetrized kpoints in 4x4 graphene')

    plt.show()
Пример #15
0
def demo_random_kpoints():
    """
    Add random k-points.
    """

    g11 = generate_structure(
        structure='graphene',
        cell='prim',
    )

    # Perform a 4x4 tiling of the primitive cell
    g44 = g11.tile(4, 4, 1)

    # Add random kpoints instead of an MP mesh
    rand = np.random.uniform(size=(20, 2))
    kpoints = np.dot(rand, g44.kaxes[0:2])
    g44.add_kpoints(kpoints)
    g11 = g44.folded_structure

    # Plot the random kpoints
    plt.figure(tight_layout=True)
    g11.plot2d_kax(0, 1, 'r', lw=2, label='primcell')
    g44.plot2d_kax(0, 1, 'k', lw=2, label='supercell')
    g11.plot2d_kp(0, 1, 'g.')
    g44.plot2d_kp(0, 1, 'bo')
    plt.legend()
    plt.axis('equal')
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo kpoints: random kpoints in 4x4 graphene')

    plt.show()
Пример #16
0
def demo_mp_kpoints():
    """
    Add k-points according to Monkhorst-Pack grid.
    """

    g11 = generate_structure(
        structure='graphene',
        cell='prim',
    )

    # Perform a 4x4 tiling of the primitive cell
    g44 = g11.tile(4, 4, 1)

    # Add a Gamma-centered 2x2 Monkhorst-Pack grid
    g44g = g44.copy()
    g11g = g44g.folded_structure

    g44g.add_kmesh(kgrid=(2, 2, 1), kshift=(0, 0, 0))

    # Add a shifted 2x2 Monkhorst-Pack grid
    g44s = g44.copy()
    g11s = g44s.folded_structure

    g44s.add_kmesh(kgrid=(2, 2, 1), kshift=(0.5, 0.5, 0))

    # Get the mapping between supercell and primitive cell k-points
    print('Monk-horst pack grid')
    kmap = g44s.kmap()
    print('# of k-points in supercell: {}'.format(len(g44s.kpoints)))
    print('# of k-points in primcell : {}'.format(len(g11s.kpoints)))
    print('index mapping from super to prim:\n{}'.format(
        str(kmap).replace('  ', '')))

    # Plot kpoints for the 2x2 unshifted MP mesh
    plt.figure(tight_layout=True)
    g11g.plot2d_kax(0, 1, 'r', lw=2, label='primcell')
    g44g.plot2d_kax(0, 1, 'k', lw=2, label='supercell')
    g11g.plot2d_kp(0, 1, 'g.')
    g44g.plot2d_kp(0, 1, 'bo')
    plt.legend()
    plt.axis('equal')
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo kpoints: unshifted 2x2 MP mesh in 4x4 graphene')

    # Plot kpoints for the 2x2 shifted MP mesh
    plt.figure(tight_layout=True)
    g11s.plot2d_kax(0, 1, 'r', lw=2, label='primcell')
    g44s.plot2d_kax(0, 1, 'k', lw=2, label='supercell')
    g11s.plot2d_kp(0, 1, 'g.')
    g44s.plot2d_kp(0, 1, 'bo')
    plt.legend()
    plt.axis('equal')
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo kpoints: shifted 2x2 MP mesh in 4x4 graphene')

    plt.show()
Пример #17
0
def test_rwigner():
    from structure import generate_structure
    s = generate_structure(
        structure='graphene',
        cell='prim',
        tiling=(4, 4, 1),
    )
    rw = s.rwigner()
    assert (value_eq(float(rw), 4.924))
Пример #18
0
def test_rinscribe():
    from structure import generate_structure
    s = generate_structure(
        structure='graphene',
        cell='prim',
        tiling=(4, 4, 1),
    )
    ri = s.rinscribe()
    assert (value_eq(float(ri), 4.2643090882345795))
Пример #19
0
def demo_water_box():
    """
    Make simulation cells for water molecule and dimer.
    """

    h2o = generate_structure(
        elem=['O', 'H', 'H'],
        pos=[[0.000000, 0.000000, 0.000000], [0.000000, -0.757160, 0.586260],
             [0.000000, 0.757160, 0.586260]],
        units='A',  # Angstroms
    )

    # add a box by hand to the water molecule
    h2o_diy = h2o.copy()
    h2o_diy.set_axes(8.0 * np.eye(3))

    # automatically add a bounding box to the water molecule
    h2o_auto = h2o.copy()
    h2o_auto.bounding_box(box='cubic', minsize=8.0)

    # make a water dimer configuration
    h2o1 = h2o.copy()
    h2o1.bounding_box(box='cubic', minsize=8.0)
    h2o2 = h2o1.copy()
    h2o1.translate((0, 0, -1.1))
    h2o2.translate((0, 0, 1.1))
    h2o_dimer = h2o1.copy()
    h2o_dimer.incorporate(h2o2)

    # plot the water molecule with DIY box
    plt.figure(tight_layout=True)
    h2o_diy.plot2d_ax(1, 2, 'k', lw=2)
    h2o_diy.plot2d_pos(1, 2, 'bo')
    plt.axis('equal')
    plt.xlabel('y (A)')
    plt.ylabel('z (A)')
    plt.title('demo water box: DIY box')

    # plot the water molecule with an automatic box
    plt.figure(tight_layout=True)
    h2o_auto.plot2d_ax(1, 2, 'k', lw=2)
    h2o_auto.plot2d_pos(1, 2, 'bo')
    plt.axis('equal')
    plt.xlabel('y (A)')
    plt.ylabel('z (A)')
    plt.title('demo water box: automatic box')

    # plot the water dimer
    plt.figure(tight_layout=True)
    h2o_dimer.plot2d_ax(1, 2, 'k', lw=2)
    h2o_dimer.plot2d_pos(1, 2, 'bo')
    plt.axis('equal')
    plt.xlabel('y (A)')
    plt.ylabel('z (A)')
    plt.title('demo water box: water dimer')

    plt.show()
Пример #20
0
def get_crystal_structures():
    from generic import obj
    from structure import Crystal, generate_structure
    if len(crystal_structures) == 0:
        crys = crystal_structures
        for (latt, cell), inputs in Crystal.known_crystals.items():
            s = generate_structure(structure=latt, cell=cell)
            crys[latt + '_' + cell] = s
        #end for
    #end if
    return obj(crystal_structures)
Пример #21
0
def get_generated_structures():
    from generic import obj
    from structure import generate_structure
    if len(generated_structures) == 0:
        ref_in = get_reference_inputs()
        gen = generated_structures
        for name, inputs in ref_in.items():
            gen[name] = generate_structure(**inputs)
        #end for
    #end if
    return obj(generated_structures)
Пример #22
0
def test_gen_graphene():
    """
    Create a graphene cell using stored information.
    """
    from structure import generate_structure

    graphene = generate_structure(
        structure='graphene',
        cell='prim',
    )

    ref = generate_structure(
        units='A',
        axes=[[2.46200000e+00, 0.00000000e+00, 0.00000000e+00],
              [-1.23100000e+00, 2.13215454e+00, 0.00000000e+00],
              [9.18485099e-16, 1.59086286e-15, 1.50000000e+01]],
        elem=['C', 'C'],
        pos=[[0., 0., 0.], [1.231, 0.71071818, 0.]],
    )

    assert (structure_same(graphene, ref))
Пример #23
0
def demo_gen_graphene():
    """
    Create a graphene cell using stored information.
    """

    graphene = generate_structure(
        structure='graphene',
        cell='prim',
    )

    # print structure data
    print(graphene)
Пример #24
0
def test_interpolate():
    """
    Interpolate between two "relaxed" structures for NEB initialization.
    """
    import numpy as np
    from structure import generate_structure

    g = generate_structure(
        structure='graphene',
        cell='prim',
        tiling=(4, 4, 1),
    )
    g11 = g.folded_structure

    # Make chromium atom positions (pretend like they are above the surface)
    npos = np.dot((1. / 3, 2. / 3, 0), g11.axes)
    npos1 = npos + 3 * g11.axes[0]
    npos2 = npos1 + g11.axes[0] + g11.axes[1]

    # "Relaxed" structure with additional atom on one ring
    gr1 = g.copy()
    gr1.add_atoms(['Cr'], [npos1])

    # "Relaxed" structure with additional atom on neighboring ring
    gr2 = g.copy()
    gr2.add_atoms(['Cr'], [npos2])
    gr2.recenter()

    # Interpolate between the two structures within min. image convention
    spath = gr1.interpolate(gr2, 10)

    Cr_positions_ref = np.array([[7.386, 1.42143636, 0.],
                                 [7.49790909, 1.61526859, 0.],
                                 [7.60981818, 1.80910083, 0.],
                                 [7.72172727, 2.00293306, 0.],
                                 [7.83363636, 2.19676529, 0.],
                                 [7.94554545, 2.39059752, 0.],
                                 [8.05745455, 2.58442975, 0.],
                                 [8.16936364, 2.77826198, 0.],
                                 [-1.56672727, 2.97209421, 0.],
                                 [-1.45481818, 3.16592644, 0.],
                                 [-1.34290909, 3.35975868, 0.],
                                 [-1.231, 3.55359091, 0.]])

    Cr_positions = []
    for gr in spath:
        Cr_positions.append(gr.pos[-1])
    #end for
    Cr_positions = np.array(Cr_positions)

    assert (value_eq(Cr_positions, Cr_positions_ref))
Пример #25
0
def generate_physical_system(**kwargs):

    for var,val in ps_defaults.iteritems():
        if not var in kwargs:
            kwargs[var] = val
        #end if
    #end for
    if 'type' in kwargs and kwargs['type']=='atom':
        del kwargs['kshift']
        if not 'units' in kwargs:
            kwargs['units'] = 'B'
        #end if
    #end if

    generation_info = obj()
    generation_info.transfer_from(deepcopy(kwargs))


    net_charge = kwargs['net_charge']
    net_spin = kwargs['net_spin']
    del kwargs['net_spin']
    del kwargs['net_charge']
    if 'particles' in kwargs:
        particles = kwargs['particles']
        del kwargs['particles']
    else:
        generation_info.particles = None
    #end if
    valency = dict()
    remove = []
    for var in kwargs:
        if var in Matter.elements:
            valency[var] = kwargs[var]
            remove.append(var)
        #end if
    #end if
    generation_info.valency = deepcopy(valency)
    for var in remove:
        del kwargs[var]
    #end for

    ps = PhysicalSystem(
        structure  = generate_structure(**kwargs),
        net_charge = net_charge,
        net_spin   = net_spin,
        **valency
        )
    
    ps.generation_info = generation_info

    return ps
Пример #26
0
def test_opt_tiling():
    import numpy as np
    from structure import generate_structure

    dprim = generate_structure(
        structure='diamond',
        cell='prim',
    )

    dopt = dprim.tile_opt(4)

    tmatrix_ref = np.array([[1, -1, 1], [1, 1, -1], [-1, 1, 1]])
    assert (value_eq(dopt.tmatrix, tmatrix_ref))
    assert (len(dopt.elem) == 4 * len(dprim.elem))
    assert (value_eq(dopt.axes, 3.57 * np.eye(3)))
Пример #27
0
def demo_unit_coords():
    """
    Get atomic positions and k-points in unit coordinates.
    """

    s = generate_structure(
        structure='diamond',
        cell='prim',
        tiling=(2, 2, 2),
        kgrid=(2, 2, 2),
        kshift=(0.5, 0.5, 0.5),
    )

    print('\nAtomic positions in unit coordinates:\n{}'.format(s.pos_unit()))

    print('\nk-points in unit coordinates:\n{}'.format(s.kpoints_unit()))
Пример #28
0
def test_gen_molecule():
    """
    Create an H2O molecule.
    """
    from structure import generate_structure

    h2o = generate_structure(
        elem=['O', 'H', 'H'],
        pos=[[0.000000, 0.000000, 0.000000], [0.000000, -0.757160, 0.586260],
             [0.000000, 0.757160, 0.586260]],
        units='A',  # Angstroms
    )

    # print important internal attributes
    assert (tuple(h2o.elem) == tuple('OHH'))
    assert (value_eq(h2o.pos[2, 2], 0.586260))
    assert (h2o.units == 'A')
Пример #29
0
def demo_interpolate():
    """
    Interpolate between two "relaxed" structures for NEB initialization.
    """

    g = generate_structure(
        structure='graphene',
        cell='prim',
        tiling=(4, 4, 1),
    )
    g11 = g.folded_structure

    # Make chromium atom positions (pretend like they are above the surface)
    npos = np.dot((1. / 3, 2. / 3, 0), g11.axes)
    npos1 = npos + 3 * g11.axes[0]
    npos2 = npos1 + g11.axes[0] + g11.axes[1]

    # "Relaxed" structure with additional atom on one ring
    gr1 = g.copy()
    gr1.add_atoms(['Cr'], [npos1])

    # "Relaxed" structure with additional atom on neighboring ring
    gr2 = g.copy()
    gr2.add_atoms(['Cr'], [npos2])
    gr2.recenter()

    # Interpolate between the two structures within min. image convention
    spath = gr1.interpolate(gr2, 10)

    # Plot the (linear) interpolation path
    plt.figure(tight_layout=True)
    for gr in spath:
        gr.plot2d_ax(0, 1, 'k', lw=2)
        gr.plot2d_pos(0, 1, 'bo')
        npos = gr.pos[-1]
        plt.plot([npos[0]], [npos[1]], 'go')
    #end for
    plt.axis('equal')
    plt.xlabel('x (A)')
    plt.ylabel('y (A)')
    plt.title('demo interpolate: paths for NEB')

    plt.show()
Пример #30
0
def test_min_image_distances():
    """
    Compute minimum image distances between nearest neighbors.
    """
    import numpy as np
    from structure import generate_structure

    g = generate_structure(
        structure='graphene',
        cell='prim',
        tiling=(4, 4, 1),
    )

    # Get the neighbor (index) table, along with sorted distance
    # and displacement tables.
    nt, dt, vt = g.neighbor_table(distances=True, vectors=True)

    # Restrict to 3 nearest neighbors (not including self at index 0)
    nt = nt[:, 1:4]
    dt = dt[:, 1:4]
    vt = vt[:, 1:4]

    nt_ref = np.array([[1, 11, 9], [30, 0, 24], [3, 11, 13], [2, 26, 24],
                       [5, 15, 13], [4, 26, 28], [7, 9, 15], [6, 30, 28],
                       [9, 19, 17], [8, 6, 0], [11, 19, 21], [10, 0, 2],
                       [13, 23, 21], [12, 2, 4], [15, 17, 23], [14, 4, 6],
                       [17, 27, 25], [16, 8, 14], [19, 27, 29], [18, 10, 8],
                       [21, 29, 31], [20, 12, 10], [23, 25, 31], [22, 12, 14],
                       [25, 1, 3], [24, 22, 16], [27, 3, 5], [26, 18, 16],
                       [29, 5, 7], [28, 18, 20], [31, 1, 7], [30, 22, 20]])

    for nti, nti_ref in zip(nt, nt_ref):
        assert (set(nti) == set(nti_ref))
    #end for

    dist = dt.ravel()
    assert (value_eq(dist.min(), 1.42143636))
    assert (value_eq(dist.max(), 1.42143636))

    vec = vt.ravel()
    vec.shape = np.prod(dt.shape), 3
    vdist = np.linalg.norm(vec, axis=1)
    assert (value_eq(vdist, dist))
Пример #31
0
def generate_physical_system(**kwargs):
    for var,val in ps_defaults.iteritems():
        if not var in kwargs:
            kwargs[var] = val
        #end if
    #end for
    type = kwargs['type']
    if type=='atom' or type=='dimer' or type=='trimer':
        del kwargs['kshift']
        del kwargs['tiling']
        #if not 'units' in kwargs:
        #    kwargs['units'] = 'B'
        ##end if
        tiling = None
    else:
        tiling = kwargs['tiling']
    #end if

    if 'structure' in kwargs:
        s = kwargs['structure']
        is_str = isinstance(s,str)
        if is_str and os.path.exists(s):# and '.' in os.path.split(s)[1]:
            if 'elem' in kwargs:
                print 'system using elem'
                kwargs['structure'] = read_structure(s,elem=kwargs['elem'])
            else:
                kwargs['structure'] = read_structure(s)
            #end if
        elif is_str and '/' in s:
            PhysicalSystem.class_error('path provided for structure file does not exist: '+s,'generate_physical_system')
        #end if
    #end if

    generation_info = obj()
    generation_info.transfer_from(deepcopy(kwargs))

    net_charge = kwargs['net_charge']
    net_spin   = kwargs['net_spin']
    tiled_spin = kwargs['tiled_spin']
    extensive  = kwargs['extensive']
    del kwargs['net_spin']
    del kwargs['net_charge']
    del kwargs['tiled_spin']
    del kwargs['extensive']
    if 'particles' in kwargs:
        particles = kwargs['particles']
        del kwargs['particles']
    else:
        generation_info.particles = None
    #end if
    pretile = kwargs['pretile']
    del kwargs['pretile']
    valency = dict()
    remove = []
    for var in kwargs:
        #if var in Matter.elements:
        if is_element(var):     
            valency[var] = kwargs[var]
            remove.append(var)
        #end if
    #end if
    generation_info.valency = deepcopy(valency)
    for var in remove:
        del kwargs[var]
    #end for

    if pretile is None:
        structure = generate_structure(**kwargs)
    else:
        for d in range(len(pretile)):
            if tiling[d]%pretile[d]!=0:
                PhysicalSystem.class_error('pretile does not divide evenly into tiling\n  tiling provided: {0}\n  pretile provided: {1}'.format(tiling,pretile),'generate_physical_system')
            #end if
        #end for
        tiling = tuple(array(tiling)/array(pretile))
        kwargs['tiling'] = pretile
        pre = generate_structure(**kwargs)
        pre.remove_folded_structure()
        structure = pre.tile(tiling)
    #end if

    if tiling!=None and tiling!=(1,1,1):
        fps = PhysicalSystem(
            structure  = structure.folded_structure,
            net_charge = net_charge,
            net_spin   = net_spin,
            **valency
            )
        structure.remove_folded()
        folded_structure = fps.structure
        if extensive:
            ncells = int(round(structure.volume()/folded_structure.volume()))
            net_charge = ncells*net_charge
            net_spin   = ncells*net_spin
        #end if
        if tiled_spin!=None:
            net_spin = tiled_spin
        #end if
        ps = PhysicalSystem(
            structure  = structure,
            net_charge = net_charge,
            net_spin   = net_spin,
            **valency
            )
        structure.set_folded(folded_structure)
        ps.folded_system = fps
    else:
        ps = PhysicalSystem(
            structure  = structure,
            net_charge = net_charge,
            net_spin   = net_spin,
            **valency
            )
    #end if
    
    ps.generation_info = generation_info

    return ps
Пример #32
0
            net_charge = net_charge,
            net_spin   = net_spin,
            **valency
            )
    #end if
    
    ps.generation_info = generation_info

    return ps
#end def generate_physical_system




if __name__=='__main__':
    
    from structure import generate_structure

    ps = PhysicalSystem(
        structure = generate_structure('diamond','sc','Ge',(2,2,2),scale=5.639,units='A'),
        net_charge = 1,
        net_spin   = 1,
        Ge = 4
        )

    print 'net_charge',ps.net_charge
    print 'net_spin  ',ps.net_spin
    print ps.particles

#end if
Пример #33
0
def generate_physical_system(**kwargs):

    for var,val in ps_defaults.iteritems():
        if not var in kwargs:
            kwargs[var] = val
        #end if
    #end for
    if 'type' in kwargs and kwargs['type']=='atom':
        del kwargs['kshift']
        if not 'units' in kwargs:
            kwargs['units'] = 'B'
        #end if
    #end if

    generation_info = obj()
    generation_info.transfer_from(deepcopy(kwargs))


    net_charge = kwargs['net_charge']
    net_spin = kwargs['net_spin']
    del kwargs['net_spin']
    del kwargs['net_charge']
    if 'particles' in kwargs:
        particles = kwargs['particles']
        del kwargs['particles']
    else:
        generation_info.particles = None
    #end if
    pretile = kwargs['pretile']
    del kwargs['pretile']
    valency = dict()
    remove = []
    for var in kwargs:
        if var in Matter.elements:
            valency[var] = kwargs[var]
            remove.append(var)
        #end if
    #end if
    generation_info.valency = deepcopy(valency)
    for var in remove:
        del kwargs[var]
    #end for

    if pretile is None:
        structure = generate_structure(**kwargs)
    else:
        tiling = kwargs['tiling']
        for d in range(len(pretile)):
            if tiling[d]%pretile[d]!=0:
                PhysicalSystem.class_error('pretile does not divide evenly into tiling\n  tiling provided: {0}\n  pretile provided: {1}'.format(tiling,pretile))
            #end if
        #end for
        tiling = tuple(array(tiling)/array(pretile))
        kwargs['tiling'] = pretile
        pre = generate_structure(**kwargs)
        pre.remove_folded_structure()
        structure = pre.tile(tiling)
    #end if

    ps = PhysicalSystem(
        structure  = structure,
        net_charge = net_charge,
        net_spin   = net_spin,
        **valency
        )
    
    ps.generation_info = generation_info

    return ps