Beispiel #1
0
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
Beispiel #2
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
Beispiel #3
0
    def _attempt_swap(self, replica, Emax):
        # sample a configuration from the harmonic superposition approximation
        m, xsampled = self.sa_sampler.sample_coords(Emax)

        # if the configuration fails the config test then reject the swap
        #        print "attempting swap"
        if self.config_tests is not None:
            for test in self.config_tests:
                if not test(coords=xsampled):
                    return None

        # if the energy returned by full energy function is too high, then reject the swap
        Esampled = self.system.get_energy(xsampled)
        if Esampled >= Emax:
            return None

        # compute the energy of the replica within the superposition approximation.
        E_SA = self._compute_energy_in_SA(replica)

        # reject if the energy is too high
        if E_SA is None or E_SA >= Emax:
            # no swap done
            return None

        if self.verbose:
            print "accepting swap: Eold %g Enew %g Eold_SA %g Emax %g" % (
                replica.energy, Esampled, E_SA, Emax)
        self.count_sampled_minima += 1

        return Replica(xsampled, Esampled, from_random=False)
 def initialise_replicas(self):
     # create the replicas
     replicas = []
     for i in xrange(self.nreplicas):
         x = self.pot.get_random_configuration()
         e = self.pot.get_energy(x)
         replicas.append(Replica(x, e))
     return replicas
Beispiel #5
0
 def create_replica(self):
     """
     creates a random configuration, evaluates its energy and creates the corresponding Replica object
     """
     x = self.system.get_random_configuration()
     pot = self.system.get_potential()
     e = pot.getEnergy(x)
     #        if self.verbose: print "pot=", e
     return Replica(x, e)
Beispiel #6
0
 def get_starting_configurations(self, Emax):
     """this function overloads the function in NestedSampling"""
     # choose a replica randomly
     configs = self.get_starting_configurations_from_replicas()
     # replace each starting configuration with a one chosen
     # from the minima with probability prob
     onset_prob = self.onset_prob_func(Emax)
     prob = onset_prob / float(self.nreplicas)
     for i in range(len(configs)):
         if np.random.uniform(0, 1) < prob:
             x, energy = self.get_starting_configuration_minima(Emax)
             configs[i] = Replica(x, energy, from_random=False)
             if self.verbose:
                 print "sampling from minima, E minimum:", energy, "with probability:", prob
     return configs
Beispiel #7
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
Beispiel #8
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)
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)
Beispiel #10
0
 def set_selected(self, x, energy):
     self.selected = Replica(x, energy)
     self.show3d.setCoords(x, index=1)
     self.show3d.setCoords(None, index=2)