def test_univ_uniform_range(self):
        """
        Distributions: Checks that the univariate uniform dist obeys limits.
        """
        for lower, upper in [(0, 1), (-1, 1), (-1, 5)]:
            dist = UniformDistribution([lower, upper])

            samples = dist.sample(1000)
            assert np.all(samples >= lower)
            assert np.all(samples <= upper)
    def test_univ_uniform_range(self):
        """
        Distributions: Checks that the univariate uniform dist obeys limits.
        """
        for lower, upper in [(0, 1), (-1, 1), (-1, 5)]:
            dist = UniformDistribution([lower, upper])

            samples = dist.sample(1000)
            assert np.all(samples >= lower)
            assert np.all(samples <= upper)
    def test_univ_uniform_moments(self):
        """
        Distributions: Checks that the univ. uniform dist. has the right moments.
        """
        dist = UniformDistribution([[0, 1]])
        samples = dist.sample(10000)

        # We use low-precision checks here, since the error goes as 1/sqrt{N}.
        # Determinism helps us be sure that once we pass, we'll keep passing,
        # but it does nothing to make the moments accurate.
        assert_almost_equal(1 / 12, samples.var(), 2)
        assert_almost_equal(1 / 2, samples.mean(), 2)
    def test_univ_uniform_moments(self):
        """
        Distributions: Checks that the univ. uniform dist. has the right moments.
        """
        dist = UniformDistribution([[0, 1]])
        samples = dist.sample(10000)

        # We use low-precision checks here, since the error goes as 1/sqrt{N}.
        # Determinism helps us be sure that once we pass, we'll keep passing,
        # but it does nothing to make the moments accurate.
        assert_almost_equal(1 / 12, samples.var(), 2)
        assert_almost_equal(1 / 2, samples.mean(), 2)
Beispiel #5
0
def simple_est_rb(data,
                  interleaved=False,
                  p_min=0.0,
                  p_max=1.0,
                  n_particles=8000,
                  return_all=False):
    r"""
    Estimates the fidelity of a gateset from a standard or interleaved randomized benchmarking
    experiment.
    
    :param data: Data to be used in estimating the gateset fidelity.
    :type data: see :ref:`simple_est_data_arg`
    :param float p_min: Minimum value of the parameter :math:`p`
        to consider feasible.
    :param float p_max: Minimum value of the parameter :math:`p`
        to consider feasible.
    :param int n_particles: The number of particles to be used in estimating
        the randomized benchmarking model.
    :param bool return_all: Controls whether additional return
        values are provided, such as the updater.

    :column counts (int): How many sequences of length :math:`m` were observed to
        survive.
    :column m (int): How many gates were used for sequences in this row of the data.
    :column n_shots (int): How many different sequences of length :math:`m`
        were measured.
    :column reference (bool): `True` if this row represents reference sequences, or
        `False` if the gate of interest is interleaved. Note that this column is omitted
        if ``interleaved`` is `False`.

    :return mean: Bayesian mean estimator for the model vector
        :math:`(p, A, B)`, or :math:`(\tilde{p}, p_{\text{ref}}, A, B)`
        for the interleaved case.
    :return var: Variance of the final posterior over RB model vectors.
    :return extra: See :ref:`simple_est_extra_return`. Only returned
        if ``return_all`` is `True`.
    """
    model = BinomialModel(RandomizedBenchmarkingModel(interleaved=interleaved))
    prior = PostselectedDistribution(
        UniformDistribution(
            [[p_min, p_max], [0, 1], [0, 1]] if not interleaved else
            [[p_min, p_max], [p_min, p_max], [0, 1], [0, 1]]), model)

    data = load_data_or_txt(data, [('counts', 'uint'), ('m', 'uint'),
                                   ('n_shots', 'uint')] +
                            ([('reference', 'uint')] if interleaved else []))

    cols_expparams = {'m': (1, 'm'), 'n_meas': (2, 'n_shots')}
    if interleaved:
        cols_expparams['reference'] = (3, 'reference')

    outcomes, expparams = data_to_params(data,
                                         model.expparams_dtype,
                                         cols_expparams=cols_expparams)

    return do_update(model, n_particles, prior, outcomes, expparams,
                     return_all)
