Example #1
0
    def read_grid(self, spin=0, *args, **kwargs):
        """ Read grid contained in the Grid file

        Parameters
        ----------
        spin : int or array_like, optional
           the spin-index for retrieving one of the components. If a vector
           is passed it refers to the fraction per indexed component. I.e.
           ``[0.5, 0.5]`` will return sum of half the first two components.
           Default to the first component.
        """
        # Read the sizes
        nspin, mesh = _siesta.read_grid_sizes(self.file)
        # Read the cell and grid
        cell = _siesta.read_grid_cell(self.file)
        grid = _siesta.read_grid(self.file, nspin, mesh[0], mesh[1], mesh[2])

        if isinstance(spin, Integral):
            grid = grid[:, :, :, spin]
        else:
            if len(spin) > grid.shape[0]:
                raise ValueError(self.__class__.__name__ + '.read_grid requires spin to be an integer or '
                                 'an array of length equal to the number of spin components.')
            g = grid[:, :, :, 0] * spin[0]
            for i, scale in enumerate(spin[1:]):
                g += grid[:, :, :, 1+i] * scale
            grid = g

        cell = np.array(cell.T, np.float64)
        cell.shape = (3, 3)

        g = Grid(mesh, sc=SuperCell(cell), dtype=np.float32)
        g.grid = np.array(grid.swapaxes(0, 2), np.float32) * self.grid_unit
        return g
Example #2
0
        def __init__(self):
            bond = 1.42
            sq3h = 3.**.5 * 0.5
            self.sc = SuperCell(
                np.array([[1.5, sq3h, 0.], [1.5, -sq3h, 0.], [0., 0., 10.]],
                         np.float64) * bond,
                nsc=[3, 3, 1])
            C = Atom(Z=6, R=[bond * 1.01] * 2)
            self.g = Geometry(
                np.array([[0., 0., 0.], [1., 0., 0.]], np.float64) * bond,
                atoms=C,
                sc=self.sc)
            self.grid = Grid(0.2, geometry=self.g)
            self.grid.grid[:, :, :] = np.random.rand(*self.grid.shape)

            self.mol = Geometry([[i, 0, 0] for i in range(10)], sc=[50])

            self.grid_mol = Grid(0.2, geometry=self.mol)
            self.grid_mol.grid[:, :, :] = np.random.rand(*self.grid_mol.shape)

            def sg_g(**kwargs):
                kwargs['ret_grid'] = True
                if 'grid' not in kwargs:
                    kwargs['grid'] = self.grid
                return sgrid(**kwargs)

            self.sg_g = sg_g

            def sg_mol(**kwargs):
                kwargs['ret_grid'] = True
                if 'grid' not in kwargs:
                    kwargs['grid'] = self.grid_mol
                return sgrid(**kwargs)

            self.sg_mol = sg_mol
Example #3
0
    def read_grid(self, name='gridfunc', idx=0, *args, **kwargs):
        """ Reads a grid in the current SIESTA.grid.nc file

        Enables the reading and processing of the grids created by SIESTA
        """
        # Swap as we swap back in the end
        sc = self.read_supercell().swapaxes(0, 2)

        # Create the grid
        nx = len(self._dimension('n1'))
        ny = len(self._dimension('n2'))
        nz = len(self._dimension('n3'))

        if name is None:
            v = self._variable('gridfunc')
        else:
            v = self._variable(name)

        # Create the grid, SIESTA uses periodic, always
        grid = Grid([nz, ny, nx], bc=Grid.Periodic, sc=sc,
                    dtype=v.dtype)

        if len(v.shape) == 3:
            grid.grid[:, :, :] = v[:, :, :]
        else:
            grid.grid[:, :, :] = v[idx, :, :, :]

        # Read the grid, we want the z-axis to be the fastest
        # looping direction, hence x,y,z == 0,1,2
        return grid.swapaxes(0, 2)
def test_default(sisl_tmp):
    f = sisl_tmp('GRID.xsf', _dir)
    print(f)
    grid = Grid(0.2)
    grid.grid = np.random.rand(*grid.shape)
    grid.write(f)
    assert grid.geometry is None
