コード例 #1
0
 def setUp1(self, nproc=1, multiproc=True):
     self.ndim = 3
     self.harmonic = Harmonic(self.ndim)
     self.nreplicas = 10
     self.stepsize = 0.1
     self.nproc = nproc
     
     self.mc_runner = MonteCarloWalker(self.harmonic, mciter=40)
     
     if multiproc == False:
         hostname=socket.gethostname()
         host = Pyro4.socketutil.getIpAddress(hostname, workaround127=True)
         self.dispatcher_URI = "PYRO:"+"test@"+host+":9090"
     else:
         self.dispatcher_URI = None
     
     replicas = []
     for i in xrange(self.nreplicas):
         x = self.harmonic.get_random_configuration()
         replicas.append(Replica(x, self.harmonic.get_energy(x)))
     self.ns = NestedSampling(replicas, self.mc_runner, 
                              stepsize=0.1, nproc=nproc, verbose=False, dispatcher_URI=self.dispatcher_URI)
     
     self.Emax0 = self.ns.replicas[-1].energy
     
     self.niter = 100
     for i in xrange(self.niter):
         self.ns.one_iteration()
     self.Emax = self.ns.replicas[-1].energy
     self.Emin = self.ns.replicas[0].energy
コード例 #2
0
ファイル: _test_ns_lj.py プロジェクト: js850/sens
class TestNS_LJ(unittest.TestCase):
    def setUp(self):
        self.setUp1()

    def compute_cv(self, Tmin=.01, Tmax=3., nT=100):
        T = np.arange(Tmin, Tmax, (Tmax - Tmin) / nT)
        Cv = compute_cv_c(np.array(self.ns.max_energies), 
                          float(self.nproc), float(self.ndof), T.min(), T.max(), T.size, float(self.ndof), live=False)
        return T, Cv


    def set_up_system(self):
        self.natoms = 13
        self.gmin = -44.3269
        self.system = LJClusterSENS(self.natoms, 2.5)
        self.ndof = 3 * self.natoms - 6

    def setUp1(self, nproc=1):
        self.set_up_system()
        self.nreplicas = 10
        self.stepsize = 0.01
        self.nproc = nproc
        
        self.mc_runner = self.system.get_mc_walker(mciter=100)

        self.ns = NestedSampling(self.system, self.nreplicas, self.mc_runner, 
                                 stepsize=0.1, nproc=nproc, verbose=False)
        
        self.Emax0 = self.ns.replicas[-1].energy
        
        self.niter = 100
        for i in xrange(self.niter):
            self.ns.one_iteration()
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy
    
    def test1(self):
        self.assert_(len(self.ns.replicas) == self.nreplicas)
        self.assert_(self.Emax < self.Emax0)
        self.assert_(self.Emin < self.Emax)
        self.assert_(self.Emin < 0)
        self.assert_(self.Emin >= self.gmin)
        self.assert_(self.ns.stepsize != self.stepsize)
        self.assertEqual(len(self.ns.max_energies), self.niter * self.nproc)
        self.assertEqual(self.ns.failed_mc_walks, 0)

    def run_ns(self, max_iter=100, Etol=1e-4):
#        max_iter = 10000
#        self.Etol = .01
        self.Etol = Etol
        for i in xrange(int(max_iter)):
            self.ns.one_iteration()
            deltaE = self.ns.replicas[-1].energy - self.ns.replicas[0].energy
            if  deltaE < self.Etol:
                break
        self.niter = i + 1
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy
コード例 #3
0
ファイル: _sens_exact.py プロジェクト: smcantab/sens
 def finish(self):
     NestedSampling.finish(self)
     if self.nproc > 1:
         # terminate the swap workers
         for worker in self._swap_workers:
             self._swap_put_queue.put("kill")
         for worker in self._swap_workers:
             worker.join()
             worker.terminate()
             worker.join()
コード例 #4
0
ファイル: make_plot.py プロジェクト: yiliu1/nested_sampling
def do_nested_sampling(nreplicas=10, niter=200, mciter=1000, stepsize=.8, estop=-.9,
                       x0=[1,1], r0=2,
                       xlim=None, ylim=None, circle=False
                       ):
    path = []
    def mc_record_position_event(coords=None, **kwargs):
        if len(path) == 0 or not np.all(path[-1] == coords):
            path.append(coords)

    p = Pot()
    print p.get_energy(np.array([1,2.]))
    mc_walker = MonteCarloWalker(p, mciter=mciter, events=[mc_record_position_event])
    
    # initialize the replicas with random positions
    replicas = []
    for i in xrange(nreplicas):
        # choose points uniformly in a circle
        if circle: 
            coords = vector_random_uniform_hypersphere(2) * r0 + x0
        else:
            coords = np.zeros(2)
            coords[0] = np.random.uniform(xlim[0], xlim[1])
            coords[1] = np.random.uniform(ylim[0], ylim[1])
