Пример #1
0
def test_minimizeSPSA():
    deltatol = 1.0

    ## basic testing without stochasticity
    def quadratic(x):
        return (x**2).sum()

    res = noisyopt.minimizeSPSA(quadratic, np.asarray([0.5, 1.0]), paired=False)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    # test with callback
    def callback(x):
        assert len(x) == 2
    res = noisyopt.minimizeSPSA(quadratic, np.asarray([0.5, 1.0]), paired=False,
                                callback=callback)

    # test with output
    res = noisyopt.minimizeSPSA(quadratic, np.asarray([0.5, 1.0]), paired=False, disp=True)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    res = noisyopt.minimizeSPSA(quadratic, np.asarray([2.5, -3.2]), paired=False)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    res = noisyopt.minimizeSPSA(quadratic, np.asarray([2.5, -3.2, 0.9, 10.0, -0.3]),
                                niter=1000, paired=False)
    npt.assert_allclose(res.x, np.zeros(5), atol=deltatol)

    ## test bound handling
    res = noisyopt.minimizeSPSA(quadratic, np.asarray([0.5, 0.5]),
                            bounds=np.asarray([[0, 1], [0, 1]]),
                            paired=False)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    res = noisyopt.minimizeSPSA(quadratic, np.asarray([0.8, 0.8]),
                            bounds=np.asarray([[0.5, 1], [0.5, 1]]),
                            paired=False)
    npt.assert_allclose(res.x, [0.5, 0.5], atol=deltatol)

    # test args passing
    def quadratic_factor(x, factor):
        return factor*(x**2).sum()

    res = noisyopt.minimizeSPSA(quadratic_factor, np.asarray([0.5, 1.0]),
                                paired=False, args=(1.0,))
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    ## test errorcontrol for stochastic function
    def stochastic_quadratic(x, seed=None):
        prng = np.random if seed is None else np.random.RandomState(seed)
        return (x**2).sum() + prng.randn(1) + 0.5*np.random.randn(1)

    # test unpaired
    res = noisyopt.minimizeSPSA(stochastic_quadratic, np.array([4.55, 3.0]),
                                paired=False, niter=500)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    # test paired
    res = noisyopt.minimizeSPSA(stochastic_quadratic, np.array([4.55, 3.0]),
                            paired=True)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)
    def min_cvar(self, s=10000, beta=0.95, random_state=None):
        """
        Find the portfolio weights that minimises the CVaR, via
        Monte Carlo sampling from the return distribution.

        :param s: number of bootstrap draws, defaults to 10000
        :type s: int, optional
        :param beta: "significance level" (i. 1 - q), defaults to 0.95
        :type beta: float, optional
        :param random_state: seed for random sampling, defaults to None
        :type random_state: int, optional
        :return: asset weights for the Sharpe-maximising portfolio
        :rtype: dict
        """
        args = (self.returns, s, beta, random_state)
        result = noisyopt.minimizeSPSA(
            objective_functions.negative_cvar,
            args=args,
            bounds=self.bounds,
            x0=self.initial_guess,
            niter=1000,
            paired=False,
        )
        self.weights = CVAROpt._normalize_weights(result["x"])
        return dict(zip(self.tickers, self.weights))
Пример #3
0
    def min_cvar(self, s=10000, beta=0.95, random_state=None):
        """
        Find the portfolio weights that minimises the CVaR, via
        Monte Carlo sampling from the return distribution.

        :param s: number of bootstrap draws, defaults to 10000
        :type s: int, optional
        :param beta: "significance level" (i. 1 - q), defaults to 0.95
        :type beta: float, optional
        :param random_state: seed for random sampling, defaults to None
        :type random_state: int, optional
        :return: asset weights for the Sharpe-maximising portfolio
        :rtype: dict
        """
        args = (self.returns, s, beta, random_state)
        result = noisyopt.minimizeSPSA(
            objective_functions.negative_cvar,
            args=args,
            bounds=self.bounds,
            x0=self.initial_guess,
            niter=1000,
            paired=False,
        )
        self.weights = self.normalize_weights(result["x"])
        return dict(zip(self.tickers, self.weights))
