### Basic Hello World with QuantumString Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Examples/HelloWorld.rst Initialize a QuantumString, assign the string 'hello world' to it, and print the result. This is a fundamental example for getting started with QRISP. ```python from qrisp import QuantumString q_str = QuantumString() q_str[:] = "hello world" print(q_str) ``` -------------------------------- ### QAOA M$\kappa$CS Example Implementation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/maxKColorableSubgraph.rst This snippet demonstrates the full setup and execution of QAOA for the Max-K-Colorable Subgraph problem. It includes graph creation, color definition, QAOA problem initialization, setting an initial state, running the QAOA algorithm, and processing the results. ```python from qrisp import QuantumArray from qrisp.qaoa import QAOAProblem, RX_mixer, apply_XY_mixer, QuantumColor, create_coloring_cl_cost_function, create_coloring_operator import networkx as nx import random from operator import itemgetter G = nx.Graph() G.add_edges_from([[0,1],[0,4],[1,2],[1,3],[1,4],[2,3],[3,4]]) color_list = ["red", "blue", "orange", "green"] qarg = QuantumArray(qtype = QuantumColor(color_list, one_hot_enc=True), shape = G.number_of_nodes()) #qarg = QuantumArray(qtype = QuantumColor(color_list, one_hot_enc=False), shape = G.number_of_nodes()) # use one_hot_enc=False for binary encoding qaoa_coloring = QAOAProblem(cost_operator=create_coloring_operator(G), mixer=apply_XY_mixer, # use RX_mixer for binary encoding cl_cost_function=create_coloring_cl_cost_function(G)) init_state = [random.choice(color_list) for _ in range(len(G))] qaoa_coloring.set_init_function(lambda x : x.encode(init_state)) result = qaoa_coloring.run(qarg, depth=3, max_iter=50) ``` ```python cl_cost =create_coloring_cl_cost_function(G) print("5 most likely solutions") max_five = sorted(result.items(), key=lambda item: item[1], reverse=True)[:5] for res, prob in max_five: print(res, prob, cl_cost({res : 1})) ``` ```python best_of_five = min([(cl_cost({item[0]:1}),item[0]) for item in max_five], key=itemgetter(0))[1] x.draw(G, with_labels=True, font_color='white', node_size=1000, font_size=22, node_color=[best_of_five[node] for node in G.nodes()], edge_color='#D3D3D3') ``` -------------------------------- ### Run Documentation Server with sphinx-autobuild Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/README.md Navigate to the documentation folder and execute this command to start a local server for live previewing documentation changes. Ensure sphinx-autobuild is installed. ```bash sphinx-autobuild source build/html --open-browser ``` -------------------------------- ### Initialize IQM Backend Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/tutorial.ipynb Connect to an IQM device using the IQM interface. Ensure qrisp is installed with the IQM extra: pip install qrisp[iqm]. Replace 'IQM_RESONANCE_API_TOKEN' with your actual API token. ```python # Make sure to install qrisp with the IQM interface: pip install qrisp[iqm] # from qrisp.interface import IQMBackend # iqm_garnet = IQMBackend(api_token = "IQM_RESONANCE_API_TOKEN", # device_instance = "garnet") # results = qch.get_measurement(backend = iqm_garnet) # print(results) ``` -------------------------------- ### Install Documentation Dependencies and Build HTML Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/README.md These commands are used to install the necessary Python packages and system dependencies for documentation, and then to generate the final HTML output for the documentation pages. ```bash make docs-install ``` ```bash make html ``` -------------------------------- ### BackendServer.start Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/generated/qrisp.interface.qunicorn.BackendServer.start.rst Starts the backend server. This method is part of the qrisp.interface.qunicorn.BackendServer class. ```APIDOC ## BackendServer.start ### Description Starts the backend server. This method is part of the qrisp.interface.qunicorn.BackendServer class. ### Method Signature `start()` ``` -------------------------------- ### Install Qrisp with IQM Dependencies Source: https://github.com/eclipse-qrisp/qrisp/blob/main/README.md Install Qrisp with additional dependencies for working with IQM quantum computers. ```bash pip install qrisp[iqm] ``` -------------------------------- ### Install Qrisp using pip Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/setup.rst Use this command to install Qrisp. Ensure you have Python 3.11 or 3.12 installed. ```bash pip install qrisp ``` -------------------------------- ### BackendServer.start Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/BackendServer.rst Starts the BackendServer. This method is used to initiate the server's operations. ```APIDOC ## BackendServer.start ### Description Starts the BackendServer. ### Method This is a method call within the BackendServer class. ### Parameters This method does not explicitly list any parameters in the documentation. ### Request Example ```python backend_server.start() ``` ### Response This method does not explicitly document a return value or response structure. ``` -------------------------------- ### QPE Test Case Setup Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/tutorial.ipynb Sets up a test case for the QPE function with a custom unitary U and a QuantumVariable psi. Requires numpy. ```python from qrisp import p, QuantumVariable, multi_measurement import numpy as np def U(psi): phi_1 = 0.5 phi_2 = 0.125 p(phi_1 * 2 * np.pi, psi[0]) p(phi_2 * 2 * np.pi, psi[1]) psi = QuantumVariable(2) h(psi) res = QPE(psi, U, 3) ``` -------------------------------- ### Full Code Example for Hamiltonian Simulation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/H2.ipynb A complete example demonstrating Hamiltonian simulation, including loading molecular data, initializing the quantum state, performing the simulation, and evaluating the number operator's expectation value. ```python # Loading molecular data from qrisp.operators import a, c, FermionicOperator from pyscf import gto mol = gto.M(atom="""H 0 0 0; H 0 0 0.74""", basis="sto-3g") H_ferm = FermionicOperator.from_pyscf(mol) # Initializing the quantum state and performing Hamiltonian simulation from qrisp import QuantumVariable U = H_ferm.trotterization() def state_prep(): electron_state = QuantumVariable(4) electron_state[:] = {"1100": 2**-0.5, "0001": 2**-0.5} U(electron_state, t=100, steps=20) return electron_state # Evaluating the number operator N = sum(c(i) * a(i) for i in range(4)) expectation_value = N.expectation_value(state_prep, precision=0.01)() print(expectation_value) ``` -------------------------------- ### E3Lin2 QAOA Problem Setup and Run Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/eThrLinTwo.rst Sets up the E3Lin2 problem with a specified number of variables and clauses, then runs the QAOA algorithm. Consider using 'init_type="tqa"' for potential performance improvements. ```python from qrisp import QuantumVariable from qrisp.qaoa import QAOAProblem, RX_mixer, create_e3lin2_cl_cost_function, create_e3lin2_cost_operator clauses = [[0,1,2,1],[1,2,3,0],[0,1,4,0],[0,2,4,1],[2,4,5,1],[1,3,5,1],[2,3,4,0]] num_variables = 6 qarg = QuantumVariable(num_variables) qaoa_e3lin2 = QAOAProblem(cost_operator=create_e3lin2_cost_operator(clauses), mixer=RX_mixer, cl_cost_function=create_e3lin2_cl_cost_function(clauses)) results = qaoa_e3lin2.run(qarg, depth=5) ``` -------------------------------- ### Example QAOA MinSetCover Implementation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/minSetCover.rst This snippet demonstrates how to set up and run the QAOA for the Minimum Set Cover problem. It defines the sets, universe, and initializes the QAOAProblem with specific functions for mixer, cost, and initial state. ```python from qrisp import QuantumVariable from qrisp.qaoa import QAOAProblem, RZ_mixer, create_min_set_cover_mixer, create_min_set_cover_cl_cost_function, min_set_cover_init_function sets = [{0,1,2,3},{1,5,6,4},{0,2,6,3,4,5},{3,4,0,1},{1,2,3,0},{1}] universe = set.union(*sets) qarg = QuantumVariable(len(sets)) qaoa_min_set_cover = QAOAProblem(cost_operator=RZ_mixer, mixer= create_min_set_cover_mixer(sets, universe), cl_cost_function=create_min_set_cover_cl_cost_function(sets, universe), init_function=min_set_cover_init_function) results = qaoa_min_set_cover.run(qarg, depth=5) ``` -------------------------------- ### Use MQTSim with QuantumFloat Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/DockerSimulators.rst Example demonstrating the use of `MQTSim` backend with `QuantumFloat` for quantum computations. Ensure to provide the `shots` argument in `get_measurement`. ```python from qrisp import QuantumFloat a = QuantumFloat(3) a[:] = 3 b = QuantumFloat(3) b[:] = 4 c = a*b from qrisp.interface import MQTSim c.get_measurement(backend = MQTSim(), shots = 1000) ``` -------------------------------- ### BackendServer Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/index.rst This class is a wrapper for convenient setup of a server capable of processing quantum circuits. Providers need to create a 'run_func' that accepts a QuantumCircuit, shots, and an optional token, returning measurement results. ```APIDOC ## BackendServer ### Description This class wraps the setup for a server that can process quantum circuits. It requires a Python function `run_func` which takes a :ref:`QuantumCircuit`, an integer `shots`, and an optional string `token`. The function should return measurement results as a dictionary of bitstrings. ### Usage ```python from qrisp.interface import BackendServer from backend_provider import run_func, ping_func server = BackendServer( run_func, port = 8080) server.start() ``` ``` -------------------------------- ### Example: Quantum-Quantum Comparison Evaluation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/Sudoku.ipynb Demonstrates the usage of `eval_qq_checks` with a QuantumArray and a list of comparison pairs. Prints the resulting QuantumBools indicating equality. ```python q_assigments = QuantumArray(qtype=QuantumFloat(2), shape=(3,)) q_assigments[:] = [3, 2, 3] comparison_bools = eval_qq_checks([(0, 1), (0, 2), (1, 2)], q_assigments) for qbl in comparison_bools: print(qbl) # Yields # {False: 1.0} # {True: 1.0} # {False: 1.0} ``` -------------------------------- ### Connect to a Backend Server Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/index.rst Connect to a BackendServer using BackendClient to send requests for processing quantum circuits. This example shows connecting to a server and then querying a remote backend with a quantum algorithm. ```python from qrisp.interface import BackendClient backend = BackendClient(server_ip, port) from some_library import some_quantum_algorithm qv = some_quantum_algorithm() res = qv.get_measurement(backend = backend) ``` -------------------------------- ### Start a Backend Server Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/index.rst Use BackendServer to wrap a Python function for processing quantum circuits. The function should accept a QuantumCircuit, shots, and an optional token, returning measurement results. ```python from qrisp.interface import BackendServer from backend_provider import run_func, ping_func server = BackendServer( run_func, port = 8080) server.start() ``` -------------------------------- ### Classical Matrix Arithmetic Example Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/index.rst Demonstrates how classical matrix operations can be translated to QRISp's Block Encoding syntax for operator manipulation. ```python # Classical: C = I + A - 2*A^2 + B^(-1) C = np.eye(4) + A - 2 * A @ A + np.linalg.inv(B) ``` ```python # Qrisp: B_C = B_A.poly([1., 1., -2.]) + B_B.inv(epsilon, kappa) ``` -------------------------------- ### Example Usage: Compute Average Cut Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/JaspQAOAtutorial.ipynb Demonstrates how to create a sample graph, define the post-processor, and compute the average cut for a given set of sample bipartitions. ```python # Create a sample graph G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 0), (1, 3)]) # Create the post processor function post_processor = create_sample_array_post_processor(G) # Sample input array representing different cuts sample_array = jnp.array( [0b0001, 0b0010, 0b0100, 0b1000] ) # Example binary representations # Compute the average cut average_cut = post_processor(sample_array) print("Average Cut:", average_cut) ``` -------------------------------- ### Run QAOA for QUBO and Post-process Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/QAOAtutorial/QUBO.ipynb Example of running the QAOA algorithm for a QUBO problem and performing classical post-processing. This includes defining the QUBO matrix, quantum arguments, running the instance, and sorting solutions by cost. ```python from qrisp.default_backend import def_backend from qrisp import QuantumVariable, QuantumArray from operator import itemgetter Q = np.array( [ [-17, 20, 20, 20, 0, 40], [0, -18, 20, 20, 20, 40], [0, 0, -29, 20, 40, 40], [0, 0, 0, -19, 20, 20], [0, 0, 0, 0, -17, 20], [0, 0, 0, 0, 0, -28], ] ) qarg = QuantumArray(qtype=QuantumVariable(1), shape=len(Q)) QUBO_instance = QUBO_problem(Q) depth = 1 res = QUBO_instance.run(qarg, depth, mes_kwargs={"backend": def_backend}, max_iter=50) costs_and_solutions = [(QUBO_obj(bitstring, Q), bitstring) for bitstring in res.keys()] sorted_costs_and_solutions = sorted(costs_and_solutions, key=itemgetter(0)) for i in range(5): print( ``` -------------------------------- ### Initialize QuantumBacktrackingTree and Plotting Setup Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/Sudoku.ipynb Initializes a `QuantumBacktrackingTree` with a specified maximum depth and branch variable type, using the previously defined `accept` and `reject` functions. It also sets up a matplotlib figure for plotting. ```python tree = QuantumBacktrackingTree( max_depth=3, branch_qv=QuantumFloat(1), # Use 1 qubit variable for a binary tree. accept=accept, reject=reject ) tree.init_node([]) # Initialize tree in the |root> = |[0,0,0]>|3> state. # Create a figure with 2 rows and 2 columns. fig, axs = plt.subplots(2, 2, figsize=(12, 8)) axs = axs.flatten() # Flatten to iterate easily: 0, 1, 2, 3. ``` -------------------------------- ### Example QUBO Matrix (Symmetric) Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/QAOAtutorial/QUBO.ipynb A sample symmetric QUBO matrix for the set partitioning problem used in the tutorial. This matrix is used to demonstrate QUBO to QAOA conversion. ```python Q_sym = np.array( [ [-17, 10, 10, 10, 0, 20], [10, -18, 10, 10, 10, 20], [10, 10, -29, 10, 20, 20], [10, 10, 10, -19, 10, 10], [0, 10, 20, 10, -17, 10], [20, 20, 20, 10, 10, -28], ] ) ``` -------------------------------- ### Run Qrisp Simulator Docker Container Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/DockerSimulators.rst Start the Qrisp simulator collection Docker container, exposing necessary ports for Qrisp to communicate with the simulators. Use `arm-version` if on an ARM-based CPU. ```console docker run -p 8083:8083 -p 8084:8084 -p 8085:8085 -p 8086:8086 -p 8087:8087 -p 8088:8088 -p 8089:8089 -p 8090:8090 -p 8091:8091 -p 8092:8092 qrisp/qrisp_sim_collection:x86-version ``` -------------------------------- ### QIRO MaxClique Example Implementation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qiro/implementations/QIROMaxClique.rst This snippet shows how to initialize and run the QIRO MaxClique algorithm with a defined graph and quantum variable. It sets up the QIRO problem with specific routines and parameters, then executes the QIRO instance. ```python from qrisp import QuantumVariable from qrisp.qiro import QIROProblem, create_max_clique_replacement_routine, create_max_clique_cost_operator_reduced, qiro_rx_mixer, qiro_init_function from qrisp.qaoa import max_clique_problem, create_max_clique_cl_cost_function import matplotlib.pyplot as plt import networkx as nx # Define a random graph via the number of nodes and the QuantumVariable arguments num_nodes = 15 G = nx.erdos_renyi_graph(num_nodes, 0.7, seed=99) qarg = QuantumVariable(G.number_of_nodes()) # QIRO qiro_instance = QIROProblem(problem=G, replacement_routine= reate_max_clique_replacement_routine, cost_operator=create_max_clique_cost_operator_reduced, mixer=qiro_rx_mixer, cl_cost_function=create_max_clique_cl_cost_function, init_function=qiro_init_function ) res_qiro = qiro_instance.run_qiro(qarg=qarg, depth=3, n_recursions=2) # The final graph that has been adjusted final_graph = qiro_instance.problem ``` -------------------------------- ### Define QUBO Matrix and Problem Size Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/CD.ipynb Initializes the QUBO matrix 'Q' and determines the number of qubits 'N' required for the problem. This setup is crucial for defining the optimization problem. ```python import numpy as np Q = np.array([[-1.1, 0.6, 0.4, 0.0, 0.0, 0.0], [0.6, -0.9, 0.5, 0.0, 0.0, 0.0], [0.4, 0.5, -1.0, -0.6, 0.0, 0.0], [0.0, 0.0, -0.6, -0.5, 0.6, 0.0], [0.0, 0.0, 0.0, 0.6, -0.3, 0.5], [0.0, 0.0, 0.0, 0.0, 0.5, -0.4]]) N = Q.shape[0] ``` -------------------------------- ### Quantum Modulo Division Example Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Examples/QuantumModDivision.rst Use this snippet to perform quantum modulo division. It requires importing QuantumFloat, q_divmod, and multi_measurement from qrisp. Ensure numbers are defined and encoded before division. ```python from qrisp import QuantumFloat, q_divmod, multi_measurement numerator = QuantumFloat(5) numerator[:] = 13 divisor = QuantumFloat(5) divisor[:] = 4 quotient, remainder = q_divmod(numerator, divisor) print(multi_measurement([quotient, remainder])) ``` -------------------------------- ### QAOA MaxClique Problem Setup and Execution Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/maxClique.rst This snippet demonstrates how to set up and run a QAOA problem for finding the maximum clique. It requires importing necessary components from `qrisp` and `networkx`. The MaxClique problem is solved by applying QAOA to the complement graph's Max Independent Set formulation. Ensure `networkx` is installed for graph operations. ```python from qrisp import QuantumVariable from qrisp.qaoa import QAOAProblem, RZ_mixer, create_max_indep_set_cl_cost_function, create_max_indep_set_mixer, max_indep_set_init_function import networkx as nx G = nx.erdos_renyi_graph(9, 0.7, seed = 133) G_complement = nx.complement(G) qarg = QuantumVariable(G.number_of_nodes()) qaoa_max_clique = QAOAProblem(cost_operator=RZ_mixer, mixer=create_max_indep_set_mixer(G_complement), cl_cost_function=create_max_indep_set_cl_cost_function(G_complement), init_function=max_indep_set_init_function) results = qaoa_max_clique.run(qarg, depth=5) ``` -------------------------------- ### Benchmark QAOA with TQA Warm-Start Initialization Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/QAOAtutorial/MaxCut.ipynb Utilize the `benchmark` method with `init_type='tqa'` to leverage TQA warm-start initialization for QAOA performance evaluation. This method also requires the `optimal_solution` for approximation ratio calculation and provides detailed performance metrics. ```python print("TQA") benchmark_data = maxcut_instance.benchmark( qarg=QuantumVariable(len(G)), depth_range=[1, 2, 3, 4, 5], shot_range=[1000, 10000], iter_range=[100, 200], optimal_solution="00011", repetitions=1, init_type="tqa", ) temp = benchmark_data.rank(print_res=True) _, tqaFO = benchmark_data.evaluate() print("Approximation ratio: ", sum(tqaFO) / len(tqaFO)) print("Variance: ", np.var(tqaFO)) ``` -------------------------------- ### Compare Block Encoding Resource Estimates Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/BE_tutorial/BE_vol1.ipynb This example shows two different resource estimates for block encodings, likely representing different construction methods. It is used to illustrate the efficiency differences between methods. ```python {'gate counts': {'u3': 6, 's': 6, 'p': 2, 't': 18, 'h': 22, 't_dg': 20, 'cx': 72, 'x': 5, 'gphase': 2, 'measure': 6}, 'depth': 60, 'qubits': 11} ``` ```python {'gate counts': {'x': 15, 'p': 7, 't': 48, 'cy': 14, 'gphase': 2, 't_dg': 64, 'u3': 30, 'cx': 156, 'h': 32}, 'depth': 220, 'qubits': 12} ``` ```python {'gate counts': {'x': 5, 's': 6, 'p': 2, 't': 18, 'gphase': 2, 't_dg': 20, 'u3': 6, 'cx': 72, 'h': 22, 'measure': 6}, 'depth': 60, 'qubits': 11} ``` -------------------------------- ### Install Catalyst Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/Jasp.ipynb Install the pennylane-catalyst package if it's not already available. This is typically needed for compiling Jasp to QIR. ```python try: import catalyst except: !pip install pennylane-catalyst ``` -------------------------------- ### Instantiate and Apply the Oracle Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/tutorial.ipynb Create a QuantumFloat, apply the `sqrt_oracle` to it, and then print the resulting quantum circuit representation using the `.qs` attribute. ```python qf = QuantumFloat(3, -1, signed=True) sqrt_oracle(qf) print(qf.qs) ``` -------------------------------- ### Initialize and Run QAOA for Portfolio Rebalancing Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/QAOAtutorial/PortfolioRebalancing.ipynb Initializes the QAOAProblem and QuantumArray instances, then runs the optimization process with a specified depth. ```python # assign QuantumArray to operate on from qrisp import QuantumVariable, QuantumArray qv = QuantumVariable(n_assets) q_array = QuantumArray(qtype=qv, shape=(2)) # run the problem! theproblem = QAOAProblem( cost_operator=cost_op, mixer=mixer_op, cl_cost_function=cl_cost ) theproblem.set_init_function(init_fun) theNiceQAOA = theproblem.run(q_array, depth=3) ``` -------------------------------- ### Generate Python Bindings for JASP MLIR Dialect Source: https://github.com/eclipse-qrisp/qrisp/blob/main/src/qrisp/jasp/mlir/dialect_definition/README.md Command to generate Python bindings for JASP MLIR dialect operations using `mlir-tblgen`. Ensure MLIR is installed and `mlir-tblgen` is in your PATH. Replace the MLIR include path with your specific installation. ```bash mlir-tblgen JaspPythonOps.td \ -gen-python-op-bindings \ -bind-dialect=jasp \ -I /path/to/llvm-project/mlir/include \ -I . \ -o ../dialect_implementation/_jasp_ops_gen.py ``` -------------------------------- ### QAOA MaxIndepSet Problem Setup and Execution Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/maxIndepSet.rst Sets up and runs the QAOA algorithm for the Maximum Independent Set problem. Requires importing necessary components from qrisp and networkx. The results are then processed to display the most likely solutions and their costs. ```python from qrisp import QuantumVariable from qrisp.qaoa import QAOAProblem, RZ_mixer, create_max_indep_set_cl_cost_function, create_max_indep_set_mixer, max_indep_set_init_function import networkx as nx G = nx.erdos_renyi_graph(9, 0.5, seed = 133) qarg = QuantumVariable(G.number_of_nodes()) qaoa_max_indep_set = QAOAProblem(cost_operator=RZ_mixer, mixer=create_max_indep_set_mixer(G), cl_cost_function=create_max_indep_set_cl_cost_function(G), init_function=max_indep_set_init_function) results = qaoa_max_indep_set.run(qarg, depth=5) ``` ```python cl_cost = create_max_indep_set_cl_cost_function(G) print("5 most likely solutions") max_five = sorted(results.items(), key=lambda item: item[1], reverse=True)[:5] for res, prob in max_five: print([index for index, value in enumerate(res) if value == '1'], prob, cl_cost({res : 1})) ``` -------------------------------- ### QuantumVariable Measurement Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Core/QuantumVariable.rst Gets the measurement outcome of the QuantumVariable. ```APIDOC ## QuantumVariable.get_measurement ### Description Retrieves the measurement outcome of the QuantumVariable. ### Method get_measurement ``` -------------------------------- ### MaxSetPacking QAOA Implementation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/maxSetPack.rst This snippet demonstrates how to set up and run the QAOA for the MaxSetPacking problem. It involves creating the constraint graph, initializing the QAOA problem with appropriate cost and mixer functions, and running the algorithm. ```python from qrisp import QuantumVariable from qrisp.qaoa import QAOAProblem, RZ_mixer, create_max_indep_set_cl_cost_function, create_max_indep_set_mixer, max_indep_set_init_function import networkx as nx from itertools import combinations sets = [{0,7,1},{6,5},{2,3},{5,4},{8,7,0},{1}] def non_empty_intersection(sets): return [(i, j) for (i, s1), (j, s2) in combinations(enumerate(sets), 2) if s1.intersection(s2)] # create constraint graph G = nx.Graph() G.add_nodes_from(range(len(sets))) G.add_edges_from(non_empty_intersection(sets)) qarg = QuantumVariable(G.number_of_nodes()) qaoa_max_indep_set = QAOAProblem(cost_operator=RZ_mixer, mixer=create_max_indep_set_mixer(G), cl_cost_function=create_max_indep_set_cl_cost_function(G), init_function=max_indep_set_init_function) results = qaoa_max_indep_set.run(qarg, depth=5) ``` -------------------------------- ### Import Matplotlib Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/BigInteger.ipynb Imports the matplotlib library for plotting. This is a common setup for data visualization in Python. ```python import matplotlib.pyplot as plt ``` -------------------------------- ### BackendClient.__init__ Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Backend Interface/BackendClient.rst Initializes the BackendClient. ```APIDOC ## BackendClient.__init__ ### Description Initializes the BackendClient. ### Method __init__ ### Parameters This method does not take any explicit parameters beyond `self`. ``` -------------------------------- ### Example Usage of eval_cq_checks Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/Sudoku.ipynb Demonstrates how to use the eval_cq_checks function with sample quantum assignments and comparison data. ```python q_assigments = QuantumArray(qtype=QuantumFloat(2), shape=(3,)) q_assigments[:] = np.arange(3) res_qbls = eval_cq_checks({0: [1, 2, 3], 1: [1, 2, 3], 2: [1, 2, 3]}, q_assigments) for qbl in res_qbls: print(qbl) ``` -------------------------------- ### Instantiate and Run QAOAProblem for Max Cut Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/QAOAtutorial/MaxCut.ipynb Instantiates the QAOAProblem class with the Max Cut cost operator and mixer, then runs the simulation. Requires importing QAOAProblem and RX_mixer. ```python from qrisp.qaoa import QAOAProblem, RX_mixer maxcut_instance = QAOAProblem(apply_cost_operator, RX_mixer, maxcut_cost_funct) res = maxcut_instance.run(qarg, depth, max_iter=50) # runs the simulation ``` -------------------------------- ### Get Number of Qubits Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Core/Uncomputation.rst Retrieves the total number of qubits currently allocated in the compiled quantum circuit. ```python compiled_qc.num_qubits() 6 ``` -------------------------------- ### Compile QuantumSession and Get Depth Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/TSP.ipynb Compile a QuantumSession to a QuantumCircuit and retrieve its depth. This is used for performance evaluation. ```python qpe_compiled_qc = perm_specifiers[0].qs.compile() qpe_compiled_qc.depth() ``` ```text Result: 1989 ``` -------------------------------- ### Run QAOA Optimization and Visualize Solution Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/QAOAtutorial/MaxCut.ipynb Initializes QAOA parameters, uses COBYLA optimizer to find optimal angles, retrieves the best solution, and visualizes the graph coloring based on the best cut. ```python import numpy as np from scipy.optimize import minimize from operator import itemgetter init_point = np.pi * np.random.rand(2 * p) res_sample = minimize( quantum_objective, init_point, method="COBYLA", options={"maxiter": 50} ) optimal_theta = res_sample["x"] qv_p = QuantumVariable(N) qv = apply_p_layers(qv_p, optimal_theta[:p], optimal_theta[p:]) results = qv_p.get_measurement() best_cut, best_solution = min( [(maxcut_obj(x), x) for x in results.keys()], key=itemgetter(0) ) print(f"Best string: {best_solution} with cut: {-best_cut}") colors = ["r" if best_solution[node] == "0" else "b" for node in G] x.draw( G, with_labels=True, font_color="white", node_size=1000, font_size=22, node_color=colors, pos=nx.bipartite_layout(G, [node for node in G if best_solution[node] == "0"]), ) ``` -------------------------------- ### QuantumBacktrackingTree.init_phi Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/generated/qrisp.quantum_backtracking.QuantumBacktrackingTree.init_phi.rst Initializes the phi parameter for the QuantumBacktrackingTree. This method is part of the internal setup for the quantum backtracking algorithm. ```APIDOC ## QuantumBacktrackingTree.init_phi ### Description Initializes the phi parameter for the QuantumBacktrackingTree. This method is part of the internal setup for the quantum backtracking algorithm. ### Method `init_phi()` ### Parameters This method does not accept any parameters. ``` -------------------------------- ### QuantumVariable.get_measurement Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Core/generated/qrisp.QuantumVariable.get_measurement.rst Retrieves the measurement of the QuantumVariable. This method is used to get the classical outcome of a quantum measurement performed on the variable. ```APIDOC ## QuantumVariable.get_measurement ### Description Retrieves the measurement of the QuantumVariable. This method is used to get the classical outcome of a quantum measurement performed on the variable. ### Method `get_measurement()` ### Parameters This method does not take any parameters. ### Returns - The classical outcome of the measurement (e.g., 0 or 1 for a qubit). ``` -------------------------------- ### Initialize and Operate on QuantumVariable Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/index.rst Demonstrates the basic usage of QuantumVariable, including initialization, applying gates, and printing the variable's state. Ensure QuantumVariable, h, and cx are imported. ```python from qrisp import QuantumVariable, h, cx qv = QuantumVariable(3) h(qv[0]) cx(qv[0], qv[1]) cx(qv[1], qv[2]) print(qv) # Outcome: {'000': 0.5, '111': 0.5} ``` -------------------------------- ### Import necessary libraries Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/QAOAtutorial/PortfolioRebalancing.ipynb Imports libraries required for the example implementation, including scikit-learn for preprocessing and numpy for numerical operations. ```python # imports import sklearn from sklearn import preprocessing # Add explicit import for preprocessing import numpy as np ``` -------------------------------- ### QuantumSession Management and Backend Integration Source: https://context7.com/eclipse-qrisp/qrisp/llms.txt Shows how to set up a QuantumSession with a backend, attach variables, perform operations, and observe automatic session merging. ```python from qrisp import QuantumSession, QuantumFloat, merge from qrisp.interface import QiskitBackend from qiskit_aer import AerSimulator # Create a session targeting the Aer simulator backend = QiskitBackend(AerSimulator()) qs = QuantumSession(backend=backend) # Attach variables to a specific session qf = QuantumFloat(4, qs=qs) qf[:] = 5 res = qf * qf # Evaluate on the bound backend print(res.get_measurement()) # {25: 1.0} # Sessions from different variables auto-merge on entanglement qa = QuantumFloat(3) qb = QuantumFloat(3) print(qa.qs == qb.qs) # False from qrisp import cx cx(qa[0], qb[0]) print(qa.qs == qb.qs) # True — sessions merged automatically # Compile to an optimised QuantumCircuit qc = qa.qs.compile() print(f"Qubits: {qc.num_qubits()}, Depth: {qc.depth()}") ``` -------------------------------- ### Get QuantumSession Statevector Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/tutorial.ipynb Retrieve the statevector of the quantum circuit managed by the QuantumSession. This provides a detailed view of the quantum state. ```python qch.qs.statevector() ``` -------------------------------- ### Example Usage of check_sudoku_assignments (Invalid Case) Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/Sudoku.ipynb Demonstrates checking a Sudoku board with invalid quantum assignments, expecting a False result. ```python # Another check q_assignments = QuantumArray(qtype=QuantumFloat(2), shape=(4,)) q_assignments[:] = [1, 2, 1, 0] sudoku_check = check_sudoku_assignments(sudoku_board, q_assignments) print(sudoku_check) # Yields {False: 1.0} ``` -------------------------------- ### QAOA MaxCut Problem Setup and Execution Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/maxCut.rst Sets up and runs the QAOA algorithm for the MaxCut problem. Requires `networkx` for graph creation and `qrisp` for quantum components. The `depth` and `max_iter` parameters control the QAOA circuit depth and classical optimization iterations. ```python from qrisp import QuantumVariable from qrisp.qaoa import QAOAProblem, RX_mixer, create_maxcut_cl_cost_function, create_maxcut_cost_operator import networkx as nx G = nx.erdos_renyi_graph(6, 0.7, seed = 133) qarg = QuantumVariable(G.number_of_nodes()) qaoa_maxcut = QAOAProblem(cost_operator=create_maxcut_cost_operator(G), mixer=RX_mixer, cl_cost_function=create_maxcut_cl_cost_function(G)) results = qaoa_maxcut.run(qarg, depth=5, max_iter=50) ``` -------------------------------- ### Example Usage of check_sudoku_assignments (Valid Case) Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/Sudoku.ipynb Demonstrates checking a Sudoku board with valid quantum assignments, expecting a True result. ```python q_assignments = QuantumArray(qtype=QuantumFloat(2), shape=(4,)) q_assignments[:] = [1, 1, 1, 2] sudoku_check = check_sudoku_assignments(sudoku_board, q_assignments) print(sudoku_check) # Yields {True: 1.0} ``` -------------------------------- ### Get Number of Qubits in Compiled Circuit Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/TSP.ipynb Determine the number of qubits utilized in a compiled QuantumCircuit. This is a fundamental measure of resource usage. ```python qdict_compiled_qc.num_qubits() ``` ```text Result: 18 ``` -------------------------------- ### Run COLD Algorithm and Print Results Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/CD.ipynb Executes the COLD algorithm using the configured DCQOProblem instance. It involves setting up quantum variables, simulation parameters, and optimization bounds. The results, including probabilities and costs of different states, are then printed. ```python from qrisp import QuantumVariable qarg = QuantumVariable(N) N_steps = 4 T = 8 method = "COLD" N_opt = 1 bounds = (-3, 3) result = cold_problem.run(qarg, N_steps, T, method, N_opt, bounds=bounds) print(result) ``` -------------------------------- ### Set Up Hamiltonians for COLD Algorithm Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/CD.ipynb Defines the initial, problem, and control Hamiltonians required for the COLD algorithm. These Hamiltonians are constructed using Qrisp's operator library. ```python from qrisp.operators.qubit import X, Y, Z h = -0.5 * np.diag(Q) - 0.5 * np.sum(Q, axis=1) J = 0.5 * Q H_init = 1 * sum([X(i) for i in range(N)]) H_prob = (sum([sum([J[i][j]*Z(i)*Z(j) for j in range(i)]) for i in range(N)]) + sum([h[i]*Z(i) for i in range(N)])) H_control = sum([Z(i) for i in range(N)]) ``` -------------------------------- ### Grover's Algorithm Implementation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/general/tutorial/tutorial.ipynb Embeds a constructed oracle into Grover's algorithm. Requires prior setup of QuantumFloat and superposition. ```python from math import pi from qrisp.grover import diffuser qf = QuantumFloat(3, -1, signed=True) n = qf.size iterations = int(0.25 * pi * (2**n / 2) ** 0.5) h(qf) for i in range(iterations): sqrt_oracle(qf) diffuser(qf) print(qf) ``` -------------------------------- ### MaxSat QAOA Problem Setup and Execution Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qaoa/implementations/maxSat.rst Sets up a MaxSat problem with specified clauses and variables, then initializes and runs a QAOAProblem object. This snippet requires the qrisp library and its QAOA components. The `run` method returns a dictionary of solutions and their probabilities. ```python from qrisp import QuantumVariable from qrisp.qaoa import QAOAProblem, RX_mixer, create_maxsat_cl_cost_function, create_maxsat_cost_operator clauses = [[1,2,-3],[1,4,-6],[4,5,6],[1,3,-4],[2,4,5],[1,3,5],[-2,-3,6]] num_vars = 6 problem = (num_vars, clauses) qarg = QuantumVariable(num_vars) qaoa_max_indep_set = QAOAProblem(cost_operator=create_maxsat_cost_operator(problem), mixer=RX_mixer, cl_cost_function=create_maxsat_cl_cost_function(problem)) results = qaoa_max_indep_set.run(qarg, depth=5) ``` -------------------------------- ### QIRO Max Independent Set Example Implementation Source: https://github.com/eclipse-qrisp/qrisp/blob/main/documentation/source/reference/Algorithms/qiro/implementations/QIROMaxIndep.rst This code demonstrates how to set up and run the QIRO algorithm for the maximum independent set problem using qRISP. It defines a graph, initializes the QIROProblem with specific routines, and runs the algorithm. It also prints the top solutions and compares them with a NetworkX solution. ```python from qrisp import QuantumVariable from qrisp.qiro import QIROProblem, create_max_indep_replacement_routine, create_max_indep_cost_operator_reduced, qiro_rx_mixer, qiro_init_function from qrisp.qaoa import create_max_indep_set_cl_cost_function import matplotlib.pyplot as plt import networkx as nx # Define a random graph via the number of nodes and the QuantumVariable arguments num_nodes = 13 G = nx.erdos_renyi_graph(num_nodes, 0.4, seed = 107) qarg = QuantumVariable(G.number_of_nodes()) qiro_instance = QIROProblem(G, replacement_routine=create_max_indep_replacement_routine, cost_operator=create_max_indep_cost_operator_reduced, mixer=qiro_rx_mixer, cl_cost_function=create_max_indep_set_cl_cost_function, init_function=qiro_init_function ) res_qiro = qiro_instance.run_qiro(qarg=qarg, depth=3, n_recursions=2) ``` ```python cl_cost = create_max_indep_set_cl_cost_function(G) print("5 most likely QIRO solutions") max_five_qiro = sorted(res_qiro, key=res_qiro.get, reverse=True)[:5] for res in max_five_qiro: print([index for index, value in enumerate(res) if value == '1']) print(cl_cost({res : 1})) print("Networkx solution") print(nx.approximation.maximum_independent_set(G)) ``` ```python # The final graph that has been adjusted final_graph = qiro_instance.problem # Draw the final graph and the original graph for comparison plt.figure(1) nx.draw(final_graph, with_labels=True, node_color='#ADD8E6', edge_color='#D3D3D3') plt.title('Final QIRO graph') plt.figure(2) most_likely = [index for index, value in enumerate(max_five_qiro[0]) if value == '1'] nx.draw(G, with_labels=True, node_color=['#FFCCCB' if node in most_likely else '#ADD8E6' for node in G.nodes()], edge_color='#D3D3D3') plt.title('Original graph with most likely QIRO solution') plt.show() ```