コード例 #1
0
    def sampler(self, walker_ratio, burnin, samples, num, threads=-1):
        """
            :param walker_ratio:  the ratio of walkers and the count of sampled parameters
            :param burnin: burin iterations
            :param samples: no. of sample iterations
            :param num: number to put in output files e.g: string(name+num)=Pk_1,Bk_1
            :param threads: no. of cpu threads

            self.chain.setup()
            print("find best fit point")
            pso = MpiParticleSwarmOptimizer(self.chain, params[:, 1], params[:, 2])
            psoTrace = np.array([pso.gbest.position.copy() for _ in pso.sample()])
            params[:, 0] = pso.gbest.position
        """

        sampler = CosmoHammerSampler(params=params,
                                     likelihoodComputationChain=self.chain,
                                     filePrefix='%s' % self.name + '%d' % num,
                                     walkersRatio=walker_ratio,
                                     burninIterations=burnin,
                                     sampleIterations=samples,
                                     threadCount=threads)

        print("started sampling:")
        start = time.time()
        sampler.startSampling()
        end = time.time()
        tics = end - start
        print("The time taken %.2f sec. done!" % tics)
        print('Done!')
コード例 #2
0
    def mcmc_CH(self,
                walkerRatio,
                n_run,
                n_burn,
                mean_start,
                sigma_start,
                lowerLimit,
                upperLimit,
                X2_chain,
                threadCount=1,
                init_pos=None):
        """
        runs mcmc on the parameter space given parameter bounds with CosmoHammerSampler
        returns the chain
        """
        params = np.array([mean_start, lowerLimit, upperLimit, sigma_start]).T

        chain = LikelihoodComputationChain(min=lowerLimit, max=upperLimit)

        # chain.addCoreModule(CambCoreModule())
        chain.addLikelihoodModule(X2_chain)
        chain.setup()

        store = InMemoryStorageUtil()
        sampler = CosmoHammerSampler(params=params,
                                     likelihoodComputationChain=chain,
                                     filePrefix="testHammer",
                                     walkersRatio=walkerRatio,
                                     burninIterations=n_burn,
                                     sampleIterations=n_run,
                                     threadCount=threadCount,
                                     initPositionGenerator=init_pos,
                                     storageUtil=store)

        sampler.startSampling()

        if sampler._sampler.pool is not None:
            sampler._sampler.pool.close()

        return store.samples
コード例 #3
0
pso = ParticleSwarmOptimizer(chain, params[:, 1], params[:, 2])
psoTrace = np.array([pso.gbest.position.copy() for _ in pso.sample()])
params[:, 0] = pso.gbest.position

storageUtil = InMemoryStorageUtil()
sampler = CosmoHammerSampler(params=params,
                             likelihoodComputationChain=chain,
                             filePrefix="pseudoCmb_pso",
                             walkersRatio=50,
                             burninIterations=0,
                             sampleIterations=100,
                             storageUtil=storageUtil,
                             threadCount=4)

print("start sampling")
sampler.startSampling()
print("done!")

print("plotting")
import matplotlib.pyplot as plt
import triangle
data = storageUtil.samples
K = data.shape[1]
factor = 2.0  # size of one side of one panel
lbdim = 0.5 * factor  # size of left/bottom margin
trdim = 0.2 * factor  # size of top/right margin
whspace = 0.05  # w/hspace size
plotdim = factor * K + factor * (K - 1.) * whspace
dim = lbdim + plotdim + trdim

fig, ax = plt.subplots(K, K, figsize=(dim, dim), tight_layout=False)
コード例 #4
0
                ("y", [1, -10, 10, 0.1]))



chain = LikelihoodComputationChain()

rosenbrock = RosenbrockModule()

chain.addLikelihoodModule(rosenbrock)
chain.setup()


sampler = CosmoHammerSampler(
                params= params, 
                likelihoodComputationChain=chain, 
                filePrefix="rosenbrock", 
                walkersRatio=50, 
                burninIterations=100, 
                sampleIterations=100)
sampler.startSampling()

try:
    import numpy as np
    import matplotlib.pyplot as plt
    data = np.loadtxt("rosenbrock.out")
    plt.scatter(data[:,0], data[:, 1], 1)
    plt.xlabel(params.keys[0])
    plt.ylabel(params.keys[1])
    plt.show()
except Exception:
    print("Plotting failed. Missing libs?")