Пример #4
0
    def minimize(self):
        # NelderMead requires an initial point
        if self.x0 is None:
            self.x0 = self.domain.l + self.domain._range / 2

        res = minimizeSPSA(self.f,
                           bounds=self.domain.bounds,
                           x0=self.x0,
                           niter=self.config.niter,
                           paired=False,
                           a=self.config.a,
                           c=self.config.c)
def train(train_data, train_labels, mod, params=None):
    """
    """

    # Set hyperparameters:
    # batch_size = 25
    # lam = .33
    # eta = 1.0
    # num_iterations = 200
    # a = .2
    # c = .2
    batch_size = 25
    lam = .234
    eta = 5.59
    num_iterations = 10
    a = 33.0
    c = 28.0
    alpha = 0.658
    gamma = 4.13

    n = len(train_data[0])
    print("n: %d" % n)

    #Save parameters
    if params is None:
        params = list(2 * math.pi * np.random.rand(mod.count))
    dim = len(params)
    print("Number of parameters in circuit: %d " % dim)

    bounds = (np.zeros(dim), 2 * math.pi * np.ones(dim))

    args = (train_data, train_labels, lam, eta, batch_size)
    result = minimizeSPSA(mod.get_loss,
                          args=args,
                          x0=params,
                          paired=True,
                          niter=num_iterations,
                          a=a,
                          alpha=alpha,
                          c=c,
                          gamma=gamma,
                          disp=False,
                          callback=utils.save_params)  #, bound=bounds)

    #    xopt, fopt = pso(model.get_loss, bounds[0], bounds[1], args=(n, train_data, train_labels, lam, eta, batch_size), swarmsize=swarm_size, maxiter=num_epochs)'
    print(result)
    params = result.x
    print("number of training circuit runs = ", mod.num_runs)
    return params, mod
def main():
    if (len(sys.argv) != 3):
        usage("Incorrect number of arguments")

    numIters = int(sys.argv[1])
    depth = int(sys.argv[2])
    analyticJs = np.linspace(0, 1, 500)
    evaluateJs = np.linspace(0, 1, 5)
    true_e = []
    evaluated_e = []
    for j in analyticJs:
        b = 1
        H = analyticSolution.buildHamiltonian(j, b)
        vals, vecs = np.linalg.eig(H)
        minIndex = np.argmin(vals)
        true_e.append(vals[minIndex])

    for j in evaluateJs:
        print("J/B Ratio : {}".format(j))
        b = 1
        thetas = np.random.uniform(0, 2 * pi, size=((depth + 1) * 8, ))
        result = minimizeSPSA(circuits.costFnx,
                              thetas, (j, depth),
                              paired=False,
                              niter=numIters)
        print("Optimizer message: {}".format(result.message))
        evaluated_e.append(circuits.costFnx(result.x, j, depth))
    plt.plot(analyticJs, true_e, label="True ground state energy")
    plt.scatter(evaluateJs,
                evaluated_e,
                label="Ground state energy from VQE",
                c="r")
    plt.xlabel(r"$J/B$")
    plt.ylabel(r"Energy (a.u)")
    plt.title("Ground state energy of four site Heisenberg Model")
    plt.legend()
    plt.show()
