Exemple #1
0
 def qho(self, dim = 4, sites = 10, spacing = 1.):
     """checks that QHO can be initialised and all functions run"""
     
     passed = True
     shape = (sites,)*dim
     raw_lattice = np.arange(sites**dim).reshape(shape)
     
     self.pot = QHO()
     self.x = Periodic_Lattice(raw_lattice)
     self.p = np.asarray(shape)
     idx_list = [(0,)*dim, (sites,)*dim, (sites-1,)*dim]
     
     passed = self._TestFns("QHO Potential", passed, self.x, self.p, idx_list)
     
     return passed
def getPotential(potFn, n_points=100):
    """Returns x,y,z of the analytic potential
    
    Required Inputs
        potFn   :: function :: the potential energy function
    
    Optional Inputs
        n_points :: int :: defines the resolution
    
    Expected
        potFn takes a 1x2 column matrix in and returns a point
    """
    
    n_points = 300    # n**2 is the number of points
    x = np.linspace(-15, 15, n_points, endpoint=True)
    x,y = np.meshgrid(x, x)
    
    z = [np.exp(-model.sampler.potential.uE(Periodic_Lattice(np.asarray([i,j])))) \
              for i,j in zip(np.ravel(x), np.ravel(y))]
    z = np.asarray(z).reshape(n_points, n_points)
    return x,y,z
    def _getInstances(self):
        """gets the relevant instances for the model"""

        self.x0 = Periodic_Lattice(self.x0, lattice_spacing=self.spacing)
        if not hasattr(self, 'save_path'): self.save_path = False
        dynamics = Leap_Frog(duE=self.pot.duE,
                             step_size=self.step_size,
                             n_steps=self.n_steps,
                             rand_steps=self.rand_steps,
                             save_path=self.save_path)

        if hasattr(self, 'accept_kwargs'):
            if 'get_accept_rates' not in self.accept_kwargs:
                self.accept_kwargs['get_accept_rates'] = True
        else:
            self.accept_kwargs = {'get_accept_rates': True}

        self.sampler = Hybrid_Monte_Carlo(self.x0,
                                          dynamics,
                                          self.pot,
                                          self.rng,
                                          accept_kwargs=self.accept_kwargs)
        pass
def testDynamics():
    dim = 1
    n = 10
    spacing = 1.
    step_size = [0.01, .1]
    n_steps = [1, 500]

    samples = 5
    step_sample = np.linspace(n_steps[0], n_steps[1], samples, True,
                              dtype=int),
    step_sizes = np.linspace(step_size[0], step_size[1], samples, True)

    x_nd = np.random.random((n, ) * dim)
    p0 = np.random.random((n, ) * dim)
    x0 = Periodic_Lattice(x_nd)

    dynamics = Leap_Frog(duE=None,
                         n_steps=n_steps[-1],
                         step_size=step_size[-1])

    for pot in [
            Simple_Harmonic_Oscillator(),
            Klein_Gordon(),
            Quantum_Harmonic_Oscillator()
    ]:

        dynamics.duE = pot.duE

        test = test_dynamics.Constant_Energy(pot, dynamics)
        utils.newTest(test.id)
        assert test.run(p0, x0, step_sample, step_sizes)

        test = test_dynamics.Reversibility(pot, dynamics)
        utils.newTest(test.id)
        assert test.run(p0, x0)
    pass
    # utils.logs.logging.root.setLevel(utils.logs.logging.DEBUG)

    dim = 1
    n = 10
    spacing = 1.
    step_size = [0.01, .1]
    n_steps = [1, 500]

    samples = 5
    step_sample = np.linspace(n_steps[0], n_steps[1], samples, True,
                              dtype=int),
    step_sizes = np.linspace(step_size[0], step_size[1], samples, True)

    for pot in [SHO(), KG(), QHO()]:

        x_nd = np.random.random((n, ) * dim)
        p0 = np.random.random((n, ) * dim)
        x0 = Periodic_Lattice(x_nd)

        dynamics = Leap_Frog(duE=pot.duE,
                             n_steps=n_steps[-1],
                             step_size=step_size[-1])

        test = Constant_Energy(pot, dynamics)
        utils.newTest(test.id)
        test.run(p0, x0, step_sample, step_sizes)

        test = Reversibility(pot, dynamics)
        utils.newTest(test.id)
        test.run(p0, x0)
Exemple #6
0
    def hmcQho(self, n_samples=100, n_burn_in=10, tol=5e-2, print_out=True):
        """A test to sample the Quantum Harmonic Oscillator
        
        Optional Inputs
            tol     ::  float   :: tolerance level allowed
            print_out   :: bool     :: print results to screen
            save    :: string   :: file to save plot. False or '' gives no plot
        """
        name = 'QHO'
        passed = True
        n = 100
        dim = 1
        spacing = 1.
        step_size = 0.1
        n_steps = 20
        mu = 1.

        x_nd = np.random.random((n, ) * dim)
        p0 = np.random.random((n, ) * dim)
        x0 = Periodic_Lattice(x_nd)

        pot = Quantum_Harmonic_Oscillator()

        lf = Leap_Frog(duE=pot.duE,
                       step_size=step_size,
                       n_steps=n_steps,
                       lattice=True)
        hmc = Hybrid_Monte_Carlo(x0, lf, pot, self.rng)

        p_samples, samples = hmc.sample(n_samples=n_samples,
                                        n_burn_in=n_burn_in,
                                        verbose=True)
        burn_in, samples = samples  # return the shape: (n, dim, 1)

        # flatten last dimension to a shape of (n, 2)
        self.samples = np.asarray(samples)
        self.burn_in = np.asarray(burn_in)
        self.p_samples = p_samples

        s = np.asarray(self.samples).reshape(n_samples + 1, n)
        fitted = norm.fit(s.ravel())

        w = mu**2 * (1 + .25 * (spacing * mu)**2)  # w  = 1/(sigma)^2
        sigma = 1. / np.sqrt(2. * w)

        passed *= (np.abs(fitted[0] - 0) <= tol)
        passed *= (np.abs(fitted[1] - sigma) <= tol)

        if print_out:
            utils.display("HMC: Quantum Harmonic Oscillator",
                          passed,
                          details={
                              'mean': [
                                  'target:    {}'.format(0),
                                  'empirical  {}'.format(fitted[0]),
                                  'tolerance  {}'.format(tol)
                              ],
                              'standard deviation': [
                                  'target:    {}'.format(sigma),
                                  'empirical  {}'.format(fitted[1]),
                                  'tolerance  {}'.format(tol)
                              ]
                          })

        return passed
    def __init__(self):
        self.id = 'lattice'
        self.a1 = np.array([[11., 12., 13., 14.], [21., 22., 23., 24.],
                            [31., 32., 33., 34.], [41., 42., 43., 44.]])

        self.l = Periodic_Lattice(self.a1, lattice_spacing=1.)
    z = [np.exp(-model.sampler.potential.uE(Periodic_Lattice(np.asarray([i,j])))) \
              for i,j in zip(np.ravel(x), np.ravel(y))]
    z = np.asarray(z).reshape(n_points, n_points)
    return x,y,z
#
if __name__ == '__main__':
    
    n_burn_in = 25
    n_samples = 1000
    
    pot = Klein_Gordon(phi_4=-0.05*np.math.factorial(4),m=0.05)
    spacing = 0.1
    n, dim = 50, 1
    x0 = np.random.random((n,)*dim)
    x0 = np.asarray(x0, dtype=np.float64)
    x0 = Periodic_Lattice(x0)
    model = Model(x0, pot=pot, step_size=0.1, n_steps=20, rand_steps=True, spacing=spacing)
    
    # adjust for nice plotting
    print "Running Model: {}".format(__file__)
    model.run(n_samples=n_samples, n_burn_in=n_burn_in, verbose=True)
    print "Finished Running Model: {}".format(__file__)
    
    # change shape from (n, 2) -> (2, n)
    samples = model.samples
    burn_in = model.burn_in
    
    xyz = getPotential(pot.uE)
    
    f_name = os.path.basename(__file__)
    save_name = os.path.splitext(f_name)[0] + '.png'