def test_imaginary(sisl_tmp):
    f = sisl_tmp('GRID.xsf', _dir)
    geom = Geometry(np.random.rand(10, 3), np.random.randint(1, 70, 10), sc=[10, 10, 10, 45, 60, 90])
    grid = Grid(0.2, geometry=geom, dtype=np.complex128)
    grid.grid = np.random.rand(*grid.shape) + 1j*np.random.rand(*grid.shape)
    grid.write(f)
    assert not grid.geometry is None
Example #6
0
File: cube.py Project: zerothi/sisl
    def read_grid(self):
        """ Returns `Grid` object from the CUBE file """
        geom = self.read_geom()

        # Now seek behind to read grid sizes
        self.fh.seek(0)

        # Skip headers and origo
        self.readline()
        self.readline()
        na = int(self.readline().split()[0])

        ngrid = [0] * 3
        for i in [0, 1, 2]:
            tmp = self.readline().split()
            ngrid[i] = int(tmp[0])

        # Read past the atoms
        for i in range(na):
            self.readline()

        grid = Grid(ngrid, dtype=np.float32, geom=geom)
        grid.grid = np.loadtxt(self.fh, dtype=grid.dtype)
        grid.grid.shape = ngrid

        return grid
Example #7
0
    def read_grid(self):
        """ Returns `Grid` object from the CUBE file """
        geom = self.read_geom()

        # Now seek behind to read grid sizes
        self.fh.seek(0)

        # Skip headers and origo
        self.readline()
        self.readline()
        na = int(self.readline().split()[0])

        ngrid = [0] * 3
        for i in [0, 1, 2]:
            tmp = self.readline().split()
            ngrid[i] = int(tmp[0])

        # Read past the atoms
        for i in range(na):
            self.readline()

        grid = Grid(ngrid, dtype=np.float32, geom=geom)
        grid.grid = np.loadtxt(self.fh, dtype=grid.dtype)
        grid.grid.shape = ngrid

        return grid
Example #8
0
    def test_read_write_grid(self, sisl_tmp, sisl_system, sile):
        g = sisl_system.g.rotate(-30, sisl_system.g.cell[2, :])
        G = Grid([10, 11, 12])
        G[:, :, :] = np.random.rand(10, 11, 12)

        f = sisl_tmp("test_read_write_grid.win", _dir)
        # Write
        try:
            with sile(f, mode="w") as s:
                s.write_grid(G)
        except SileError:
            with sile(f, mode="wb") as s:
                s.write_grid(G)
        # Read 1
        try:
            with sile(f, mode="r") as s:
                g = s.read_grid()
            assert np.allclose(g.grid, G.grid, atol=1e-5)
        except UnicodeDecodeError as e:
            pass
        # Read 2
        try:
            with sile(f, mode='r') as s:
                g = Grid.read(s)
            assert np.allclose(g.grid, G.grid, atol=1e-5)
        except UnicodeDecodeError as e:
            pass
Example #9
0
    def read_grid(self, name='gridfunc', idx=0, *args, **kwargs):
        """ Reads a grid in the current SIESTA.grid.nc file

        Enables the reading and processing of the grids created by SIESTA
        """
        # Swap as we swap back in the end
        sc = self.read_sc().swapaxes(0, 2)

        # Create the grid
        nx = len(self._dimension('n1'))
        ny = len(self._dimension('n2'))
        nz = len(self._dimension('n3'))

        if name is None:
            v = self._variable('gridfunc')
        else:
            v = self._variable(name)

        # Create the grid, SIESTA uses periodic, always
        grid = Grid([nz, ny, nx], bc=Grid.Periodic, sc=sc,
                    dtype=v.dtype)

        if len(v[:].shape) == 3:
            grid.grid = v[:, :, :]
        else:
            grid.grid = v[idx, :, :, :]

        # Read the grid, we want the z-axis to be the fastest
        # looping direction, hence x,y,z == 0,1,2
        return grid.swapaxes(0, 2)
Example #10
0
 def setUp(self):
     alat = 1.42
     sq3h = 3.**.5 * 0.5
     self.sc = SuperCell(np.array(
         [[1.5, sq3h, 0.], [1.5, -sq3h, 0.], [0., 0., 10.]], np.float64) *
                         alat,
                         nsc=[3, 3, 1])
     self.g = Grid([10, 10, 100], sc=self.sc)
