Input six qubit but the result only have four qubit(QAOA))

OK,thank you for your reading.So why i create a circuit which has six qubit,but output a four qubit and only 0000 0010 have the result?How can i modify my code?

Best wishes!

# 
import pennylane as qml
from pennylane import numpy as np
from matplotlib import pyplot as plt
np.random.seed(42)
n_wires = 6
G = 23.5
q = 3.0
# unitary operator U_B with parameter beta
def U_B(beta):
    for wire in range(n_wires):
        qml.RX(2 * beta, wires=wire)


# unitary operator U_C with parameter gamma
def U_C(gamma):
    for wire in range(n_wires):
        wire0 = 0
        wire1 = 1
        wire2 = 2
        wire3 = 3
        wire4 = 4
        wire5 = 5

        qml.CNOT(wires=[wire0, wire1])
        qml.RZ(2 * G * gamma, wires=wire1)
        qml.CNOT(wires=[wire0, wire1])

        qml.CNOT(wires=[wire1, wire2])
        qml.RZ(2 * G * gamma, wires=wire2)
        qml.CNOT(wires=[wire1, wire2])

        qml.CNOT(wires=[wire2, wire3])
        qml.RZ(2 * G * gamma, wires=wire3)
        qml.CNOT(wires=[wire2, wire3])

        qml.CNOT(wires=[wire3, wire4])
        qml.RZ(2 * G * gamma, wires=wire4)
        qml.CNOT(wires=[wire3, wire4])

        qml.CNOT(wires=[wire4, wire5])
        qml.RZ(2 * G * gamma, wires=wire5)
        qml.CNOT(wires=[wire4, wire5])

        qml.Barrier()

        qml.CNOT(wires=[wire0, wire2])
        qml.RZ(2 * G * gamma, wires=wire2)
        qml.CNOT(wires=[wire0, wire2])
        qml.CNOT(wires=[wire1, wire3])
        qml.RZ(2 * G * gamma, wires=wire3)
        qml.CNOT(wires=[wire1, wire3])

        qml.CNOT(wires=[wire2, wire4])
        qml.RZ(2 * G * gamma, wires=wire4)
        qml.CNOT(wires=[wire2, wire4])

        qml.CNOT(wires=[wire3, wire5])
        qml.RZ(2 * G * gamma, wires=wire5)
        qml.CNOT(wires=[wire3, wire5])

        qml.Barrier()

        qml.CNOT(wires=[wire0, wire3])
        qml.RZ(2 * G * gamma, wires=wire3)
        qml.CNOT(wires=[wire0, wire3])

        qml.CNOT(wires=[wire1, wire4])
        qml.RZ(2 * G * gamma, wires=wire4)
        qml.CNOT(wires=[wire1, wire4])

        qml.CNOT(wires=[wire2, wire5])
        qml.RZ(2 * G * gamma, wires=wire5)
        qml.CNOT(wires=[wire2, wire5])

        qml.Barrier()

        qml.CNOT(wires=[wire0, wire4])
        qml.RZ(2 * G * gamma, wires=wire4)
        qml.CNOT(wires=[wire0, wire4])

        qml.CNOT(wires=[wire1, wire5])
        qml.RZ(2 * G * gamma, wires=wire5)
        qml.CNOT(wires=[wire1, wire5])

        qml.Barrier()

        qml.CNOT(wires=[wire0, wire5])
        qml.RZ(2 * G * gamma, wires=wire5)
        qml.CNOT(wires=[wire0, wire5])
        
        qml.Barrier()

        qml.RZ(2 * q * gamma, wires=wire0)
        qml.RZ(2 * q * gamma, wires=wire1)
        qml.RZ(2 * q * gamma, wires=wire2)
        qml.RZ(2 * q * gamma, wires=wire3)
        qml.RZ(2 * q * gamma, wires=wire4)
        qml.RZ(2 * q * gamma, wires=wire5)
        qml.Barrier()
def bitstring_to_int(bit_string_sample):
       bit_string = "".join(str(bs) for bs in bit_string_sample)
       return int(bit_string, base=2)
dev = qml.device("lightning.qubit", wires=n_wires, shots=1)
wire0 = [0]
wire1 = [1]
@qml.qnode(dev)
def circuit(gammas, betas,  n_layers=1):
    # apply Hadamards to get the n qubit |+> state
    for wire in range(n_wires):
        qml.Hadamard(wires=wire)
    # p instances of unitary operators
    for i in range(n_layers):
        U_C(gammas[i])
        U_B(betas[i])

    # during the optimization phase we are evaluating a term
    # in the objective using expval
    H = qml.PauliZ(wire0) @ qml.PauliZ(wire1) + qml.PauliZ(wire0)
    
    return qml.expval(H) 