Пример #7
0
def do_experiment(theta,hamiltonian,parameters):
    """
    Use variational quantum eigensovler (VQE) to obtain ground state energy of the Hamiltonian.
    Energies at each step evaluated by running a quatnum circuit.

    Parameters
        theta (np.array) : Initial guesses for the ground state wavefunction theta parameters.

        hamiltonian : Deuteron Hamiltonian. See src/hamiltonian.py for class definitions.

        parameters (dictionary) : Input parameters for VQE.

    Returns
        res (scipy.optimize.OptimizeResult) : Results of VQE

    """
    # Set up backend
    backend = Aer.get_backend(parameters['backend'])
    device = None
    noise_model = None
    if parameters['device_name'] is not None:
        if ( parameters['device_name'][0:6] == "custom" ):
            noise_model = noise.NoiseModel()
            errors = parameters['device_name'].split("_")
            error1 = float(errors[1])
            error2 = float(errors[2])
            error_1 = noise.errors.depolarizing_error(error1, 1)
            error_2 = noise.errors.depolarizing_error(error2, 2)
            noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3'])
            noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
        else:
            if parameters['mitigate_meas_error']:
                device = Device(parameters['device_name'], True, hamiltonian.N_qubits, layout=parameters['layout'])
            else:
                device = Device(parameters['device_name'], False, hamiltonian.N_qubits, layout=parameters['layout'])

    if device is not None:
        print("Device specifications")
        pprint(vars(device))

    number_cnot_pairs = 0
    if( "number_cnot_pairs" in parameters ): number_cnot_pairs = parameters['number_cnot_pairs']
    number_circuit_folding = 0
    if( "number_circuit_folding" in parameters ): number_cnot_pairs = parameters['number_circuit_folding']
    zero_noise_extrapolation=False
    if( "zero_noise_extrapolation" in parameters): zero_noise_extrapolation = parameters['zero_noise_extrapolation']

    # Run the minimization routine
    if parameters['optimizer'] != 'SPSA':
        if parameters['optimizer'] == 'MIGRAD': # iminuit option
            res = iminimize(compute_energy, theta,
                    args=(backend, hamiltonian,
                        device,
                        noise_model,
                        parameters['N_shots'],
                        number_cnot_pairs,
                        number_circuit_folding,
                        zero_noise_extrapolation),
                    method=parameters['optimizer'], options={'maxfev':parameters['N_iter']})
            # Display diagnostic information:
            # res = iminimize(compute_energy, theta, args=(backend, hamiltonian, device), method=parameters['optimizer'], options={'maxfev':parameters['N_iter'],'disp':True})
        else:
            # "Regular" scipy optimizers
            res = minimize(compute_energy, theta,
                    args=(backend, hamiltonian,
                        device,
                        noise_model,
                        parameters['N_shots'],
                        number_cnot_pairs,
                        number_circuit_folding,
                        zero_noise_extrapolation),
                    method=parameters['optimizer'], options={'maxiter':parameters['N_iter']})
    else:
        res = minimizeSPSA(compute_energy,
                x0=theta,
                args=(backend, hamiltonian,
                    device,
                    noise_model,
                    parameters['N_shots'],
                    number_cnot_pairs,
                    number_circuit_folding,
                    zero_noise_extrapolation),
                niter=parameters['N_iter'],
                paired=False,
                a=parameters['spsa_a'],
                c=parameters['spsa_c'],
        )

    return res
Пример #8
0
# This is a minimal usage example for the optimization routines
# see also http://noisyopt.readthedocs.io/en/latest/tutorial.html

import numpy as np
from noisyopt import minimizeCompass, minimizeSPSA


# definition of noisy function to be optimized
def obj(x):
    return (x**2).sum() + 0.1 * np.random.randn()


bounds = [[-3.0, 3.0], [0.5, 5.0]]
x0 = np.array([-2.0, 2.0])
res = minimizeCompass(obj, bounds=bounds, x0=x0, deltatol=0.1, paired=False)
print(res)

res = minimizeSPSA(obj, bounds=bounds, x0=x0, niter=1000, paired=False)
print(res)
Пример #9
0
def test_minimizeSPSA():
    deltatol = 1.0

    ## basic testing without stochasticity
    def quadratic(x):
        return (x**2).sum()

    res = noisyopt.minimizeSPSA(quadratic,
                                np.asarray([0.5, 1.0]),
                                paired=False)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    # test with callback
    def callback(x):
        assert len(x) == 2

    res = noisyopt.minimizeSPSA(quadratic,
                                np.asarray([0.5, 1.0]),
                                paired=False,
                                callback=callback)

    # test with output
    res = noisyopt.minimizeSPSA(quadratic,
                                np.asarray([0.5, 1.0]),
                                paired=False,
                                disp=True)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    res = noisyopt.minimizeSPSA(quadratic,
                                np.asarray([2.5, -3.2]),
                                paired=False)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    res = noisyopt.minimizeSPSA(quadratic,
                                np.asarray([2.5, -3.2, 0.9, 10.0, -0.3]),
                                niter=1000,
                                paired=False)
    npt.assert_allclose(res.x, np.zeros(5), atol=deltatol)

    ## test bound handling
    res = noisyopt.minimizeSPSA(quadratic,
                                np.asarray([0.5, 0.5]),
                                bounds=np.asarray([[0, 1], [0, 1]]),
                                paired=False)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    res = noisyopt.minimizeSPSA(quadratic,
                                np.asarray([0.8, 0.8]),
                                bounds=np.asarray([[0.5, 1], [0.5, 1]]),
                                paired=False)
    npt.assert_allclose(res.x, [0.5, 0.5], atol=deltatol)

    # test args passing
    def quadratic_factor(x, factor):
        return factor * (x**2).sum()

    res = noisyopt.minimizeSPSA(quadratic_factor,
                                np.asarray([0.5, 1.0]),
                                paired=False,
                                args=(1.0, ))
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    ## test errorcontrol for stochastic function
    def stochastic_quadratic(x, seed=None):
        prng = np.random if seed is None else np.random.RandomState(seed)
        return (x**2).sum() + prng.randn(1) + 0.5 * np.random.randn(1)

    # test unpaired
    res = noisyopt.minimizeSPSA(stochastic_quadratic,
                                np.array([4.55, 3.0]),
                                paired=False,
                                niter=500)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)

    # test paired
    res = noisyopt.minimizeSPSA(stochastic_quadratic,
                                np.array([4.55, 3.0]),
                                paired=True)
    npt.assert_allclose(res.x, [0.0, 0.0], atol=deltatol)
