Exemplo n.º 1
0
 def __init__(self, name='hamiltonian', **kwargs):
     super(HamiltonianBase, self).__init__()
     # lattice
     if 'lattice' in kwargs:
         ltc = kwargs.pop('lattice')
         if islattice(ltc):
             self.lattice = ltc
         elif isinstance(ltc, dict):
             self.lattice = Lattice(**ltc)
         else:
             lattice_kwargs = self.__get_lattice_kwargs(kwargs)
             self.lattice = Lattice(ltc, **lattice_kwargs)
         self.size = self.lattice.size()
     elif self.__has_shape(kwargs):
         lattice_kwargs = self.__get_lattice_kwargs(kwargs)
         self.lattice = Chain(**lattice_kwargs)
         self.size = self.lattice.size()
         if len(self.size) is not 1:
             raise ValueError("Wrong size, default lattice"
                              " is chain lattice")
     else:
         self.lattice = None
         self.size = 1
     self.name = name
     self.params = kwargs
Exemplo n.º 2
0
 def test_tfi(self):
     test = TFI(Chain(3, pbc=True), mag=1.0)
     exact = - kronsum(sigmax, sigmax, sigmax) -\
         kronprod(sigmaz, sigmaz, iden) - \
         kronprod(sigmaz, iden, sigmaz) - \
         kronprod(iden, sigmaz, sigmaz)
     self.assertEqual((test != exact).nnz, 0)
Exemplo n.º 3
0
    def test_j1j2(self):
        for i in range(4, 10):
            lattice = Chain(i, pbc=True)
            interaction = (1, 0.5)
            test_h = J1J2(J=interaction, pbc=True, lattice=lattice)
            exact = testutils.J1J2(lattice, J=interaction)
            testutils.assertEqualSparse(self, test_h.mat(), exact)
            self._test_energy(test_h)

        for x in range(2, 4):
            for y in range(2, 4):
                lattice = Square(x, y, pbc=True)
                test_h = J1J2(J=interaction, pbc=True, lattice=lattice)
                exact = testutils.J1J2(lattice)
                testutils.assertEqualSparse(self, test_h.mat(), exact)
                self._test_energy(test_h)
Exemplo n.º 4
0
    def test_nlocal(self):
        for k in range(1, 3):
            self._test_chain(sigmax, k)
            self._test_chain(sigmay, k)
            self._test_chain(sigmaz, k)
        # test square
        for k in range(1, 3):
            self._test_square(sigmax, k)
            self._test_square(sigmay, k)
            self._test_square(sigmaz, k)
        # test J1J2
        gen = J1J2(Chain(3, pbc=True))

        def local(op, J=(1.0, 0.5)):
            return J[0] * (kronprod(op, op, iden) +
                           kronprod(iden, op, op) +
                           kronprod(op, iden, op)) + \
                J[1] * (kronprod(op, iden, op) +
                        kronprod(op, op, iden) +
                        kronprod(iden, op, op))

        exact = local(sigmax) + local(sigmay) + local(sigmaz)
        self.assertEqual((gen != exact).nnz, 0)
Exemplo n.º 5
0
        self.layers = nn.ModuleList(
            [nn.Linear(x, y) for x, y in zip(sizes[0:-1], sizes[1:])])

    def forward(self, x):
        for i, layer in enumerate(self.layers):
            if i is not len(self.layers) - 1:
                x = F.relu(layer(x))
        x = self.layers[-1](x)
        return x


lattice = configurations['hamiltonian']['lattice']
size = configurations['hamiltonian']['lattice']['size']

model = MLP(*tuple(model['size']))
lattice = Chain(lattice['size'], pbc=lattice['pbc'])
hamiltonian = TFI(hamiltonain['mag'], lattice=lattice)
# model = FakeModel(hamiltonian)

# TODO: cuda support
# if device == 'cuda':
#     model.cuda()

eigs, vecs = ed(hamiltonian.mat())
print(eigs[0])


def eloc(x):
    ret = sum(val * model(Variable(config))
              for config, val in hamiltonian.nnz(x))
    return ret / model(Variable(x))
Exemplo n.º 6
0
    def __init__(self, *sizes):
        super(MLP, self).__init__()
        self.sizes = sizes
        self.layers = nn.ModuleList(
            [nn.Linear(x, y) for x, y in zip(sizes[0:-1], sizes[1:])])

    def forward(self, x):
        for i, layer in enumerate(self.layers):
            if i is not len(self.layers) - 1:
                x = F.relu(layer(x))
        x = self.layers[-1](x)
        return x