#         coords = np.random.uniform(-1,3,size=2)
        r = Replica(coords, p.get_energy(coords))
        replicas.append(r)
    
        
    ns = NestedSampling(replicas, mc_walker, stepsize=stepsize)
    results = [Result()]
    results[0].replicas = [r.copy() for r in replicas]
    for i in xrange(niter):
        ns.one_iteration()
        new_res = Result()
        new_res.replicas = [r.copy() for r in replicas]
        new_res.starting_replica = ns.starting_replicas[0].copy()
        new_res.new_replica = ns.new_replicas[0].copy()
        path.insert(0, new_res.starting_replica.x)
        new_res.mc_path = path
        results.append(new_res)
        path = []
        
        if ns.replicas[-1].energy < estop:
            break
        
        
        
#    plt.plot(ns.max_energies)
#    plt.show()
    
    return ns, results
コード例 #5
0
class TestNS(unittest.TestCase):
    """to test distributed computing must start a dispatcher with --server-name test and --port 9090
    """
    def setUp(self):
        self.setUp1()

    def setUp1(self, nproc=1, multiproc=True):
        self.ndim = 3
        self.harmonic = Harmonic(self.ndim)
        self.nreplicas = 10
        self.stepsize = 0.1
        self.nproc = nproc

        self.mc_runner = MonteCarloWalker(self.harmonic, mciter=40)

        if multiproc == False:
            hostname = socket.gethostname()
            host = Pyro4.socketutil.getIpAddress(hostname, workaround127=True)
            self.dispatcher_URI = "PYRO:" + "test@" + host + ":9090"
        else:
            self.dispatcher_URI = None

        replicas = []
        for i in range(self.nreplicas):
            x = self.harmonic.get_random_configuration()
            replicas.append(Replica(x, self.harmonic.get_energy(x)))
        self.ns = NestedSampling(replicas,
                                 self.mc_runner,
                                 stepsize=0.1,
                                 nproc=nproc,
                                 verbose=False,
                                 dispatcher_URI=self.dispatcher_URI)

        self.Emax0 = self.ns.replicas[-1].energy

        self.niter = 100
        for i in range(self.niter):
            self.ns.one_iteration()
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy

    def test1(self):
        print("running TestNS")
        self.assert_(len(self.ns.replicas) == self.nreplicas)
        self.assert_(self.Emax < self.Emax0)
        self.assert_(self.Emin < self.Emax)
        self.assert_(self.Emin >= 0)
        self.assert_(self.ns.stepsize != self.stepsize)
        self.assertEqual(len(self.ns.max_energies), self.niter * self.nproc)
コード例 #6
0
ファイル: _test_ns.py プロジェクト: HuangTY96/nested_sampling
class TestNS(unittest.TestCase):
    """to test distributed computing must start a dispatcher with --server-name test and --port 9090
    """
    def setUp(self):
        self.setUp1()

    def setUp1(self, nproc=1, multiproc=True):
        self.ndim = 3
        self.harmonic = Harmonic(self.ndim)
        self.nreplicas = 10
        self.stepsize = 0.1
        self.nproc = nproc
        
        self.mc_runner = MonteCarloWalker(self.harmonic, mciter=40)
        
        if multiproc == False:
            hostname=socket.gethostname()
            host = Pyro4.socketutil.getIpAddress(hostname, workaround127=True)
            self.dispatcher_URI = "PYRO:"+"test@"+host+":9090"
        else:
            self.dispatcher_URI = None
        
        replicas = []
        for i in xrange(self.nreplicas):
            x = self.harmonic.get_random_configuration()
            replicas.append(Replica(x, self.harmonic.get_energy(x)))
        self.ns = NestedSampling(replicas, self.mc_runner, 
                                 stepsize=0.1, nproc=nproc, verbose=False, dispatcher_URI=self.dispatcher_URI)
        
        self.Emax0 = self.ns.replicas[-1].energy
        
        self.niter = 100
        for i in xrange(self.niter):
            self.ns.one_iteration()
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy
    
    def test1(self):
        print "running TestNS"
        self.assert_(len(self.ns.replicas) == self.nreplicas)
        self.assert_(self.Emax < self.Emax0)
        self.assert_(self.Emin < self.Emax)
        self.assert_(self.Emin >= 0)
        self.assert_(self.ns.stepsize != self.stepsize)
        self.assertEqual(len(self.ns.max_energies), self.niter * self.nproc)