Example #11
0
 def test_iadd1(self):
     g = Grid([10, 10, 10])
     g.fill(1)
     old = g.copy()
     g += g
     g -= old
     assert np.allclose(g.grid, 1)
     g -= g
     assert np.allclose(g.grid, 0)
Example #12
0
 class t():
     def __init__(self):
         alat = 1.42
         sq3h = 3.**.5 * 0.5
         self.sc = SuperCell(np.array([[1.5, sq3h, 0.],
                                       [1.5, -sq3h, 0.],
                                       [0., 0., 10.]], np.float64) * alat, nsc=[3, 3, 1])
         self.g = Grid([10, 10, 100], sc=self.sc)
         self.g.fill(2.)
Example #13
0
def test_wavefunction1():
    N = 50
    o1 = SphericalOrbital(0, (np.linspace(0, 2, N), np.exp(-np.linspace(0, 100, N))))
    G = Geometry([[1] * 3, [2] * 3], Atom(6, o1), sc=[4, 4, 4])
    H = Hamiltonian(G)
    R, param = [0.1, 1.5], [1., 0.1]
    H.construct([R, param])
    ES = H.eigenstate(dtype=np.float64)
    # Plot in the full thing
    grid = Grid(0.1, geometry=H.geom)
    grid.fill(0.)
    ES.sub(0).wavefunction(grid)
Example #14
0
    def test_smooth_gaussian(self, setup):
        g = Grid(0.1, sc=[[2, 0, 0], [0, 2, 0], [0, 0, 2]])
        g[10, 10, 10] = 1

        # With a sigma of 0.3 Ang, that single value should be propagated
        # to the whole grid
        smoothed = g.smooth(r=0.7, truncate=4)
        assert not np.any(smoothed.grid == 0)

        # With a sigma of 0.2 Ang, borders should be still 0
        smoothed = g.smooth(r=0.1, truncate=4)
        assert np.any(smoothed.grid == 0)
Example #15
0
def test_grid_tile_sc():
    grid = Grid([4, 5, 6])
    grid2 = grid.tile(2, 2)
    assert grid.shape[:2] == grid2.shape[:2]
    assert grid.shape[2] == grid2.shape[2] // 2
    assert grid.volume * 2 == pytest.approx(grid2.volume)

    grid4 = grid2.tile(2, 1)
    assert grid.shape[0] == grid4.shape[0]
    assert grid.shape[1] == grid4.shape[1] // 2
    assert grid.shape[2] == grid4.shape[2] // 2
    assert grid.volume * 4 == pytest.approx(grid4.volume)
Example #16
0
    def test_smooth_uniform(self, setup):
        g = Grid(0.1, sc=[[2, 0, 0], [0, 2, 0], [0, 0, 2]])
        g[10, 10, 10] = 1

        # With a radius of 0.7 Ang, that single value should be propagated
        # to the whole grid
        smoothed = g.smooth(r=1., method='uniform')
        assert not np.any(smoothed.grid == 0)

        # With a sigma of 0.1 Ang, borders should still be 0
        smoothed = g.smooth(r=0.9, method='uniform')
        assert np.any(smoothed.grid == 0)
Example #17
0
def test_wavefunction2():
    N = 50
    o1 = SphericalOrbital(0, (np.linspace(0, 2, N), np.exp(-np.linspace(0, 100, N))))
    G = Geometry([[1] * 3, [2] * 3], Atom(6, o1), sc=[4, 4, 4])
    H = Hamiltonian(G)
    R, param = [0.1, 1.5], [1., 0.1]
    H.construct([R, param])
    ES = H.eigenstate(dtype=np.float64)
    # This is effectively plotting outside where no atoms exists
    # (there could however still be psi weight).
    grid = Grid(0.1, sc=SuperCell([2, 2, 2], origo=[2] * 3))
    grid.fill(0.)
    ES.sub(0).wavefunction(grid)