model = MLP(3, 12, 12, 1)
lattice = Chain(3, pbc=True)
hamiltonian = TFI(mag=1.0, lattice=lattice)


def eloc(x):
    ret = sum(val * model(Variable(config))
              for config, val in hamiltonian.nnz(x))
    return ret / model(Variable(x))


def exact_energy():
    return sum(torch.abs(model(Variable(config)))**2 * eloc(config))


def proposal(x):
    amp = model(Variable(x))
Exemplo n.º 7
0
 def test_general_constructor(self):
     lattice = Chain(3, pbc=True)
     for name in __traits__.keys():
         h = Ham(name, lattice=lattice)
         self.assertIsInstance(h, __traits__[name])
Exemplo n.º 8
0
 def test_tfi(self):
     for i in range(4, 10):
         lattice = Chain(i, pbc=True)
         test_h = TFI(mag=1.0, pbc=True, lattice=lattice)
         exact = testutils.TFI(lattice, mag=1.0)
         testutils.assertEqualSparse(self, test_h.mat(), exact)
Exemplo n.º 9
0
 def _test_chain(self, op, k):
     gen = nlocal(op, Chain(3, pbc=True), k)
     exact = sp.kron(sp.kron(op, op), iden) + \
         sp.kron(sp.kron(op, iden), op) + \
         sp.kron(sp.kron(iden, op), op)
     self.assertEqual((gen != exact).nnz, 0)
Exemplo n.º 10
0
class HamiltonianBase(object):
    """Hamiltonian Base"""
    @staticmethod
    def __has_shape(kwargs):
        return any(['size' in kwargs, 'shape' in kwargs, 'length' in kwargs])

    @staticmethod
    def __get_lattice_kwargs(kwargs):
        lattice_kwargs = {}
        if 'size' in kwargs:
            lattice_kwargs['shape'] = kwargs.pop('size')
        elif 'shape' in kwargs:
            lattice_kwargs['shape'] = kwargs.pop('shape')
        elif 'length' in kwargs:
            lattice_kwargs['length'] = kwargs.pop('length')
        else:
            raise TypeError("missing shape of the hamiltonian")

        if 'pbc' in kwargs:
            lattice_kwargs['pbc'] = kwargs.pop('pbc')
        if 'lattice_params' in kwargs:
            ltc_params = kwargs.pop('lattice_params')
            if isinstance(ltc_params, dict):
                lattice_kwargs.update(ltc_params)
            else:
                raise ValueError("lattice parameters should be dict"
                                 "not %s" % type(ltc_params))
        return lattice_kwargs

    def __init__(self, name='hamiltonian', **kwargs):
        super(HamiltonianBase, self).__init__()
        # lattice
        if 'lattice' in kwargs:
            ltc = kwargs.pop('lattice')
            if islattice(ltc):
                self.lattice = ltc
            elif isinstance(ltc, dict):
                self.lattice = Lattice(**ltc)
            else:
                lattice_kwargs = self.__get_lattice_kwargs(kwargs)
                self.lattice = Lattice(ltc, **lattice_kwargs)
            self.size = self.lattice.size()
        elif self.__has_shape(kwargs):
            lattice_kwargs = self.__get_lattice_kwargs(kwargs)
            self.lattice = Chain(**lattice_kwargs)
            self.size = self.lattice.size()
            if len(self.size) is not 1:
                raise ValueError("Wrong size, default lattice"
                                 " is chain lattice")
        else:
            self.lattice = None
            self.size = 1
        self.name = name
        self.params = kwargs

    def nnz(self, config):
        """
        return the non-zero values in a hamiltonian H,
        with its related configurations
        """
        RHS = config.clone()
        if self.lattice.dim is not config.dim():
            raise ValueError('config size should meets hamiltonian')
        return self.nnz_iter(RHS)

    def nnz_iter(self, RHS):
        raise NotImplementedError

    def __str__(self):
        ret = '%s:' % (self.name)
        ret += '\n size: %s' % self.size
        for param_key, param_val in self.params.items():
            ret += '\n %s: %s' % (param_key, param_val)
        return ret

    def mat(self):
        """get the matrix form

        Returns:
            hamiltonian matrix: a scipy.sparse.lil_matrix

        Raises:
            Warning: when number of elements in the hamiltonian
            is too large (> 25) a waring will raises.
        """
        numel = 2**_prod(self.size)
        if _prod(self.size) > 25:
            raise Warning('this hamiltonian could be too large')
        data = lil_matrix((numel, numel), dtype='complex128')
        for lhs in IterateAll(size=self.size):
            for rhs, val in self.nnz(lhs):
                data[utils.bin(lhs), utils.bin(rhs)] += val
        return data