### Install Metal-Quantum from Source Source: https://github.com/masa-whitestone/metal-quantum/blob/main/README.md Builds the native Metal library from source before installing the Python package. ```bash git clone https://github.com/masa-whitestone/metal-quantum.git cd metal-quantum # Compile native Metal library cd native && make && cd .. # Install Python package pip install -e . ``` -------------------------------- ### Install Package Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CLAUDE.md Installs the package in editable mode for development. ```bash pip install -e . ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CONTRIBUTING.md Install the necessary development dependencies for the project. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install Metal-Quantum from Source Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/installation.md Install the Python package in editable mode after cloning and compiling the native library. ```bash pip install -e . ``` -------------------------------- ### Verify Metal-Quantum Installation Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/installation.md Run this Python script to verify that Metal-Quantum has been installed correctly by executing a simple quantum circuit. ```python from metalq import Circuit, run # Create a small circuit pc = Circuit(2) pc.h(0) pc.cx(0, 1) # Run on MPS backend result = run(qc, shots=100) print(result.counts) ``` -------------------------------- ### Install Metal-Quantum from PyPI Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/installation.md Use this command to install the latest stable version of Metal-Quantum using pip. ```bash pip install metalq ``` -------------------------------- ### Clone Metal-Quantum Repository Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/installation.md Clone the Metal-Quantum repository from GitHub to install from source. ```bash git clone https://github.com/masa-whitestone/metal-quantum.git cd metal-quantum ``` -------------------------------- ### Safe MkDocs Configuration Example Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/SECURITY.md Use this template to ensure documentation settings remain secure by restricting plugins, extensions, and navigation paths. ```yaml site_name: Metal-Q Documentation site_url: https://example.com/metalq # Use HTTPS URLs only repo_url: https://github.com/user/repo edit_uri: edit/main/docs/ # Only use trusted themes theme: name: material # Don't use custom_dir with external paths # Whitelist plugins explicitly plugins: - search - mkdocstrings: handlers: python: options: show_source: false # Don't expose source code # Safe navigation - relative paths only nav: - Home: index.md - Guide: guide/intro.md # Don't use: ../../../etc/passwd # Safe markdown extensions markdown_extensions: - admonition - codehilite # Don't use: markdown_include (can include arbitrary files) ``` -------------------------------- ### Build Native Libraries Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CONTRIBUTING.md Clean and install the native libraries required for the project. ```bash make clean && make install ``` -------------------------------- ### Audit Log Format Example Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/SECURITY.md Example of the security event log entries generated in docs_security_audit.log. ```text 2024-01-15 10:30:45 - SECURITY - Validating MkDocs configuration: mkdocs.yml 2024-01-15 10:30:45 - SECURITY - Configuration validation passed 2024-01-15 10:30:46 - SECURITY - Created sandbox: /tmp/metalq_docs_sandbox_abc123 2024-01-15 10:30:46 - SECURITY - Sandbox prepared successfully 2024-01-15 10:30:55 - SECURITY - Documentation built successfully 2024-01-15 10:30:55 - SECURITY - Sandbox cleaned up ``` -------------------------------- ### Compile Native Metal Library Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/installation.md Compile the native Metal library as part of the source installation process. ```bash cd native && make && cd .. ``` -------------------------------- ### Build 20-Qubit GHZ Quantum Circuit Source: https://github.com/masa-whitestone/metal-quantum/blob/main/examples/ghz_20q.ipynb Constructs a standard GHZ circuit for 20 qubits, starting with a Hadamard gate on the first qubit and followed by a chain of CNOT gates. ```python num_qubits = 20 qc = QuantumCircuit(num_qubits) # H gate on the first qubit pc.h(0) # CNOT chain for i in range(num_qubits - 1): qc.cx(i, i + 1) # Measure all pc.measure_all() ``` -------------------------------- ### Documentation Commands Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CLAUDE.md Commands for previewing or building the project documentation. ```bash mkdocs serve # local preview mkdocs build # build static site ``` -------------------------------- ### Run Simulation on CPU Backend Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/basics.md Simulates a quantum circuit using the CPU backend, which is optimized with Numba and Polars. This is an alternative when the MPS backend is not available or desired. ```python # Run on CPU print("\nRunning on CPU backend...") result_cpu = run(pc, shots=1000, backend='cpu') print(f"Counts (CPU): {result_cpu.counts}") ``` -------------------------------- ### Create and Visualize a Bell State Circuit Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/index.md Create a 2-qubit circuit and visualize it using Metal-Q. This demonstrates basic circuit construction. ```python from metalq import Circuit, run # 1. Create a Circuit pc = Circuit(2) pc.h(0) pc.cx(0, 1) # 2. Visualize print(pc) ``` ```text ╭─╮ q_0: │H│─●─ ╰─╯ │ ╭┴╮ q_1: ───│X│ ╰─╯ ``` -------------------------------- ### Build Native Library Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CLAUDE.md Compiles Metal shaders and Objective-C code required for the MPS backend. ```bash cd native && make clean && make && cd .. ``` -------------------------------- ### Import Libraries for Metal-Q Simulation Source: https://github.com/masa-whitestone/metal-quantum/blob/main/examples/ghz_20q.ipynb Imports necessary libraries for building quantum circuits and running simulations with Metal-Q. ```python from qiskit import QuantumCircuit import metalq import time ``` -------------------------------- ### Run GHZ State Simulation with Metal-Q Source: https://github.com/masa-whitestone/metal-quantum/blob/main/examples/ghz_20q.ipynb Executes the constructed quantum circuit on the Metal-Q backend, measuring the simulation time. ```python print(f"Simulating {num_qubits} qubits...") start_time = time.time() result = metalq.run(qc, shots=1024) end_time = time.time() print(f"Simulation completed in {end_time - start_time:.4f} seconds.") ``` -------------------------------- ### Run Security Test Suite Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/SECURITY.md Execute these commands to validate documentation security, including path validation and configuration integrity. ```bash # Run all security tests pytest tests/test_docs_security.py -v # Test path validation only pytest tests/test_docs_security.py::TestPathValidator -v # Test configuration validation pytest tests/test_docs_security.py::TestMkDocsConfigValidator -v ``` -------------------------------- ### Run Simulation on MPS Backend Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/basics.md Simulates a quantum circuit using the MPS (Metal Performance Shaders) backend, which is the default for Apple Silicon GPUs. Specify `shots` for probabilistic outcomes. ```python from metalq import run # Run on MPS print("\nRunning on MPS backend...") result = run(pc, shots=1000, backend='mps') print(f"Counts: {result.counts}") print(f"Statevector (first 4 elements): {result.statevector[:4]}") ``` -------------------------------- ### Programmatic Secure Build with Python Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/SECURITY.md Utilize the SandboxedBuilder class to perform documentation builds within a secure environment. ```python from docs.secure_build import SandboxedBuilder from pathlib import Path # Build documentation builder = SandboxedBuilder(Path.cwd()) success = builder.build(output_dir=Path('site')) if success: print("Documentation built successfully") else: print("Build failed - check audit log") ``` -------------------------------- ### Optimize Quantum Layer Parameter with PyTorch Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/pytorch.md Demonstrates optimizing a single parameter in a QuantumLayer to minimize the expectation value of an observable. Requires PyTorch, optim, and metalq.torch.QuantumLayer. ```python import torch import torch.optim as optim from metalq import Circuit, Parameter, Z from metalq.torch import QuantumLayer print("=== PyTorch Integration: Simple Optimization ===") # 1. Define Hamiltonian: H = Z0 H = Z(0) # 2. Define Circuit with 1 parameter nc = Circuit(1) theta = Parameter('theta') nc.rx(theta, 0) # 3. Create Quantum Layer # Input: None (handled internally or via batch inputs) # Output: Expectation value model = QuantumLayer(qc, H, backend_name='mps') optimizer = optim.Adam(model.parameters(), lr=0.1) # Initial parameter print(f"Initial param: {list(model.parameters())[0].item():.4f}") # 4. Optimization Loop print("\nStarting optimization (Target: Minimize -> |1> state)...") for i in range(21): optimizer.zero_grad() loss = model() # Forward pass loss.backward() # Backward pass (Adjoint Differentiation) optimizer.step() if i % 5 == 0: print(f"Step {i}: Loss = {loss.item():.4f}, Param = {list(model.parameters())[0].item():.4f}") print("\nOptimization complete.") ``` -------------------------------- ### Qiskit Interoperability with Metal-Q Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/basics.md Demonstrates converting a Qiskit `QuantumCircuit` to Metal-Q format, running it on Metal-Q's MPS backend, and converting it back to Qiskit. This allows leveraging Metal-Q's performance for existing Qiskit code. ```python from qiskit import QuantumCircuit from metalq.adapters import to_metalq, to_qiskit from metalq import run print("=== Qiskit Interoperability ===") # 1. Create Qiskit Circuit pc_qiskit = QuantumCircuit(2) pc_qiskit.h(0) pc_qiskit.cx(0, 1) pc_qiskit.rz(0.5, 1) print("Qiskit Circuit created.") # 2. Convert to Metal-Q print("\nConverting to Metal-Q...") pc_metalq = to_metalq(npc_qiskit) print(f"Metal-Q Circuit:\n{npc_metalq}") # 3. Run on Metal-Q print("\nRunning on Metal-Q MPS backend...") result = run(npc_metalq, shots=100) print(f"Counts: {result.counts}") # 4. Convert back to Qiskit print("\nConverting back to Qiskit...") pc_back = to_qiskit(npc_metalq) print("Conversion successful.") print(npc_back) ``` -------------------------------- ### Run VQE with PyTorch Integration Source: https://github.com/masa-whitestone/metal-quantum/blob/main/README.md Optimizes a variational circuit using PyTorch's Adam optimizer and GPU-accelerated adjoint differentiation. ```python import torch import torch.optim as optim from metalq import Circuit, Parameter, Hamiltonian, Z, X from metalq.torch import QuantumLayer # Define Hamiltonian: H = Z0 * Z1 H = Z(0) * Z(1) # Define Ansatz circuit = Circuit(2) theta = Parameter('theta') circuit.rx(theta, 0) circuit.cx(0, 1) # Create PyTorch Layer model = QuantumLayer(circuit, H, backend_name='mps') optimizer = optim.Adam(model.parameters(), lr=0.1) # Optimization Loop for step in range(100): optimizer.zero_grad() loss = model() # Expectation value loss.backward() # Computes gradients via GPU Adjoint Differentiation optimizer.step() if step % 20 == 0: print(f"Step {step}, Energy: {loss.item():.4f}") ``` -------------------------------- ### Execute Secure Build Commands Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/SECURITY.md Use these shell commands to trigger secure documentation builds, validation, or audit logging. ```bash # Build documentation securely ./build_docs_secure.sh # Build and serve locally ./build_docs_secure.sh --serve # Validate configuration only ./build_docs_secure.sh --validate # Build with custom output directory ./build_docs_secure.sh --output /tmp/docs # Export audit log ./build_docs_secure.sh --audit security_audit.log ``` -------------------------------- ### Simulate a Bell State Circuit Source: https://github.com/masa-whitestone/metal-quantum/blob/main/README.md Demonstrates creating a 2-qubit circuit and executing it on the MPS backend. ```python from metalq import Circuit, run # Create a circuit with 2 qubits qc = Circuit(2) qc.h(0) qc.cx(0, 1) # Run on MPS (Metal Performance Shaders) backend result = run(qc, shots=1000, backend='mps') print(f"Counts: {result.counts}") # Counts: {'00': 502, '11': 498} ``` -------------------------------- ### Create Hybrid PyTorch Model with QuantumLayer Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/pytorch.md Shows how to combine QuantumLayer with standard PyTorch layers (nn.Linear) to build a hybrid quantum-classical neural network. Note potential adaptations needed for batch inputs to QuantumLayer. ```python import torch.nn as nn class HybridModel(nn.Module): def __init__(self): super().__init__() self.classical_pre = nn.Linear(4, 2) self.quantum = QuantumLayer(qc, H) self.classical_post = nn.Linear(1, 1) def forward(self, x): x = self.classical_pre(x) x = torch.sigmoid(x) # Note: QuantumLayer currently might need adaptation for batch inputs # typical usage involves mapping classical features to rotation angles x_q = self.quantum(inputs={theta: x}) return self.classical_post(x_q) ``` -------------------------------- ### SandboxedBuilder.build Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/SECURITY.md Builds documentation in a secure, sandboxed environment. ```APIDOC ## SandboxedBuilder.build(output_dir) ### Description Initiates the documentation build process within a sandboxed environment. Returns a boolean indicating success or failure. ### Parameters - **output_dir** (Path) - Required - The directory path where the built documentation will be stored. ### Returns - **success** (bool) - True if the build completed successfully, False otherwise. ``` -------------------------------- ### Construct a Bell State Circuit Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/basics.md Demonstrates how to create a 2-qubit circuit and apply Hadamard and CNOT gates to form a Bell state using the Metal-Q Circuit class. ```python from metalq import Circuit print("=== Basic Circuit Simulation ===") # Create a Bell State circuit pc = Circuit(2) pc.h(0) # Hadamard gate on qubit 0 pc.cx(0, 1) # CNOT gate (control 0, target 1) print("Circuit created:") print(pc) ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CONTRIBUTING.md Create a new branch for your feature development. ```bash git checkout -b feature/amazing-feature ``` -------------------------------- ### Run a Circuit on Metal GPU Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/index.md Execute a Metal-Q circuit on the Metal Performance Shaders (MPS) backend and retrieve measurement counts. This requires a previously defined circuit. ```python # 3. Run on Metal GPU (MPS) result = run(pc, shots=1000) print(f"Counts: {result.counts}") ``` ```text Counts: {'11': 502, '00': 498} ``` -------------------------------- ### Run Project Tests Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CONTRIBUTING.md Execute the project's tests using pytest with verbose output. ```bash pytest tests/ -v ``` -------------------------------- ### Run Tests Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CLAUDE.md Executes the test suite using pytest. ```bash pytest tests/ -v # all tests pytest tests/test_api_basic.py -v # single file pytest tests/test_api_basic.py::test_name -v # single test ``` -------------------------------- ### QAOA for MaxCut on Triangle Graph Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/algorithms.md Solves the MaxCut problem on a triangle graph using the Quantum Approximate Optimization Algorithm (QAOA). Defines the cost Hamiltonian and runs QAOA to find optimal parameters. ```python from metalq.algorithms import QAOA from metalq import Hamiltonian, Z, run import networkx as nx print("=== QAOA: MaxCut on Triangle Graph ===") # 1. Define Graph & Hamiltonian # Triangle (0-1, 1-2, 2-0) edges = [(0, 1), (1, 2), (2, 0)] # Cost Hamiltonian for MaxCut: H_C = 0.5 * sum_{i,j} (1 - Zi Zj) # Effectively minimize sum (Zi Zj) to maximize cuts H_cost = Hamiltonian() for i, j in edges: H_cost = H_cost + (Z(i) * Z(j)) print(f"Graph Edges: {edges}") # 2. Run QAOA # p (reps): Number of QAOA layers print("Running QAOA (p=1)...") qaoa = QAOA(H_cost, reps=1) result = qaoa.compute(max_iter=30) print(f"Optimal Value (Energy): {result.eigenvalue:.4f}") # 3. Get Solution # Bind optimal parameters to ansatz and measure qc_solved = qaoa.ansatz.bind_parameters(result.optimal_params) final_res = run(qc_solved, shots=1000) print(f"Measurement Counts: {final_res.counts}") ``` -------------------------------- ### Parameter Classes Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/circuit.md Classes for defining parameters and parameter expressions used in parameterized quantum circuits. ```APIDOC ## metalq.Parameter ## metalq.ParameterExpression ### Description Classes for defining and manipulating parameters within quantum circuits. ### Usage ```python # Example usage (conceptual) from metalq import Parameter, ParameterExpression param_a = Parameter('a') param_b = Parameter('b') expr = ParameterExpression(2 * param_a + param_b) ``` ``` -------------------------------- ### Dangerous MkDocs Configuration Patterns Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/SECURITY.md Avoid these configurations as they introduce vulnerabilities such as path traversal, arbitrary file inclusion, and remote code execution. ```yaml # DON'T: Use absolute paths nav: - Page: /etc/passwd # BLOCKED # DON'T: Use path traversal nav: - Page: ../../sensitive/data.md # BLOCKED # DON'T: Use file:// URLs repo_url: file:///local/repo # BLOCKED # DON'T: Use dangerous plugins plugins: - exec # BLOCKED - can execute code # DON'T: Use dangerous extensions markdown_extensions: - markdown_include # BLOCKED - can include any file ``` -------------------------------- ### QAOA Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/algorithms.md Represents the Quantum Approximate Optimization Algorithm. ```APIDOC ## QAOA ::: metalq.algorithms.QAOA ``` -------------------------------- ### Analyze GHZ State Simulation Results Source: https://github.com/masa-whitestone/metal-quantum/blob/main/examples/ghz_20q.ipynb Analyzes the simulation results by retrieving counts, sorting them, and calculating the probabilities of the expected `00...0` and `11...1` states for a GHZ state. ```python counts = result.get_counts() # Filter and show top results sorted_counts = sorted(counts.items(), key=lambda x: x[1], reverse=True) for bitstring, count in sorted_counts[:5]: print(f"{bitstring}: {count}") # Verify GHZ property zeros = '0' * num_qubits ones = '1' * num_qubits total = sum(counts.values()) p_zeros = counts.get(zeros, 0) / total p_ones = counts.get(ones, 0) / total print(f"\nProbability |{zeros}>: {p_zeros:.4f}") print(f"Probability |{ones}>: {p_ones:.4f}") ``` -------------------------------- ### QuantumFunction Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/torch.md A custom PyTorch function for quantum computations. ```APIDOC ## metalq.torch.QuantumFunction ### Description Allows defining custom quantum operations as PyTorch functions, enabling automatic differentiation. ### Usage ```python import torch from metalq.torch import QuantumFunction # Define your quantum operation logic within a function # def my_quantum_op(params, state): # # ... quantum operations ... # return result # Wrap it with QuantumFunction # quantum_op_func = QuantumFunction(my_quantum_op) # Use it in your PyTorch code # params = torch.randn(..., requires_grad=True) # initial_state = ... # output = quantum_op_func(params, initial_state) ``` ``` -------------------------------- ### QuantumLayer Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/torch.md Represents a quantum layer that can be integrated into PyTorch models. ```APIDOC ## metalq.torch.QuantumLayer ### Description Provides a PyTorch-compatible layer for quantum operations. ### Usage ```python import torch from metalq.torch import QuantumLayer # Assuming you have a quantum circuit defined # quantum_circuit = ... # Instantiate the QuantumLayer # q_layer = QuantumLayer(quantum_circuit) # Use it in your PyTorch model # class MyModel(torch.nn.Module): # def __init__(self): # super(MyModel, self).__init__() # self.quantum_layer = QuantumLayer(quantum_circuit) # # def forward(self, x): # # Process input and pass to quantum layer # # ... # return self.quantum_layer(processed_x) ``` ``` -------------------------------- ### Data Flow Architecture Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CLAUDE.md Visual representation of the circuit execution flow. ```text Circuit.bind_parameters() → Backend.run()/statevector()/expectation() CPU: NumPy matrix ops MPS: ctypes → libmetalq.dylib → Metal GPU shaders → Result (counts, statevector, probabilities, expectation) ``` -------------------------------- ### draw_circuit Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/visualization.md Draws a quantum circuit. This function provides a way to visualize the structure of a quantum circuit. ```APIDOC ## draw_circuit ### Description Draws a quantum circuit. ### Method This is a function call, not an HTTP method. ### Endpoint N/A ### Parameters (No specific parameters are detailed in the source text) ### Request Example (No request example is provided in the source text) ### Response (No specific response details are provided in the source text) ``` -------------------------------- ### Commit Changes Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CONTRIBUTING.md Commit your staged changes with a descriptive message. ```bash git commit -m 'Add amazing feature' ``` -------------------------------- ### Execution Functions Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/index.md Functions for executing quantum operations and managing their state. ```APIDOC ## metalq.run ### Description Executes a quantum circuit or operation. ### Method (Not specified, likely a function call) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` ```APIDOC ## metalq.expect ### Description Calculates the expectation value of an observable. ### Method (Not specified, likely a function call) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` ```APIDOC ## metalq.statevector ### Description Retrieves the statevector of a quantum system. ### Method (Not specified, likely a function call) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` -------------------------------- ### Gate Class Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/circuit.md Base class for all quantum gates in the library. Specific gates like H, CNOT, etc., inherit from this. ```APIDOC ## metalq.circuit.Gate ### Description Base class for quantum gates. ### Usage ```python # Example usage (conceptual) from metalq.circuit import H, CNOT h_gate = H(qubit=0) cnot_gate = CNOT(control=0, target=1) ``` ``` -------------------------------- ### Operator Classes Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/circuit.md Classes for representing quantum operators, including Hamiltonians and Pauli terms. ```APIDOC ## metalq.Hamiltonian ## metalq.PauliTerm ### Description Classes for representing quantum operators such as Hamiltonians and Pauli terms. ### Usage ```python # Example usage (conceptual) from metalq import Hamiltonian, PauliTerm pauli_z = PauliTerm('Z0') ham = Hamiltonian([pauli_z], [1.0]) ``` ``` -------------------------------- ### VQE Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/algorithms.md Represents the Variational Quantum Eigensolver algorithm. ```APIDOC ## VQE ::: metalq.algorithms.VQE ``` -------------------------------- ### Result Types Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/index.md Classes and structures for representing the results of quantum computations. ```APIDOC ## metalq.Result ### Description Represents the outcome of a quantum computation. ### Method (Not specified, likely a class) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` -------------------------------- ### VQE for H2 Molecule Ground State Energy Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/user_guide/algorithms.md Finds the ground state energy of a simplified H2 molecule using the Variational Quantum Eigensolver (VQE). Requires defining the Hamiltonian and an ansatz circuit. ```python from metalq import Circuit, Parameter, Z, X, Hamiltonian from metalq.algorithms import VQE import numpy as np print("=== VQE: H2 Molecule (Simplified) ===") # 1. Define Hamiltonian # H2 simplified 2-qubit mapping H = 0.39 * Z(0) + 0.39 * Z(1) + 0.18 * (Z(0) * Z(1)) + 0.01 * (X(0) * X(1)) print(f"Hamiltonian terms: {len(H.terms)}") # 2. Construct Ansatz (Hardware Efficient) qc = Circuit(2) theta = [Parameter(f't{i}') for i in range(4)] qc.ry(theta[0], 0) qc.ry(theta[1], 1) qc.cx(0, 1) qc.ry(theta[2], 0) qc.ry(theta[3], 1) print("Ansatz constructed.") # 3. Run VQE # VQE init takes ansatz and optimizer options vqe = VQE(qc, optimizer_kwargs={'lr': 0.1}) print("\nRunning VQE...") # compute_minimum_eigenvalue takes hamiltonian result = vqe.compute_minimum_eigenvalue(H, max_iter=50) print(f"Minimum Eigenvalue found: {result.eigenvalue:.6f}") print(f"Optimal Parameters: {[f'{p:.4f}' for p in result.optimal_params]}") print(f"Total offset (approx -1.05): {result.eigenvalue - 1.05:.6f} Ha") ``` -------------------------------- ### Circuit Class Source: https://github.com/masa-whitestone/metal-quantum/blob/main/docs/api/circuit.md Represents a quantum circuit, which is a sequence of quantum gates applied to qubits. ```APIDOC ## metalq.Circuit ### Description Represents a quantum circuit. ### Usage ```python # Example usage (conceptual) from metalq import Circuit, H, CNOT circuit = Circuit(num_qubits=2) circuit.append(H(0)) circuit.append(CNOT(0, 1)) ``` ``` -------------------------------- ### Push Changes to Branch Source: https://github.com/masa-whitestone/metal-quantum/blob/main/CONTRIBUTING.md Push your committed changes to the remote feature branch. ```bash git push origin feature/amazing-feature ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.