File size: 4,999 Bytes
8248c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import numpy as np
import random
import io
import duckdb
import gradio as gr
import math
from datetime import datetime
import PIL
import matplotlib.pyplot as plt
from PIL import Image
import pennylane as qml

# Hugging Face and DuckDB function placeholders
def store_in_hf_dataset(data):
    # Implement storing data in the Hugging Face dataset
    pass

def load_from_hf_dataset():
    # Implement loading data from the Hugging Face dataset
    return []

# Store image in bytes for DuckDB
def pil_image_to_bytes(image):
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format='PNG')
    return img_byte_arr.getvalue()

# Function to generate a random Hamiltonian
def generate_random_hamiltonian(num_qubits):
    terms = []
    for _ in range(random.randint(1, 5)):
        coeff = round(random.uniform(-1, 1), 2)
        pauli_ops = [random.choice(['I', 'X', 'Y', 'Z']) for _ in range(num_qubits)]
        term = f"{coeff} * {' '.join(pauli_ops)}"
        terms.append(term)
    return " + ".join(terms)

# Store data in DuckDB
def store_in_duckdb(data, db_file='quantum_hamiltonians.duckdb'):
    conn = duckdb.connect(database=db_file)
    conn.execute("""CREATE TABLE IF NOT EXISTS hamiltonians (
        id INTEGER,
        plot BLOB,
        hamiltonian VARCHAR,
        qasm_code VARCHAR,
        trotter_code VARCHAR,
        num_qubits INTEGER,
        trotter_order INTEGER,
        timestamp TIMESTAMP
    )""")
    conn.executemany("""INSERT INTO hamiltonians (id, plot, hamiltonian, qasm_code, trotter_code, num_qubits, trotter_order, timestamp)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", data)
    conn.close()

# Load results from DuckDB
def load_from_duckdb(db_file='quantum_hamiltonians.duckdb'):
    conn = duckdb.connect(database=db_file)
    df = conn.execute("SELECT * FROM hamiltonians").df()
    conn.close()
    return df

# Function to generate Hamiltonians
def generate_hamiltonians(num_hamiltonians, selected_qubits, selected_order, write_to_hf, write_to_duckdb):
    results_table = []
    timestamp = datetime.now()

    for i in range(num_hamiltonians):
        num_qubits = random.choice(selected_qubits)
        order = selected_order
        hamiltonian = generate_random_hamiltonian(num_qubits)
        qasm_code = hamiltonian_to_qasm(hamiltonian, num_qubits)
        trotter_code = trotter_decomposition(hamiltonian, order)

        # Create a dummy plot (replace with actual plot creation logic)
        fig, ax = plt.subplots()
        ax.plot([0, 1], [0, 1])
        circuit_plot_image = buffer_plot_and_get(fig)
        circuit_plot_bytes = pil_image_to_bytes(circuit_plot_image)

        # Append data to results table
        results_table.append((i + 1, circuit_plot_bytes, hamiltonian, qasm_code, trotter_code, num_qubits, order, timestamp))

    # Write data to Hugging Face dataset if selected
    if write_to_hf:
        store_in_hf_dataset(results_table)
    
    # Write data to DuckDB if selected
    if write_to_duckdb:
        store_in_duckdb(results_table)

# Function to load results from either DuckDB or Hugging Face dataset
def load_results(load_from_hf, load_from_duckdb):
    if load_from_hf:
        return load_from_hf_dataset()  # Load from HF dataset
    if load_from_duckdb:
        return load_from_duckdb()  # Load from DuckDB

# Gradio app
with gr.Blocks() as app:
    gr.Markdown("# Quantum Hamiltonian Generator")
    
    with gr.Tab("Generate Hamiltonians"):
        num_hamiltonians = gr.Dropdown(label="Select number of Hamiltonians to generate", choices=[1, 10, 20, 100], value=20)
        qubit_choices = [1, 2, 3, 4, 5, 6]
        selected_qubits = gr.CheckboxGroup(label="Select number of qubits", choices=qubit_choices, value=[1])
        order_choices = [1, 2, 3, 4, 5]
        selected_order = gr.Dropdown(label="Select Trotter order", choices=order_choices, value=1)

        # Checkboxes for writing to HF dataset and DuckDB
        write_to_hf = gr.Checkbox(label="Write to Hugging Face dataset", value=False)
        write_to_duckdb = gr.Checkbox(label="Write to DuckDB", value=True)

        generate_button = gr.Button("Generate Hamiltonians")
        status = gr.Markdown("Click 'Generate Hamiltonians' to start the process.")

        def update_status(num, qubits, order, write_hf, write_duckdb):
            generate_hamiltonians(num, qubits, order, write_hf, write_duckdb)
            return "Data stored as per selection."

        generate_button.click(update_status, inputs=[num_hamiltonians, selected_qubits, selected_order, write_to_hf, write_to_duckdb], outputs=status)

    with gr.Tab("View Results"):
        load_from_hf = gr.Checkbox(label="Load from Hugging Face dataset", value=False)
        load_from_duckdb = gr.Checkbox(label="Load from DuckDB", value=True)

        load_button = gr.Button("Load Results")
        output_display = gr.HTML()

        load_button.click(load_results, inputs=[load_from_hf, load_from_duckdb], outputs=output_display)

app.launch()