Example #18
0
def test_wavefunction_eta():
    N = 50
    o1 = SphericalOrbital(0, (np.linspace(0, 2, N), np.exp(-np.linspace(0, 100, N))))
    G = Geometry([[1] * 3, [2] * 3], Atom(6, o1), sc=[4, 4, 4])
    H = Hamiltonian(G, spin=Spin('nc'))
    R, param = [0.1, 1.5], [[0., 0., 0.1, -0.1],
                            [1., 1., 0.1, -0.1]]
    H.construct([R, param])
    ES = H.eigenstate()
    # Plot in the full thing
    grid = Grid(0.1, dtype=np.complex128, sc=SuperCell([2, 2, 2], origo=[-1] * 3))
    grid.fill(0.)
    ES.sub(0).wavefunction(grid, eta=True)
Example #19
0
def test_grid_tile_geom():
    grid = Grid([4, 5, 6], geometry=Geometry([0] * 3, Atom[4], sc=4.))
    grid2 = grid.tile(2, 2)
    assert grid.shape[:2] == grid2.shape[:2]
    assert grid.shape[2] == grid2.shape[2] // 2
    assert grid.volume * 2 == pytest.approx(grid2.volume)
    assert grid.geometry.na * 2 == grid2.geometry.na

    grid4 = grid2.tile(2, 1)
    assert grid.shape[0] == grid4.shape[0]
    assert grid.shape[1] == grid4.shape[1] // 2
    assert grid.shape[2] == grid4.shape[2] // 2
    assert grid.volume * 4 == pytest.approx(grid4.volume)
    assert grid.geometry.na * 4 == grid4.geometry.na
Example #20
0
    def read_grid(self, index=0, dtype=np.float64, *args, **kwargs):
        """ Read grid contained in the Grid file

        Parameters
        ----------
        index : int or array_like, optional
           the spin-index for retrieving one of the components. If a vector
           is passed it refers to the fraction per indexed component. I.e.
           ``[0.5, 0.5]`` will return sum of half the first two components.
           Default to the first component.
        dtype : numpy.float64, optional
           default data-type precision
        """
        index = kwargs.get('spin', index)
        # Read the sizes and cell
        nspin, mesh = self.read_grid_size()
        cell = _siesta.read_grid_cell(self.file)
        _bin_check(self, 'read_grid', 'could not read grid cell.')
        grid = _siesta.read_grid(self.file, nspin, mesh[0], mesh[1], mesh[2])
        _bin_check(self, 'read_grid', 'could not read grid.')

        if isinstance(index, Integral):
            grid = grid[:, :, :, index]
        else:
            if len(index) > grid.shape[0]:
                raise ValueError(
                    self.__class__.__name__ +
                    '.read_grid requires spin to be an integer or '
                    'an array of length equal to the number of spin components.'
                )
            # It is F-contiguous, hence the last index
            g = grid[:, :, :, 0] * index[0]
            for i, scale in enumerate(index[1:]):
                g += grid[:, :, :, 1 + i] * scale
            grid = g

        cell = np.array(cell.T, np.float64)
        cell.shape = (3, 3)

        # Simply create the grid (with no information)
        # We will overwrite the actual grid
        g = Grid([1, 1, 1], sc=SuperCell(cell))
        # NOTE: there is no need to swap-axes since the returned array is in F ordering
        #       and thus the first axis is the fast (x, y, z) is retained
        g.grid = (grid * self.grid_unit).astype(dtype=dtype,
                                                order='C',
                                                copy=False)
        return g
Example #21
0
 def setUp(self):
     alat = 1.42
     sq3h = 3.**.5 * 0.5
     self.sc = SuperCell(np.array([[1.5, sq3h, 0.],
                                   [1.5, -sq3h, 0.],
                                   [0., 0., 10.]], np.float64) * alat, nsc=[3, 3, 1])
     self.g = Grid([10, 10, 100], sc=self.sc)
Example #22
0
    def test_isosurface_non_orthogonal(self, setup):

        pytest.importorskip("skimage", reason="scikit-image not available")

        # If the grid is non-orthogonal, there should be 20 unique values
        # (10 for each (HERE), see test_isosurface_orthogonal)
        grid = Grid(0.1, sc=[[1, 0, 0], [0, 1, 0], [0, 2, 1]])

        grid.grid = np.tile([1, 2, 3, 4, 5, 4, 3, 2, 1, 0],
                            100).reshape(10, 10, 10)

        verts, *returns = grid.isosurface(2.5)

        # we have twice as many since the 3rd lattice vector has components in y
        assert np.unique(verts[:, 1]).shape == (20, )
        assert np.unique(verts[:, 2]).shape == (2, )