Пример #10
0
                h[i][j] = np.array([[1, 0], [0, -1]])
            elif h[i][j] == "i":
                h[i][j] = np.array([[1, 0], [0, 1]])
    full = np.zeros(shape=(2**len(h[0]), 2**len(h[0]))).astype('complex128')
    for i in range(len(h)):
        op = np.kron(h[i][0], h[i][1])
        for j in range(2, len(h[i])):
            op = np.kron(op, h[i][j])
        full += (w[i] * op)
    eig = np.real(np.linalg.eigvals(full))
    print(full.shape)
    return min(eig)


opt = minimize(vqe,
               np.random.uniform(0, 2 * np.pi, q * lay),
               method='Nelder-Mead')
print("NM", opt['fun'])
opt = minimize(vqe, np.random.uniform(0, 2 * np.pi, q * lay), method='COBYLA')
print("COBYLA", opt['fun'])
opt = opt = minimizeSPSA(vqe,
                         bounds=[[0, 2 * np.pi] for _ in range(q * lay)],
                         x0=np.random.uniform(0, 2 * np.pi, q * lay),
                         niter=200,
                         paired=False)
print("SPSA", opt['fun'])
opt = rotosolve(vqe, q * lay)
print("Rotosolve", opt['fun'])

print("Real min:", real_min(hamilton, h_weights))
Пример #11
0
def Run_SPSA():

    
    for l in range(len(simulation_budget)) :
        
        OP.sim_budget = simulation_budget[l]
        simulation_length = simulation_budget[l]
        print " Simulation length = ",simulation_length
        RESULTS.append([])


        for trial in range(NUM_TRIALS):
            
            #set simulation_length for this optimization:
            OP.sim_length = simulation_length

            print "\tOptimization Run = ",trial,
            x_start = initial_guesses[trial]

            #clear the count of objective function evaluations.
            OP.objective_function_count=0
            
            t_start = time.time()

            #perform an optimization run
            res  = minimizeSPSA(func=OP.ObjectiveFunction, 
				x0=x_start,
                                bounds=OP.bounds,
                                paired=False,
                                niter=500,
				disp=False)
            t_end=time.time()

            #round x_opt to the nearest decimal point,
            #and clip it to lie within the domain 
            
            x_opt = OP.Round(OP.Clip(res.x))
            
            #compute results, using the best possible simulation_length:
            OP.sim_length = sim_length_best

            fevals = OP.objective_function_count-1 
            f_opt = OP.ObjectiveFunction(x_opt)
            throughput_opt = OP.NormalizedThroughput(x_opt)
            cost_opt = OP.NormalizedCost(x_opt)
            opt_time = t_end - t_start
            
            print "\t fevals = ", fevals,"\t time = ",opt_time
            
            #package the result into  a tuple
            R = Result(x_opt, f_opt, throughput_opt, cost_opt, fevals, opt_time)

            RESULTS[l].append(R)
    
    print " =============================================================="
    #write the Result array out to a file
    fname = "RESULTS_SPSA.py"
    print " Printing results to file",fname,"..."
    results_file = open(fname, "w")
    print >>results_file, "from collections import namedtuple"
    print >>results_file, "Result = namedtuple('Result', 'x_opt f_opt throughput_opt cost_opt fevals time')"
    print >>results_file, "RESULTS=",RESULTS
    print " Done."
    print " ==============================================================="
    results_file.close()
        print(i, len(all_coeff))
        coeff = all_coeff[i]
        readout_operators = sum(
            hamiltonian(qubits, coeff[0], coeff[1], coeff[2], coeff[3],
                        coeff[4], coeff[5]))
        ins = tf.keras.layers.Input(shape=(), dtype=tf.dtypes.string)
        outs = tfq.layers.PQC(vqe_circuit, readout_operators,
                              repetitions=1000)(ins)
        vqe = tf.keras.models.Model(inputs=ins, outputs=outs)
        opt = minimize(f,
                       np.random.uniform(0, 2 * np.pi, 1),
                       method='Nelder-Mead')
        nm.append(opt['fun'])
        opt = minimizeSPSA(f,
                           bounds=[[0, 2 * np.pi]],
                           x0=np.random.uniform(0, 2 * np.pi, 1),
                           niter=200,
                           paired=False)
        spsa.append(opt['fun'])
        opt = rotosolve(f, 1)
        roto.append(opt['fun'])
    nms.append(nm)
    spsas.append(spsa)
    rotos.append(roto)