Beispiel #6
0
def simple_est_prec(data, freq_min=0.0, freq_max=1.0, n_particles=6000, return_all=False):
    """
    Estimates a simple precession (cos²) from experimental data.
    Note that this model is mainly for testing purposes, as it does not
    consider the phase or amplitude of precession, leaving only the frequency.

    :param data: Data to be used in estimating the precession frequency.
    :type data: see :ref:`simple_est_data_arg`
    :param float freq_min: The minimum feasible frequency to consider.
    :param float freq_max: The maximum feasible frequency to consider.
    :param int n_particles: The number of particles to be used in estimating
        the precession frequency.
    :param bool return_all: Controls whether additional return
        values are provided, such as the updater.

    :column counts (int): How many counts were observed at the sampled
        time.
    :column t (float): The evolutions time at which the samples
        were collected.
    :column n_shots (int): How many samples were collected at the
        given evolution time.

    :return mean: Bayesian mean estimator for the precession frequency.
    :return var: Variance of the final posterior over frequency.
    :return extra: See :ref:`simple_est_extra_return`. Only returned
        if ``return_all`` is `True`.
    """
    model = BinomialModel(SimplePrecessionModel(freq_min))
    prior = UniformDistribution([0, freq_max])

    data = load_data_or_txt(data, [
        ('counts', 'uint'),
        ('t', float),
        ('n_shots', 'uint')
    ])

    outcomes, expparams = data_to_params(data,
        model.expparams_dtype,
        cols_expparams={
            'x': (1, 't'),
            'n_meas': (2, 'n_shots')
        }
    )

    return do_update(
        model, n_particles, prior, outcomes, expparams,
        return_all
    )
Beispiel #7
0
    def run_estimate(data, freq,
                     n_particles=10000, return_all=False):
        """this is a copy of qinfer.simple_

        Args:
            data:
            n_particles:
            return_all:

        Returns:

        """
        model = BinomialModel(AmplitudeEstimator(freq))
        
        prior =  PostselectedDistribution(
        UniformDistribution(
            [
                [0.30, 0.5],
                [0.30, 0.5]
             ]),
           model,
           maxiters=10000
        )

#         prior = MyDistribution()


        data = load_data_or_txt(data, [
            ('counts', 'uint'),
            ('t', float),
            ('n_shots', 'uint')
        ])

        outcomes, expparams = data_to_params(data,
            model.expparams_dtype,
            cols_expparams={
                't': (1, 't'),
                'n_meas': (2, 'n_shots')
            }
        )

        return do_update(
            model, n_particles, prior, outcomes, expparams,
            return_all
        )
Beispiel #8
0
 def _mk_updater(self, n_particles, **kwargs):
     return SMCUpdater(self.model, n_particles, UniformDistribution([0, 1]), **kwargs)
Beispiel #9
0
        mps_buf.release()
        eps_buf.release()
        dest_buf.release()

        # Now we concatenate over outcomes.
        return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0)


## SCRIPT ######################################################################

if __name__ == "__main__":
    # NOTE: This is now redundant with the perf_testing module.

    simple_model = SimplePrecessionModel()

    for model in [AcceleratedPrecessionModel(), SimplePrecessionModel()]:

        true = np.random.random(1)
        updater = SMCUpdater(model, 100000, UniformDistribution([0, 1]))

        tic = time.time()

        for idx_exp in range(200):
            if not (idx_exp % 20):
                print(idx_exp)
            expparams = np.array([(9 / 8)**idx_exp])
            updater.update(simple_model.simulate_experiment(true, expparams),
                           expparams)

        print(model, updater.est_mean(), true, time.time() - tic)
"""
from __future__ import division
from t1_model import T1Model
from qinfer.distributions import UniformDistribution
from qinfer.smc import SMCUpdater
from qinfer.resamplers import LiuWestResampler
import numpy as np
import matplotlib.pyplot as plt
from qinfer.expdesign import ExperimentDesigner
import logging

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)

model = T1Model()
prior = UniformDistribution(np.array([0, 10]))
N_particles = 1000000
updater = SMCUpdater(
        model, N_particles, prior, resampler=LiuWestResampler(),
        zero_weight_policy='reset'
)
designer = ExperimentDesigner(updater, opt_algo=1)

# Set the value of T1 to Learn, pick 1 value from prior
true_model = prior.sample()
# true_model=np.array([11.032], dtype=model.expparams_dtype)

performance_dtype = [
    ('expparams', 'float'),
    ('sim_outcome', 'float'),
    ('est_mean', 'float'),
 def test_uniform_shape(self):
     """
     Distributions: Checks that the multivar. uni. dist has the right shape.
     """
     dist = UniformDistribution([[0, 1], [0, 2], [0, 3]])
     assert dist.sample(100).shape == (100, 3)
 def test_uniform_shape(self):
     """
     Distributions: Checks that the multivar. uni. dist has the right shape.
     """
     dist = UniformDistribution([[0, 1], [0, 2], [0, 3]])
     assert dist.sample(100).shape == (100, 3)