import sys
import os
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from tensorflow.python.keras.layers import Dense
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from pennylane.qnn.keras import KerasLayer

# 重定向stdout以捕获打印输出
class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush()
    def flush(self):
        for f in self.files:
            f.flush()

output_file = open('output.log', 'w', encoding='utf-8')
original_stdout = sys.stdout
sys.stdout = Tee(sys.stdout, output_file)

def save_plot(fig, filename):
    fig.savefig(filename)
    plt.close(fig)

def plot_history(history):
    # 绘制训练和验证准确率
    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(history.history['accuracy'])
    ax.plot(history.history['val_accuracy'])
    ax.set_title('Model Accuracy')
    ax.set_ylabel('Accuracy')
    ax.set_xlabel('Epoch')
    ax.legend(['Train', 'Validation'], loc='upper left')
    save_plot(fig, 'accuracy_plot.png')

    # 绘制训练和验证损失
    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(history.history['loss'])
    ax.plot(history.history['val_loss'])
    ax.set_title('Model Loss')
    ax.set_ylabel('Loss')
    ax.set_xlabel('Epoch')
    ax.legend(['Train', 'Validation'], loc='upper left')
    save_plot(fig, 'loss_plot.png')

def calculate_accuracy_fluctuation(history):
    val_accuracies = history.history['val_accuracy']
    mean_accuracy = np.mean(val_accuracies)
    fluctuation = np.sum(np.abs(val_accuracies - mean_accuracy))
    return mean_accuracy, fluctuation

# 新的量子神经网络实现
# 定义设备，使用11个量子比特，不设置dtype
dev = qml.device("default.qubit", wires=11)

def encode_group(control_qubits, data_qubits, angles_q2, angles_q3):
    """
    模块化方法，用于对一组量子比特进行角度编码。

    参数：
    - control_qubits (list[int]): 控制比特的索引，例如 [0, 1]。
    - data_qubits (dict): 包含 'q2' 和 'q3' 的量子比特索引，例如 {'q2': 2, 'q3': 3}。
    - angles_q2 (list[float]): q2 在不同控制状态下的 Ry 旋转角度。
    - angles_q3 (list[float]): q3 在不同控制状态下的 Ry 旋转角度。
    """
    control_values = [[0, 0], [0, 1], [1, 0], [1, 1]]

    for cv, angle_q2, angle_q3 in zip(control_values, angles_q2, angles_q3):
        # 翻转控制比特为0的量子比特，以便使用受控RY门
        for qubit, val in zip(control_qubits, cv):
            if val == 0:
                qml.PauliX(wires=qubit)

        # 对 q2 应用受控 RY 旋转
        qml.ctrl(qml.RY, control=control_qubits)(angle_q2, wires=data_qubits['q2'])

        # 对 q3 应用受控 RY 旋转
        qml.ctrl(qml.RY, control=control_qubits)(angle_q3, wires=data_qubits['q3'])

        # 恢复控制比特的原始状态
        for qubit, val in zip(control_qubits, cv):
            if val == 0:
                qml.PauliX(wires=qubit)

def apply_controlled_swap(swap_qubit, q_swap1, q_swap2):
    """
    模块化方法，用于应用受控 SWAP 门。

    参数：
    - swap_qubit (int): 作为交换门控制比特的量子比特索引。
    - q_swap1 (int): 受交换操作影响的第一个量子比特索引。
    - q_swap2 (int): 受交换操作影响的第二个量子比特索引。
    """
    # 对 swap_qubit 应用 Hadamard 门
    qml.Hadamard(wires=swap_qubit)

    # 应用受控 SWAP 门
    qml.CSWAP(wires=[swap_qubit, q_swap1, q_swap2])

    # 再次对 swap_qubit 应用 Hadamard 门以恢复控制比特
    qml.Hadamard(wires=swap_qubit)

# 定义一个量子节点 (QNode) 用于训练
@qml.qnode(dev, interface='tf', diff_method='backprop')
def quantum_neural_network(inputs, weights):
    control_qubits = [0, 1]

    encoding_data = [
        {
            'data_qubits': {'q2': 2, 'q3': 3},
            'swap_qubit': 4,
            'angles_q2': [1.0, 3.0, 5.0, 7.0],
            'angles_q3': [2.0, 4.0, 6.0, 8.0]
        },
        {
            'data_qubits': {'q2': 5, 'q3': 6},
            'swap_qubit': 7,
            'angles_q2': [1.5, 3.5, 5.5, 7.5],
            'angles_q3': [2.5, 4.5, 6.5, 8.5]
        },
        {
            'data_qubits': {'q2': 8, 'q3': 9},
            'swap_qubit': 10,
            'angles_q2': [2.0, 4.0, 6.0, 8.0],
            'angles_q3': [3.0, 5.0, 7.0, 9.0]
        }
    ]

    # 编码输入数据
    for data_set in encoding_data:
        data_qubits = data_set['data_qubits']
        angles_q2 = data_set['angles_q2']
        angles_q3 = data_set['angles_q3']
        encode_group(control_qubits, data_qubits, angles_q2, angles_q3)

    # 应用交换操作
    for data_set in encoding_data:
        swap_qubit = data_set['swap_qubit']
        data_qubits = data_set['data_qubits']
        apply_controlled_swap(swap_qubit, data_qubits['q3'], data_qubits['q2'])

    # 应用 Rot 层
    for layer in range(weights.shape[0]):
        for qubit in range(weights.shape[1]):
            qml.Rot(weights[layer, qubit, 0],
                    weights[layer, qubit, 1],
                    weights[layer, qubit, 2],
                    wires=qubit)

    # 测量 PauliZ 期望值
    results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]

    # 直接返回结果，由 QNode 自动转换为 TensorFlow 张量
    return results
# 定义一个量子节点 (QNode) 用于绘制电路
@qml.qnode(dev)  # 移除 interface='tf' 和 diff_method='backprop'
def quantum_neural_network_draw(inputs, weights):
    """
    量子神经网络的 QNode，用于绘制量子电路。
    不涉及 TensorFlow 的操作，直接返回结果。
    """
    # 控制比特为 q0 和 q1
    control_qubits = [0, 1]

    # 定义各组的量子比特索引和旋转角度
    encoding_data = [
        {
            'data_qubits': {'q2': 2, 'q3': 3},
            'swap_qubit': 4,
            'angles_q2': [1.0, 3.0, 5.0, 7.0],
            'angles_q3': [2.0, 4.0, 6.0, 8.0]
        },
        {
            'data_qubits': {'q2': 5, 'q3': 6},
            'swap_qubit': 7,
            'angles_q2': [1.5, 3.5, 5.5, 7.5],
            'angles_q3': [2.5, 4.5, 6.5, 8.5]
        },
        {
            'data_qubits': {'q2': 8, 'q3': 9},
            'swap_qubit': 10,
            'angles_q2': [2.0, 4.0, 6.0, 8.0],
            'angles_q3': [3.0, 5.0, 7.0, 9.0]
        }
    ]

    # 对每组数据进行编码
    for idx, data_set in enumerate(encoding_data):
        data_qubits = data_set['data_qubits']
        angles_q2 = data_set['angles_q2']
        angles_q3 = data_set['angles_q3']
        encode_group(control_qubits, data_qubits, angles_q2, angles_q3)

    # 对每组数据应用交换操作
    for idx, data_set in enumerate(encoding_data):
        swap_qubit = data_set['swap_qubit']
        data_qubits = data_set['data_qubits']
        apply_controlled_swap(swap_qubit, data_qubits['q3'], data_qubits['q2'])

    # 应用 Rot 层
    # 这里假设 weights 的形状为 (n_layers, n_qubits, 3)
    for layer in range(weights.shape[0]):
        for qubit in range(weights.shape[1]):
            qml.Rot(weights[layer, qubit, 0],
                    weights[layer, qubit, 1],
                    weights[layer, qubit, 2],
                    wires=qubit)

    # 测量每个交换控制比特的 Pauli-Z 期望值
    results = [qml.expval(qml.PauliZ(data_set['swap_qubit'])) for data_set in encoding_data]

    # 直接返回结果，不使用 TensorFlow
    return results

# 定义一个量子神经网络层
class QuantumNeuralNetworkLayer(tf.keras.layers.Layer):
    def __init__(self, n_qubits, n_layers, num_classes, **kwargs):
        super(QuantumNeuralNetworkLayer, self).__init__(**kwargs)
        self.n_qubits = n_qubits
        self.n_layers = n_layers
        self.num_classes = num_classes

        # 初始化权重，设置为float64以匹配量子设备
        weights_shape = (n_layers, n_qubits, 3)
        self.weights_qnn = self.add_weight(
            shape=weights_shape,
            initializer=tf.keras.initializers.GlorotUniform(),
            trainable=True,
            name='weights_qnn',
            dtype=tf.float64  # 设置为float64
        )

    def call(self, inputs):
        # 定义一个函数将单个样本传递给量子节点，并进行类型转换
        def apply_qnode(x):
            x = tf.cast(x, dtype=tf.float64)  # 转换为float64
            result = quantum_neural_network(x, self.weights_qnn)
            return tf.cast(result, dtype=tf.float32)  # 转换回float32

        # 使用tf.map_fn对每个样本应用量子神经网络
        outputs = tf.map_fn(
            apply_qnode,
            inputs,
            dtype=tf.float32  # 输出类型为float32
        )
        return outputs