Example #23
0
    def test_rho2(self, setup):
        bond = 1.42
        sq3h = 3.**.5 * 0.5
        sc = SuperCell(np.array(
            [[1.5, sq3h, 0.], [1.5, -sq3h, 0.], [0., 0., 10.]], np.float64) *
                       bond,
                       nsc=[3, 3, 1])

        n = 60
        rf = np.linspace(0, bond * 1.01, n)
        rf = (rf, rf)
        orb = SphericalOrbital(1, rf, 2.)
        C = Atom(6, orb)
        g = Geometry(np.array([[0., 0., 0.], [1., 0., 0.]], np.float64) * bond,
                     atom=C,
                     sc=sc)
        D = DensityMatrix(g)
        D.construct([[0.1, bond + 0.01], [1., 0.1]])
        grid = Grid(0.2, geometry=D.geom)
        D.density(grid)

        D = DensityMatrix(g, spin=Spin('P'))
        D.construct([[0.1, bond + 0.01], [(1., 0.5), (0.1, 0.1)]])
        grid = Grid(0.2, geometry=D.geom)
        D.density(grid)
        D.density(grid, [1., -1])
        D.density(grid, 0)
        D.density(grid, 1)

        D = DensityMatrix(g, spin=Spin('NC'))
        D.construct([[0.1, bond + 0.01],
                     [(1., 0.5, 0.01, 0.01), (0.1, 0.1, 0.1, 0.1)]])
        grid = Grid(0.2, geometry=D.geom)
        D.density(grid)
        D.density(grid, [[1., 0.], [0., -1]])

        D = DensityMatrix(g, spin=Spin('SO'))
        D.construct([[0.1, bond + 0.01],
                     [(1., 0.5, 0.01, 0.01, 0.01, 0.01, 0., 0.),
                      (0.1, 0.1, 0.1, 0.1, 0., 0., 0., 0.)]])
        grid = Grid(0.2, geometry=D.geom)
        D.density(grid)
        D.density(grid, [[1., 0.], [0., -1]])
        D.density(grid, Spin.X)
        D.density(grid, Spin.Y)
        D.density(grid, Spin.Z)
Example #24
0
    def read_grid(self, *args, **kwargs):
        """ Reads the TranSiesta potential input grid """
        # Create the grid
        na = len(self._dimension('a'))
        nb = len(self._dimension('b'))
        nc = len(self._dimension('c'))

        v = self._variable('V')

        # Create the grid, Siesta uses periodic, always
        grid = Grid([nc, nb, na], bc=Grid.PERIODIC, dtype=v.dtype)

        grid.grid[:, :, :] = v[:, :, :] / eV2Ry

        # Read the grid, we want the z-axis to be the fastest
        # looping direction, hence x,y,z == 0,1,2
        return grid.swapaxes(0, 2)
Example #25
0
    def test_isosurface_orthogonal(self, setup):

        pytest.importorskip("skimage", reason="scikit-image not available")

        # Build an empty grid
        grid = Grid(0.1, sc=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])

        # Fill it with some values that have a clear isosurface
        grid.grid = np.tile([1, 2, 3, 4, 5, 4, 3, 2, 1, 0],
                            100).reshape(10, 10, 10)

        # Calculate the isosurface for the value of 2.5
        verts, *returns = grid.isosurface(2.5)

        # The third dimension should contain only two coordinates
        # [1, 2, (HERE) 3, 4, 5, 4, 3, (HERE) 2, 1, 0]
        assert np.unique(verts[:, 1]).shape == (10, )
        assert np.unique(verts[:, 2]).shape == (2, )