def qaoa_1(n_layers=1):
    print("\np={:d}".format(n_layers))

    # initialize the parameters near zero
    init_params = 0.01 * np.random.rand(2, n_layers)

    # minimize the negative of the objective function
    def objective(params):
        gammas = params[0]
        betas = params[1]
        neg_obj = 0

        neg_obj -= circuit(gammas, betas, n_layers=n_layers)
        return neg_obj

    # initialize optimizer: Adagrad works well empirically
    opt = qml.AdagradOptimizer(stepsize=0.5)

    # optimize parameters in objective
    params = init_params
    steps = 30
    for i in range(steps):
        params = opt.step(objective, params)
        if (i + 1) % 5 == 0:
            print("Objective after step {:5d}: {: .7f}".format(i + 1, -objective(params)))

    # sample measured bitstrings 100 times
    bit_strings = []
    n_samples = 100
    for i in range(n_samples):
        bit_strings.append(abs(int(circuit(params[0], params[1], n_layers=n_layers))))

    
    bit_strings_np = np.array(bit_strings)
    bit_strings_np = np.abs(bit_strings_np)
    counts = np.bincount(bit_strings_np)
    # print optimal parameters and most frequently sampled bitstring
    most_freq_bit_string = np.argmax(counts)
    print("Optimized (gamma, beta) vectors:\n{}".format(params[:, :n_layers]))

    print("Most frequently sampled bit string is: {:04b}".format(most_freq_bit_string))

    return -objective(params), bit_strings

# perform qaoa on our graph with p=1,2 and
# keep the bitstring sample lists
bitstrings1 = qaoa_1(n_layers=1)[1]
bitstrings2 = qaoa_1(n_layers=2)[1]
import matplotlib.pyplot as plt

xticks = range(0, 16)
xtick_labels = list(map(lambda x: format(x, "04b"), xticks))     
bins = np.arange(0, 17) - 0.5

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))     
plt.subplot(1, 2, 1)
plt.title("n_layers=1")
plt.xlabel("bitstrings")
plt.ylabel("freq.")
plt.xticks(xticks, xtick_labels, rotation="vertical")
plt.hist(bitstrings1, bins=bins)
plt.subplot(1, 2, 2)
plt.title("n_layers=2")
plt.xlabel("bitstrings")
plt.ylabel("freq.")
plt.xticks(xticks, xtick_labels, rotation="vertical")
plt.hist(bitstrings2, bins=bins)
plt.tight_layout()
plt.show()
# Put full error message here
p=1
Objective after step     5:  2.0000000
Objective after step    10: -2.0000000
Objective after step    15: -0.0000000
Objective after step    20: -0.0000000
Objective after step    25: -0.0000000
Objective after step    30: -0.0000000
Optimized (gamma, beta) vectors:
[[0.0037454 ]
 [0.00950714]]
Most frequently sampled bit string is: 0000

p=2
Objective after step     5:  2.0000000
Objective after step    10: -2.0000000
Objective after step    15: -0.0000000
Objective after step    20: -2.0000000
Objective after step    25: -0.0000000
Objective after step    30: -2.0000000
Optimized (gamma, beta) vectors:
[[0.00798295 0.00649964]
 [0.00701967 0.00795793]]
Most frequently sampled bit string is: 0000
Name: PennyLane
Version: 0.33.1
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: https://github.com/PennyLaneAI/pennylane
Author: 
Author-email: 
License: Apache License 2.0
Location: d:\download\Anaconda\envs\xming\Lib\site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml, typing-extensions
Required-by: PennyLane-Lightning, pennylane-qulacs

Platform info:           Windows-11-10.0.22621-SP0
Python version:          3.12.0
Numpy version:           1.26.1
Scipy version:           1.11.3
Installed devices:
- default.gaussian (PennyLane-0.33.1)
- default.mixed (PennyLane-0.33.1)
- default.qubit (PennyLane-0.33.1)
- default.qubit.autograd (PennyLane-0.33.1)
- default.qubit.jax (PennyLane-0.33.1)
- default.qubit.legacy (PennyLane-0.33.1)
- default.qubit.tf (PennyLane-0.33.1)
- default.qubit.torch (PennyLane-0.33.1)
- default.qutrit (PennyLane-0.33.1)
- null.qubit (PennyLane-0.33.1)
- lightning.qubit (PennyLane-Lightning-0.33.1)
- qulacs.simulator (pennylane-qulacs-0.32.0)

Hey @ming,

Your output is being formatted as a length-4 binary string by writing :04b :slightly_smiling_face:. A length-6 binary string would be printed if you wrote :06b instead.

Hope this helps!

Thank you for your reply!But modify this,the result only plus two qubit|00>,all the change is add to |00>,and the frequence is not changing. it is not true.
Could you have any ideas?Please tell me.

Best wishes

It might not be what you anticipated, but it might be that that’s the result!

Maybe it would help if you use qml.sample and / or qml.counts instead? Maybe that will help clear things up :slight_smile: