Пример #1
0
    def run(self,
            conf,
            y_obs,
            y_obs_times,
            max_iter=2000,
            burning=500,
            jupyter=False):
        '''
        run_mcmc takes an epsilon and compute the y_obs and then run mcmc using those observations.

        Returns
        -------

        samples: list
        '''
        from UQuant.mcmc import MCMC

        self.epsilon = conf["epsilon"]
        self.sigma_normal = conf["sigma_normal"]
        self.initial_point_mcmc = conf["initial_point_mcmc"]
        self.uni_prior_range = conf["uni_prior_range"]

        self.y_obs = y_obs
        self.y_obs_times = y_obs_times

        self.sampler = MCMC(self.density, self.proposal_density,
                            self.draw_from_proposal, self.initial_point_mcmc)

        self.sampler.run(max_iter=max_iter, burning=burning, jupyter=jupyter)
Пример #2
0
Файл: uq.py Проект: hajians/UQ
    # plot the noisy pressure drop
    plt.plot(pipe_true.timeslices,
             y_obs,
             linestyle="--",
             marker="x",
             label="noisy pressure drop")
    plt.xlabel("$t_n$", fontsize=24)
    plt.ylabel("$\delta p_h^n$", fontsize=24)
    plt.yticks(fontsize=20)
    plt.xticks(fontsize=20)
    plt.legend(loc=4, borderaxespad=0.0, prop={'size': 20}, frameon=False)
    plt.tight_layout()
    plt.show(block=True)

    ### instantiate an MCMC sampler
    mcmc = MCMC(density, proposal_density, draw_from_proposal,
                initial_point_mcmc)

    # run the MCMC sample
    mcmc.run(max_iter=10000, burning=1000)
    # write the samples into a file
    #mcmc.write("samples-N3-fric0.075-wNoise.dat")

    # plotting the sampled friction coefficients
    for idx, coef in enumerate(mcmc.density_samples):
        pipe.get_lambda_average(coef)
        plt.plot(pipe.mesh, pipe.lambda_avg)

    pipe_true.get_lambda_average(true_friction)
    plt.plot(pipe_true.mesh,
             pipe_true.lambda_avg,
             '--',
Пример #3
0
class MCMCBayesianInversion(BayesianInversion):
    '''
    GasBayesianInversion solves a Bayesian Inverse 
    problem for Gas pipe friction coefficients.
    '''
    def __init__(self, c_sound, t_final, x_l, x_r, dx, expan_coef,
                 boundary_eps, time_ins):
        BayesianInversion.__init__(self, c_sound, t_final, x_l, x_r, dx,
                                   expan_coef, boundary_eps, time_ins)

    def uni_prior(self, x):
        '''
        uniform prior

        Parameters
        ----------

        x: float * len(x)
        '''

        uni_prior_up = self.uni_prior_range["up"]
        uni_prior_down = self.uni_prior_range["down"]

        volume = 1.0

        for i in range(len(x)):
            volume *= abs(uni_prior_up[i] - uni_prior_down[i])

        normalize = 1.0 / volume

        for i in range(len(x)):
            if (((x[i] < uni_prior_up[i]) &
                 (x[i] > uni_prior_down[i])) == False):
                return 0.0

        return normalize

    def proposal_density(self, new, old):
        '''
        proposal density function

        Parameters
        ----------
        new: float * len(new)

        old: float * len(old)
        '''

        length = len(new)

        out = empty(length, dtype=float)

        for i in range(length):
            out[i] = 1.0/(2*pi*self.sigma_normal**2) * \
                     exp( -0.5*(new[i] - old[i])**2 / self.sigma_normal**2 )

        return out

    def draw_from_proposal(self, old):
        '''
        draw from the proposal

        Parameters
        ----------
        old: float * len(old)
        '''
        return normal(old, self.sigma_normal, size=len(old))

    def likelihood(self, x):
        '''
        computes the likelihood function

        Parameters
        ----------

        pipe: SemiLinSystem

        x: float * len(x)
        '''

        pipe = self.pipe

        pipe.run(x, progress_bool=False)

        # check if we have negative friction
        pipe.get_current_lambda_average()
        for i in pipe.lambda_avg:
            if i < 0.0: return 0.0

        S = pipe.get_presure_drop(time_instance=self.time_ins, inplace=False)

        Proj_y_obs = self.EvalY_obs(pipe.timeslices, self.y_obs,
                                    self.y_obs_times)

        out = exp(-0.5 * dot(S - Proj_y_obs, S - Proj_y_obs) / self.epsilon)

        #print (out, self.epsilon)

        return out

    def density(self, x):
        '''
        density function for the MCMC: 
        multiplication of the likelihood and the prior distribution

        Parameters
        ----------
        x: float * len(x)

        '''
        PRIOR = self.uni_prior(x)
        if PRIOR > 10.0**-8:
            return self.likelihood(x) * PRIOR
        else:
            return 0.0

    def run(self,
            conf,
            y_obs,
            y_obs_times,
            max_iter=2000,
            burning=500,
            jupyter=False):
        '''
        run_mcmc takes an epsilon and compute the y_obs and then run mcmc using those observations.

        Returns
        -------

        samples: list
        '''
        from UQuant.mcmc import MCMC

        self.epsilon = conf["epsilon"]
        self.sigma_normal = conf["sigma_normal"]
        self.initial_point_mcmc = conf["initial_point_mcmc"]
        self.uni_prior_range = conf["uni_prior_range"]

        self.y_obs = y_obs
        self.y_obs_times = y_obs_times

        self.sampler = MCMC(self.density, self.proposal_density,
                            self.draw_from_proposal, self.initial_point_mcmc)

        self.sampler.run(max_iter=max_iter, burning=burning, jupyter=jupyter)
Пример #4
0
        #plt.plot(pipe.timeslices, pipe.pressure_drop, "o-")
        if i in [1, 9, 11, 19, 25, 41]:
            plt.plot(pipe_tmp.mesh,
                     pipe_tmp.lambda_avg,
                     linestyle=linestyles[counter % len(linestyles)],
                     label="$N=" + str(i / 2) + "$")
            counter += 1

    plt.legend(loc="best", prop={'size': 16}, frameon=False)
    plt.yticks(fontsize=20)
    plt.xticks(fontsize=20)
    plt.xlabel("$x$", fontsize=24)
    plt.ylabel("$\lambda^N(x)$", fontsize=24)
    plt.tight_layout()
    plt.savefig("results/figure_fric_bump.pgf")
    plt.show()

    # clean memory
    collect()

    pipe.info()
    ### instantiate an MCMC sampler
    mcmc = MCMC(density, proposal_density, draw_from_proposal,
                initial_point_mcmc)

    # run the MCMC sample
    mcmc.run(max_iter=200000, burning=5000)
    # write the samples into a file
    mcmc.write(filename, write_prob=True)
Пример #5
0
    # pipe = SemiLinSystem(c_sound, t_final, x_l, x_r, dx, expan_coef, boundary_eps)
    # pipe.run([0.075])
    # pipe.get_presure_drop(inplace=True)
    # plt.plot(pipe.timeslices, pipe.pressure_drop, "-x")
    # #plt.plot(pipe_true.timeslices, pipe_true.pressure_drop, "-o")
    # #plt.plot(y_obs_times, y_obs, "-o")
    # plt.plot(pipe.timeslices, EvalY_obs(pipe.timeslices), "-*")
    # plt.show(block=False)

    for i in range(0, 51):
        if i % 10 == 1:
            pipe = SemiLinSystem(c_sound, t_final, x_l, x_r, dx, expan_coef,
                                 boundary_eps)
            pipe.info()
            mcmc = MCMC(density, proposal_density, draw_from_proposal,
                        initial_point_mcmc)
            mcmc.run(2000, burning=500)
            samples[dx] = mcmc.density_samples
        dx += 0.0001

        gc.collect()  # collect un-used objects

    # plt.legend(loc=2, borderaxespad=0.0)
    # plt.show(block=False)

    Samples = {}
    for idx in samples:
        Samples[idx] = []
        for point in samples[idx]:
            Samples[idx].append(point[0])
Пример #6
0
    # pipe = SemiLinSystem(c_sound, t_final, x_l, x_r, dx, expan_coef, boundary_eps)
    # pipe.run([0.075])
    # pipe.get_presure_drop(inplace=True)
    # plt.plot(pipe.timeslices, pipe.pressure_drop, "-x")
    # #plt.plot(pipe_true.timeslices, pipe_true.pressure_drop, "-o")
    # #plt.plot(y_obs_times, y_obs, "-o")
    # plt.plot(pipe.timeslices, EvalY_obs(pipe.timeslices), "-*")
    # plt.show(block=False)

    for i in range(0, 11):
        if i % 10 == 1:
            pipe = SemiLinSystem(c_sound, t_final, x_l, x_r, dx, expan_coef,
                                 boundary_eps)
            pipe.info()
            mcmc = MCMC(density, proposal_density, draw_from_proposal,
                        initial_point_mcmc)
            mcmc.run(2000, burning=500)
            mcmc.write("samples" + str(i))
            samples[dx] = mcmc.density_samples
        dx += 0.0001

        gc.collect()  # collect un-used objects

    # plt.legend(loc=2, borderaxespad=0.0)
    # plt.show(block=False)

    # Samples = {}
    # for idx in samples:
    #     Samples[idx] = []
    #     for point in samples[idx]:
    #         Samples[idx].append(point[0])