Example #26
0
File: chg.py Project: fyalcin/sisl
    def read_grid(self, index=0, dtype=np.float64):
        """ Reads the charge density from the file and returns with a grid (plus geometry)

        Parameters
        ----------
        index : int, optional
           the index of the grid to read. For a spin-polarized VASP calculation 0 and 1 are
           allowed, UP/DOWN. For non-collinear 0, 1, 2 or 3 is allowed which equals,
           TOTAL, x, y, z charge density with the Cartesian directions equal to the charge
           magnetization.
        dtype : numpy.dtype, optional
           grid stored dtype

        Returns
        -------
        Grid : charge density grid with associated geometry
        """
        geom = self.read_geometry()
        V = geom.sc.volume

        # Now we are past the cell and geometry
        # We can now read the size of CHGCAR
        self.readline()
        nx, ny, nz = list(map(int, self.readline().split()))
        n = nx * ny * nz

        i = 0
        vals = []
        while i < n * (index + 1):
            dat = [float(l) for l in self.readline().split()]
            vals.append(dat)
            i += len(dat)
        vals = np.swapaxes(np.array(vals).reshape(nz, ny, nx), 0, 2)
        vals = vals[index * n:(index + 1) * n] / V

        # Create the grid with data
        # Since we populate the grid data afterwards there
        # is no need to create a bigger grid than necessary.
        grid = Grid([1, 1, 1], dtype=dtype, geometry=geom)
        grid.grid = vals

        return grid
    def test_read_write_grid(self, sisl_tmp, sisl_system, sile):
        g = sisl_system.g.rotatec(-30)
        G = Grid([10, 11, 12])
        G[:, :, :] = np.random.rand(10, 11, 12)

        f = sisl_tmp('test_read_write_grid.win', _dir)
        # Write
        try:
            sile(f, mode='w').write_grid(G)
        except SileError:
            sile(f, mode='wb').write_grid(G)
        # Read 1
        try:
            g = sile(f, mode='r').read_grid()
            assert np.allclose(g.grid, G.grid, atol=1e-5)
        except UnicodeDecodeError as e:
            pass
        # Read 2
        try:
            g = Grid.read(sile(f, mode='r'))
            assert np.allclose(g.grid, G.grid, atol=1e-5)
        except UnicodeDecodeError as e:
            pass
Example #28
0
def test_default_size(sisl_tmp):
    f = sisl_tmp('GRID.cube', _dir)
    grid = Grid(0.2, sc=2.0)
    grid.grid = np.random.rand(*grid.shape)
    grid.write(f)
    read = grid.read(f)
    assert np.allclose(grid.grid, read.grid)
    assert grid.geometry is None
    assert len(read.geometry) == 1
Example #29
0
def test_geometry(sisl_tmp):
    f = sisl_tmp('GRID.cube', _dir)
    geom = Geometry(np.random.rand(10, 3), np.random.randint(1, 70, 10), sc=[10, 10, 10, 45, 60, 90])
    grid = Grid(0.2, geometry=geom)
    grid.grid = np.random.rand(*grid.shape)
    grid.write(f)
    read = grid.read(f)
    assert np.allclose(grid.grid, read.grid)
    assert not grid.geometry is None
    assert not read.geometry is None
    assert grid.geometry == read.geometry
Example #30
0
    def test_rho_fail_nc(self, setup):
        bond = 1.42
        sq3h = 3.**.5 * 0.5
        sc = SuperCell(np.array([[1.5, sq3h, 0.],
                                      [1.5, -sq3h, 0.],
                                      [0., 0., 10.]], np.float64) * bond, nsc=[3, 3, 1])

        n = 60
        rf = np.linspace(0, bond * 1.01, n)
        rf = (rf, rf)
        orb = SphericalOrbital(1, rf, 2.)
        C = Atom(6, orb)
        g = Geometry(np.array([[0., 0., 0.],
                                    [1., 0., 0.]], np.float64) * bond,
                        atoms=C, sc=sc)

        D = DensityMatrix(g, spin=Spin('NC'))
        D.construct([[0.1, bond + 0.01], [(1., 0.5, 0.01, 0.01), (0.1, 0.1, 0.1, 0.1)]])
        grid = Grid(0.2, geometry=D.geometry)
        with pytest.raises(ValueError):
            D.density(grid, [1., 0.])
