def q_fast_evaluation(circ: QuantumCircuit) -> QuantumCircuit: """ Evaluation of the Q-Fast algorithm using Qskits Aer to create the unitary matrix * QFast is an approximate tool hence, its not granted to find, the correct out circuit, but a unitary, that is close => we will not assert this here * QFast doesn't allow natively to adjust the set of gates and produces circuits, that include the u/u3 gate by IBM. They claim, that this gate is one of their basic instructions, hence I would assume this as also part of the clifford+T group. :param circ: :return:, 0 """ log.warning("Evaluating Qfast") unitary = qiskit_circuit_to_zx_circuit(circ).to_matrix().astype( dtype=np.complex128) circ_qasm = qfast.synthesize(unitary) circ_ = QuantumCircuit.from_qasm_str(circ_qasm) log.warning("Done") return circ_
def run_tests(): # Register Signal Handlers signal.signal(signal.SIGALRM, term_trial) signal.signal(signal.SIGINT, term_trial) # Initialize Data Folders if not os.path.isdir(".checkpoints"): os.makedirs(".checkpoints") start_date = str(date.today()) exp_folder = ".checkpoints/" + start_date + "/" if not os.path.isdir(exp_folder): os.makedirs(exp_folder) data = {} hierarchy_fn = lambda x: 3 if x > 6 else 2 for file in os.listdir(): if os.path.isfile(file) and file[-8:] == ".unitary": name = file[:-8] utry = np.loadtxt(file, dtype=np.complex128) num_qubits = utils.get_num_qubits(utry) # Record QFAST's logger stream = StringIO() handler = logging.StreamHandler(stream) handler.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) logger.addHandler(handler) logger.info("-" * 40) logger.info(get_exp_header()) logger.info(start_date) logger.info(name) logger.info("-" * 40) soltree = SolutionTree(utry) timeout = False timeouts = { 3: 10 * 60, 4: 20 * 60, 5: 45 * 60, 6: 90 * 60, 7: 360 * 60 } signal.alarm(timeouts[num_qubits]) # Set Random Seed np.random.seed(21211411) # Run Benchmark start = timer() try: qasm = synthesize( utry, model="PermModel", hierarchy_fn=hierarchy_fn, intermediate_solution_callback=soltree.add_intermediate, model_options={ "partial_solution_callback": soltree.add_partial, "success_threshold": 1e-3 }) except TrialTerminatedException: timeout = True except: timeout = True logger.error( "Benchmark %s encountered error during execution." % name) logger.error(traceback.format_exc()) traceback.print_exc() end = timer() handler.flush() logger.removeHandler(handler) handler.close() log_out = stream.getvalue() if not timeout: data[name] = (num_qubits, qasm.count("cx"), end - start, get_error(utry, qasm), qasm, log_out, soltree) else: data[name] = (num_qubits, log_out, soltree) # Save data filenum = 0 filename = exp_folder + name + str(filenum) + ".dat" while os.path.isfile(filename): filenum += 1 filename = exp_folder + name + str(filenum) + ".dat" file = open(filename, 'wb') pickle.dump(data[name], file) # Print Summary for test in data: if len(data[test]) < 6: continue print("-" * 40) print(test) print("CX count:", data[test][1]) print("Time (s):", data[test][2]) print("Error:", data[test][3]) print("-" * 40)
"""Example synthesis of a 4-qubit QFT program using QFAST and the UQ Tool.""" import numpy as np from qfast import synthesize # You can enable verbose logging with the following two lines. # import logging # logging.getLogger( "qfast" ).setLevel( logging.DEBUG ) # Read the qft4 file in qft4 = np.loadtxt( "qft4.unitary", dtype = np.complex128 ) # Synthesize the qft4 unitary and print the resulting qasm code print( synthesize( qft4, tool = "UQTool" ) )
"""Example synthesis of a 4-qubit QFT program using QFAST with QISKit.""" import numpy as np from qfast import synthesize # You can enable verbose logging with the following two lines. # import logging # logging.getLogger( "qfast" ).setLevel( logging.DEBUG ) # Read the qft4 file in qft4 = np.loadtxt("qft4.unitary", dtype=np.complex128) # Synthesize the qft4 unitary and print the resulting qasm code print(synthesize(qft4, tool="QiskitTool", combiner="QiskitCombiner"))
"""Example synthesis of a 4-qubit QFT program using QFAST.""" import numpy as np from qfast import synthesize # You can enable verbose logging with the following two lines. # import logging # logging.getLogger( "qfast" ).setLevel( logging.DEBUG ) # Read the qft4 file in qft4 = np.loadtxt( "qft4.unitary", dtype = np.complex128 ) # Synthesize the qft4 unitary and print the resulting qasm code print( synthesize( qft4 ) )
choices = plugins.get_models(), help = "The model to use during decomposition." ) parser.add_argument( "-o", "--optimizer", type = str, default = "LFBGSOptimizer", choices = plugins.get_optimizers(), help = "The optimizer to use during decomposition." ) args = parser.parse_args() # Logger init if args.verbose == 2: logger.setLevel( logging.DEBUG ) elif args.verbose == 1: logger.setLevel( logging.INFO ) # Load input unitary try: utry = np.loadtxt( args.unitary, dtype = np.complex128 ) except Exception as ex: raise RuntimeError( "Cannot load unitary input." ) from ex qasm_out = synthesize( utry, model = args.model, optimizer = args.optimizer, tool = args.native_tool ) with open( args.qasm, "w" ) as f: f.write( qasm_out )
def synthesize_for_qiskit(utry, **kwargs): return qfast.synthesize(utry, **kwargs)
try: mkdir(output) except FileExistsError: pass qasm_iteration = 0 def print_potentials(gate_list): global qasm_iteration tool = "QSearchTool" combiner = "NaiveCombiner" instantiater = qfast.Instantiater(tool) qasm_list = instantiater.instantiate(gate_list) combiner = qfast.plugins.get_combiner(combiner)() qasm_out = combiner.combine(qasm_list) newfile = open(output + "/" + output + str(qasm_iteration) + ".qasm", "w") qasm_iteration += 1 newfile.write(str(qasm_out)) newfile.close() kwdict = {} kwdict["partial_solution_callback"] = print_potentials final_circ = str( qfast.synthesize(matrix, intermediate_solution_callback=None, model_options=kwdict)) final_file = open(output + "/" + output + str(qasm_iteration) + ".qasm", "w") final_file.write(final_circ) final_file.close()
import numpy as np from qfast import synthesize U = np.loadtxt("U.unitary", dtype=np.complex128) # U = np.array([[1, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 0, 0, 0, 0, 0, 0], # [0, 0, 1, 0, 0, 0, 0, 0], # [0, 0, 0, 1, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 1, 0], # [0, 0, 0, 0, 0, 1, 0, 0], # [0, 0, 0, 0, 1, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 1]], dtype=np.complex128) # print(U) print(synthesize(U))
""" Example synthesis of a 4-qubit QFT program using QFAST and the QSearch Tool. """ import numpy as np from qfast import synthesize # You can enable verbose logging with the following two lines. # import logging # logging.getLogger( "qfast" ).setLevel( logging.DEBUG ) # Read the qft4 file in qft4 = np.loadtxt("qft4.unitary", dtype=np.complex128) # Synthesize the qft4 unitary and print the resulting qasm code print(synthesize(qft4, tool="QSearchTool"))