Esempio n. 1
0
def test_caching():
    x = COO({(10, 10, 10): 1})
    assert x[:].reshape((100, 10)).transpose().tocsr() is not x[:].reshape((100, 10)).transpose().tocsr()

    x = COO({(10, 10, 10): 1}, cache=True)
    assert x[:].reshape((100, 10)).transpose().tocsr() is x[:].reshape((100, 10)).transpose().tocsr()

    x = COO({(1, 1, 1, 1, 1, 1, 1, 2): 1}, cache=True)

    for i in range(x.ndim):
        x.reshape((1,) * i + (2,) + (1,) * (x.ndim - i - 1))

    assert len(x._cache['reshape']) < 5
Esempio n. 2
0
def test_caching():
    x = COO({(9, 9, 9): 1})
    assert (x[:].reshape((100, 10)).transpose().tocsr() is not x[:].reshape(
        (100, 10)).transpose().tocsr())

    x = COO({(9, 9, 9): 1}, cache=True)
    assert (x[:].reshape((100, 10)).transpose().tocsr() is x[:].reshape(
        (100, 10)).transpose().tocsr())

    x = COO({(1, 1, 1, 1, 1, 1, 1, 2): 1}, cache=True)

    for i in range(x.ndim):
        x.reshape(x.size)

    assert len(x._cache["reshape"]) < 5
Esempio n. 3
0
def test_large_reshape():
    n = 100
    m = 10
    row = np.arange(n, dtype=np.uint16)  # np.random.randint(0, n, size=n, dtype=np.uint16)
    col = row % m  # np.random.randint(0, m, size=n, dtype=np.uint16)
    data = np.ones(n, dtype=np.uint8)

    x = COO((data, (row, col)), sorted=True, has_duplicates=False)

    assert_eq(x, x.reshape(x.shape))
Esempio n. 4
0
    def unfold_third_order(self, reduced_third=None, distance_threshold=None):
        """
        This method extrapolates a third order force constant matrix from a unit
        cell into a matrix for a larger supercell.

        Parameters
        ----------

        reduced_third : array, optional
            The third order force constant matrix.
            Default is `self.third`
        distance_threshold : float, optional
            When calculating force constants, contributions from atoms further than
            the distance threshold will be ignored.
            Default is self.distance_threshold
        """
        logging.info('Unfolding third order matrix')
        if distance_threshold is None:
            if self.distance_threshold is not None:
                distance_threshold = self.distance_threshold
            else:
                raise ValueError(
                    'Please specify a distance threshold in Angstrom')

        logging.info('Distance threshold: ' + str(distance_threshold) + ' A')
        if (self.atoms.cell[0, 0] / 2 < distance_threshold) | \
                (self.atoms.cell[1, 1] / 2 < distance_threshold) | \
                (self.atoms.cell[2, 2] / 2 < distance_threshold):
            logging.warning(
                'The cell size should be at least twice the distance threshold'
            )
        if reduced_third is None:
            reduced_third = self.third.value
        n_unit_atoms = self.n_atoms
        atoms = self.atoms
        n_replicas = self.n_replicas
        replicated_cell_inv = np.linalg.inv(self.third.replicated_atoms.cell)

        reduced_third = reduced_third.reshape(
            (n_unit_atoms, 3, n_replicas, n_unit_atoms, 3, n_replicas,
             n_unit_atoms, 3))
        replicated_positions = self.third.replicated_atoms.positions.reshape(
            (n_replicas, n_unit_atoms, 3))
        dxij_reduced = wrap_coordinates(
            atoms.positions[:, np.newaxis, np.newaxis, :] -
            replicated_positions[np.newaxis, :, :, :],
            self.third.replicated_atoms.cell, replicated_cell_inv)
        indices = np.argwhere(
            np.linalg.norm(dxij_reduced, axis=-1) < distance_threshold)

        coords = []
        values = []
        for index in indices:
            for l in range(n_replicas):
                for j in range(n_unit_atoms):
                    dx2 = dxij_reduced[index[0], l, j]

                    is_storing = (np.linalg.norm(dx2) < distance_threshold)
                    if is_storing:
                        for alpha in range(3):
                            for beta in range(3):
                                for gamma in range(3):
                                    coords.append([
                                        index[0], alpha, index[1], index[2],
                                        beta, l, j, gamma
                                    ])
                                    values.append(reduced_third[index[0],
                                                                alpha, 0,
                                                                index[2], beta,
                                                                0, j, gamma])

        logging.info('Created unfolded third order')

        shape = (n_unit_atoms, 3, n_replicas, n_unit_atoms, 3, n_replicas,
                 n_unit_atoms, 3)
        expanded_third = COO(np.array(coords).T, np.array(values), shape)
        expanded_third = expanded_third.reshape(
            (n_unit_atoms * 3, n_replicas * n_unit_atoms * 3,
             n_replicas * n_unit_atoms * 3))
        return expanded_third
