From 40f231f118787a1a972a6026aed09cbc884b37b2 Mon Sep 17 00:00:00 2001 From: CHAMS1111 Date: Sun, 10 Nov 2024 15:14:50 +0000 Subject: [PATCH] my homewuork(chams) Signed-off-by: CHAMS1111 --- .../chams/\344\275\234\344\270\232.ipynb" | 229 ++++++++++++++++++ 1 file changed, 229 insertions(+) create mode 100644 "homework/uestc202306/chams/\344\275\234\344\270\232.ipynb" diff --git "a/homework/uestc202306/chams/\344\275\234\344\270\232.ipynb" "b/homework/uestc202306/chams/\344\275\234\344\270\232.ipynb" new file mode 100644 index 000000000..c106d68d8 --- /dev/null +++ "b/homework/uestc202306/chams/\344\275\234\344\270\232.ipynb" @@ -0,0 +1,229 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 作业1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from mindquantum.core.gates import H, X, RZ, CNOT, RY\n", + "from mindquantum.core import Circuit,ParameterResolver\n", + "from mindquantum.simulator import Simulator\n", + "import random\n", + "\n", + "alpha = [random.randint(1, 100) for i in range(7)]\n", + "print(\"alpha =\",alpha)\n", + "pr = ParameterResolver({f'alpha_{i}': alpha[i] for i in range(len(alpha))})\n", + "\n", + "# TODO: 请根据图中所示构建量子线路\n", + "circ = Circuit()\n", + "def ansatz_IQP(tq,cq,alpha_symbol,j):\n", + " circ = Circuit()\n", + " circ += CNOT.on(tq,cq)\n", + " circ += RZ(alpha_symbol).on(tq)\n", + " circ += CNOT.on(tq,cq)\n", + " return circ\n", + "def IQP(nq):\n", + " circ = Circuit()\n", + " for i in range(nq):\n", + " circ += H.on(i)\n", + " circ += RZ(f'alpha_{i}').on(i)\n", + " params = [(1, 0, \"alpha_4\",4), (2, 1, \"alpha_5\",5), (3, 2, \"alpha_6\",6)]\n", + " for nq, tq, a,j in params:\n", + " circ += ansatz_IQP(nq, tq, a, j)\n", + " return circ\n", + "\n", + "# 在这里添加量子门...\n", + "\n", + "circ += IQP(4)\n", + "\n", + "# TODO: 使用模拟器运行线路,打印运行后的量子态\n", + "sim = Simulator('mqvector', circ.n_qubits)\n", + "# 在这里补充代码...\n", + "circ.barrier()\n", + "circ.measure_all()\n", + "\n", + "# TODO: 使用模拟器采样线路结果10000次\n", + "sim = Simulator('mqvector', circ.n_qubits)\n", + "# 在这里补充代码...\n", + "res =sim.sampling(circ,pr,shots=10000)\n", + "\n", + "print(res)\n", + "circ.svg()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 作业2:使用VQE算法计算氢分子的势能曲线\n", + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "ename": "ModuleNotFoundError", + "evalue": "No module named 'openfermionpyscf'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[1;32mIn[48], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mopenfermion\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mchem\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m MolecularData\n\u001b[1;32m----> 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mopenfermionpyscf\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m run_pyscf\n\u001b[0;32m 3\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mmindquantum\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mcore\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01moperators\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Hamiltonian\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mmindquantum\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01malgorithm\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m get_qubit_hamiltonian, HardwareEfficientAnsatz\n", + "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'openfermionpyscf'" + ] + } + ], + "source": [ + "from openfermion.chem import MolecularData\n", + "from openfermionpyscf import run_pyscf\n", + "from mindquantum.core.operators import Hamiltonian\n", + "from mindquantum.algorithm import get_qubit_hamiltonian, HardwareEfficientAnsatz\n", + "from mindquantum.core.gates import X, H, RY\n", + "from mindquantum.core.circuit import Circuit\n", + "from mindquantum.simulator import Simulator\n", + "from mindquantum.framework import MQAnsatzOnlyLayer \n", + "import mindspore.nn as nn\n", + "from matplotlib import pyplot as plt\n", + "\n", + "\n", + "def get_H2_ham(d):\n", + " \"\"\"\n", + " 根据键长生成H2分子哈密顿量\n", + " Args:\n", + " d (float): 键长,单位埃米\n", + " Returns:\n", + " Hamiltonian: H2分子哈密顿量\n", + " \"\"\"\n", + " mol = MolecularData([(\"H\", (0, 0, 0)), (\"H\", (0, 0, d))], \"sto3g\", multiplicity=1)\n", + " mol = run_pyscf(mol, run_fci=1)\n", + " return Hamiltonian(get_qubit_hamiltonian(mol)), mol.fci_energy, mol.hf_energy\n", + "\n", + "nq = 4\n", + "# TODO: 请根据图中所示构建量子线路\n", + "circ = Circuit()\n", + "# 在这里添加量子门...\n", + "def encoder(nq):\n", + " circ = Circuit()\n", + " circ += H.on(0)\n", + " circ += H.on(1)\n", + " circ.barrier()\n", + "\n", + " for i in range(nq):\n", + " circ += RY(f\"a{i}\").on(i)\n", + " return circ\n", + "\n", + "def ansatz_Layer(nq):\n", + " circ = Circuit()\n", + " for i in range(nq-1):\n", + " circ += CNOT.on(i+1, i) \n", + "\n", + " for i in range(nq-1):\n", + " circ += RY(f'b{i}').on(i)\n", + " circ.barrier()\n", + " return circ\n", + "\n", + "circ += encoder(nq)\n", + "for i in range(3):\n", + " circ += ansatz_Layer(4)\n", + "circ.svg()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Initialize lists to store results\n", + "distances = [i/20 for i in range(10, 23)] # From 0.5 to 1.1 Angstrom with 0.05 step\n", + "energies = []\n", + "fci_energies = []\n", + "hf_energies = []\n", + "\n", + "# Create simulator\n", + "sim = Simulator('mqvector', 4)\n", + "\n", + "for d in distances:\n", + " # Calculate Hamiltonian for current distance\n", + " ham, fci_energy, hf_energy = get_H2_ham(d)\n", + " fci_energies.append(fci_energy)\n", + " hf_energies.append(hf_energy)\n", + "\n", + "\n", + " # TODO: 获取期望值和梯度算子\n", + " grad_ops = sim.get_expectation_with_grad(ham, circ) # 在这里补充代码...\n", + "\n", + " # TODO: 生成待训练的神经网络\n", + " # TODO: 设置优化器\n", + " # TODO: 生成能对神经网络进行一步训练的算子\n", + " # 在这里补充代码...\n", + " net = MQAnsatzOnlyLayer(grad_ops)\n", + " opti = nn.Adam(net.trainable_params(), learning_rate=0.05)\n", + " train_net = nn.TrainOneStepCell(net, opti)\n", + "\n", + " # 对网络进行200步训练\n", + " for i in range(200):\n", + " energy = train_net().asnumpy()\n", + "\n", + " # 获取第201步训练后的网络的输出,并将其添加到energies列表中\n", + " # Get the energy after training\n", + " energies.append(energy)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Plot results\n", + "plt.figure(figsize=(10, 6))\n", + "if energies:\n", + " plt.plot(distances, energies, 'b-', label='VQE Energy', linewidth=2)\n", + "plt.plot(distances, fci_energies, 'r--', label='FCI Energy', linewidth=2)\n", + "plt.plot(distances, hf_energies, 'g-.', label='HF Energy', linewidth=2)\n", + "plt.xlabel('Bond Length (Angstrom)', fontsize=12)\n", + "plt.ylabel('Energy (Hartree)', fontsize=12)\n", + "plt.title('H2 Molecule Energy vs Bond Length', fontsize=14)\n", + "plt.grid(True, linestyle='--', alpha=0.7)\n", + "plt.legend(fontsize=10)\n", + "plt.tight_layout()\n", + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.10" + } + }, + "nbformat": 4, + "nbformat_minor": 2 + } \ No newline at end of file -- Gitee