Example #1
0
def estimate_gradient(f_h, precision, n_measurements=50, cxn=False):
    """ Estimate the gradient from point of evaluation
        to point of perturbation, h

    :param float f_h: Oracle output at perturbation h.
    :param int precision: Bit precision of gradient.
    :param Connection cxn: connection to the QPU or QVM
    :param int n_measurements: Number of times to measure system.
    """

    # enumerate input and ancilla qubits
    input_qubits = list(range(precision))
    ancilla_qubit = precision

    # generate gradient program
    perturbation_sign = np.sign(f_h)
    p_gradient = gradient_estimator(abs(f_h), ancilla_qubit)

    # run gradient program
    if not cxn:
        from pyquil.api import SyncConnection
        cxn = SyncConnection()
    measurements = cxn.run(p_gradient, input_qubits, n_measurements)

    # summarize measurements
    bf_estimate = perturbation_sign * measurements_to_bf(measurements)
    bf_explicit = '{0:.16f}'.format(bf_estimate)
    deci_estimate = binary_to_real(bf_explicit)

    return deci_estimate
def test_binary_to_real():
    precision = 9
    decimal_rep = 0.345703125
    binary_rep = 0.010110001

    decimal_convert = binary_to_real(binary_rep)

    assert (np.isclose(decimal_rep, decimal_convert))
Example #3
0
def test_binary_to_real():
    for sign in [1, -1]:
        decimal_rep = sign * 0.345703125
        binary_rep = str(sign * 0.010110001)

        decimal_convert = binary_to_real(binary_rep)

        assert (np.isclose(decimal_rep, decimal_convert))
Example #4
0
def estimate_gradient(f_h,
                      precision,
                      gradient_max=1,
                      n_measurements=50,
                      cxn=None):
    """Estimate the gradient using function evaluation at perturbation, h

    :param float f_h: Oracle output at perturbation h.
    :param int precision: Bit precision of gradient.
    :param int gradient_max: OOM estimate of largest gradient value
    :param int n_measurements: Number of times to measure system.
    :param Connection cxn: Connection to the QPU or QVM.
    :return: Decimal estimate of gradient.
    :rtype: float
    """

    # scale f_h by range of values gradient can take on
    f_h *= 1. / gradient_max

    # generate gradient program
    perturbation_sign = np.sign(f_h)
    p_gradient = gradient_program(f_h, precision)

    # run gradient program
    if cxn is None:
        from pyquil.api import QVMConnection
        cxn = QVMConnection()
    measured_qubits = list(range(precision + 1))
    measurements = cxn.run(p_gradient, measured_qubits, n_measurements)

    # summarize measurements
    bf_estimate = perturbation_sign * measurements_to_bf(measurements)
    bf_explicit = '{0:.16f}'.format(bf_estimate)
    deci_estimate = binary_to_real(bf_explicit)

    # rescale gradient
    deci_estimate *= gradient_max

    return deci_estimate