Esempio n. 5
0
def optimize_onesite(forward, mpo0, lopr, ropr, wfn0, wfn1, M, tol):
    """
    Optimization for onesite algorithm.
    
    Parameters
    ----------
    forward : int 
        0 for left and 1 for right.
    mpo0 : ndarray
        MPO.
    lopr : ndarray
        left block opr.
    ropr : ndarray
        right block opr.
    wfn0 : ndarray
        MPS for canonicalization.
    wfn1 : ndarray
        MPS.
    M : int
        bond dimension
     
    Returns
    -------
    energy : float or list of floats
        The energy of desired root(s).

    """

    #diag_flat = diag_onesite(mpo0, lopr, ropr).ravel()
    diag_flat = diag_onesite(mpo0, lopr, ropr).ravel().todense()

    mps_shape = wfn0.shape

    def dot_flat(x):
        #return dot_onesite(mpo0, lopr, ropr, x.reshape(mps_shape)).ravel()
        return dot_onesite(mpo0, lopr, ropr,
                           COO(x.reshape(mps_shape))).ravel().todense()

    def compute_precond_flat(dx, e, x0):
        #return COO(dx.todense() / (diag_flat.todense() - e))
        return dx / (diag_flat - e)

    #dot_func = sparse.coo.common.dot
    dot_func = np.dot
    #energy, wfn0 = linalg_helper.davidson(dot_flat, wfn0.ravel(), compute_precond_flat, tol = tol, dot = dot_func)
    energy, wfn0 = linalg_helper.davidson(dot_flat,
                                          wfn0.ravel().todense(),
                                          compute_precond_flat,
                                          tol=tol,
                                          dot=dot_func)
    #wfn0 = wfn0.reshape(mps_shape)
    wfn0 = COO(wfn0.reshape(mps_shape))

    if forward:
        wfn0, gaug = canonicalize(1, wfn0, M)  # wfn0 R => lmps gaug
        wfn1 = einsum("ij,jkl->ikl", gaug, wfn1)
        lopr = renormalize(1, mpo0, lopr, wfn0.conj(), wfn0)
        return energy, wfn0, wfn1, lopr
    else:
        wfn0, gaug = canonicalize(0, wfn0, M)  # wfn0 R => lmps gaug
        wfn1 = einsum("ijk,kl->ijl", wfn1, gaug)
        ropr = renormalize(0, mpo0, ropr, wfn0.conj(), wfn0)
        return energy, wfn0, wfn1, ropr
Esempio n. 6
0
def read_third_order_matrix_2(third_file, atoms, third_supercell, order='C'):
    supercell = third_supercell
    n_unit_atoms = atoms.positions.shape[0]
    n_replicas = np.prod(supercell)
    current_grid = Grid(third_supercell, order=order).grid(is_wrapping=True)
    list_of_index = current_grid
    list_of_replicas = list_of_index.dot(atoms.cell)
    replicated_cell = atoms.cell * supercell
    # replicated_cell_inv = np.linalg.inv(replicated_cell)

    coords = []
    data = []
    second_cell_positions = []
    third_cell_positions = []
    atoms_coords = []
    sparse_data = []
    with open(third_file, 'r') as file:
        line = file.readline()
        n_third = int(line)
        for i in range(n_third):
            file.readline()
            file.readline()

            second_cell_position = np.fromstring(file.readline(),
                                                 dtype=np.float,
                                                 sep=' ')
            second_cell_positions.append(second_cell_position)
            d_1 = list_of_replicas[:, :] - second_cell_position[np.newaxis, :]
            # d_1 = wrap_coordinates(d_1,  replicated_cell, replicated_cell_inv)

            mask_second = np.linalg.norm(d_1, axis=1) < 1e-5
            second_cell_id = np.argwhere(mask_second).flatten()

            third_cell_position = np.fromstring(file.readline(),
                                                dtype=np.float,
                                                sep=' ')
            third_cell_positions.append(third_cell_position)
            d_2 = list_of_replicas[:, :] - third_cell_position[np.newaxis, :]
            # d_2 = wrap_coordinates(d_2,  replicated_cell, replicated_cell_inv)
            mask_third = np.linalg.norm(d_2, axis=1) < 1e-5
            third_cell_id = np.argwhere(mask_third).flatten()

            atom_i, atom_j, atom_k = np.fromstring(
                file.readline(), dtype=np.int, sep=' ') - 1
            atoms_coords.append([atom_i, atom_j, atom_k])
            small_data = []
            for _ in range(27):

                values = np.fromstring(file.readline(),
                                       dtype=np.float,
                                       sep=' ')
                alpha, beta, gamma = values[:3].round(0).astype(int) - 1
                coords.append([
                    atom_i, alpha, second_cell_id, atom_j, beta, third_cell_id,
                    atom_k, gamma
                ])
                data.append(values[3])
                small_data.append(values[3])
            sparse_data.append(small_data)

    third_order = COO(np.array(coords).T,
                      np.array(data),
                      shape=(n_unit_atoms, 3, n_replicas, n_unit_atoms, 3,
                             n_replicas, n_unit_atoms, 3))
    third_order = third_order.reshape(
        (n_unit_atoms * 3, n_replicas * n_unit_atoms * 3,
         n_replicas * n_unit_atoms * 3))
    return third_order, np.array(sparse_data), np.array(
        second_cell_positions), np.array(third_cell_positions), np.array(
            atoms_coords)