コード例 #7
0
ファイル: _test_ns_lj.py プロジェクト: js850/sens
    def setUp1(self, nproc=1):
        self.set_up_system()
        self.nreplicas = 10
        self.stepsize = 0.01
        self.nproc = nproc

        self.mc_runner = self.system.get_mc_walker(mciter=100)

        self.ns = NestedSampling(self.system,
                                 self.nreplicas,
                                 self.mc_runner,
                                 stepsize=0.1,
                                 nproc=nproc,
                                 verbose=False)

        self.Emax0 = self.ns.replicas[-1].energy

        self.niter = 100
        for i in xrange(self.niter):
            self.ns.one_iteration()
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy
コード例 #8
0
ファイル: _test_ns_lj.py プロジェクト: js850/sens
    def setUp1(self, nproc=1):
        self.set_up_system()
        self.nreplicas = 10
        self.stepsize = 0.01
        self.nproc = nproc
        
        self.mc_runner = self.system.get_mc_walker(mciter=100)

        self.ns = NestedSampling(self.system, self.nreplicas, self.mc_runner, 
                                 stepsize=0.1, nproc=nproc, verbose=False)
        
        self.Emax0 = self.ns.replicas[-1].energy
        
        self.niter = 100
        for i in xrange(self.niter):
            self.ns.one_iteration()
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy
コード例 #9
0
    def setUp1(self, nproc=4):
        self.set_up_system()
        self.nreplicas = 50
        self.stepsize = 0.01
        self.nproc = nproc

        self.mc_runner = self.system.get_mc_walker(mciter=10000)

        self.ns = NestedSampling(self.system,
                                 self.nreplicas,
                                 self.mc_runner,
                                 stepsize=self.stepsize,
                                 nproc=nproc,
                                 verbose=True,
                                 iprint=100)

        self.Emax0 = self.ns.replicas[-1].energy

        self.run_ns(max_iter=10000, Etol=.01)
コード例 #10
0
def main():
    parser = argparse.ArgumentParser(
        description=
        "do nested sampling on a p[article in a n-dimensional Harmonic well")
    #    parser.add_argument("--db", type=str, nargs=1, help="database filename",
    #                        default="otp.db")
    parser.add_argument("-K",
                        "--nreplicas",
                        type=int,
                        help="number of replicas",
                        default=300)
    parser.add_argument("-A",
                        "--ndof",
                        type=int,
                        help="number of degrees of freedom",
                        default=4)
    parser.add_argument("-P",
                        "--nproc",
                        type=int,
                        help="number of processors",
                        default=1)
    parser.add_argument("--trivparal",
                        action='store_true',
                        help="set whether to do trivial parallelisation",
                        default=False)
    parser.add_argument(
        "-q",
        action="store_true",
        help="turn off verbose printing of information at every step")
    args = parser.parse_args()

    system = HarParticle(args.ndof, Emax_init=1000.)
    mcrunner = HarRunner(system)
    #    ns = NestedSamplingSerial(system, args.nreplicas, mcrunner,
    #                              verbose=not args.q)
    ns = NestedSampling(system,
                        args.nreplicas,
                        mcrunner,
                        nproc=args.nproc,
                        triv_paral=args.trivparal,
                        verbose=not args.q)
    print "harmonic particle ndof", args.ndof
    run_nested_sampling(ns, label="hparticle", etol=.00000001)