# 定义一个量子神经网络模型
class QuantumNeuralNetwork(tf.keras.Model):
    def __init__(self, n_qubits, n_layers, num_classes, **kwargs):
        super(QuantumNeuralNetwork, self).__init__(**kwargs)
        self.n_qubits = n_qubits
        self.n_layers = n_layers
        self.num_classes = num_classes

        # Quantum layer
        self.quantum_layer = QuantumNeuralNetworkLayer(n_qubits, n_layers, num_classes)

        # Classical layers
        self.dense = Dense(num_classes, activation='softmax')

    def call(self, inputs):
        q_output = self.quantum_layer(inputs)
        return self.dense(q_output)

if __name__ == "__main__":
    parser = get_parser("Train model on Iris dataset")
    args = parser.parse_args()

    iris = load_iris()
    X = iris['data'].astype(np.float32)
    y = iris['target'].reshape(-1, 1)

    encoder = OneHotEncoder(sparse_output=False)
    y = encoder.fit_transform(y).astype(np.float32)

    x_train, x_test, y_train, y_test = train_test_split(
        X, y, test_size=0.3, random_state=116
    )

    learning_rate = 0.05
    epochs = 100
    batch_size = 8
    num_classes = 3
    n_qubits = 11  # 调整为11个量子比特（0到10）
    n_layers = 2

    model = QuantumNeuralNetwork(
        n_qubits=n_qubits,
        n_layers=n_layers,
        num_classes=num_classes
    )

    model.compile(
        optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),
        loss='categorical_crossentropy',
        metrics=['accuracy']
    )

    def is_quantum_model(model):
        for layer in model.layers:
            if isinstance(layer, QuantumNeuralNetworkLayer):
                return True
        return False

    if is_quantum_model(model):
        print("The model contains a Quantum Neural Network (QNN) layer.")
    else:
        print("The model does not contain a Quantum Neural Network (QNN) layer.")

    print("\nQuantum Circuit Diagram:")
    sample_inputs = np.ones(n_qubits, dtype=np.float64) * 0.0  # 使用 float64
    sample_weights = np.zeros((n_layers, n_qubits, 3), dtype=np.float64)  # 使用 float64
    print(qml.draw(quantum_neural_network_draw)(sample_inputs, sample_weights))  # 使用绘制专用的 QNode

    if args.importance_training:
        wrapped_model = ConstantTimeImportanceTraining(model, score="loss")
        history = wrapped_model.fit(
            x_train, y_train,
            batch_size=batch_size,
            epochs=epochs,
            verbose=1,
            validation_data=(x_test, y_test)
        )
    else:
        history = model.fit(
            x_train, y_train,
            batch_size=batch_size,
            epochs=epochs,
            verbose=1,
            validation_data=(x_test, y_test)
        )

    score = model.evaluate(x_test, y_test, verbose=0)
    print('Test loss:', score[0])
    print('Test accuracy:', score[1])

    mean_accuracy, fluctuation = calculate_accuracy_fluctuation(history)
    print('Mean validation accuracy:', mean_accuracy)
    print('Accuracy fluctuation:', fluctuation)

    plot_history(history)

    # 关闭输出文件并恢复stdout
    sys.stdout = original_stdout
    output_file.close()

print("脚本执行完成。查看 'output.log' 获取打印输出，查看当前目录获取保存的图表。")
上述代码中的def quantum_neural_network(inputs, weights):
    control_qubits = [0, 1]

    encoding_data = [
        {
            'data_qubits': {'q2': 2, 'q3': 3},
            'swap_qubit': 4,
            'angles_q2': [1.0, 3.0, 5.0, 7.0],
            'angles_q3': [2.0, 4.0, 6.0, 8.0]
        },
        {
            'data_qubits': {'q2': 5, 'q3': 6},
            'swap_qubit': 7,
            'angles_q2': [1.5, 3.5, 5.5, 7.5],
            'angles_q3': [2.5, 4.5, 6.5, 8.5]
        },
        {
            'data_qubits': {'q2': 8, 'q3': 9},
            'swap_qubit': 10,
            'angles_q2': [2.0, 4.0, 6.0, 8.0],
            'angles_q3': [3.0, 5.0, 7.0, 9.0]
        }
    ]
为什么会对angles_q2与angles_q3直接进行编码？因为按照我的设想，angles_q2是用于对数据集的values来进行编码的，而angles_q3是对数据集中的weights来进行编码的，你为什么没有如此实现？如果没有实现的话，现在来进行实现，我得量子神经网络是三层的结构