Qiskit / qiskit-aer

Aer is a high performance simulator for quantum circuits that includes noise models
https://qiskit.github.io/qiskit-aer/
Apache License 2.0
480 stars 354 forks source link

TypeError: (): incompatible function arguments. AerConfig, arg0: list[list[tuple[tuple[int, int], list[float]]]]) -> None #2195

Open nabdak opened 1 month ago

nabdak commented 1 month ago

Informations

Maybe this is not considered a bug, but it stopped my work for a week while I was in many tries to solve it with no change except for different types of errors.

What is the current behavior?

`TypeError: (): incompatible function arguments. The following argument types are supported:

  1. (self: qiskit_aer.backends.controller_wrappers.AerConfig, arg0: list[list[tuple[tuple[int, int], list[float]]]]) -> None

Invoked with: <qiskit_aer.backends.controller_wrappers.AerConfig object at 0x000001C4AAA431B0>, [[[(4, 0), 0.7853981852531433], [(5, 0), 0.7853981852531433], [(6, 0), 0.7853981852531433], [(7, 0), 0.7853981852531433], [(11, 0), 0.7853981852531433], [(12, 0), 0.7853981852531433], [(13, 0), 0.7853981852531433], [(14, 0), 0.7853981852531433]]]`

even if I changed it to param_binds = [{str(self.thetas[k]) : params[k].item() for k in range(NUM_QUBITS)}], it keeps rejecting the second part for "TypeError: object of type 'float' has no len()", then with changing the second part to param_binds = [{str(self.thetas[k]) : torch.Tensor([params[k].item()]) for k in range(NUM_QUBITS)}] , TypeError: ParameterExpression with unbound parameters (dict_keys([Parameter(Theta0)])) cannot be cast to a float.

now all my tries went to vain, and I need to use the updated versions of the libraries, because there are functions I need in my real project that is perfectly served with the new versions of the libraries.

Steps to reproduce the problem

I got the code from this repository , aiming to branch it but I need it to work first, so then I can add my updates on. However, in the function run, there is always this error no matter what how I change it, there will be an error. `def run(self, i): params = i print('params = {}'.format(len(params))) backend = Aer.get_backend('qasm_simulator')

    ''' param_binds = [[{_:_}] for _ in range(NUM_QUBITS)] 
    for k in range(NUM_QUBITS) :   
        param_binds[k]=({(self.thetas[k]) : params[k].item()})
    param_binds = [{}]
    for k in range(NUM_QUBITS) :   
        param_binds[(self.thetas[k])] = params[k].item()
    param_binds = []
    for k in range(self.n_qubits):
          param_binds.append({str(self.thetas[k]): torch.tensor([params[k].item()])})'''
    param_binds = [{self.thetas[k] : params[k].item() for k in range(NUM_QUBITS)}]
    print(param_binds)

    job_sim = backend.run(self.circuit,
                          shots=self.shots,
                          parameter_binds = param_binds)#[{self.thetas[k] : params[k].item() for k in range(2*NUM_QUBITS)}])

    result_sim = job_sim.result()
    counts = result_sim.get_counts(self.circuit)
    return self.N_qubit_expectation_Z(counts,self.shots,NUM_QUBITS)`

'''

What is the expected behavior?

It is supposed to create the circuit and provide an illustration to it as it appears in the link above.

Suggested solutions

I know that the solution is to use the old versions, but I need the new versions in the same project too. Thus, I need to know what is the solution to represent the parameter list dynamically for the job to continue the work. Other files in the project link if using parameter lists like param_binds = [{'theta': self.beta, 'phi': self.gamma}] are working good. However, it always fails when it comes to dynamically assigning param_binds. Any solutions?

doichanj commented 1 month ago

Could you please provide full script to reproduce the issue?

nabdak commented 1 month ago

Could you please provide full script to reproduce the issue?

The full script of the code I want to branch is in this link to be branched , except that I am working on the latest updated libraries of qiskit, qiskit_aer, numpy, and torch. The execute function is deprecated already, thus we need to change it to run. I tried to attach the file as I modified it to work on the recent updates of the libraries, but it is not supported.

in tab ## 3. Contruct QuantumCircuit Class, I modified run user defined function as the following:

#modified run
    def run(self, i):
        params = i
        print('params = {}'.format(len(params)))
        backend = Aer.get_backend('qasm_simulator')        
        param_binds = [{(self.thetas[k]) : torch.Tensor([params[k].item()]) for k in range(NUM_QUBITS)}]
        print(param_binds)
        job_sim = backend.run(self.circuit,
                              shots=self.shots,
                              parameter_binds = param_binds)
        result_sim = job_sim.result()
        counts = result_sim.get_counts(self.circuit)
        return self.N_qubit_expectation_Z(counts,self.shots,NUM_QUBITS)

When I try to run its following instructions

circuit = QiskitCircuit(NUM_QUBITS, SIMULATOR, NUM_SHOTS)
print('Expected value for rotation [pi/4]: {}'.format(circuit.run(torch.Tensor([np.pi/4]*NUM_QUBITS))))
circuit.circuit.draw(output='mpl', filename='Figures/{}-qubit circuit ryN.jpg'.format(NUM_QUBITS))

it shows the following error:

TypeError: (): incompatible function arguments. The following argument types are supported:
    1. (self: qiskit_aer.backends.controller_wrappers.AerConfig, arg0: list[list[tuple[tuple[int, int], list[float]]]]) -> None
Invoked with: <qiskit_aer.backends.controller_wrappers.AerConfig object at 0x000001F4DCE92630>, [[[(4, 0), tensor([0.7854])], [(5, 0), tensor([0.7854])], [(6, 0), tensor([0.7854])], [(7, 0), tensor([0.7854])], [(11, 0), tensor([0.7854])], [(12, 0), tensor([0.7854])], [(13, 0), tensor([0.7854])], [(14, 0), tensor([0.7854])]]]
doichanj commented 1 month ago

could you provide simple complete script (can be executed by python test.py) to reproduce the issue?

nabdak commented 1 month ago

could you provide simple complete script (can be executed by python test.py) to reproduce the issue?

I am sorry .. actually I didn't use it in a .py file.. and I was trying to re-run the jupyter notebook I shared its link earlier. Anyway, that was a real problem in the aerbackend.py file. Either correct or not, but this was the updates I made so that the notebook worked for me.

`

append_param_value

    def append_param_values(index, bind_pos, param):
        if param in binds:
            parameterizations.append([(index, bind_pos), binds[param]])
        elif isinstance(param, ParameterExpression):
            # If parameter expression has no unbound parameters
            # it's already bound and should be skipped
            if not param.parameters:
                return
            if not binds:
                raise AerError("The element of parameter_binds is empty.")
            len_vals = len(binds.values())
            bind_list = []
            for i in range(len_vals):
                bind_dict = {}
                for parameter in  binds.keys():
                    for params in param.parameters :
                        if str(parameter)==str(params):
                            if isinstance(binds[parameter], float):
                                bind_dict[params] = binds[parameter]
                        break
                bind_list.append(bind_dict)
            bound_values = [float(param.bind(x)) for x in bind_list]
            parameterizations.append([(index, bind_pos), bound_values])

`