コード例 #11
0
    def setUp1(self, nproc=1):
        self.ndim = 3
        self.harmonic = Harmonic(self.ndim)
        self.nreplicas = 10
        self.stepsize = 0.1
        self.nproc = nproc
        
        self.mc_runner = MonteCarloWalker(self.harmonic, mciter=40)

        replicas = []
        for i in range(self.nreplicas):
            x = self.harmonic.get_random_configuration()
            replicas.append(Replica(x, self.harmonic.get_energy(x)))
        self.ns = NestedSampling(replicas, self.mc_runner, 
                                 stepsize=0.1, nproc=nproc, verbose=False)


        self.etol = 0.01
        run_nested_sampling(self.ns, label="test", etol=self.etol)
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy
コード例 #12
0
def main():
    parser = argparse.ArgumentParser(description="do nested sampling on a p[article in a n-dimensional Harmonic well")
    parser.add_argument("-K", "--nreplicas", type=float, help="number of replicas", default=1e1)
    parser.add_argument("-A", "--ndof", type=int, help="number of degrees of freedom", default=3)
    parser.add_argument("-P", "--nproc", type=int, help="number of processors", default=1)
    parser.add_argument("-N", "--nsteps", type=int, help="number of MC steps per NS iteration", default=int(1e3))
    parser.add_argument("--stepsize", type=float, help="stepsize, adapted between NS iterations", default=20)
    parser.add_argument("--etol", type=float, help="energy tolerance: the calculation terminates when the energy difference \
                                                    between Emax and Emin is less than etol", default=0.1)
    parser.add_argument("-q", action="store_true", help="turn off verbose printing of information at every step")
    args = parser.parse_args()
    ndof = args.ndof
    nproc = args.nproc
    nsteps = int(args.nsteps)-8
    nreplicas = int(args.nreplicas)
    stepsize = args.stepsize
    etol = args.etol
    
    #construct potential (cost function)
    potential = Harmonic(ndof)
    
    #construct Monte Carlo walker
    mc_runner = MonteCarloWalker(potential, mciter=nsteps)

    #initialise replicas (initial uniformly samples set of configurations)
    replicas = []
    for _ in range(nreplicas):
        x = potential.get_random_configuration()
        print(x)
        print(potential.get_energy(x))
        replicas.append(Replica(x, potential.get_energy(x)))
    
    #construct Nested Sampling object
    ns = NestedSampling(replicas, mc_runner, stepsize=stepsize, nproc=nproc, max_stepsize=10, verbose=not args.q)
    
    #run Nested Sampling (NS), output:
    ## label.energies (one for each iteration) 
    ## label.replicas_final (live replica energies when NS terminates)
    run_nested_sampling(ns, label="run_hparticle", etol=etol)
コード例 #13
0
def main():
    parser = argparse.ArgumentParser(
        description=
        "do nested sampling on a p[article in a n-dimensional Harmonic well")
    parser.add_argument("-K",
                        "--nreplicas",
                        type=int,
                        help="number of replicas",
                        default=300)
    parser.add_argument("-A",
                        "--ndof",
                        type=int,
                        help="number of degrees of freedom",
                        default=4)
    parser.add_argument("-P",
                        "--nproc",
                        type=int,
                        help="number of processors",
                        default=1)
    parser.add_argument("-N",
                        "--nsteps",
                        type=int,
                        help="number of MC steps per NS iteration",
                        default=100)
    parser.add_argument("--stepsize",
                        type=float,
                        help="stepsize, adapted between NS iterations",
                        default=0.1)
    parser.add_argument(
        "--etol",
        type=float,
        help=
        "energy tolerance: the calculation terminates when the energy difference \
                                                    between Emax and Emin is less than etol",
        default=0.01)
    parser.add_argument(
        "-q",
        action="store_true",
        help="turn off verbose printing of information at every step")
    parser.add_argument(
        "--dispatcherURI",
        action="store_true",
        help="use URI of the dispatcher server in default location",
        default=False)
    parser.add_argument(
        "--dispatcherURI-file",
        type=str,
        help="use URI of the dispatcher server if different from default",
        default=None)

    #set basic parameters
    args = parser.parse_args()
    ndof = args.ndof
    nproc = args.nproc
    nsteps = args.nsteps
    nreplicas = args.nreplicas
    stepsize = args.stepsize
    etol = args.etol

    #try to read dispatecher URI from default file location
    if args.dispatcherURI is True:
        with open("dispatcher_uri.dat", "r") as rfile:
            dispatcherURI = rfile.read().replace('\n', '')
    elif args.dispatcherURI_file != None:
        with open(args.dispatcherURI_file, "r") as rfile:
            dispatcherURI = rfile.read().replace('\n', '')
    else:
        dispatcherURI = None

    #construct potential (cost function)
    potential = Harmonic(ndof)

    #construct Monte Carlo walker
    mc_runner = MonteCarloWalker(potential, mciter=nsteps)

    #initialise replicas (initial uniformly samples set of configurations)
    replicas = []
    for _ in xrange(nreplicas):
        x = potential.get_random_configuration()
        replicas.append(Replica(x, potential.get_energy(x)))

    #construct Nested Sampling object and pass dispatcher address
    ns = NestedSampling(replicas,
                        mc_runner,
                        stepsize=stepsize,
                        nproc=nproc,
                        dispatcher_URI=dispatcherURI,
                        max_stepsize=10,
                        verbose=not args.q)

    #run Nested Sampling (NS), output:
    ## label.energies (one for each iteration)
    ## label.replicas_final (live replica energies when NS terminates)
    run_nested_sampling(ns, label="run_hparticle", etol=etol)