Example #31
0
    def read_grid(self, name, idx=0):
        """ Reads a grid in the current SIESTA.nc file

        Enables the reading and processing of the grids created by SIESTA
        """
        # Swap as we swap back in the end
        geom = self.read_geom().swapaxes(0, 2)

        # Shorthand
        g = self.groups['GRID']

        # Create the grid
        nx = len(g.dimensions['nx'])
        ny = len(g.dimensions['ny'])
        nz = len(g.dimensions['nz'])

        # Shorthand variable name
        v = g.variables[name]

        # Create the grid, SIESTA uses periodic, always
        grid = Grid([nz, ny, nx], bc=Grid.Periodic, dtype=v.dtype)

        if len(v[:].shape) == 3:
            grid.grid = v[:, :, :]
        else:
            grid.grid = v[idx, :, :, :]

        try:
            u = v.unit
            if u == 'Ry':
                # Convert to ev
                grid *= Ry2eV
        except:
            # Simply, we have no units
            pass

        # Read the grid, we want the z-axis to be the fastest
        # looping direction, hence x,y,z == 0,1,2
        grid = grid.swapaxes(0, 2)
        grid.set_geom(geom)

        return grid
Example #32
0
    def read_grid(self, name, idx=0):
        """ Reads a grid in the current SIESTA.nc file

        Enables the reading and processing of the grids created by SIESTA
        """
        # Swap as we swap back in the end
        geom = self.read_geom().swapaxes(0, 2)

        # Shorthand
        g = self.groups['GRID']

        # Create the grid
        nx = len(g.dimensions['nx'])
        ny = len(g.dimensions['ny'])
        nz = len(g.dimensions['nz'])

        # Shorthand variable name
        v = g.variables[name]

        # Create the grid, SIESTA uses periodic, always
        grid = Grid([nz, ny, nx], bc=Grid.Periodic, dtype=v.dtype)

        if len(v[:].shape) == 3:
            grid.grid = v[:, :, :]
        else:
            grid.grid = v[idx, :, :, :]

        try:
            u = v.unit
            if u == 'Ry':
                # Convert to ev
                grid *= Ry2eV
        except:
            # Simply, we have no units
            pass

        # Read the grid, we want the z-axis to be the fastest
        # looping direction, hence x,y,z == 0,1,2
        grid = grid.swapaxes(0, 2)
        grid.set_geom(geom)

        return grid
Example #33
0
    def read_grid(self, name, spin=0, **kwargs):
        """ Reads a grid in the current Siesta.nc file

        Enables the reading and processing of the grids created by Siesta

        Parameters
        ----------
        name : str
           name of the grid variable to read
        spin : int or array_like, optional
           the spin-index for retrieving one of the components. If a vector
           is passed it refers to the fraction per indexed component. I.e.
           ``[0.5, 0.5]`` will return sum of half the first two components.
           Default to the first component.
        """
        spin = kwargs.get('index', spin)
        geom = self.read_geometry()

        # Shorthand
        g = self.groups['GRID']

        # Create the grid
        nx = len(g.dimensions['nx'])
        ny = len(g.dimensions['ny'])
        nz = len(g.dimensions['nz'])

        # Shorthand variable name
        v = g.variables[name]

        # Create the grid, Siesta uses periodic, always
        grid = Grid([nz, ny, nx],
                    bc=Grid.PERIODIC,
                    geometry=geom,
                    dtype=v.dtype)

        # Unit-conversion
        BohrC2AngC = Bohr2Ang**3

        unit = {
            'Rho': 1. / BohrC2AngC,
            'RhoInit': 1. / BohrC2AngC,
            'RhoTot': 1. / BohrC2AngC,
            'RhoDelta': 1. / BohrC2AngC,
            'RhoXC': 1. / BohrC2AngC,
            'RhoBader': 1. / BohrC2AngC,
            'Chlocal': 1. / BohrC2AngC,
        }.get(name, 1.)

        if len(v[:].shape) == 3:
            grid.grid = v[:, :, :] * unit
        elif isinstance(spin, Integral):
            grid.grid = v[spin, :, :, :] * unit
        else:
            if len(spin) > v.shape[0]:
                raise SileError(
                    self.__class__.__name__ +
                    '.read_grid requires spin to be an integer or '
                    'an array of length equal to the number of spin components.'
                )
            grid.grid[:, :, :] = v[0, :, :, :] * (spin[0] * unit)
            for i, scale in enumerate(spin[1:]):
                grid.grid[:, :, :] += v[1 + i, :, :, :] * (scale * unit)

        try:
            if v.unit == 'Ry':
                # Convert to ev
                grid *= Ry2eV
        except:
            # Allowed pass due to pythonic reading
            pass

        # Read the grid, we want the z-axis to be the fastest
        # looping direction, hence x,y,z == 0,1,2
        grid.grid = np.copy(np.swapaxes(grid.grid, 0, 2), order='C')

        return grid
