From 0855a064c90474692674fb7eb0b2fe468b83726a Mon Sep 17 00:00:00 2001 From: DeOwl Date: Mon, 16 Mar 2026 22:13:26 +0300 Subject: [PATCH] rabbitmq tests --- .github/workflows/docker-publish.yml | 98 ------- .gitignore | 414 +++++++++++++-------------- .sesskey | 1 + README.md | 4 +- docker-compose.yml | 10 + dockerfile | 7 - main.py | 142 ++++++--- methane.xyz | 4 - requirements.txt | 4 +- source/archive/mqtt.py | 46 --- source/rabbitmq_test.py | 82 +++--- source/vqe.py | 108 ++++--- structure.xyz | 6 +- 13 files changed, 437 insertions(+), 489 deletions(-) delete mode 100644 .github/workflows/docker-publish.yml create mode 100644 .sesskey create mode 100644 docker-compose.yml delete mode 100644 dockerfile delete mode 100644 methane.xyz delete mode 100644 source/archive/mqtt.py diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml deleted file mode 100644 index e72d1fc..0000000 --- a/.github/workflows/docker-publish.yml +++ /dev/null @@ -1,98 +0,0 @@ -name: Docker - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -on: - schedule: - - cron: '16 23 * * *' - push: - branches: [ "master" ] - # Publish semver tags as releases. - tags: [ 'v*.*.*' ] - pull_request: - branches: [ "master" ] - -env: - # Use docker.io for Docker Hub if empty - REGISTRY: ghcr.io - # github.repository as / - IMAGE_NAME: ${{ github.repository }} - - -jobs: - build: - - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - # This is used to complete the identity challenge - # with sigstore/fulcio when running outside of PRs. - id-token: write - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - # Install the cosign tool except on PR - # https://github.com/sigstore/cosign-installer - - name: Install cosign - if: github.event_name != 'pull_request' - uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0 - with: - cosign-release: 'v2.2.4' - - # Set up BuildKit Docker container builder to be able to build - # multi-platform images and export cache - # https://github.com/docker/setup-buildx-action - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 - - # Login against a Docker registry except on PR - # https://github.com/docker/login-action - - name: Log into registry ${{ env.REGISTRY }} - if: github.event_name != 'pull_request' - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.DOCKER_SECRET }} - - # Extract metadata (tags, labels) for Docker - # https://github.com/docker/metadata-action - - name: Extract Docker metadata - id: meta - uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - - # Build and push Docker image with Buildx (don't push on PR) - # https://github.com/docker/build-push-action - - name: Build and push Docker image - id: build-and-push - uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 - with: - context: . - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max - - # Sign the resulting Docker image digest except on PRs. - # This will only write to the public Rekor transparency log when the Docker - # repository is public to avoid leaking data. If you would like to publish - # transparency data even for private images, pass --force to cosign below. - # https://github.com/sigstore/cosign - - name: Sign the published Docker image - if: ${{ github.event_name != 'pull_request' }} - env: - # https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable - TAGS: ${{ steps.meta.outputs.tags }} - DIGEST: ${{ steps.build-and-push.outputs.digest }} - # This step uses the identity token to provision an ephemeral certificate - # against the sigstore community Fulcio instance. - run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST} diff --git a/.gitignore b/.gitignore index b7faf40..12aeee2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,207 +1,207 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[codz] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py.cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# UV -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -#uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock -#poetry.toml - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. -# https://pdm-project.org/en/latest/usage/project/#working-with-version-control -#pdm.lock -#pdm.toml -.pdm-python -.pdm-build/ - -# pixi -# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. -#pixi.lock -# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one -# in the .venv directory. It is recommended not to include this directory in version control. -.pixi - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.envrc -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ - -# Abstra -# Abstra is an AI-powered process automation framework. -# Ignore directories containing user credentials, local state, and settings. -# Learn more at https://abstra.io/docs -.abstra/ - -# Visual Studio Code -# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore -# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore -# and can be added to the global gitignore or merged into this file. However, if you prefer, -# you could uncomment the following to ignore the entire vscode folder -# .vscode/ - -# Ruff stuff: -.ruff_cache/ - -# PyPI configuration file -.pypirc - -# Cursor -# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to -# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data -# refer to https://docs.cursor.com/context/ignore-files -.cursorignore -.cursorindexingignore - -# Marimo -marimo/_static/ -marimo/_lsp/ -__marimo__/ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ diff --git a/.sesskey b/.sesskey new file mode 100644 index 0000000..d7ec727 --- /dev/null +++ b/.sesskey @@ -0,0 +1 @@ +af029f61-4c27-46bd-9c98-ed059d315b92 \ No newline at end of file diff --git a/README.md b/README.md index bff8d77..bf3fc99 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# local_quantum_simulator -This is a repository for a local app that gets deployed for the sake of simulating thq VQE algorythm +# local_quantum_simulator +This is a repository for a local app that gets deployed for the sake of simulating thq VQE algorythm diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ae7ce29 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +services: + local_quantum_app: + build: + context: . + restart: unless-stopped + ports: + - 5001:5001 + environment: + MQTT_HOST: mqtt.deowl.ru + MQTT_PORT: 1883 diff --git a/dockerfile b/dockerfile deleted file mode 100644 index 3d6ba60..0000000 --- a/dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM pennylaneai/pennylane:latest-lightning-qubit -WORKDIR /app -COPY ./source ./source -COPY ./main.py ./ -COPY ./requirements.txt ./ -RUN pip install --no-cache-dir -r requirements.txt -CMD ["python", "main.py"] \ No newline at end of file diff --git a/main.py b/main.py index 5259bb9..8c2a9af 100644 --- a/main.py +++ b/main.py @@ -1,39 +1,103 @@ -import datetime -from time import sleep, time - -from multiprocessing import Process, Queue -import source.vqe as vqe -#import project.source.archive.mqtt as mqtt - -if __name__ == "__main__": - - - broker_address = "mqtt.deowl.ru" # Example public broker - broker_port = 1883 - #mqttBroker = mqtt.vqeMqttBroker(broker_address, broker_port, max_connection_attempts=5) - #print(mqttBroker.get_status()) - #mqttBroker.connect_to_server() - - #while True: - # print(mqttBroker.get_status()) - # sleep(1) - - # GLOBAL SYSTEM PARAMETERS - #active_electrons=2 - '''active_orbitals=2 - max_iterations = 500 - conv_tol = 1e-04 - step_size = 0.05 - - q = Queue() - p = Process(target=vqe.run_vqe, args=(q, symbols, coordinates, active_electrons, active_orbitals, max_iterations, conv_tol, step_size)) - p.start() - while p.is_alive(): - try: - print(q.get_nowait(), datetime.datetime.now()) - except Exception as e: - print("no_data_to_get", e) - sleep(0.1) - - client.loop_stop() # Stop the background loop thread if used - client.disconnect()''' \ No newline at end of file +import asyncio +import datetime +import logging +import os +from ast import Lambda +from multiprocessing import Process, Queue +from socket import timeout +from time import sleep, time + +import aio_pika +import source.vqe as vqe +from fasthtml.common import Div, P, fast_app, serve + +logger = logging.basicConfig(level=logging.INFO) +app, rt = fast_app() + + +async def rabbit_worker(): + broker_address = os.environ.get("MQTT_HOST") # Example public broker + broker_port = os.environ.get("MQTT_PORT") + + if not broker_address or not broker_port: + if not broker_address: + logging.fatal("Not Found Environment Variable: MQTT_HOST") + if not broker_port: + logging.fatal("Not Found Environment Variable: MQTT_PORT") + logging.info("Shutting down") + return + logging.info(f"starting connection: {broker_address}, {broker_port}") + connection = await aio_pika.connect( + host=broker_address, port=int(broker_port), timeout=5 + ) + logging.info("debug") + channel = await connection.channel() + queue = await channel.declare_queue("my_queue", durable=True) + + async with queue.iterator() as queue_iter: + async for message in queue_iter: + async with message.process(): + asyncio.create_task(handle_message(message.body)) + + +async def handle_message(body): + print("Processing:", body) + await asyncio.sleep(2) # simulate work + + +def handle_done(body): + logging.info(f"done, {body}") + + +@app.on_event("startup") +async def startup(): + global rabbit_task + rabbit_task = asyncio.create_task(rabbit_worker()) + rabbit_task.add_done_callback(handle_done) + + +@app.on_event("shutdown") +async def shutdown(): + rabbit_task.cancel() + + +@rt("/") +def get(): + return Div(P("Hello World!"), hx_get="/change") + + +if __name__ == "__main__": + serve() + + """ + # GLOBAL SYSTEM PARAMETERS + active_electrons = 2 + active_orbitals = 2 + max_iterations = 500 + conv_tol = 1e-04 + step_size = 0.05 + + q = Queue() + p = Process( + target=vqe.run_vqe, + args=( + q, + symbols, + coordinates, + active_electrons, + active_orbitals, + max_iterations, + conv_tol, + step_size, + ), + ) + p.start() + while p.is_alive(): + try: + print(q.get_nowait(), datetime.datetime.now()) + except Exception as e: + print("no_data_to_get", e) + sleep(0.1) + + # client.loop_stop() # Stop the background loop thread if used + # client.disconnect()""" diff --git a/methane.xyz b/methane.xyz deleted file mode 100644 index 56152aa..0000000 --- a/methane.xyz +++ /dev/null @@ -1,4 +0,0 @@ -2 -Hydrogen molecule -H 0.000 0.000 0.000 -H 0.740 0.000 0.000 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index d8df59e..5eaffc8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ -basis-set-exchange==0.11 -pika==1.3.2 \ No newline at end of file +aio-pika==9.5.8 +python-fasthtml==0.12.41 diff --git a/source/archive/mqtt.py b/source/archive/mqtt.py deleted file mode 100644 index 244e658..0000000 --- a/source/archive/mqtt.py +++ /dev/null @@ -1,46 +0,0 @@ -import paho.mqtt.client as paho -import paho.mqtt.enums as paho_enums - -class vqeMqttBroker: - def __init__(self, broker_address, broker_port, username="correct", password="any", use_tls=True, max_connection_attempts=30): - self.server = broker_address - self.port = broker_port - self.client = paho.Client(callback_api_version=paho.CallbackAPIVersion.VERSION2, client_id="my_python_client", reconnect_on_failure=True) - self.client.username_pw_set(username, password) - if use_tls: - self.client.tls_set() - self.client.on_connect = self.on_connect - self.client.on_message = self.on_message - self.client.on_connect_fail = self.on_connect_fail - self.client.on_disconnect = self.on_disconnect - self.max_connection_attempts=max_connection_attempts - self.connection_attempt_number=0 - - def connect_to_server(self): - self.connection_attempt_number=0 - self.client.connect_async(self.server, self.port, 5) - self.client.loop_start() - - def get_status(self): - - return self.client._state #self.client.is_connected() - - def on_connect(self, client, userdata, flags, reason_code, properties): - print(f"Connected with result code {reason_code}") - # Subscribe to topics here if needed - client.subscribe("my/topic") - - def on_message(self, client, userdata, msg): - print(f"Received message: {msg.payload.decode()} on topic {msg.topic}") - - def on_connect_fail(self, client, userdata): - self.connection_attempt_number+=1 - print("fail") - - def on_disconnect(self, client, userdata, disconnect_flags, reason_code, properties): - self.connection_attempt_number+=1 - print("disconnected") - if (self.connection_attempt_number > self.max_connection_attempts): - self.client.disconnect() - self.client.loop_stop() - self.connection_attempt_number=0 \ No newline at end of file diff --git a/source/rabbitmq_test.py b/source/rabbitmq_test.py index c3c9bdb..8b47a0c 100644 --- a/source/rabbitmq_test.py +++ b/source/rabbitmq_test.py @@ -1,36 +1,46 @@ -import os -import sys -import pika -import ssl - -context = ssl.create_default_context() -context.verify_mode = ssl.CERT_REQUIRED - -ssl_options= pika.SSLOptions(context=context, server_hostname="rabbitmq.deowl.ru") - -credential = pika.PlainCredentials("test", "test") - - -def main(): - connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq.deowl.ru', virtual_host='/', port=5671, ssl_options=ssl_options, credentials=credential)) - channel = connection.channel() - - channel.queue_declare(queue='hello') - - def callback(ch, method, properties, body): - print(f" [x] Received {body}") - - channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True) - - print(' [*] Waiting for messages. To exit press CTRL+C') - channel.start_consuming() - -if __name__ == '__main__': - try: - main() - except KeyboardInterrupt: - print('Interrupted') - try: - sys.exit(0) - except SystemExit: - os._exit(0) \ No newline at end of file +import os +import ssl +import sys + +import pika + +context = ssl.create_default_context() +context.verify_mode = ssl.CERT_REQUIRED + +ssl_options = pika.SSLOptions(context=context, server_hostname="rabbitmq.deowl.ru") + +credential = pika.PlainCredentials("test", "test") + + +def main(): + connection = pika.BlockingConnection( + pika.ConnectionParameters( + "rabbitmq.deowl.ru", + virtual_host="/", + port=5671, + ssl_options=ssl_options, + credentials=credential, + ) + ) + channel = connection.channel() + + channel.queue_declare(queue="hello") + + def callback(ch, method, properties, body): + print(f" [x] Received {body}") + + channel.basic_consume(queue="hello", on_message_callback=callback, auto_ack=True) + + print(" [*] Waiting for messages. To exit press CTRL+C") + channel.start_consuming() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("Interrupted") + try: + sys.exit(0) + except SystemExit: + os._exit(0) diff --git a/source/vqe.py b/source/vqe.py index b95927e..f25ea8e 100644 --- a/source/vqe.py +++ b/source/vqe.py @@ -1,45 +1,63 @@ -from pennylane import numpy as np -import pennylane as qml -import os -from multiprocessing import Queue - -os.environ["OMP_NUM_THREADS"] = '16' - -def get_sctructure_from_xyz_path(path: str): - return qml.qchem.read_structure("methane.xyz") - -def run_vqe(q: Queue, symbols, coordinates, active_electrons, active_orbitals, max_iterations, conv_tol, step_size): - molecule = qml.qchem.Molecule(symbols, coordinates, load_data=True) - H, qubits = qml.qchem.molecular_hamiltonian(molecule, active_electrons=active_electrons, - active_orbitals=active_orbitals) - dev = qml.device("lightning.qubit", wires=qubits) - - - - singles, doubles = qml.qchem.excitations(active_electrons, qubits) - params = np.array(np.zeros(len(singles) + len(doubles)), requires_grad=True) - @qml.qnode(dev) - def circuit(param, wires): - # Map excitations to the wires the UCCSD circuit will act on - s_wires, d_wires = qml.qchem.excitations_to_wires(singles, doubles) - qml.UCCSD(param, wires, s_wires=s_wires, d_wires=d_wires, init_state=qml.qchem.hf_state(active_electrons, qubits)) - return qml.expval(H) - - def cost_fn(param): - return circuit(param, wires=range(qubits)) - - opt = qml.GradientDescentOptimizer(stepsize=step_size) - - for n in range(max_iterations): - # Take step - params, prev_energy = opt.step_and_cost(cost_fn, params) - - energy = cost_fn(params) - - # Calculate difference between new and old energies - conv = np.abs(energy - prev_energy) - - q.put([n, energy,params]) - - if conv <= conv_tol: - break \ No newline at end of file +import os +from multiprocessing import Queue + +import pennylane as qml +from pennylane import numpy as np + +os.environ["OMP_NUM_THREADS"] = "16" + + +def get_sctructure_from_xyz_path(path: str): + return qml.qchem.read_structure("methane.xyz") + + +def run_vqe( + queue_callback: Queue, + symbols, + coordinates, + active_electrons, + active_orbitals, + max_iterations, + conv_tol, + step_size, +): + molecule = qml.qchem.Molecule(symbols, coordinates, load_data=True) + H, qubits = qml.qchem.molecular_hamiltonian( + molecule, active_electrons=active_electrons, active_orbitals=active_orbitals + ) + dev = qml.device("lightning.qubit", wires=qubits) + + singles, doubles = qml.qchem.excitations(active_electrons, qubits) + params = np.array(np.zeros(len(singles) + len(doubles)), requires_grad=True) + + @qml.qnode(dev) + def circuit(param, wires): + # Map excitations to the wires the UCCSD circuit will act on + s_wires, d_wires = qml.qchem.excitations_to_wires(singles, doubles) + qml.UCCSD( + param, + wires, + s_wires=s_wires, + d_wires=d_wires, + init_state=qml.qchem.hf_state(active_electrons, qubits), + ) + return qml.expval(H) + + def cost_fn(param): + return circuit(param, wires=range(qubits)) + + opt = qml.GradientDescentOptimizer(stepsize=step_size) + + for n in range(max_iterations): + # Take step + params, prev_energy = opt.step_and_cost(cost_fn, params) + + energy = cost_fn(params) + + # Calculate difference between new and old energies + conv = np.abs(energy - prev_energy) + + queue_callback.put([n, energy, params]) + + if conv <= conv_tol: + break diff --git a/structure.xyz b/structure.xyz index 56152aa..04aaf23 100644 --- a/structure.xyz +++ b/structure.xyz @@ -1,4 +1,4 @@ -2 -Hydrogen molecule -H 0.000 0.000 0.000 +2 +Hydrogen molecule +H 0.000 0.000 0.000 H 0.740 0.000 0.000 \ No newline at end of file