ProjectQ-Framework / ProjectQ

ProjectQ: An open source software framework for quantum computing
https://projectq.ch
Apache License 2.0
876 stars 271 forks source link

Decomposition of Toffoli gate #350

Closed monica1131 closed 3 years ago

monica1131 commented 4 years ago

Im new to Quantum computing, Im trying to execute decomposition of the Toffoli gate can you please help me with how to decompose a n bit Toffoli gate or 2bit controlled qubit Toffoli gate with the code

dbretaud commented 4 years ago

Hi, here is the most basic example below: we run a circuit with one Toffoli gate that we decompose via the restrictedgateset setup. If you would like to adapt it to a n bit Toffoli gate you just have to use the 'with Control' statement: https://projectq.readthedocs.io/en/latest/projectq.meta.html#projectq.meta.Control

from projectq import MainEngine  # import the main compiler engine
from projectq.ops import Toffoli, Measure  # import the operations you want to perform (For now just Toffoli and Measure)
from projectq.setups import restrictedgateset
from projectq.cengines import DummyEngine

def circuit(eng):
    #basic example with 3 qubits circuit
    Q1 = eng.allocate_qubit()
    Q2 = eng.allocate_qubit()
    Q3 = eng.allocate_qubit()
    #code to insert before Toffoli gate
    Toffoli | (Q1,Q2,Q3)
    #code to insert after Toffoli gate
    Measure | Q1
    Measure | Q2
    Measure | Q3
    eng.flush()
    return 0

Dummy=DummyEngine(save_commands=True) # allow to display decomposed circuit
engines=restrictedgateset.get_engine_list() # generic decomposer to any single and two qubit gates
#Note: you can change the parameter of get_engine_list to precise which gate set you want to decompose
#the toffoli gate
Meng = MainEngine(Dummy,engine_list=engines)
circuit(Meng) #run the circuit defined above
for cmd in Dummy.received_commands:
    print(cmd.to_string(symbols=True)) #display the decomposed circuit
monica1131 commented 4 years ago

When I tried running the code it gives me an error

AttributeError Traceback (most recent call last)

in 25 circuit(Meng) #run the circuit defined above 26 for cmd in Dummy.received_commands: ---> 27 print(cmd.to_string(symbols=True)) #display the decomposed circuit AttributeError: 'Command' object has no attribute 'to_string'
dbretaud commented 4 years ago

The 'to_string()' function was implemented in the last commit. You can just replace with the str() function:

for cmd in Dummy.received_commands:
    print(str(cmd)) #display the decomposed circuit
Takishima commented 3 years ago

This should not be an issue in the current version of ProjectQ anymore. Closing this issue.