def find_valid_y_time_ntimes(self):
     valid_y_info_dic = {}  #sample:[occurrences, chain_break_fraction]
     calculation_time = 0
     for _ in range(self.n):
         s3_destination_folder = ('amazon-braket-ecc806acea4c',
                                  'qaExactLogisticRegression_ssato')
         dw = BraketDWaveSampler(
             s3_destination_folder,
             device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6')
         qa_sampler = AutoEmbeddingComposite(dw)
         res = qa_sampler.sample(self.bqm,
                                 chain_strength=self.chain_strength,
                                 chain_break_fraction=True,
                                 num_reads=self.num_reads)
         for sample, energy, num_occurrences, chain_break_fraction in res.data(
             [
                 'sample', 'energy', 'num_occurrences',
                 'chain_break_fraction'
             ]):
             if energy == 0.0:
                 sample_tuple = tuple(sample.values())
                 if sample_tuple in list(valid_y_info_dic.keys()):
                     valid_y_info_dic[sample_tuple][0] += num_occurrences
                 else:
                     valid_y_info_dic[sample_tuple] = [
                         num_occurrences, chain_break_fraction
                     ]
         calculation_time += res.info['additionalMetadata'][
             'dwaveMetadata']['timing']['qpuAccessTime'] * 10**(-6)
     return valid_y_info_dic, calculation_time
예제 #2
0
class QPUSubproblemAutoEmbeddingSampler(traits.SubproblemSampler, traits.SISO, Runnable):
    r"""A quantum sampler for a subproblem with automated heuristic
    minor-embedding.

    Args:
        num_reads (int, optional, default=100):
            Number of states (output solutions) to read from the sampler.

        qpu_sampler (:class:`dimod.Sampler`, optional, default=\ :class:`~dwave.system.samplers.DWaveSampler`\ ()):
            Quantum sampler such as a D-Wave system. Subproblems that do not fit the
            sampler's structure are minor-embedded on the fly with
            :class:`~dwave.system.composites.AutoEmbeddingComposite`.

        sampling_params (dict):
            Dictionary of keyword arguments with values that will be used
            on every call of the (embedding-wrapped QPU) sampler.

        auto_embedding_params (dict, optional):
            If provided, parameters are passed to the
            :class:`~dwave.system.composites.AutoEmbeddingComposite` constructor
            as keyword arguments.

    See :ref:`samplers-examples`.
    """

    def __init__(self, num_reads=100, qpu_sampler=None, sampling_params=None,
                 auto_embedding_params=None, **runopts):
        super(QPUSubproblemAutoEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()

        if sampling_params is None:
            sampling_params = {}
        self.sampling_params = sampling_params

        # embed on the fly and only if needed
        if auto_embedding_params is None:
            auto_embedding_params = {}
        self.sampler = AutoEmbeddingComposite(qpu_sampler, **auto_embedding_params)

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                       "qpu_sampler={self.sampler!r}, "
                       "sampling_params={self.sampling_params!r})").format(self=self)

    def next(self, state, **runopts):
        num_reads = runopts.get('num_reads', self.num_reads)
        sampling_params = runopts.get('sampling_params', self.sampling_params)

        params = sampling_params.copy()
        params.update(num_reads=num_reads)

        response = self.sampler.sample(state.subproblem, **params)

        return state.updated(subsamples=response)
예제 #3
0
class ReverseAnnealingAutoEmbeddingSampler(traits.SubproblemSampler, traits.SISO, Runnable):
    """A quantum reverse annealing sampler for a subproblem with automated
    heuristic minor-embedding.

    Args:
        num_reads (int, optional, default=100):
            Number of states (output solutions) to read from the sampler.

        qpu_sampler (:class:`dimod.Sampler`, optional,
                default=:class:`AutoEmbeddingComposite`(:class:`DWaveSampler`())):
            Quantum sampler such as a D-Wave system. Subproblems that do not fit
            the sampler's structure are minor-embedded on the fly with
            :class:`~dwave.system.composites.AutoEmbeddingComposite`.

        anneal_schedule (list(list), optional, default=[[0, 1], [0.5, 0.5], [1, 1]]):
            An anneal schedule defined by a series of pairs of floating-point
            numbers identifying points in the schedule at which to change slope.
            The first element in the pair is time t in microseconds; the second,
            normalized persistent current s in the range [0,1]. The resulting
            schedule is the piecewise-linear curve that connects the provided
            points. For more details, see
            :meth:`~dwave.system.DWaveSampler.validate_anneal_schedule`.
    """

    def __init__(self, num_reads=100, qpu_sampler=None, anneal_schedule=None, **runopts):
        super(ReverseAnnealingAutoEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if anneal_schedule is None:
            anneal_schedule = [[0, 1], [0.5, 0.5], [1, 1]]
        self.anneal_schedule = anneal_schedule

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler(
                solver={'max_anneal_schedule_points__gte': len(self.anneal_schedule)})

        # validate schedule, raising `ValueError` on invalid schedule or
        # `RuntimeError` if anneal schedule not supported by QPU (this could
        # happen only if user provided the `qpu_sampler`)
        qpu_sampler.validate_anneal_schedule(anneal_schedule)

        # embed on fly and only if needed
        self.sampler = AutoEmbeddingComposite(qpu_sampler)

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                       "qpu_sampler={self.sampler!r}, "
                       "anneal_schedule={self.anneal_schedule!r})").format(self=self)

    def next(self, state, **runopts):
        # TODO: handle more than just the first subsample (not yet supported via API)
        subsamples = self.sampler.sample(
            state.subproblem, num_reads=self.num_reads,
            initial_state=state.subsamples.first.sample,
            anneal_schedule=self.anneal_schedule)
        return state.updated(subsamples=subsamples)
예제 #4
0
class QPUSubproblemAutoEmbeddingSampler(Runnable, traits.SubproblemSampler):
    """A quantum sampler for a subproblem with automated heuristic
    minor-embedding.

    Args:
        num_reads (int, optional, default=100):
            Number of states (output solutions) to read from the sampler.

        qpu_sampler (:class:`dimod.Sampler`, optional,
                default=:class:`AutoEmbeddingComposite`(:class:`DWaveSampler`())):
            Quantum sampler such as a D-Wave system. Subproblems that do not fit
            the sampler's structure are minor-embedded on the fly with
            :class:`~dwave.system.composites.AutoEmbeddingComposite`.

        qpu_params (dict):
            Dictionary of keyword arguments with values that will be used
            on every call of the QPU sampler.

    See :ref:`samplers-examples`.
    """
    def __init__(self,
                 num_reads=100,
                 qpu_sampler=None,
                 qpu_params=None,
                 **runopts):
        super(QPUSubproblemAutoEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()

        # embed on fly and only if needed
        self.sampler = AutoEmbeddingComposite(qpu_sampler)

        if qpu_params is None:
            qpu_params = {}
        self.qpu_params = qpu_params

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                "qpu_sampler={self.sampler!r}, "
                "qpu_params={self.qpu_params!r})").format(self=self)

    def next(self, state, **runopts):
        num_reads = runopts.get('num_reads', self.num_reads)
        qpu_params = runopts.get('qpu_params', self.qpu_params)

        params = qpu_params.copy()
        params.update(num_reads=num_reads)

        response = self.sampler.sample(state.subproblem, **params)

        return state.updated(subsamples=response)
def aws_get_response(bqm, chain_strength, num_reads):
    s3_destination_folder = ('amazon-braket-ecc806acea4c',
                             'qaExactLogisticRegression_ssato')
    dw = BraketDWaveSampler(
        s3_destination_folder,
        device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6')
    qa_sampler = AutoEmbeddingComposite(dw)
    res = qa_sampler.sample(bqm,
                            chain_strength=chain_strength,
                            chain_break_fraction=True,
                            num_reads=num_reads)
    return res
def pyqubo_response(df, param_a, param_b, param_c, num_reads, do_qbsolve):
    t_list = calc_marginals(df)

    #make H
    N = len(df)
    Y = Array.create('Y', shape=N, vartype='BINARY')
    ysum = sum(y for y in Y)
    H_0 = (ysum - t_list[0])**2

    sex = df['SEX'].values.tolist()
    sex_array = sum(s * y for s, y in zip(sex, Y))
    H_1 = (sex_array - t_list[1])**2

    aop = df['AOP'].values.tolist()
    aop_array = sum(a * y for a, y in zip(aop, Y))
    H_2 = (aop_array - t_list[2])**2

    alpha = Placeholder("alpha")
    beta = Placeholder("beta")
    gamma = Placeholder("gamma")

    H = alpha * H_0 + beta * H_1 + gamma * H_2

    #パラメータ
    feed_dict = {'alpha': param_a, 'beta': param_b, 'gamma': param_c}

    #QUBOのコンパイル
    model = H.compile()
    qubo, offset = model.to_qubo(feed_dict=feed_dict)

    if do_qbsolve == True:
        res = QBSolv().sample_qubo(qubo, num_reads=num_reads)
    else:
        s3_destination_folder = ('amazon-braket-ecc806acea4c',
                                 'qaExactLogisticRegression_ssato')
        dw = BraketDWaveSampler(
            s3_destination_folder,
            device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6')
        qa_sampler = AutoEmbeddingComposite(dw)
        res = qa_sampler.sample(bqm,
                                chain_strength=chain_strength,
                                auto_scale=True,
                                chain_break_fraction=True,
                                num_reads=num_reads)
    return res
 def p_value_transition(self, output_path):
     t1 = int(np.dot(self.df['Y'], self.df['LI']))
     t1_y = 0
     p_dic = {}
     valid_y_list = []
     for _ in range(self.n):
         s3_destination_folder = ('amazon-braket-ecc806acea4c',
                                  'qaExactLogisticRegression_ssato')
         dw = BraketDWaveSampler(
             s3_destination_folder,
             device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6')
         qa_sampler = AutoEmbeddingComposite(dw)
         res = qa_sampler.sample(self.bqm,
                                 chain_strength=self.chain_strength,
                                 chain_break_fraction=True,
                                 num_reads=self.num_reads)
         for sample, energy, num_occurrences, chain_break_fraction in res.data(
             [
                 'sample', 'energy', 'num_occurrences',
                 'chain_break_fraction'
             ]):
             if energy == 0.:
                 this_time_y = tuple(sample.values())
                 if this_time_y in valid_y_list:
                     continue
                 else:
                     valid_y_list.append(this_time_y)  #
                     this_time_y_se = pd.Series(this_time_y)
                     if int(np.dot(this_time_y_se, self.df['LI'])) == t1:
                         t1_y += 1
                         p_dic[len(valid_y_list)] = t1_y / len(valid_y_list)
     plt.xlabel('number of valid y')
     plt.ylabel('p value')
     plt.plot(list(p_dic.keys()), list(p_dic.values()))
     plt.savefig(output_path)
     plt.show()
     plt.close()
     return valid_y_list, p_dic
 def num_y_transition(self, path):
     time_list = []  #
     valid_y_num_nodup = {}
     time_0 = time.time()
     for _ in range(self.n):
         s3_destination_folder = ('amazon-braket-ecc806acea4c',
                                  'qaExactLogisticRegression_ssato')
         dw = BraketDWaveSampler(
             s3_destination_folder,
             device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6')
         qa_sampler = AutoEmbeddingComposite(dw)
         res = qa_sampler.sample(self.bqm,
                                 chain_strength=self.chain_strength,
                                 chain_break_fraction=True,
                                 num_reads=self.num_reads)
         for sample, energy, num_occurrences, chain_break_fraction in res.data(
             [
                 'sample', 'energy', 'num_occurrences',
                 'chain_break_fraction'
             ]):
             if energy == 0.:
                 sample_tuple = tuple(sample.values())
                 if sample_tuple in list(valid_y_num_nodup.keys()):
                     continue
                 else:
                     valid_y_num_nodup[sample_tuple] = 1
                     time_1 = time.time()
                     elapsed_time = time_1 - time_0
                     time_list.append(elapsed_time)
     valid_y_num_list = [i for i in range(1, len(valid_y_num_nodup) + 1)]
     plt.xlabel('time')
     plt.ylabel('number of valid y')
     plt.plot(time_list, valid_y_num_list)
     plt.savefig(path)
     plt.show()
     plt.close()
     return time_list
예제 #9
0
class ReverseAnnealingAutoEmbeddingSampler(traits.SubproblemSampler,
                                           traits.SubsamplesIntaking,
                                           traits.SISO, Runnable):
    r"""A quantum reverse annealing sampler for a subproblem with automated
    heuristic minor-embedding.

    Args:
        num_reads (int, optional, default=100):
            Number of states (output solutions) to read from the sampler.

        anneal_schedule (list(list), optional, default=[[0, 1], [0.5, 0.5], [1, 1]]):
            An anneal schedule defined by a series of pairs of floating-point
            numbers identifying points in the schedule at which to change slope.
            The first element in the pair is time t in microseconds; the second,
            normalized persistent current s in the range [0,1]. The resulting
            schedule is the piecewise-linear curve that connects the provided
            points. For more details, see
            :meth:`~dwave.system.DWaveSampler.validate_anneal_schedule`.

        qpu_sampler (:class:`dimod.Sampler`, optional):
            Quantum sampler such as a D-Wave system. Subproblems that do not fit
            the sampler's structure are minor-embedded on the fly with
            :class:`~dwave.system.composites.AutoEmbeddingComposite`.

            If sampler is not provided, it defaults to::

                qpu_sampler = DWaveSampler(
                    solver=dict(max_anneal_schedule_points__gte=len(anneal_schedule)))

        sampling_params (dict):
            Dictionary of keyword arguments with values that will be used
            on every call of the (embedding-wrapped QPU) sampler.

        auto_embedding_params (dict, optional):
            If provided, parameters are passed to the
            :class:`~dwave.system.composites.AutoEmbeddingComposite` constructor
            as keyword arguments.

    """

    def __init__(self, num_reads=100, anneal_schedule=None, qpu_sampler=None,
                 sampling_params=None, auto_embedding_params=None, **runopts):
        super(ReverseAnnealingAutoEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if anneal_schedule is None:
            anneal_schedule = [[0, 1], [0.5, 0.5], [1, 1]]
        self.anneal_schedule = anneal_schedule

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler(
                solver=dict(max_anneal_schedule_points__gte=len(self.anneal_schedule)))

        # validate schedule, raising `ValueError` on invalid schedule or
        # `RuntimeError` if anneal schedule not supported by QPU (this could
        # happen only if user provided the `qpu_sampler`)
        qpu_sampler.validate_anneal_schedule(anneal_schedule)

        if sampling_params is None:
            sampling_params = {}
        self.sampling_params = sampling_params

        # embed on the fly and only if needed
        if auto_embedding_params is None:
            auto_embedding_params = {}
        self.sampler = AutoEmbeddingComposite(qpu_sampler, **auto_embedding_params)

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                       "anneal_schedule={self.anneal_schedule!r}, "
                       "qpu_sampler={self.sampler!r}, "
                       "sampling_params={self.sampling_params!r})").format(self=self)

    def next(self, state, **runopts):
        num_reads = runopts.get('num_reads', self.num_reads)
        anneal_schedule = runopts.get('anneal_schedule', self.anneal_schedule)
        sampling_params = runopts.get('sampling_params', self.sampling_params)

        params = sampling_params.copy()
        params.update(num_reads=num_reads, anneal_schedule=anneal_schedule)

        # TODO: handle more than just the first subsample (not yet supported via API)
        subsamples = self.sampler.sample(
            state.subproblem, initial_state=state.subsamples.first.sample, **params)

        return state.updated(subsamples=subsamples)