Example #34
0
 def test_rho_smaller_grid1(self, setup):
     D = setup.D.copy()
     D.construct(setup.func)
     sc = setup.D.geom.cell.copy() / 2
     grid = Grid(0.2, geometry=setup.D.geom.copy(), sc=sc)
     D.density(grid)
Example #35
0
class TestGrid(object):

    def setUp(self):
        alat = 1.42
        sq3h = 3.**.5 * 0.5
        self.sc = SuperCell(np.array([[1.5, sq3h, 0.],
                                      [1.5, -sq3h, 0.],
                                      [0., 0., 10.]], np.float64) * alat, nsc=[3, 3, 1])
        self.g = Grid([10, 10, 100], sc=self.sc)

    def tearDown(self):
        del self.sc
        del self.g

    def test_append(self):
        g = self.g.append(self.g, 0)
        assert_true(np.allclose(g.grid.shape, [20, 10, 100]))
        g = self.g.append(self.g, 1)
        assert_true(np.allclose(g.grid.shape, [10, 20, 100]))
        g = self.g.append(self.g, 2)
        assert_true(np.allclose(g.grid.shape, [10, 10, 200]))

    def test_size(self):
        assert_true(np.allclose(self.g.grid.shape, [10, 10, 100]))
        
    def test_item(self):
        assert_true(np.allclose(self.g[1:2, 1:2, 2:3], self.g.grid[1:2, 1:2, 2:3]))

    def test_dcell(self):
        assert_true(np.all(self.g.dcell*self.g.cell >= 0))

    def test_dvol(self):
        assert_true(self.g.dvol > 0)

    def test_shape(self):
        assert_true(np.all(self.g.shape == self.g.grid.shape))

    def test_dtype(self):
        assert_true(self.g.dtype == self.g.grid.dtype)

    def test_copy(self):
        assert_true(self.g.copy() == self.g)

    def test_swapaxes(self):
        g = self.g.swapaxes(0, 1)
        assert_true(np.allclose(self.g.cell[0,:], g.cell[1,:]))
        assert_true(np.allclose(self.g.cell[1,:], g.cell[0,:]))

    def test_interp(self):
        shape = np.array(self.g.shape, np.int32)
        g = self.g.interp(shape * 2)
        g1 = g.interp(shape)
        assert_true(np.allclose(self.g.grid, g1.grid))

    def test_index1(self):
        mid = np.array(self.g.shape, np.int32) // 2
        idx = self.g.index(self.sc.center())
        print(mid, idx)
        assert_true(np.all(mid == idx))

    def test_sum(self):
        for i in range(3):
            assert_true(self.g.sum(i).shape[i] == 1)

    def test_mean(self):
        for i in range(3):
            assert_true(self.g.mean(i).shape[i] == 1)

    def test_cross_section(self):
        for i in range(3):
            assert_true(self.g.cross_section(1, i).shape[i] == 1)

    def test_remove_part(self):
        for i in range(3):
            assert_true(self.g.remove_part(1, i, above=True).shape[i] == 1)

    def test_sub_part(self):
        for i in range(3):
            assert_true(self.g.sub_part(1, i, above=False).shape[i] == 1)

    def test_sub(self):
        for i in range(3):
            assert_true(self.g.sub(1, i).shape[i] == 1)
        for i in range(3):
            assert_true(self.g.sub([1,2], i).shape[i] == 2)

    def test_remove(self):
        for i in range(3):
            assert_true(self.g.remove(1, i).shape[i] == self.g.shape[i]-1)
        for i in range(3):
            assert_true(self.g.remove([1,2], i).shape[i] == self.g.shape[i]-2)

    def test_argumentparser(self):
        self.g.ArgumentParser()