fig, ax = plt.subplots()

avg = np.mean(np.array(nms), axis=0)
plt.plot(dist, avg, color='red', label='NM')
plus = avg + np.std(avg, axis=0)
minus = avg - np.std(avg, axis=0)
    where 'method' has to be one of {'entropy', 'lbp', 'cluster'}
    """
    if sys.argv[1] == "run":
        method = sys.argv[2]
        RESULTS_JSON = []
        #method = 'entropy' # the method used for comparison. One of {'lbp', 'cluster', 'entropy'}
        num_repetitions = 10  # number of runs with different random seeds per parameter combination and per dataset
        bounds = [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0],
                  [0.0, 1.0]]  # bounds for the parameters to be estimated
        x0 = np.array([0.25, 0.25, 0.25, 0.25])  # initial guess for parameters

        # simultaneous perturbation stochastic approximation algorithm
        result = minimizeSPSA(objective_function,
                              x0,
                              args=(num_repetitions, method),
                              bounds=bounds,
                              niter=200,
                              paired=False)

        save_json(method)

        print(result)
    """
    Load and analyse the results from parameter estimation.

    Usage: python3 parameter_estimation.py load method/file_name.json [--plot]

    where the second argument specifies which results to load.
    If --plot is given, the seating patterns are plotted and saved for all datasets individually.
    """
    if sys.argv[1] == "load":
Пример #14
0
# This is a minimal usage example for the optimization routines
# see also http://noisyopt.readthedocs.io/en/latest/tutorial.html

import numpy as np
from noisyopt import minimizeCompass, minimizeSPSA

# definition of noisy function to be optimized
def obj(x):
    return (x**2).sum() + 0.1*np.random.randn()

bounds = [[-3.0, 3.0], [0.5, 5.0]]
x0 = np.array([-2.0, 2.0])
res = minimizeCompass(obj, bounds=bounds, x0=x0, deltatol=0.1, paired=False)
print(res)

res = minimizeSPSA(obj, bounds=bounds, x0=x0, niter=1000, paired=False)
print(res)
Пример #15
0
# strongly on the specific problem), [#spall_implementation]_ includes
# guidelines for the selection. In our case, the initial values for :math:`c`
# and :math:`a` were selected as a result of a grid search to ensure a fast
# convergence.  We further note that apart from :math:`c` and :math:`a`, there
# are further coefficients that are initialized in the ``noisyopt`` package
# using the
# previously mentioned guidelines.
#
# Our cost function does not take a seed as a keyword argument (which would be
# the default behaviour for ``minimizeSPSA``), so we set ``paired=False``.
#
res = minimizeSPSA(
    cost_spsa,
    x0=init_params_spsa.copy(),
    niter=niter_spsa,
    paired=False,
    c=0.15,
    a=0.2,
    callback=callback_fn,
)

##############################################################################
# .. rst-class:: sphx-glr-script-out
#
#  Out:
#
#  .. code-block:: none
#
#     Iteration = 10, Number of device executions = 14, Cost = 0.09
#     Iteration = 20, Number of device executions = 29, Cost = -0.638
#     Iteration = 30, Number of device executions = 44, Cost = -0.842