コード例 #14
0
ファイル: _test_ns_lj.py プロジェクト: js850/sens
class TestNS_LJ(unittest.TestCase):
    def setUp(self):
        self.setUp1()

    def compute_cv(self, Tmin=.01, Tmax=3., nT=100):
        T = np.arange(Tmin, Tmax, (Tmax - Tmin) / nT)
        Cv = compute_cv_c(np.array(self.ns.max_energies),
                          float(self.nproc),
                          float(self.ndof),
                          T.min(),
                          T.max(),
                          T.size,
                          float(self.ndof),
                          live=False)
        return T, Cv

    def set_up_system(self):
        self.natoms = 13
        self.gmin = -44.3269
        self.system = LJClusterSENS(self.natoms, 2.5)
        self.ndof = 3 * self.natoms - 6

    def setUp1(self, nproc=1):
        self.set_up_system()
        self.nreplicas = 10
        self.stepsize = 0.01
        self.nproc = nproc

        self.mc_runner = self.system.get_mc_walker(mciter=100)

        self.ns = NestedSampling(self.system,
                                 self.nreplicas,
                                 self.mc_runner,
                                 stepsize=0.1,
                                 nproc=nproc,
                                 verbose=False)

        self.Emax0 = self.ns.replicas[-1].energy

        self.niter = 100
        for i in xrange(self.niter):
            self.ns.one_iteration()
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy

    def test1(self):
        self.assert_(len(self.ns.replicas) == self.nreplicas)
        self.assert_(self.Emax < self.Emax0)
        self.assert_(self.Emin < self.Emax)
        self.assert_(self.Emin < 0)
        self.assert_(self.Emin >= self.gmin)
        self.assert_(self.ns.stepsize != self.stepsize)
        self.assertEqual(len(self.ns.max_energies), self.niter * self.nproc)
        self.assertEqual(self.ns.failed_mc_walks, 0)

    def run_ns(self, max_iter=100, Etol=1e-4):
        #        max_iter = 10000
        #        self.Etol = .01
        self.Etol = Etol
        for i in xrange(int(max_iter)):
            self.ns.one_iteration()
            deltaE = self.ns.replicas[-1].energy - self.ns.replicas[0].energy
            if deltaE < self.Etol:
                break
        self.niter = i + 1
        self.Emax = self.ns.replicas[-1].energy
        self.Emin = self.ns.replicas[0].energy
コード例 #15
0
def run_nested_sampling_lj(system,
                           nreplicas=300,
                           mciter=1000,
                           target_ratio=0.7,
                           label="test",
                           minima=None,
                           use_compiled=True,
                           nproc=1,
                           triv_paral=True,
                           minprob=1,
                           maxiter=1e100,
                           **kwargs):
    takestep = RandomDisplacement(stepsize=0.07)
    accept_tests = system.get_config_tests()

    if type(system) is LJClusterNew:
        if use_compiled:
            mc_runner = MonteCarloCompiled(system.radius)

#       import pickle
#       with open("testpickle", "w") as pout:
#           pickle.dump(mc_runner, pout)
        else:
            mc_runner = MonteCarloChain(system.get_potential(),
                                        takestep,
                                        accept_tests=accept_tests)
        print "using the compiled MC = ", use_compiled
    elif type(system) is HarParticle:
        mc_runner = HarRunner(system)
        print "using HarRunner"
    elif type(system) is IsingSystem:
        mc_runner = IsingRunnerC(system)
        print "using IsingRunner"
    else:
        raise TypeError('system type is not known')

    print "using", nproc, "processors"

    if minima is not None:
        assert (len(minima) > 0)
        print "using", len(minima), "minima"
        ns = NestedSamplingBS(system,
                              nreplicas,
                              mc_runner,
                              minima,
                              mciter=mciter,
                              target_ratio=target_ratio,
                              stepsize=0.07,
                              nproc=nproc,
                              triv_paral=triv_paral,
                              minprob=minprob,
                              **kwargs)
    else:
        ns = NestedSampling(system,
                            nreplicas,
                            mc_runner,
                            mciter=mciter,
                            target_ratio=target_ratio,
                            stepsize=0.07,
                            nproc=nproc,
                            triv_paral=triv_paral,
                            **kwargs)
    etol = 0.01

    ns = run_nested_sampling(ns, label, etol, maxiter=maxiter)
    return ns