From a5f69958bc01216bc8935f77752e04e0e1b84e91 Mon Sep 17 00:00:00 2001 From: Mica Date: Tue, 28 May 2024 18:09:37 +0200 Subject: [PATCH 1/2] Connect to qat-computer --- .github/workflows/docker-image.yml | 46 +- .github/workflows/docker-tag.yml | 92 +- Dockerfile | 24 +- README.md | 19 +- build/cirq.sh | 5 - build/myqlm.sh | 8 - build/qiskit-full.sh | 13 - build/qiskit-light.sh | 5 - build/qml.sh | 5 - build/qsharp.sh | 17 - build/requirements.txt | 5 +- build/simulaqron.sh | 3 - data/README.md | 9 - data/examples/cirq/hello_cirq.py | 19 - data/examples/myqlm/hello_myqlm.py | 33 - data/examples/qiskit/hello_nature.py | 65 - data/examples/qiskit/hello_qiskit.py | 30 - data/examples/qml/hello_qml.py | 12 - data/examples/qsharp/Operation.qs | 11 - data/examples/qsharp/host.py | 4 - data/examples/simulaqron/CQC-Python/.DS_Store | Bin 8196 -> 0 bytes data/examples/simulaqron/CQC-Python/README.md | 9 - .../CQC-Python/cqc/MessageHandler.py | 559 -------- .../simulaqron/CQC-Python/cqc/Protocol.py | 178 --- .../simulaqron/CQC-Python/cqc/__init__.py | 1 - .../simulaqron/CQC-Python/cqc/cqcHeader.py | 1171 ----------------- .../CQC-Python/cqc/entInfoHeader.py | 450 ------- .../simulaqron/CQC-Python/cqc/hostConfig.py | 75 -- .../CQC-Python/cqc/pythonLib/__init__.py | 15 - .../cqc/pythonLib/cqc_connection.py | 616 --------- .../CQC-Python/cqc/pythonLib/cqc_handler.py | 911 ------------- .../CQC-Python/cqc/pythonLib/cqc_mix.py | 480 ------- .../CQC-Python/cqc/pythonLib/cqc_to_file.py | 169 --- .../CQC-Python/cqc/pythonLib/qubit.py | 523 -------- .../CQC-Python/cqc/pythonLib/util.py | 90 -- .../cqc/pythonLib_protocols/__init__.py | 0 .../pythonLib_protocols/coinflip_leader.py | 63 - .../cqc/pythonLib_protocols/measurements.py | 128 -- .../cqc/pythonLib_protocols/wstate.py | 54 - .../simulaqron/CQC-Python/cqc/util.py | 100 -- .../CQC-Python/examples/python/.DS_Store | Bin 6148 -> 0 bytes .../examples/python/hello_noLib/README.txt | 1 - .../examples/python/hello_noLib/aliceTest.py | 114 -- .../examples/python/hello_noLib/run.sh | 3 - .../CQC-Python/examples/pythonLib/.DS_Store | Bin 6148 -> 0 bytes .../examples/pythonLib/QBER/README.txt | 6 - .../examples/pythonLib/QBER/aliceTest.py | 111 -- .../examples/pythonLib/QBER/bobTest.py | 76 -- .../CQC-Python/examples/pythonLib/QBER/run.sh | 4 - .../examples/pythonLib/butterfly/node_R1.py | 101 -- .../examples/pythonLib/butterfly/node_R2.py | 81 -- .../examples/pythonLib/butterfly/node_S1.py | 69 - .../examples/pythonLib/butterfly/node_S2.py | 69 - .../examples/pythonLib/butterfly/node_T1.py | 80 -- .../examples/pythonLib/butterfly/node_T2.py | 80 -- .../examples/pythonLib/butterfly/run.sh | 7 - .../pythonLib/coinflipLeader/README.txt | 32 - .../coinflipLeader/fourPartyCoinFlip.py | 24 - .../coinflipLeader/nPartyCoinFlip.py | 34 - .../examples/pythonLib/corrRNG/README.txt | 3 - .../examples/pythonLib/corrRNG/aliceTest.py | 54 - .../examples/pythonLib/corrRNG/bobTest.py | 54 - .../examples/pythonLib/corrRNG/run.sh | 4 - .../examples/pythonLib/extendGHZ/README.txt | 3 - .../examples/pythonLib/extendGHZ/aliceTest.py | 55 - .../examples/pythonLib/extendGHZ/bobTest.py | 63 - .../pythonLib/extendGHZ/charlieTest.py | 54 - .../examples/pythonLib/extendGHZ/run.sh | 5 - .../examples/pythonLib/hello/README.txt | 1 - .../examples/pythonLib/hello/aliceTest.py | 58 - .../examples/pythonLib/hello/run.sh | 3 - .../programming_q_network/README.txt | 3 - .../programming_q_network/aliceTest.py | 66 - .../programming_q_network/bobTest.py | 58 - .../programming_q_network/eveTest.py | 50 - .../programming_q_network/run_example.sh | 5 - .../quantum_number_generation/README.md | 4 - .../quantum_number_generation.py | 29 - .../examples/pythonLib/teleport/README.txt | 4 - .../examples/pythonLib/teleport/aliceTest.py | 69 - .../examples/pythonLib/teleport/bobTest.py | 66 - .../examples/pythonLib/teleport/run.sh | 4 - .../examples/pythonLib/wstate/README.txt | 21 - .../pythonLib/wstate/additional_functions.py | 34 - .../wstate/default_Wstate_receiver.py | 67 - .../wstate/default_Wstate_transmitter.py | 81 -- .../examples/pythonLib/wstate/run.sh | 9 - data/examples/simulaqron/hello_simu.sh | 11 - 88 files changed, 13 insertions(+), 7834 deletions(-) delete mode 100755 build/cirq.sh delete mode 100755 build/myqlm.sh delete mode 100755 build/qiskit-full.sh delete mode 100755 build/qiskit-light.sh delete mode 100755 build/qml.sh delete mode 100755 build/qsharp.sh delete mode 100755 build/simulaqron.sh delete mode 100644 data/examples/cirq/hello_cirq.py delete mode 100644 data/examples/myqlm/hello_myqlm.py delete mode 100644 data/examples/qiskit/hello_nature.py delete mode 100644 data/examples/qiskit/hello_qiskit.py delete mode 100644 data/examples/qml/hello_qml.py delete mode 100644 data/examples/qsharp/Operation.qs delete mode 100644 data/examples/qsharp/host.py delete mode 100644 data/examples/simulaqron/CQC-Python/.DS_Store delete mode 100644 data/examples/simulaqron/CQC-Python/README.md delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/MessageHandler.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/Protocol.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/__init__.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/cqcHeader.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/entInfoHeader.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/hostConfig.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib/__init__.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_connection.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_handler.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_mix.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_to_file.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib/qubit.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib/util.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/__init__.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/coinflip_leader.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/measurements.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/wstate.py delete mode 100644 data/examples/simulaqron/CQC-Python/cqc/util.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/python/.DS_Store delete mode 100644 data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/aliceTest.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/run.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/.DS_Store delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/aliceTest.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/bobTest.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/run.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R1.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R2.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S1.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S2.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T1.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T2.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/run.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/fourPartyCoinFlip.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/nPartyCoinFlip.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/aliceTest.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/bobTest.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/run.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/aliceTest.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/bobTest.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/charlieTest.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/run.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/aliceTest.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/run.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/aliceTest.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/bobTest.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/eveTest.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/run_example.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/README.md delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/quantum_number_generation.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/aliceTest.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/bobTest.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/run.sh delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/README.txt delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/additional_functions.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_receiver.py delete mode 100644 data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_transmitter.py delete mode 100755 data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/run.sh delete mode 100755 data/examples/simulaqron/hello_simu.sh diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 9a2c835..8926ed2 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -12,47 +12,5 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v2 - - name: Build the Docker qiskit-light - run: docker build --build-arg quantum_env=qiskit-light.sh . --file Dockerfile --tag quantum_lab_qiskit:main - - build_qiskit-full: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Build the Docker qiskit-light - run: docker build --build-arg quantum_env=qiskit-full.sh . --file Dockerfile --tag quantum_lab_qiskit-full:main - - build_qml: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Build the Docker qml - run: docker build --build-arg quantum_env=qml.sh . --file Dockerfile --tag quantum_lab_qml:main - -# build_qsharp: -# runs-on: ubuntu-22.04 -# steps: -# - uses: actions/checkout@v2 -# - name: Build the Docker Q# -# run: docker build --build-arg quantum_env=qsharp.sh . --file Dockerfile --tag quantum_lab_qsharp:main - -# build_simulaqron: -# runs-on: ubuntu-22.04 -# steps: -# - uses: actions/checkout@v2 -# - name: Build the Docker SimulaQron -# run: docker build --build-arg quantum_env=simulaqron.sh . --file Dockerfile --tag quantum_lab_simulaqron:main - - build_myqlm: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Build the Docker myQLM - run: docker build --build-arg quantum_env=myqlm.sh . --file Dockerfile --tag quantum_lab_myqlm:main - - build_cirq: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Build the Docker Cirq - run: docker build --build-arg quantum_env=cirq.sh . --file Dockerfile --tag quantum_lab_cirq:main + - name: Build the Docker qiskit + run: docker build . --file Dockerfile --tag quantum_lab_qiskit:main diff --git a/.github/workflows/docker-tag.yml b/.github/workflows/docker-tag.yml index 70c5fdc..b4c6606 100644 --- a/.github/workflows/docker-tag.yml +++ b/.github/workflows/docker-tag.yml @@ -17,97 +17,7 @@ jobs: env: DOCKERHUB_PASS: ${{ secrets.DOCKERHUB_PASS }} run: | - docker build --build-arg quantum_env=qiskit-light.sh . --file Dockerfile --tag mickahell/quantum_lab_qiskit:${RELEASE_VERSION} + docker build . --file Dockerfile --tag mickahell/quantum_lab_qiskit:${RELEASE_VERSION} docker tag mickahell/quantum_lab_qiskit:${RELEASE_VERSION} mickahell/quantum_lab_qiskit:latest docker login --username=mickahell --password=${DOCKERHUB_PASS} docker push mickahell/quantum_lab_qiskit --all-tags - - build_qiskit-full: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set env - run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - - name: Build qiskit-full and push to Docker Hub - env: - DOCKERHUB_PASS: ${{ secrets.DOCKERHUB_PASS }} - run: | - docker build --build-arg quantum_env=qiskit-full.sh . --file Dockerfile --tag mickahell/quantum_lab_qiskit-full:${RELEASE_VERSION} - docker tag mickahell/quantum_lab_qiskit-full:${RELEASE_VERSION} mickahell/quantum_lab_qiskit-full:latest - docker login --username=mickahell --password=${DOCKERHUB_PASS} - docker push mickahell/quantum_lab_qiskit-full --all-tags - - build_qml: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set env - run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - - name: Build qml and push to Docker Hub - env: - DOCKERHUB_PASS: ${{ secrets.DOCKERHUB_PASS }} - run: | - docker build --build-arg quantum_env=qml.sh . --file Dockerfile --tag mickahell/quantum_lab_qml:${RELEASE_VERSION} - docker tag mickahell/quantum_lab_qml:${RELEASE_VERSION} mickahell/quantum_lab_qml:latest - docker login --username=mickahell --password=${DOCKERHUB_PASS} - docker push mickahell/quantum_lab_qml --all-tags - -# build_qsharp: -# runs-on: ubuntu-22.04 -# steps: -# - uses: actions/checkout@v2 -# - name: Set env -# run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV -# - name: Build Q# and push to Docker Hub -# env: -# DOCKERHUB_PASS: ${{ secrets.DOCKERHUB_PASS }} -# run: | -# docker build --build-arg quantum_env=qsharp.sh . --file Dockerfile --tag mickahell/quantum_lab_qsharp:${RELEASE_VERSION} -# docker tag mickahell/quantum_lab_qsharp:${RELEASE_VERSION} mickahell/quantum_lab_qsharp:latest -# docker login --username=mickahell --password=${DOCKERHUB_PASS} -# docker push mickahell/quantum_lab_qsharp --all-tags - -# build_simulaqron: -# runs-on: ubuntu-22.04 -# steps: -# - uses: actions/checkout@v2 -# - name: Set env -# run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV -# - name: Build SimulaQron and push to Docker Hub -# env: -# DOCKERHUB_PASS: ${{ secrets.DOCKERHUB_PASS }} -# run: | -# docker build --build-arg quantum_env=simulaqron.sh . --file Dockerfile --tag mickahell/quantum_lab_simulaqron:${RELEASE_VERSION} -# docker tag mickahell/quantum_lab_simulaqron:${RELEASE_VERSION} mickahell/quantum_lab_simulaqron:latest -# docker login --username=mickahell --password=${DOCKERHUB_PASS} -# docker push mickahell/quantum_lab_simulaqron --all-tags - - build_myqlm: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set env - run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - - name: Build myQLM and push to Docker Hub - env: - DOCKERHUB_PASS: ${{ secrets.DOCKERHUB_PASS }} - run: | - docker build --build-arg quantum_env=myqlm.sh . --file Dockerfile --tag mickahell/quantum_lab_myqlm:${RELEASE_VERSION} - docker tag mickahell/quantum_lab_myqlm:${RELEASE_VERSION} mickahell/quantum_lab_myqlm:latest - docker login --username=mickahell --password=${DOCKERHUB_PASS} - docker push mickahell/quantum_lab_myqlm --all-tags - - build_cirq: - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set env - run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - - name: Build cirq and push to Docker Hub - env: - DOCKERHUB_PASS: ${{ secrets.DOCKERHUB_PASS }} - run: | - docker build --build-arg quantum_env=cirq.sh . --file Dockerfile --tag mickahell/quantum_lab_cirq:${RELEASE_VERSION} - docker tag mickahell/quantum_lab_cirq:${RELEASE_VERSION} mickahell/quantum_lab_cirq:latest - docker login --username=mickahell --password=${DOCKERHUB_PASS} - docker push mickahell/quantum_lab_cirq --all-tags diff --git a/Dockerfile b/Dockerfile index cc8c5e8..5e3c219 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,4 @@ -FROM ubuntu:22.04 - -# Choose your quantum env -ARG quantum_env -#ARG quantum_env=qiskit-light.sh -#ARG quantum_env=qml.sh -#ARG quantum_env=qsharp.sh -#ARG quantum_env=simulaqron.sh -#ARG quantum_env=myqlm.sh -#ARG quantum_env=cirq.sh +FROM mickahell/qatcomputer-full:latest # Var for labels ARG GITHUB_ACTOR @@ -29,20 +20,17 @@ LABEL org.opencontainers.image.title="Quantum Lab" \ # OS requirements RUN apt-get update -yq \ -&& apt-get install python3-pip -y \ -&& apt-get install python3-tk -y \ -&& apt-get install vim -y \ -&& apt-get install wget -y \ -&& apt-get clean -y +&& apt-get install python3-tk -yq \ +&& apt-get dist-upgrade -yq \ +&& apt-get clean -yq # Add script & data ADD build/* /opt/quantum_lab/build/ ADD data/ /opt/quantum_lab/data/ # General & env requirements -RUN pip3 install --upgrade pip setuptools -RUN pip3 install -r /opt/quantum_lab/build/requirements.txt -RUN /opt/quantum_lab/build/${quantum_env} +RUN pip install --upgrade pip setuptools +RUN pip install -r /opt/quantum_lab/build/requirements.txt WORKDIR /opt/quantum_lab/data VOLUME /opt/quantum_lab/data/share diff --git a/README.md b/README.md index 2484435..b4d1393 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ [![GitHub release (latest by date)](https://img.shields.io/github/v/release/mickahell/quantum_lab)](https://github.com/mickahell/quantum_lab/releases) [![Docker Pulls](https://img.shields.io/docker/pulls/mickahell/quantum_lab_qiskit?label=Quantum%20Lab%20Qiskit&style=for-the-badge)](https://hub.docker.com/r/mickahell/quantum_lab_qiskit) + +__Those image are now depreciated, please use the Qiskit one just above.__ [![Docker Pulls](https://img.shields.io/docker/pulls/mickahell/quantum_lab_qiskit-full?label=Quantum%20Lab%20Qiskit-full&style=for-the-badge)](https://hub.docker.com/r/mickahell/quantum_lab_qiskit-full) [![Docker Pulls](https://img.shields.io/docker/pulls/mickahell/quantum_lab_qml?label=Quantum%20Lab%20QML&style=for-the-badge)](https://hub.docker.com/r/mickahell/quantum_lab_qml) [![Docker Pulls](https://img.shields.io/docker/pulls/mickahell/quantum_lab_qsharp?label=Quantum%20Lab%20Q%23&style=for-the-badge)](https://hub.docker.com/r/mickahell/quantum_lab_qsharp) @@ -34,22 +36,7 @@ - To create a new containeur and go inside, run the script : `./start.sh` ### Environment -- Libs common for every env : ```networkx, numpy, matplotlib, notebook, pandas, scipy, tk, vim``` -- 6 libs setup are available, one for installating [PennyLane](https://pennylane.ai), one for using [Qiskit](https://qiskit.org), one for using [Q#](https://azure.microsoft.com/fr-fr/resources/development-kit/quantum-computing/), one for [SimulaQron](https://softwarequtech.github.io/SimulaQron/html/GettingStarted.html), one for [myQLM](https://atos.net/en/lp/myqlm) and one for [Cirq](https://quantumai.google/cirq). - - `qml.sh` - - Libs : ```autograd, pennylane, pennylane-sf, pennylane-qiskit``` - - `qiskit-light.sh` - - Libs : ```qiskit, qiskit-aer, qiskit[visualization]``` - - `qiskit-full.sh` - - Libs : ```qiskit, qiskit-aer, qiskit[visualization], qiskit-nature, qiskit-finance, qiskit-optimization, qiskit-machine-learning``` - - `qsharp.sh` - - Libs : ```qsharp, iqsharp``` - - `simulaqron.sh` - - Libs : ```simulaqron``` - - `myqlm.sh` - - Libs : ```myqlm, libmagickwand-dev, myqlm-interop[qiskit_binder]``` - - `cirq.sh` - - Libs : ```cirq, cirq-core[contrib], texlive-latex-base, latexmk``` +The env is based on the image [qat-computer](https://github.com/mickahell/qat-computer). ### Volume The folder `data/share` is link to the host file and allow to register the modification in the host computer diff --git a/build/cirq.sh b/build/cirq.sh deleted file mode 100755 index 7c311dd..0000000 --- a/build/cirq.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -pip3 install cirq -pip3 install cirq-core[contrib] -apt-get install texlive-latex-base latexmk -y diff --git a/build/myqlm.sh b/build/myqlm.sh deleted file mode 100755 index 8169e08..0000000 --- a/build/myqlm.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash - -apt-get install libmagickwand-dev -y - -pip3 install myqlm -python3 -m qat.magics.install - -pip3 install myqlm-interop[qiskit_binder] diff --git a/build/qiskit-full.sh b/build/qiskit-full.sh deleted file mode 100755 index 380221b..0000000 --- a/build/qiskit-full.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -pip3 install qiskit -pip3 install qiskit-aer -pip3 install 'qiskit[visualization]' - -pip3 install qiskit-nature -pip3 install qiskit-finance -pip3 install qiskit-optimization -pip3 install qiskit-machine-learning - -# Qiskit extensions -pip3 install purplecaffeine diff --git a/build/qiskit-light.sh b/build/qiskit-light.sh deleted file mode 100755 index 02c531d..0000000 --- a/build/qiskit-light.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -pip3 install qiskit -pip3 install qiskit-aer -pip3 install 'qiskit[visualization]' diff --git a/build/qml.sh b/build/qml.sh deleted file mode 100755 index f1b7a9b..0000000 --- a/build/qml.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -pip3 install pennylane -pip3 install pennylane-sf pennylane-qiskit -pip3 install autograd diff --git a/build/qsharp.sh b/build/qsharp.sh deleted file mode 100755 index c767b53..0000000 --- a/build/qsharp.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash - -# Installing .NET -wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb -dpkg -i packages-microsoft-prod.deb -apt-get update -apt-get install -y apt-transport-https apt-utils -apt-get install -y dotnet-sdk-6.0 -apt-get install -y aspnetcore-runtime-6.0 -apt-get install -y dotnet-runtime-6.0 - -# Installing Q# and .NET quantum env -pip3 install qsharp -dotnet tool install -g Microsoft.Quantum.IQSharp -~/.dotnet/tools/dotnet-iqsharp install --user --path-to-tool="~/.dotnet/tools/dotnet-iqsharp" -export PATH="~/.dotnet/tools:$PATH" -dotnet iqsharp install diff --git a/build/requirements.txt b/build/requirements.txt index 7acde28..11f4b8a 100644 --- a/build/requirements.txt +++ b/build/requirements.txt @@ -1,6 +1,3 @@ -networkx -numpy matplotlib notebook -pandas -scipy +purplecaffeine diff --git a/build/simulaqron.sh b/build/simulaqron.sh deleted file mode 100755 index fe85e55..0000000 --- a/build/simulaqron.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -pip3 install simulaqron diff --git a/data/README.md b/data/README.md index 0b19ab2..5b60042 100644 --- a/data/README.md +++ b/data/README.md @@ -5,15 +5,6 @@ ## Sharing file - File sync with your host computer -## Program example -- Some example of program for each environment are available here : - - `qiskit` - - `qml`(Pennylane) - - `Q#` - - `SimulaQron` - -Every code examples are running simply by taping : `python3 script.py` or `./script.sh` - ## Jupyter - To start the jupyter server, run the script `./start_jupyter.sh` - Then go to your host browser and tape `http://127.0.0.1:8888/` diff --git a/data/examples/cirq/hello_cirq.py b/data/examples/cirq/hello_cirq.py deleted file mode 100644 index 572b10b..0000000 --- a/data/examples/cirq/hello_cirq.py +++ /dev/null @@ -1,19 +0,0 @@ - import cirq - - # Pick a qubit. - qubit = cirq.GridQubit(0, 0) - - # Create a circuit - circuit = cirq.Circuit( - cirq.X(qubit)**0.5, # Square root of NOT. - cirq.measure(qubit, key='m') # Measurement. - ) - print("Circuit:") - print(circuit) - - # Simulate the circuit several times. - simulator = cirq.Simulator() - result = simulator.run(circuit, repetitions=20) - print("Results:") - print(result) - diff --git a/data/examples/myqlm/hello_myqlm.py b/data/examples/myqlm/hello_myqlm.py deleted file mode 100644 index 90391e6..0000000 --- a/data/examples/myqlm/hello_myqlm.py +++ /dev/null @@ -1,33 +0,0 @@ -# Doc here -> https://myqlm.github.io/index.html - -from qat.lang.AQASM import Program, H, CNOT -from qat.qpus import PyLinalg - -# Create a Program -qprog = Program() -# Number of qbits -nbqbits = 2 -# Allocate some qbits -qbits = qprog.qalloc(nbqbits) - -# Apply some quantum Gates -qprog.apply(H, qbits[0]) -qprog.apply(CNOT, qbits[0], qbits[1]) - -print(qprog) - -# Export this program into a quantum circuit -circuit = qprog.to_circ() - -# Create a Quantum Processor Unit -linalgqpu = PyLinalg() - -# Create a job -job = circuit.to_job() - -# Submit the job to the QPU -result = linalgqpu.submit(job) - -# Iterate over the final state vector to get all final components -for sample in result: - print("State %s amplitude %s" % (sample.state, sample.amplitude)) diff --git a/data/examples/qiskit/hello_nature.py b/data/examples/qiskit/hello_nature.py deleted file mode 100644 index 3e43a63..0000000 --- a/data/examples/qiskit/hello_nature.py +++ /dev/null @@ -1,65 +0,0 @@ -from qiskit_nature.drivers import PySCFDriver, UnitsType -from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem - -# Use PySCF, a classical computational chemistry software -# package, to compute the one-body and two-body integrals in -# electronic-orbital basis, necessary to form the Fermionic operator -driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', - unit=UnitsType.ANGSTROM, - basis='sto3g') -problem = ElectronicStructureProblem(driver) - -# generate the second-quantized operators -second_q_ops = problem.second_q_ops() -main_op = second_q_ops[0] - -num_particles = (problem.molecule_data_transformed.num_alpha, - problem.molecule_data_transformed.num_beta) - -num_spin_orbitals = 2 * problem.molecule_data.num_molecular_orbitals - -# setup the classical optimizer for VQE -from qiskit.algorithms.optimizers import L_BFGS_B - -optimizer = L_BFGS_B() - -# setup the mapper and qubit converter -from qiskit_nature.mappers.second_quantization import ParityMapper -from qiskit_nature.converters.second_quantization import QubitConverter - -mapper = ParityMapper() -converter = QubitConverter(mapper=mapper, two_qubit_reduction=True) - -# map to qubit operators -qubit_op = converter.convert(main_op, num_particles=num_particles) - -# setup the initial state for the ansatz -from qiskit_nature.circuit.library import HartreeFock - -init_state = HartreeFock(num_spin_orbitals, num_particles, converter) - -# setup the ansatz for VQE -from qiskit.circuit.library import TwoLocal - -ansatz = TwoLocal(num_spin_orbitals, ['ry', 'rz'], 'cz') - -# add the initial state -ansatz.compose(init_state, front=True) - -# set the backend for the quantum computation -from qiskit import Aer - -backend = Aer.get_backend('aer_simulator_statevector') - -# setup and run VQE -from qiskit.algorithms import VQE - -algorithm = VQE(ansatz, - optimizer=optimizer, - quantum_instance=backend) - -result = algorithm.compute_minimum_eigenvalue(qubit_op) -print(result.eigenvalue.real) - -electronic_structure_result = problem.interpret(result) -print(electronic_structure_result) diff --git a/data/examples/qiskit/hello_qiskit.py b/data/examples/qiskit/hello_qiskit.py deleted file mode 100644 index c3b97c8..0000000 --- a/data/examples/qiskit/hello_qiskit.py +++ /dev/null @@ -1,30 +0,0 @@ -import numpy as np -from qiskit import QuantumCircuit, execute, Aer -from qiskit.visualization import plot_histogram -import matplotlib.pyplot as plt - -# Use Aer's qasm_simulator -simulator = Aer.get_backend('qasm_simulator') - -circuit = QuantumCircuit(2, 2) - -# Add a H gate on qubit 0 -circuit.h(0) -circuit.cx(0, 1) - -# Map the quantum measurement to the classical bits -circuit.measure([0,1], [0,1]) - -# Execute the circuit on the qasm simulator -job = execute(circuit, simulator, shots=1000) - -# Grab results from the job -result = job.result() - -# Returns counts -counts = result.get_counts(circuit) -print("\nTotal count for 00 and 11 are:",counts) - -# Draw the circuit -circuit.draw() # to plot inside jupyter -print(circuit) diff --git a/data/examples/qml/hello_qml.py b/data/examples/qml/hello_qml.py deleted file mode 100644 index fb66324..0000000 --- a/data/examples/qml/hello_qml.py +++ /dev/null @@ -1,12 +0,0 @@ -import pennylane as qml -from pennylane import numpy as np - -dev = qml.device("default.qubit", wires=1) - -@qml.qnode(dev) -def circuit(params): - qml.RX(params[0], wires=0) - qml.RY(params[1], wires=0) - return qml.expval(qml.PauliZ(0)) - -print(circuit([0.54, 0.12])) diff --git a/data/examples/qsharp/Operation.qs b/data/examples/qsharp/Operation.qs deleted file mode 100644 index 5a438d3..0000000 --- a/data/examples/qsharp/Operation.qs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Qrng { - open Microsoft.Quantum.Intrinsic; - - operation SampleQuantumRandomNumberGenerator() : Result { - use q = Qubit(); // Allocate a qubit. - H(q); // Put the qubit to superposition. It now has a 50% chance of being 0 or 1. - let r = M(q); // Measure the qubit value. - Reset(q); - return r; - } -} diff --git a/data/examples/qsharp/host.py b/data/examples/qsharp/host.py deleted file mode 100644 index ba71b3c..0000000 --- a/data/examples/qsharp/host.py +++ /dev/null @@ -1,4 +0,0 @@ -import qsharp -from Qrng import SampleQuantumRandomNumberGenerator - -print(SampleQuantumRandomNumberGenerator.simulate()) diff --git a/data/examples/simulaqron/CQC-Python/.DS_Store b/data/examples/simulaqron/CQC-Python/.DS_Store deleted file mode 100644 index 774be4f2920fde2147740e63540f571b87bfc250..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMKX21O6n~e5;shZgwGvrC9$-L;5e$IZIF1rawl7T_0)!y1 zz|s{4#5dq8ATf1ffoVnP(|N$-B=_vg;{dx>5A`05nv> z;stCL2>D4!|gNbys>oU%e z7zz~Wz~teB$(flvp|EIn9AA&Zff)i-s~AuWq#2;Idk!kl1qXt}`F(%$bKK|gX47)H zg*NSG?Z%t$g)du4zkRB|-;2E)m>gg#WT6fF(B5%*TaHX$-cP8NpOH||QIs_v_GQ$e z)pwm?P_2GrnQZRd(s@lQXoZV~CuWb2&7c*GhK<(X5nbJF1wBjl?{n_X`Yr2$(;4p; zS8j7ZXgPjo5G6Zy2SXk|bbOnS8+_#3!)P2+I5aJ<<#&sv$z*k7qpYvi*QRBCQm7#-_Mtqpgy~FZSIK^zx>sEEs2-p zd3;WL+M6If`;jJ=c~8xO?{dG37P>nPI`9ly;6Wc;><^PgVQ(=eUX)b)zgnKuLKB5z zSJxMj7cZG}aClU*)L8N2ofelUW9A1=nJ(C|g682KY{M2b;SOR23u_-M=@lI1L+pD- zqb7wu7& -CQC_CMD_SEND = 5 # Send qubit to another node -CQC_CMD_RECV = 6 # Ask to receive qubit -CQC_CMD_EPR = 7 # Create EPR pair with the specified node -CQC_CMD_EPR_RECV = 8 # Receive half of EPR pair created with other node - -CQC_CMD_X = 10 # Pauli X -CQC_CMD_Z = 11 # Pauli Z -CQC_CMD_Y = 12 # Pauli Y -CQC_CMD_T = 13 # T Gate -CQC_CMD_ROT_X = 14 # Rotation over angle around X in 2pi/256 increments -CQC_CMD_ROT_Y = 15 # Rotation over angle around Y in 2pi/256 increments -CQC_CMD_ROT_Z = 16 # Rotation over angle around Z in 2pi/256 increments -CQC_CMD_H = 17 # Hadamard H -CQC_CMD_K = 18 # K Gate - taking computational to Y eigenbasis - -CQC_CMD_CNOT = 20 # CNOT Gate with this as control -CQC_CMD_CPHASE = 21 # CPHASE Gate with this as control - -CQC_CMD_ALLOCATE = 22 # Allocate a number of qubits -CQC_CMD_RELEASE = 23 # Release a qubit - -# Command options -CQC_OPT_NOTIFY = 0x01 # Send a notification when cmd done -CQC_OPT_ACTION = 0x02 # On if there are actions to execute when done -CQC_OPT_BLOCK = 0x04 # Block until command is done - -_CMD_TO_STRING = { - CQC_CMD_I: "I", - CQC_CMD_NEW: "NEW", - CQC_CMD_MEASURE: "MEASURE", - CQC_CMD_MEASURE_INPLACE: "MEASURE_INPLACE", - CQC_CMD_RESET: "RESET", - CQC_CMD_SEND: "SEND", - CQC_CMD_RECV: "RECV", - CQC_CMD_EPR: "EPR", - CQC_CMD_EPR_RECV: "EPR_RECV", - CQC_CMD_X: "X", - CQC_CMD_Z: "Z", - CQC_CMD_Y: "Y", - CQC_CMD_T: "T", - CQC_CMD_ROT_X: "ROT_X", - CQC_CMD_ROT_Y: "ROT_Y", - CQC_CMD_ROT_Z: "ROT_Z", - CQC_CMD_H: "H", - CQC_CMD_K: "K", - CQC_CMD_CNOT: "CNOT", - CQC_CMD_CPHASE: "CPHASE", - CQC_CMD_ALLOCATE: "ALLOCATE", - CQC_CMD_RELEASE: "RELEASE", -} - - -def command_to_string(cmd_id): - cmd_str = _CMD_TO_STRING.get(cmd_id) - if cmd_str is None: - raise ValueError("Unknown instruction id {}".format(cmd_id)) - return cmd_str - - -class CQCType(IntEnum): - HELLO = 0 # Alive check - COMMAND = 1 # Execute a command list - FACTORY = 2 # Start executing command list repeatedly - EXPIRE = 3 # Qubit has expired - DONE = 4 # Done with command - RECV = 5 # Received qubit - EPR_OK = 6 # Created EPR pair - MEASOUT = 7 # Measurement outcome - GET_TIME = 8 # Get creation time of qubit - INF_TIME = 9 # Return timinig information - NEW_OK = 10 # Created a new qubit - MIX = 11 # Indicate that the CQC program will contain multiple header types - IF = 12 # Announce a CQC IF header - - ERR_GENERAL = 20 # General purpose error (no details - ERR_NOQUBIT = 21 # No more qubits available - ERR_UNSUPP = 22 # No sequence not supported - ERR_TIMEOUT = 23 # Timeout - ERR_INUSE = 24 # Qubit already in use - ERR_UNKNOWN = 25 # Unknown qubit ID - - -class CQCLogicalOperator(IntEnum): - EQ = 0 # Equal - NEQ = 1 # Not equal - - @staticmethod - def opposite_of(operator: 'CQCLogicalOperator'): - opposites = { - CQCLogicalOperator.EQ: CQCLogicalOperator.NEQ, - CQCLogicalOperator.NEQ: CQCLogicalOperator.EQ - } - return opposites[operator] - - @staticmethod - def is_true(first_operand: int, operator: 'CQCLogicalOperator', second_operand: int): - comparison_method = { - CQCLogicalOperator.EQ: first_operand.__eq__, - CQCLogicalOperator.NEQ: first_operand.__ne__ - } - return comparison_method[operator](second_operand) - - -class Header(metaclass=abc.ABCMeta): - """ - Abstact class for headers. - Should be subclassed - """ - - PACKAGING_FORMAT = "!" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def __init__(self, headerBytes=None): - """ - Initialize using values received from a packet. - Don't override this but rather _setVals - """ - if headerBytes is None: - self.setVals() - self.is_set = False - else: - self.unpack(headerBytes) - - def __str__(self): - return self.printable() - - def setVals(self, *args, **kwargs): - """ - Set using given values. - Don't override this but rather _setVals - - :return: None - """ - self._setVals(*args, **kwargs) - self._check_vals() - - def _check_vals(self): - """ - Method to be called after setting values, checks if values can be packed and sets is_set to True. - - :return: None - """ - - try: - self.is_set = True - self.pack() - except Exception as err: - # Set default values again - raise ValueError("Invalid arguments. Could not packed since: {}".format(err)) - self.__init__() - - @abc.abstractmethod - def _setVals(self, *args, **kwargs): - """ - Set using given values. - Should be overridden - - :return: None - """ - pass - - def unpack(self, headerBytes): - """ - Unpack packet data. - Don't override this but rather _unpack - - :return: None - """ - try: - self._unpack(headerBytes) - except Exception as err: - raise ValueError("Could not unpack headerBytes={} to a {}, since {}" - .format(headerBytes, self.__class__.__name__, err)) - self.is_set = True - - @abc.abstractmethod - def _unpack(self, headerBytes): - """ - Unpack packet data. - Should be overridden - - :return: None - """ - pass - - def pack(self): - """ - Pack data into packet format. - Don't override this but rather _pack - - :return: bytes - """ - if not self.is_set: - raise RuntimeError("Cannot pack a header which is not set") - return self._pack() - - @abc.abstractmethod - def _pack(self): - """ - Pack data into packet format. - Should be overridden - - :return: bytes - """ - pass - - def printable(self): - """ - Produce a printable string for information purposes. - Don't override this but rather _printable - - :return: str - """ - if not self.is_set: - raise RuntimeError("Cannot print a header which is not set") - - return self._printable() - - @abc.abstractmethod - def _printable(self): - """ - Produce a printable string for information purposes. - Should be overridden - - :return: str - """ - pass - - -class CQCHeader(Header): - """ - Definition of the general CQC header. - """ - - PACKAGING_FORMAT = "!BBHL" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, version=0, tp=0, app_id=0, length=0): - """ - Set using given values. - """ - self.version = version - self.tp = tp - self.app_id = app_id - self.length = length - self.is_set = True - - def _pack(self): - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - cqcH = struct.pack(self.PACKAGING_FORMAT, self.version, self.tp, self.app_id, self.length) - return cqcH - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - """ - cqcH = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.version = cqcH[0] - self.tp = cqcH[1] - self.app_id = cqcH[2] - self.length = cqcH[3] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "CQC Header. Version: " + str(self.version) + " " - toPrint = toPrint + "Type: " + str(self.tp) + " " - toPrint = toPrint + "App ID: " + str(self.app_id) + " " - toPrint += "Length: " + str(self.length) - return toPrint - - -class CQCTypeHeader(Header): - """ - Definition of the CQC Type header. This header announces the type of the headers that will follow. - """ - - PACKAGING_FORMAT = "!BI" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, tp: CQCType = 0, length: int = 0) -> None: - """ - Set using given values. - """ - self.type = tp - self.length = length - - def _pack(self) -> bytes: - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - return struct.pack(self.PACKAGING_FORMAT, self.type, self.length) - - def _unpack(self, headerBytes) -> None: - """ - Unpack packet data. - """ - unpacked = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.type = unpacked[0] - self.length = unpacked[1] - - def _printable(self) -> str: - """ - Produce a printable string for information purposes. - """ - return "CQC Type header. Type=" + str(self.type) + " | Length=" + str(self.length) - - def make_equivalent_CQCHeader(self, version: int, app_id: int) -> CQCHeader: - """ - Produce a CQC Header that is equivalent to this CQCTypeHeader. - This method does not make any modifications to self. - """ - cqc_header = CQCHeader() - cqc_header.setVals(version, self.type, app_id, self.length) - return cqc_header - - -class CQCIfHeader(Header): - """ - Definition of the CQC IF header. - """ - - PACKAGING_FORMAT = "!IBBII" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - TYPE_VALUE = 0 - TYPE_REF_ID = 1 - - def _setVals( - self, - first_operand: int = 0, - operator: CQCLogicalOperator = 0, - type_of_second_operand: int = 0, - second_operand: int = 0, - length: int = 0 - ) -> None: - """ - Set the fields of this header. - first_operand must be a reference id. - second_operand will be interpreted as eiter a reference id or a value, dependent on type_of_second_operand. - type_of_second_operand must either be CQCIfHeader.TYPE_VALUE or CQCIfHeader.TYPE_REF_ID - """ - - self.first_operand = first_operand - self.operator = operator - self.type_of_second_operand = type_of_second_operand - self.second_operand = second_operand - self.length = length - - def _pack(self) -> bytes: - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - - return struct.pack( - self.PACKAGING_FORMAT, - self.first_operand, - self.operator, - self.type_of_second_operand, - self.second_operand, - self.length - ) - - def _unpack(self, headerBytes) -> None: - """ - Unpack packet data. For definitions see cLib/cqc.h - """ - unpacked = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - - self.first_operand = unpacked[0] - self.operator = unpacked[1] - self.type_of_second_operand = unpacked[2] - self.second_operand = unpacked[3] - self.length = unpacked[4] - - def _printable(self) -> str: - """ - Produce a printable string for information purposes. - """ - - if self.type_of_second_operand == self.TYPE_REF_ID: - operand_type = "RefID" - else: - operand_type = "Value" - - # parenthesis to concatenate the string over multiple lines - return ( - "CQC IF header. RefID=" + str(self.first_operand) - + " | Operator=" + str(self.operator) - + " | " + operand_type + "=" + str(self.second_operand) - + " | Second_operand_type=" + operand_type - + " | Body_length=" + str(self.length) - ) - - -class CQCCmdHeader(Header): - """ - Header for a command instruction packet. - """ - - PACKAGING_FORMAT = "!HBB" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, qubit_id=0, instr=0, notify=False, block=False, action=False): - """ - Set using given values. - """ - self.qubit_id = qubit_id - self.instr = instr - self.notify = notify - self.block = block - self.action = action - - def _pack(self): - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - - opt = 0 - if self.notify: - opt = opt | CQC_OPT_NOTIFY - if self.block: - opt = opt | CQC_OPT_BLOCK - if self.action: - opt = opt | CQC_OPT_ACTION - - cmdH = struct.pack(self.PACKAGING_FORMAT, self.qubit_id, self.instr, opt) - return cmdH - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - """ - cmdH = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - - self.qubit_id = cmdH[0] - self.instr = cmdH[1] - - if cmdH[2] & CQC_OPT_NOTIFY: - self.notify = True - else: - self.notify = False - if cmdH[2] & CQC_OPT_BLOCK: - self.block = True - else: - self.block = False - if cmdH[2] & CQC_OPT_ACTION: - self.action = True - else: - self.action = False - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Command Header. Qubit ID: " + str(self.qubit_id) + " " - toPrint = toPrint + "Instruction: " + str(self.instr) + " " - toPrint = toPrint + "Notify: " + str(self.notify) + " " - toPrint = toPrint + "Block: " + str(self.block) + " " - toPrint = toPrint + "Action: " + str(self.action) - return toPrint - - -class CQCAssignHeader(Header): - """ - Sub header that follows a CMD Measure header. It contains the reference id which can be used - to refer to the measurement outcome - """ - - PACKAGING_FORMAT = "!I" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, ref_id: int = 0) -> None: - """ - Set using given values. - """ - self.ref_id = ref_id - - def _pack(self) -> bytes: - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - - return struct.pack(self.PACKAGING_FORMAT, self.ref_id) - - def _unpack(self, headerBytes) -> None: - """ - Unpack packet data. For definitions see cLib/cqc.h - """ - unpacked = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - - self.ref_id = unpacked[0] - - def _printable(self) -> str: - """ - Produce a printable string for information purposes. - """ - - return "CQC Assign sub header. RefID=" + str(self.ref_id) - - -class CQCXtraHeader(Header): - """ - Optional addtional cmd header information. Only relevant for certain commands. - """ - - PACKAGING_FORMAT = "!HHLLHBB" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - # Deprecated, split into multiple headers - def __init__(self, headerBytes=None): - """ - Initialize using values received from a packet. - """ - warnings.warn("Xtra Header is deprecated, it is split into different headers", DeprecationWarning) - super().__init__(headerBytes) - - def _setVals(self, xtra_qubit_id=0, step=0, remote_app_id=0, remote_node=0, remote_port=0, cmdLength=0): - """ - Set using given values. - """ - self.qubit_id = xtra_qubit_id - self.step = step - self.remote_app_id = remote_app_id - self.remote_node = remote_node - self.remote_port = remote_port - self.cmdLength = cmdLength - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - """ - xtraH = struct.pack( - self.PACKAGING_FORMAT, - self.qubit_id, - self.remote_app_id, - self.remote_node, - self.cmdLength, - self.remote_port, - self.step, - 0, - ) - return xtraH - - def _unpack(self, headerBytes): - """ - Unpack packet data. For defnitions see cLib/cqc.h - """ - xtraH = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - - self.qubit_id = xtraH[0] - self.remote_app_id = xtraH[1] - self.remote_node = xtraH[2] - self.cmdLength = xtraH[3] - self.remote_port = xtraH[4] - self.step = xtraH[5] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - - toPrint = "Xtra Qubit: " + str(self.qubit_id) + " " - toPrint = toPrint + "Angle Step: " + str(self.step) + " " - toPrint = toPrint + "Remote App ID: " + str(self.remote_app_id) + " " - toPrint = toPrint + "Remote Node: " + str(self.remote_node) + " " - toPrint = toPrint + "Remote Port: " + str(self.remote_port) + " " - toPrint = toPrint + "Command Length: " + str(self.cmdLength) - - return toPrint - - -class CQCSequenceHeader(Header): - """ - Header used to indicate size of a sequence. - Currently exactly the same as CQCRotationHeaer. - Seperate classes used clearity and for possible future adaptability. (Increase length for example) - """ - - PACKAGING_FORMAT = "!B" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, cmd_length=0): - """ - Set header using given values - :param cmd_length: The step size of the rotation - """ - self.cmd_length = cmd_length - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - :returns the packed header - """ - header = struct.pack(self.PACKAGING_FORMAT, self.cmd_length) - return header - - def _unpack(self, headerBytes): - """ - Unpack packet data. For defnitions see cLib/cqc.h - :param headerBytes: The unpacked headers. - """ - header = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.cmd_length = header[0] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Sequence header. " - toPrint += "Command length: " + str(self.cmd_length) + " " - - return toPrint - - -class CQCRotationHeader(Header): - """ - Header used to define the rotation angle of a gate - """ - - PACKAGING_FORMAT = "!B" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, step=0): - """ - Set header using given values - :param step: The step size of the rotation - """ - self.step = step - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - :returns the packed header - """ - header = struct.pack(self.PACKAGING_FORMAT, self.step) - return header - - def _unpack(self, headerBytes): - """ - Unpack packet data. For defnitions see cLib/cqc.h - :param headerBytes: The unpacked headers. - """ - header = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.step = header[0] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Rotation header. " - toPrint += "step size: " + str(self.step) + " " - - return toPrint - - -class CQCXtraQubitHeader(Header): - """ - Header used to send qubit of a secondary qubit for two qubit gates - """ - - PACKAGING_FORMAT = "!H" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, qubit_id=0): - """ - Set header using given values - :param qubit_id: The id of the secondary qubit - """ - self.qubit_id = qubit_id - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - :returns the packed header - """ - header = struct.pack(self.PACKAGING_FORMAT, self.qubit_id) - return header - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - :param headerBytes: The unpacked headers. - """ - header = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.qubit_id = header[0] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Extra Qubit header. " - toPrint += "qubit id: " + str(self.qubit_id) + " " - - return toPrint - - -class CQCCommunicationHeader(Header): - """ - Header used to send information to which node to send information to. - Used for example in Send and EPR commands - This header has a size of 8 - """ - - PACKAGING_FORMAT = "!HHL" - PACKAGING_FORMAT_V1 = "!HLH" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) # Both versions have the same size - - def __init__(self, headerBytes=None, cqc_version=CQC_VERSION): - """ - Initialize from packet data - :param headerBytes: packet data - """ - self._cqc_version = cqc_version - super().__init__(headerBytes) - - def _setVals(self, remote_app_id=0, remote_node=0, remote_port=0): - """ - Set header using given values - :param remote_app_id: Application ID of remote host - :param remote_node: IP of remote host in cqc network - :param remote_port: port of remote hode in cqc network - """ - self.remote_app_id = remote_app_id - self.remote_port = remote_port - self.remote_node = remote_node - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - :param cqc_version: The CQC version to be used - :returns the packed header - """ - if self._cqc_version < 2: - header = struct.pack(self.PACKAGING_FORMAT_V1, self.remote_app_id, self.remote_node, self.remote_port) - else: - header = struct.pack(self.PACKAGING_FORMAT, self.remote_app_id, self.remote_port, self.remote_node) - return header - - def _unpack(self, headerBytes): - """ - Unpack packet data. For defnitions see cLib/cqc.h - :param headerBytes: The unpacked headers. - :param cqc_version: The CQC version to be used - """ - if self._cqc_version < 2: - header = struct.unpack(self.PACKAGING_FORMAT_V1, headerBytes) - self.remote_app_id = header[0] - self.remote_node = header[1] - self.remote_port = header[2] - else: - header = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.remote_app_id = header[0] - self.remote_port = header[1] - self.remote_node = header[2] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Communication header. " - toPrint += "Remote App ID: " + str(self.remote_app_id) + " " - toPrint += "Remote Node: " + str(self.remote_node) + " " - toPrint += "Remote Port: " + str(self.remote_port) + " " - - return toPrint - - -class CQCFactoryHeader(Header): - """ - Header used to send factory information - """ - - # could maybe include the notify flag in num_iter? - # That halfs the amount of possible num_iter from 256 to 128 - PACKAGING_FORMAT = "!BB" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, num_iter=0, notify=0, block=0): - """ - Set using give values - :param num_iter: The amount of iterations to this factory - :param notify: True if the factory should send a done message back - :param block: True if all commands in this factory should be blocked - """ - self.num_iter = num_iter - self.notify = notify - self.block = block - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - """ - opt = 0 - if self.notify: - opt = opt | CQC_OPT_NOTIFY - if self.block: - opt = opt | CQC_OPT_BLOCK - - factH = struct.pack(self.PACKAGING_FORMAT, self.num_iter, opt) - return factH - - def _unpack(self, headerBytes): - """ - Unpack packet data. For defnitions see cLib/cqc.h - """ - fact_hdr = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - - self.notify = fact_hdr[1] & CQC_OPT_NOTIFY - self.block = fact_hdr[1] & CQC_OPT_BLOCK - - self.num_iter = fact_hdr[0] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Factory Header. " - toPrint += "Number of iterations: " + str(self.num_iter) + " " - return toPrint - - -class CQCNotifyHeader(Header): - """ - Header used to specify notification details. - """ - - PACKAGING_FORMAT = "!HHLQHBB" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def __init__(self, headerBytes=None): - """ - Initialize from packet data. - """ - warnings.warn("Notify Header is deprecated, it is split into CQCXtraQubitHeader, CQCMeasOutHeader, " - "CQCTimeInfoHeader", DeprecationWarning) - super().__init__(headerBytes) - - def _setVals(self, qubit_id=0, outcome=0, remote_app_id=0, remote_node=0, remote_port=0, datetime=0): - """ - Set using given values. - """ - self.qubit_id = qubit_id - self.outcome = outcome - self.remote_app_id = remote_app_id - self.remote_node = remote_node - self.remote_port = remote_port - self.datetime = datetime - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - """ - xtraH = struct.pack( - self.PACKAGING_FORMAT, - self.qubit_id, - self.remote_app_id, - self.remote_node, - self.datetime, - self.remote_port, - self.outcome, - 0, - ) - return xtraH - - def _unpack(self, headerBytes): - """ - Unpack packet data. For defnitions see cLib/cqc.h - """ - xtraH = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - - self.qubit_id = xtraH[0] - self.remote_app_id = xtraH[1] - self.remote_node = xtraH[2] - self.datetime = xtraH[3] - self.remote_port = xtraH[4] - self.outcome = xtraH[5] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Qubit ID: " + str(self.qubit_id) + " " - toPrint = toPrint + "Outcome: " + str(self.outcome) + " " - toPrint = toPrint + "Remote App ID: " + str(self.remote_app_id) + " " - toPrint = toPrint + "Remote Node: " + str(self.remote_node) + " " - toPrint = toPrint + "Remote Port: " + str(self.remote_port) + " " - toPrint = toPrint + "Datetime: " + str(self.datetime) - return toPrint - - -class CQCMeasOutHeader(Header): - """ - Header used to send a measurement outcome. - """ - - PACKAGING_FORMAT = "!B" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, outcome=0): - """ - Set header using given values - :param meas_out: The measurement outcome - """ - self.outcome = outcome - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - :returns the packed header - """ - header = struct.pack(self.PACKAGING_FORMAT, self.outcome) - return header - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - :param headerBytes: The unpacked headers. - """ - header = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.outcome = header[0] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Measurement Outcome header. " - toPrint += "measurement outcome: " + str(self.outcome) + " " - - return toPrint - - -class CQCTimeinfoHeader(Header): - """ - Header used to send timing information - """ - - PACKAGING_FORMAT = "!Q" - HDR_LENGTH = struct.calcsize(PACKAGING_FORMAT) - - def _setVals(self, datetime=0): - """ - Set header using given values - :param datetime: The timestamp - """ - self.datetime = datetime - - def _pack(self): - """ - Pack data into packet form. For definitions see cLib/cqc.h - :returns the packed header - """ - header = struct.pack(self.PACKAGING_FORMAT, self.datetime) - return header - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - :param headerBytes: The unpacked headers. - """ - header = struct.unpack(self.PACKAGING_FORMAT, headerBytes) - self.datetime = header[0] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Time Info header. " - toPrint += "timestamp: " + str(self.datetime) + " " - - return toPrint - - -class CQCEPRRequestHeader(Header): - HDR_LENGTH = 16 - PACKAGING_FORMAT = ( - "uint:32=remote_ip, " - "float:32=min_fidelity, " - "float:32=max_time, " - "uint:16=remote_port, " - "uint:8=num_pairs, " - "uint:4=priority, " - "uint:1=store, " - "uint:1=atomic, " - "uint:1=measure_directly, " - "uint:1=0" - ) - - def _setVals(self, remote_ip=0, remote_port=0, num_pairs=0, min_fidelity=0.0, max_time=0.0, priority=0, store=True, - atomic=False, measure_directly=False): - """ - Stores required parameters of Entanglement Generation Protocol Request - - :param remote_ip: int - IP of the other node we are attempting to generate entanglement with - :param remote_port: int - Port number of other node. - :param num_pairs: int - The number of entangled pairs we are trying to generate - :param min_fidelity: float - The minimum acceptable fidelity for the pairs we are generating - :param max_time: float - The maximum amount of time we are permitted to take when generating the pairs - :param priority: obj - Priority on the request - :param store: bool - Specifies whether entangled qubits should be stored within a storage qubit or left within the communication - qubit - :param measure_directly: bool - Specifies whether to measure the communication qubit directly after the photon is emitted - """ - self.remote_ip = remote_ip - self.remote_port = remote_port - self.num_pairs = num_pairs - self.min_fidelity = min_fidelity - self.max_time = max_time - self.priority = priority - self.store = store - self.atomic = atomic - self.measure_directly = measure_directly - - def _pack(self): - """ - Pack the data in packet form. - :return: str - """ - to_pack = { - "remote_ip": self.remote_ip, - "remote_port": self.remote_port, - "min_fidelity": self.min_fidelity, - "max_time": self.max_time, - "num_pairs": self.num_pairs, - "priority": self.priority, - "store": self.store, - "atomic": self.atomic, - "measure_directly": self.measure_directly, - } - request_Bitstring = bitstring.pack(self.PACKAGING_FORMAT, **to_pack) - requestH = request_Bitstring.tobytes() - - return requestH - - def _unpack(self, headerBytes): - """ - Unpack data. - :param headerBytes: str - :return: - """ - request_Bitstring = bitstring.BitString(headerBytes) - request_fields = request_Bitstring.unpack(self.PACKAGING_FORMAT) - self.remote_ip = request_fields[0] - self.min_fidelity = request_fields[1] - self.max_time = request_fields[2] - self.remote_port = request_fields[3] - self.num_pairs = request_fields[4] - self.priority = request_fields[5] - self.store = request_fields[6] - self.atomic = request_fields[7] - self.measure_directly = request_fields[8] - - def _printable(self): - """ - Produce printable string for information purposes - :return: str - """ - to_print = "EPR Request Header." - to_print += "Remote IP: {}".format(self.remote_ip) - to_print += "Remote port: {}".format(self.remote_port) - to_print += "Min Fidelity: {}".format(self.min_fidelity) - to_print += "Max Time: {}".format(self.max_time) - to_print += "Num Pairs: {}".format(self.num_pairs) - to_print += "Priority: {}".format(self.priority) - to_print += "Store: {}".format(self.store) - to_print += "Atomic: {}".format(self.atomic) - to_print += "Measure Directly: {}".format(self.measure_directly) - - return to_print diff --git a/data/examples/simulaqron/CQC-Python/cqc/entInfoHeader.py b/data/examples/simulaqron/CQC-Python/cqc/entInfoHeader.py deleted file mode 100644 index a5afede..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/entInfoHeader.py +++ /dev/null @@ -1,450 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES -# LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import logging - -import struct -import bitstring - -from cqc.cqcHeader import Header - -# Lengths of the headers in bytes -ENT_INFO_LENGTH = 40 # Length of a entanglement information header -ENT_INFO_CREATE_KEEP_LENGTH = 32 # Length of a entanglement information header (for create and keep) -ENT_INFO_MEAS_DIRECT_LENGTH = 28 # Length of a entanglement information header (for measure directly) - -ENT_INFO_TP_CREATE_KEEP = 1 # Type of message when entanglement is kept -ENT_INFO_TP_MEAS_DIRECT = 2 # Type of message when entanglement is measured directly (for classical correlations) - - -class EntInfoHeader(Header): - """ - Header for a entanglement information packet. Fo - """ - - HDR_LENGTH = ENT_INFO_LENGTH - packaging_format = "!LHHLHHLQQHBB" - - def __init__(self, headerBytes=None): - """ - Initialize using values received from a packet, if available. - """ - super().__init__(headerBytes) - if headerBytes is None: - self.node_A = 0 - self.port_A = 0 - self.app_id_A = 0 - - self.node_B = 0 - self.port_B = 0 - self.app_id_B = 0 - - self.id_AB = 0 - - self.timestamp = 0 - self.ToG = 0 - self.goodness = 0 - self.DF = 0 - self.is_set = False - else: - self.unpack(headerBytes) - self.is_set = True - - def _setVals(self, node_A=0, port_A=0, app_id_A=0, node_B=0, port_B=0, app_id_B=0, id_AB=0, timestamp=0, ToG=0, - goodness=0, DF=0): - """ - Set using given values. - """ - self.type = type - self.node_A = node_A - self.port_A = port_A - self.app_id_A = app_id_A - - self.node_B = node_B - self.port_B = port_B - self.app_id_B = app_id_B - - self.id_AB = id_AB - - self.timestamp = timestamp - self.ToG = ToG - self.goodness = goodness - self.DF = DF - - self.is_set = True - - def _pack(self): - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - ent_info = struct.pack( - self.packaging_format, - self.node_A, - self.port_A, - self.app_id_A, - self.node_B, - self.port_B, - self.app_id_B, - self.id_AB, - self.timestamp, - self.ToG, - self.goodness, - self.DF, - 0, - ) - return ent_info - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - """ - ent_info = struct.unpack(self.packaging_format, headerBytes) - - self.node_A = ent_info[0] - self.port_A = ent_info[1] - self.app_id_A = ent_info[2] - - self.node_B = ent_info[3] - self.port_B = ent_info[4] - self.app_id_B = ent_info[5] - - self.id_AB = ent_info[6] - - self.timestamp = ent_info[7] - self.ToG = ent_info[8] - self.goodness = ent_info[9] - self.DF = ent_info[10] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "A: ({}, {}, {})".format(self.node_A, self.port_A, self.app_id_A) + " " - toPrint += "B: ({}, {}, {})".format(self.node_B, self.port_B, self.app_id_B) + " " - toPrint += "Entanglement ID: " + str(self.id_AB) + " " - toPrint += "Timestamp: " + str(self.timestamp) + " " - toPrint += "Time of Goodness: " + str(self.ToG) + " " - toPrint += "Goodness: " + str(self.goodness) + " " - toPrint += "Directionality Flag: " + str(self.DF) - return toPrint - - def switch_nodes(self): - """ - Switches the ip and port of the nodes and flips the directionality flag. - Used to give correct message to both nodes. - """ - - # Get current info - node_A = self.node_A - port_A = self.port_A - app_id_A = self.app_id_A - node_B = self.node_B - port_B = self.port_B - app_id_B = self.app_id_B - DF = self.DF - - # Update - self.node_A = node_B - self.port_A = port_B - self.app_id_A = app_id_B - self.node_B = node_A - self.port_B = port_A - self.app_id_B = app_id_A - if DF == 0: - self.DF = 0 - elif DF == 1: - self.DF = 2 - elif DF == 2: - self.DF = 1 - else: - logging.warning("Unknown directionality flag") - self.DF = DF - - -class EntInfoCreateKeepHeader(Header): - """ - Header for a entanglement information packet, where entanglement is kept after generation - """ - - type = ENT_INFO_TP_CREATE_KEEP - package_format = ( - "uint:4=type, " - "uint:16=mhp_seq, " - "uint:1=DF, " - "uint:11=0, " - "uint:32=ip_A, " - "uint:32=ip_B, " - "uint:16=port_A, " - "uint:16=port_B, " - "float:32=t_create, " - "float:32=t_goodness, " - "float:32=goodness, " - "uint:32=create_id" - ) - - HDR_LENGTH = ENT_INFO_CREATE_KEEP_LENGTH - - def _setVals(self, ip_A=0, port_A=0, ip_B=0, port_B=0, mhp_seq=0, t_create=0.0, t_goodness=0.0, goodness=0.0, DF=0, - create_id=0): - """ - Set using given values. - """ - self.ip_A = ip_A - self.port_A = port_A - - self.ip_B = ip_B - self.port_B = port_B - - self.mhp_seq = mhp_seq - - self.t_create = t_create - self.t_goodness = t_goodness - self.goodness = goodness - self.DF = DF - self.create_id = create_id - - def _pack(self): - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - - to_pack = { - "type": self.type, - "ip_A": self.ip_A, - "port_A": self.port_A, - "ip_B": self.ip_B, - "port_B": self.port_B, - "mhp_seq": self.mhp_seq, - "t_create": self.t_create, - "t_goodness": self.t_goodness, - "goodness": self.goodness, - "DF": self.DF, - "create_id": self.create_id, - } - ent_info_Bitstring = bitstring.pack(self.package_format, **to_pack) - ent_info = ent_info_Bitstring.tobytes() - return ent_info - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - """ - ent_info_Bitstring = bitstring.BitString(headerBytes) - type = ent_info_Bitstring.read("uint:4") - if type != self.type: - raise ValueError("Not an OK of type create-keep") - - ent_info = ent_info_Bitstring.unpack(self.package_format) - - self.mhp_seq = ent_info[1] - self.DF = ent_info[2] - self.ip_A = ent_info[4] - self.ip_B = ent_info[5] - self.port_A = ent_info[6] - self.port_B = ent_info[7] - self.t_create = ent_info[8] - self.t_goodness = ent_info[9] - self.goodness = ent_info[10] - self.create_id = ent_info[11] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Create and Keep OK with createID={}".format(self.create_id) + " " - toPrint += "A: ({}, {})".format(self.ip_A, self.port_A) + " " - toPrint += "B: ({}, {})".format(self.ip_B, self.port_B) + " " - toPrint += "MHP seq.: " + str(self.mhp_seq) + " " - toPrint += "Time of creation: " + str(self.t_create) + " " - toPrint += "Time of Goodness: " + str(self.t_goodness) + " " - toPrint += "Goodness: " + str(self.goodness) + " " - toPrint += "Directionality Flag: " + str(self.DF) - return toPrint - - def switch_nodes(self): - """ - Switches the ip and port of the nodes and flips the directionality flag. - Used to give correct message to both nodes. - """ - - # Get current info - ip_A = self.ip_A - port_A = self.port_A - ip_B = self.ip_B - port_B = self.port_B - DF = self.DF - - # Update - self.ip_A = ip_B - self.port_A = port_B - self.ip_B = ip_A - self.port_B = port_A - if DF == 0: - self.DF = 0 - elif DF == 1: - self.DF = 2 - elif DF == 2: - self.DF = 1 - else: - logging.warning("Unknown directionality flag") - self.DF = DF - - -class EntInfoMeasDirectHeader(Header): - """ - Header for a entanglement information packet, where communication qubit is measured directly after emission. - """ - - type = ENT_INFO_TP_MEAS_DIRECT - package_format = ( - "uint:4=type, " - "uint:16=mhp_seq, " - "uint:1=DF, " - "uint:1=meas_out, " - "uint:2=basis, " - "uint:8=0, " - "uint:32=ip_A, " - "uint:32=ip_B, " - "uint:16=port_A, " - "uint:16=port_B, " - "float:32=t_create, " - "float:32=goodness, " - "uint:32=create_id" - ) - - HDR_LENGTH = ENT_INFO_MEAS_DIRECT_LENGTH - - def _setVals(self, ip_A=0, port_A=0, ip_B=0, port_B=0, mhp_seq=0, meas_out=0, basis=0, t_create=0.0, goodness=0.0, - DF=0, create_id=0): - """ - Set using given values. - """ - self.ip_A = ip_A - self.port_A = port_A - - self.ip_B = ip_B - self.port_B = port_B - - self.mhp_seq = mhp_seq - - self.meas_out = meas_out - self.basis = basis - - self.t_create = t_create - self.goodness = goodness - self.DF = DF - self.create_id = create_id - - def _pack(self): - """ - Pack data into packet format. For defnitions see cLib/cgc.h - """ - to_pack = { - "type": self.type, - "ip_A": self.ip_A, - "port_A": self.port_A, - "ip_B": self.ip_B, - "port_B": self.port_B, - "mhp_seq": self.mhp_seq, - "meas_out": self.meas_out, - "basis": self.basis, - "t_create": self.t_create, - "goodness": self.goodness, - "DF": self.DF, - "create_id": self.create_id, - } - ent_info_Bitstring = bitstring.pack(self.package_format, **to_pack) - ent_info = ent_info_Bitstring.tobytes() - return ent_info - - def _unpack(self, headerBytes): - """ - Unpack packet data. For definitions see cLib/cqc.h - """ - ent_info_Bitstring = bitstring.BitString(headerBytes) - type = ent_info_Bitstring.read("uint:4") - if type != self.type: - raise ValueError("Not an OK of type measure-directly") - - ent_info = ent_info_Bitstring.unpack(self.package_format) - - self.mhp_seq = ent_info[1] - self.DF = ent_info[2] - self.meas_out = ent_info[3] - self.basis = ent_info[4] - self.ip_A = ent_info[6] - self.ip_B = ent_info[7] - self.port_A = ent_info[8] - self.port_B = ent_info[9] - self.t_create = ent_info[10] - self.goodness = ent_info[11] - self.create_id = ent_info[12] - - def _printable(self): - """ - Produce a printable string for information purposes. - """ - toPrint = "Measure Direclty OK with createID={}".format(self.create_id) + " " - toPrint += "A: ({}, {})".format(self.ip_A, self.port_A) + " " - toPrint += "B: ({}, {})".format(self.ip_B, self.port_B) + " " - toPrint += "MHP seq.: " + str(self.mhp_seq) + " " - toPrint += "Measurement outcome: " + str(self.meas_out) + " " - toPrint += "Measurement basis: " + str(self.basis) + " " - toPrint += "Time of creation: " + str(self.t_create) + " " - toPrint += "Goodness: " + str(self.goodness) + " " - toPrint += "Directionality Flag: " + str(self.DF) - return toPrint - - def switch_nodes(self): - """ - Switches the ip and port of the nodes and flips the directionality flag. - Used to give correct message to both nodes. - """ - - # Get current info - ip_A = self.ip_A - port_A = self.port_A - ip_B = self.ip_B - port_B = self.port_B - DF = self.DF - - # Update - self.ip_A = ip_B - self.port_A = port_B - self.ip_B = ip_A - self.port_B = port_A - if DF == 0: - self.DF = 0 - elif DF == 1: - self.DF = 2 - elif DF == 2: - self.DF = 1 - else: - logging.warning("Unknown directionality flag") - self.DF = DF diff --git a/data/examples/simulaqron/CQC-Python/cqc/hostConfig.py b/data/examples/simulaqron/CQC-Python/cqc/hostConfig.py deleted file mode 100644 index 81da502..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/hostConfig.py +++ /dev/null @@ -1,75 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import socket -import struct -from twisted.spread import pb -from ipaddress import IPv4Address - - -def cqc_node_id(fam, ip): - if fam == socket.AF_INET: - return struct.unpack("!L", IPv4Address(ip).packed)[0] - else: - raise ValueError("No IPv6 yet :(") - - -def cqc_node_id_from_addrinfo(addr): - fam = addr[0] - sockaddr = addr[4] - ip = sockaddr[0] - return cqc_node_id(fam, ip) - - -class host(pb.Referenceable): - def __init__(self, name, hostname, port): - """ - Initialize the details of the host. For now, we just keep the following: - - name informal name of the host (e.g. Alice) - hostname name of the node on the network (e.g. localhost or yournode.qutech.nl) - port port number on hostname - """ - - self.name = name - self.hostname = hostname - self.port = int(port) - - # Lookup IP address - addrs = socket.getaddrinfo(hostname, port, proto=socket.IPPROTO_TCP, family=socket.AF_INET) - addr = addrs[0] - self.family = addr[0] - self.addr = addr - - self.ip = cqc_node_id_from_addrinfo(addr) - - # Connection identifiers used after connected - self.factory = 0 - self.root = 0 - self.defer = 0 diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/__init__.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib/__init__.py deleted file mode 100644 index e9d2d5a..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from .cqc_handler import CQCHandler -from .cqc_connection import CQCConnection -from .cqc_mix import CQCMix, CQCVariable, CQCMixConnection, mix_qubit -from .cqc_to_file import CQCToFile -from .qubit import qubit -from .util import ( - ProgressBar, - CQCGeneralError, - CQCNoQubitError, - CQCUnsuppError, - CQCTimeoutError, - CQCInuseError, - CQCUnknownError, - QubitNotActiveError, -) diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_connection.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_connection.py deleted file mode 100644 index 396a2d7..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_connection.py +++ /dev/null @@ -1,616 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import time -import socket -import logging - -from cqc.cqcHeader import ( - CQC_TP_NEW_OK, - CQC_TP_RECV, - CQC_TP_EPR_OK, - CQC_TP_MEASOUT, - CQC_TP_EXPIRE, - CQC_TP_INF_TIME, - Header, - CQCHeader, - CQCMeasOutHeader, - CQCTimeinfoHeader, - CQCXtraQubitHeader, -) -from cqc.entInfoHeader import EntInfoHeader -from cqc.hostConfig import cqc_node_id_from_addrinfo -from .cqc_handler import CQCHandler -from .util import CQCUnsuppError -from .qubit import qubit - -try: - import simulaqron - from simulaqron.general.hostConfig import socketsConfig - from simulaqron.settings import simulaqron_settings - _simulaqron_version = simulaqron.__version__ - _simulaqron_major = int(_simulaqron_version.split('.')[0]) -except ImportError: - _simulaqron_major = -1 - - -class CQCConnection(CQCHandler): - """Handler to be used when sending commands over a socket.""" - def __init__(self, name, socket_address=None, appID=None, pend_messages=False, - retry_connection=True, conn_retry_time=0.1, log_level=None, backend=None, - use_classical_communication=True, network_name=None): - """ - Initialize a connection to the cqc server. - - Since version 3.0.0: If socket_address is None or use_classical_communication is True, the CQC connection - needs some way of finding the correct socket addresses. If backend is None or "simulaqron" the connection - will try to make use of the network config file setup in simulaqron. If simulaqron is not installed - - - **Arguments** - :param name: Name of the host. - :param socket_address: tuple (str, int) of ip and port number. - :param appID: Application ID. If set to None, defaults to a nonused ID. - :param pend_messages: True if you want to wait with sending messages to the back end. - Use flush() to send all pending messages in one go as a sequence to the server - :param retry_connection: bool - Whether to retry a failed connection or not - :param conn_retry_time: float - How many seconds to wait between each connection retry - :param log_level: int or None - The log-level, for example logging.DEBUG (default: logging.WARNING) - :param backend: None or str - If socket_address is None or use_classical_communication is True, If None or "simulaqron" is used - the cqc library tries to use the network config file setup in simulaqron if network_config_file is None. - If network_config_file is None and simulaqron is not installed a ValueError is raised. - :param use_classical_communication: bool - Whether to use the built-in classical communication or not. - :param network_name: None or str - Used if simulaqron is used to load socket addresses for the backend - """ - - super().__init__( - name=name, - app_id=appID, - pend_messages=pend_messages, - ) - - self._setup_logging(log_level) - - # Connection retry time - self._conn_retry_time = conn_retry_time - - # Buffer received data - self.buf = None - - # ClassicalServer - self._classicalServer = None - - # Classical connections in the application network - self._classicalConn = {} - - # Get network configuraton and addresses - addr, cqc_net, app_net = self._setup_network_data( - socket_address=socket_address, - use_classical_communication=use_classical_communication, - backend=backend, - network_name=network_name, - ) - self._cqcNet = cqc_net - self._appNet = app_net - - # Open a socket to the backend - self._s = None - cqc_socket = self._setup_socket(addr=addr, retry_connection=retry_connection) - self._s = cqc_socket - - @staticmethod - def _setup_logging(level): - """ - Sets up the logging to the specified level (default logging.WARNING) - :param level: int or None - For example logging.DEBUG - :return: None - """ - if level is None: - logging.basicConfig(format="%(asctime)s:%(levelname)s:%(message)s", level=logging.WARNING) - else: - logging.basicConfig(format="%(asctime)s:%(levelname)s:%(message)s", level=level) - - def _setup_network_data(self, socket_address, use_classical_communication, backend, - network_name): - addr = None - cqc_net = None - app_net = None - if socket_address is None or use_classical_communication: - cqc_net, app_net = self._get_net_configs( - use_classical_communication=use_classical_communication, - backend=backend, - network_name=network_name, - ) - - # Host data - if self.name in cqc_net.hostDict: - myHost = cqc_net.hostDict[self.name] - else: - raise ValueError("Host name '{}' is not in the cqc network".format(self.name)) - - # Get IP and port number - addr = myHost.addr - - if socket_address is not None: - try: - hostname, port = socket_address - if not isinstance(hostname, str): - raise TypeError() - if not isinstance(port, int): - raise TypeError() - addrs = socket.getaddrinfo(hostname, port, proto=socket.IPPROTO_TCP, family=socket.AF_INET) - addr = addrs[0] - - except Exception: - raise TypeError("When specifying the socket address, this should be a tuple (str,int).") - return addr, cqc_net, app_net - - def _get_net_configs(self, use_classical_communication, backend, network_name): - cqc_net = None - app_net = None - if backend is None or backend == "simulaqron": - if _simulaqron_major < 3: - raise ValueError("If (socket_address is None or use_classical_communication is True)" - "and (backend is None or 'simulaqron'\n" - "you need simulaqron>=3.0.0 installed.") - else: - network_config_file = simulaqron_settings.network_config_file - cqc_net = socketsConfig(network_config_file, network_name=network_name, config_type="cqc") - if use_classical_communication: - app_net = socketsConfig(network_config_file, network_name=network_name, config_type="app") - else: - raise ValueError("Unknown backend") - - return cqc_net, app_net - - def _setup_socket(self, addr, retry_connection): - cqc_socket = None - while True: - try: - logging.debug("App {} : Trying to connect to CQC server".format(self.name)) - - cqc_socket = socket.socket(addr[0], addr[1], addr[2]) - cqc_socket.connect(addr[4]) - break - except ConnectionRefusedError as err: - logging.debug("App {} : Could not connect to CQC server, trying again...".format(self.name)) - time.sleep(self._conn_retry_time) - cqc_socket.close() - if not retry_connection: - self.close() - raise err - except Exception as err: - logging.exception("App {} : Critical error when connection to CQC server: {}".format(self.name, err)) - cqc_socket.close() - raise err - return cqc_socket - - def commit(self, msg): - """Send message through the socket.""" - self._s.send(msg) - - def close(self, release_qubits=True, notify=True): - """Handle closing actions. - - Flushes remaining headers, releases all qubits, closes the - connections, and removes the app ID from the used app IDs. - """ - super().close() - - if self._s is not None: - self._s.close() - - self.closeClassicalServer() - - for name in list(self._classicalConn): - self.closeClassicalChannel(name) - - def new_qubitID(self, print_cqc=False): - """Provide new qubit ID. - - For CQCConnection the qubit ID is given by the server. A message - has to be read and the qubit ID extracted from it. - """ - - msg = self.readMessage() - otherHdr = msg[1] - - if print_cqc: - self.print_CQC_msg(msg) - - return otherHdr.qubit_id - - def startClassicalServer(self): - """Sets up a server for the application communication, - if not already set up. - """ - if self._appNet is None: - raise ValueError( - "Since use_classical_communication was set to False upon init, the built-in classical communication" - "cannot be used." - ) - - if not self._classicalServer: - logging.debug("App {}: Starting classical server".format(self.name)) - # Get host data - myHost = self._appNet.hostDict[self.name] - hostaddr = myHost.addr - - # Setup server - s = socket.socket(hostaddr[0], hostaddr[1], hostaddr[2]) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind(hostaddr[4]) - s.listen(1) - (conn, addr) = s.accept() - logging.debug("App {}: Classical server started".format(self.name)) - self._classicalServer = conn - - def closeClassicalServer(self): - """Closes classical server.""" - - if self._classicalServer: - logging.debug("App {}: Closing classical server".format(self.name)) - self._classicalServer.close() - logging.debug("App {}: Classical server closed".format(self.name)) - self._classicalServer = None - - def recvClassical(self, timout=1, msg_size=1024, close_after=True): - """Receive classical message.""" - - if not self._classicalServer: - self.startClassicalServer() - for _ in range(10 * timout): - logging.debug("App {}: Trying to receive classical message".format(self.name)) - msg = self._classicalServer.recv(msg_size) - if len(msg) > 0: - logging.debug("App {}: Received classical message".format(self.name)) - if close_after: - self.closeClassicalServer() - return msg - time.sleep(0.1) - raise RuntimeError("Timeout: No message received") - - def openClassicalChannel(self, name): - """ - Opens a classical connection to another host in the application network. - - - **Arguments** - - :name: The name of the host in the application network. - :timout: The time to try to connect to the server. When timout is reached an RuntimeError is raised. - """ - if self._appNet is None: - raise ValueError( - "Since use_classical_communication was set to False upon init, the built-in classical communication" - "cannot be used." - ) - if name not in self._classicalConn: - logging.debug("App {}: Opening classical channel to {}".format(self.name, name)) - if name in self._appNet.hostDict: - remoteHost = self._appNet.hostDict[name] - else: - raise ValueError("Host name '{}' is not in the cqc network".format(name)) - - addr = remoteHost.addr - while True: - try: - s = socket.socket(addr[0], addr[1], addr[2]) - s.connect(addr[4]) - logging.debug("App {}: Classical channel to {} opened".format(self.name, name)) - break - except ConnectionRefusedError: - logging.debug( - "App {}: Could not open classical channel to {}, trying again..".format(self.name, name) - ) - time.sleep(self._conn_retry_time) - except Exception as e: - logging.warning( - "App {} : Critical error when connection to app node {}: {}".format(self.name, name, e) - ) - break - self._classicalConn[name] = s - - def closeClassicalChannel(self, name): - """ - Closes a classical connection to another host in the application network. - - - **Arguments** - - :name: The name of the host in the application network. - """ - if name in self._classicalConn: - logging.debug("App {}: Closing classical channel to {}".format(self.name, name)) - s = self._classicalConn.pop(name) - s.close() - logging.debug("App {}: Classical channel to {} closed".format(self.name, name)) - - def sendClassical(self, name, msg, close_after=True): - """ - Sends a classical message to another host in the application network. - - - **Arguments** - - :name: The name of the host in the application network. - :msg: The message to send. Should be either a int in range(0,256) or a list of such ints. - :timout: The time to try to connect to the server. When timout is reached an RuntimeError is raised. - """ - if name not in self._classicalConn: - self.openClassicalChannel(name) - try: - to_send = bytes([int(msg)]) - except (TypeError, ValueError): - to_send = bytes(msg) - logging.debug("App {}: Sending classical message {} to {}".format(self.name, to_send, name)) - self._classicalConn[name].send(to_send) - logging.debug("App {}: Classical message {} to {} sent".format(self.name, to_send, name)) - if close_after: - self.closeClassicalChannel(name) - - def _handle_create_qubits(self, num_qubits, notify): - qubits = [] - for _ in range(num_qubits): - msg = self.readMessage() - self.check_error(msg[0]) - if msg[0].tp != CQC_TP_NEW_OK: - raise CQCUnsuppError("Unexpected message of type {} send back from backend".format(msg[0].tp)) - qubits.append(self.parse_CQC_msg(msg)) - self.print_CQC_msg(msg) - - if notify: - message = self.readMessage() - self._assert_done_message(message) - self.print_CQC_msg(message) - - return qubits - - def readMessage(self, maxsize=192): # WHAT IS GOOD SIZE? - """Receive the whole message from cqc server. - - Returns (CQCHeader,None,None), (CQCHeader,CQCNotifyHeader,None) - or (CQCHeader,CQCNotifyHeader,EntInfoHeader) depending on the - type of message. - - Maxsize is the max size of message. - """ - - # Initialize checks - gotCQCHeader = False - if self.buf: - checkedBuf = False - else: - checkedBuf = True - - while True: - # If buf does not contain enough data, read in more - if checkedBuf: - # Receive data - data = self._s.recv(maxsize) - - # Read whatever we received into a buffer - if self.buf: - self.buf += data - else: - self.buf = data - - # If we don't have the CQC header yet, try and read it in full. - if not gotCQCHeader: - if len(self.buf) < CQCHeader.HDR_LENGTH: - # Not enough data for CQC header, return and wait for the rest - checkedBuf = True - continue - - # Got enough data for the CQC Header so read it in - gotCQCHeader = True - rawHeader = self.buf[0:CQCHeader.HDR_LENGTH] - currHeader = CQCHeader(rawHeader) - - # Remove the header from the buffer - self.buf = self.buf[CQCHeader.HDR_LENGTH : len(self.buf)] - - # Check for error - self.check_error(currHeader) - - # Check whether we already received all the data - if len(self.buf) < currHeader.length: - # Still waiting for data - checkedBuf = True - continue - else: - break - # We got all the data, read other headers if there is any - if currHeader.length == 0: - return currHeader, None, None - else: - if currHeader.tp == CQC_TP_INF_TIME: - timeinfo_header = self._extract_header(CQCTimeinfoHeader) - return currHeader, timeinfo_header, None - elif currHeader.tp == CQC_TP_MEASOUT: - measout_header = self._extract_header(CQCMeasOutHeader) - return currHeader, measout_header, None - elif currHeader.tp in [CQC_TP_RECV, CQC_TP_NEW_OK, CQC_TP_EXPIRE]: - xtra_qubit_header = self._extract_header(CQCXtraQubitHeader) - return currHeader, xtra_qubit_header, None - elif currHeader.tp == CQC_TP_EPR_OK: - xtra_qubit_header = self._extract_header(CQCXtraQubitHeader) - ent_info_hdr = self._extract_header(EntInfoHeader) - return currHeader, xtra_qubit_header, ent_info_hdr - - def _extract_header(self, header_class): - """ - Extracts the given header class from the first part of the current buffer. - :param header_class: Subclassed from `cqc.backend.cqcHeader.Header` - :return: An instance of the class - """ - if not issubclass(header_class, Header): - raise ValueError("header_class {} is not a subclass of Header".format(header_class)) - - try: - rawHeader = self.buf[:header_class.HDR_LENGTH] - except IndexError: - raise ValueError("Got a header message of unexpected size") - self.buf = self.buf[header_class.HDR_LENGTH: len(self.buf)] - header = header_class(rawHeader) - - return header - - def sendQubit(self, q, name, remote_appID=0, notify=True, block=True, remote_socket=None): - """Sends qubit to another node in the cqc network. - - If this node is not in the network an error is raised. - - - **Arguments** - - :q: The qubit to send. - :Name: Name of the node as specified in the cqc network config file. - :remote_appID: The app ID of the application running on the receiving node. - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - :remote_socket: tuple (str, int) of ip and port number. Needed if no cqcFile was specified - """ - q = super().sendQubit( - q=q, - name=name, - remote_appID=remote_appID, - notify=notify, - block=block, - remote_socket=remote_socket, - ) - - def createEPR(self, name, remote_appID=0, notify=True, block=True, remote_socket=None): - """Creates epr with other host in cqc network. - - - **Arguments** - - :name: Name of the node as specified in the cqc network config file. - :remote_appID: The app ID of the application running on the receiving node. - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - :remote_socket: tuple (str, int) of ip and port number. Needed if no cqcFile was specified - """ - return super().createEPR( - name, - remote_appID=remote_appID, - notify=notify, - block=block, - remote_socket=remote_socket, - ) - - def _handle_epr_response(self, notify): - # Get RECV message - message = self.readMessage() - otherHdr = message[1] - entInfoHdr = message[2] - q_id = otherHdr.qubit_id - - self.print_CQC_msg(message) - - if notify: - message = self.readMessage() - self.print_CQC_msg(message) - - # initialize the qubit - q = qubit(self, createNew=False) - - q._set_entanglement_info(entInfoHdr) - q._qID = q_id - # Activate and return qubit - q._set_active(True) - return q - - def _handle_factory_response(self, num_iter, response_amount, should_notify=False): - """Handles the responses from a factory command and returns a list of results""" - res = [] - for _ in range(num_iter): - for _ in range(response_amount): - message = self.readMessage() - self.check_error(message[0]) - # TODO handle new qubit! - res.append(self.parse_CQC_msg(message)) - self.print_CQC_msg(message) - - if should_notify: - message = self.readMessage() - self.check_error(message[0]) - - return res - - def return_meas_outcome(self): - """Return measurement outcome.""" - - msg = self.readMessage() - - try: - otherHdr = msg[1] - return otherHdr.outcome - except AttributeError: - raise RuntimeError("Didn't receive a measurement outcome") - - message = self.readMessage() - self._assert_done_message(message) - self.print_CQC_msg(message) - - def get_remote_from_directory_or_address(self, name, remote_socket=None): - cqcNet = self._cqcNet - if remote_socket is None: - try: - # Get receiving host - hostDict = cqcNet.hostDict - except AttributeError: - raise ValueError( - "If a CQCConnections is initialized without specifying a cqcFile you need to also provide a" - "socket address for the remote node here." - ) - if name in hostDict: - recvHost = hostDict[name] - remote_ip = recvHost.ip - remote_port = recvHost.port - else: - raise ValueError("Host name '{}' is not in the cqc network".format(name)) - else: - try: - remote_host, remote_port = remote_socket - if not isinstance(remote_host, str): - raise TypeError() - if not isinstance(remote_port, int): - raise TypeError() - except Exception: - raise TypeError("When specifying the remote socket address, this should be a tuple (str,int).") - - # Pack the IP - addrs = socket.getaddrinfo(remote_host, remote_port, proto=socket.IPPROTO_TCP, family=socket.AF_INET) - addr = addrs[0] - remote_ip = cqc_node_id_from_addrinfo(addr) - remote_port = addr[4][1] - return remote_ip, remote_port diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_handler.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_handler.py deleted file mode 100644 index 8b456a4..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_handler.py +++ /dev/null @@ -1,911 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import abc -import math -import logging -import warnings -from typing import Any, List -from itertools import count - -from cqc.cqcHeader import ( - CQC_VERSION, - CQC_TP_COMMAND, - CQC_TP_GET_TIME, - CQC_TP_HELLO, - CQC_TP_DONE, - CQC_TP_NEW_OK, - CQC_TP_RECV, - CQC_TP_EPR_OK, - CQC_TP_MEASOUT, - CQC_TP_EXPIRE, - CQC_TP_INF_TIME, - CQC_ERR_GENERAL, - CQC_ERR_NOQUBIT, - CQC_ERR_UNSUPP, - CQC_ERR_TIMEOUT, - CQC_ERR_UNKNOWN, - CQC_CMD_NEW, - CQC_CMD_SEND, - CQC_CMD_EPR, - CQC_CMD_CNOT, - CQC_CMD_CPHASE, - CQC_CMD_ROT_X, - CQC_CMD_ROT_Y, - CQC_CMD_ROT_Z, - CQC_CMD_MEASURE, - CQC_CMD_MEASURE_INPLACE, - CQC_CMD_RECV, - CQC_CMD_EPR_RECV, - CQC_CMD_ALLOCATE, - CQC_TP_FACTORY, - Header, - CQCHeader, - CQCCmdHeader, - CQCTypeHeader, - CQCAssignHeader, - CQCFactoryHeader, - CQCRotationHeader, - CQCXtraQubitHeader, - CQCCommunicationHeader, - CQCType, -) -from .util import ( - CQCUnsuppError, - CQCGeneralError, - CQCNoQubitError, - CQCTimeoutError, - CQCUnknownError, - ProgressBar, -) -from .qubit import qubit - - -class CQCHandler(abc.ABC): - """This class defines the things any CQCHandler must do. - - It is to be subclassed by the various actual classes that handle CQC, such - as CQCConnection and CQCToFile. - """ - - _appIDs = {} - - def __init__(self, name, app_id=None, pend_messages=False, notify=True): - - self.name = name - - # This flag is used to check if CQCConnection is opened using a 'with' statement. - # Otherwise an deprecation warning is printed when instantiating qubits. - self._opened_with_with = False - - # Set an app ID - self._appID = self._get_new_app_id(app_id) - - # This is a sort of global notify - self.notify = notify - - # All qubits active for this connection - self.active_qubits = [] - - # List of pended header objects waiting to be sent to the backend - self._pending_headers = [] # ONLY cqc.cqcHeader.Header objects should be in this list - - # Bool that indicates whether we are in a factory and thus should pend commands - self.pend_messages = pend_messages - - # Keep track of pending messages - self._pending_headers = [] - - @property - def pend_messages(self): - return self._pend_messages - - @pend_messages.setter - def pend_messages(self, value): - self.set_pending(value) - - def __str__(self): - return "CQC handler for node '{}'".format(self.name) - - def _get_new_app_id(self, app_id): - """Finds a new app ID if not specific""" - name = self.name - if name not in self._appIDs: - self._appIDs[name] = [] - - # Which appID - if app_id is None: - for app_id in count(0): - if app_id not in self._appIDs[name]: - self._appIDs[name].append(app_id) - return app_id - else: - if app_id in self._appIDs[name]: - raise ValueError("appID={} is already in use".format(app_id)) - self._appIDs[name].append(app_id) - return app_id - - def __enter__(self): - # This flag is used to check if CQCHandler is opened using a - # 'with' statement. - # Otherwise an deprecation warning is printed when instantiating - # qubits. - self._opened_with_with = True - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - # All qubits should now be released - self.close(release_qubits=True) - - @abc.abstractmethod - def new_qubitID(self, print_cqc=False): - """Provide new qubit ID. - - This method must provide the new qubit ID. This qubit ID could - be given by the server you are communicating with, or it might - simply be a number that increases by one every time the method - is used. This will depend on the type of CQCHandler being used. - """ - pass - - @abc.abstractmethod - def _handle_create_qubits(self, num_qubits, notify): - """Handles responses after allocating qubits and returns a list of qubits""" - pass - - @abc.abstractmethod - def return_meas_outcome(self): - """Return measurement outcome.""" - pass - - @abc.abstractmethod - def commit(self, msg): - """Commit a message. - - This can mean sending it to the backend or just writing to file. - """ - pass - - @abc.abstractmethod - def _handle_factory_response(self, num_iter, response_amount, should_notify=False): - """Handles the responses from a factory command and returns a list of results""" - pass - - @abc.abstractmethod - def get_remote_from_directory_or_address(self, name, **kwargs): - """Returns the remote address of a given node""" - pass - - @abc.abstractmethod - def _handle_epr_response(self, notify): - """Waits for and handles the response message and returns a qubit object.""" - pass - - @abc.abstractmethod - def readMessage(self): - """Receive the whole message from cqc server. - - Returns (CQCHeader,None,None), (CQCHeader,CQCNotifyHeader,None) - or (CQCHeader,CQCNotifyHeader,EntInfoHeader) depending on the - type of message. - """ - pass - - def get_appID(self): - """Returns the application ID.""" - - return self._appID - - def commit_command(self, qID, command, notify=1, block=1, action=0, - xtra_qID=0, step=0, remote_appID=0, remote_node=0, - remote_port=0, ref_id=0): - """Construct and commit command.""" - - headers = self.construct_command_headers( - qID, command, notify=notify, block=block, action=action, - xtra_qID=xtra_qID, step=step, remote_appID=remote_appID, - remote_node=remote_node, remote_port=remote_port, ref_id=ref_id) - self.commit_headers(headers) - - def commit_headers(self, headers): - """Packs a list of headers and commits the message""" - msg = b'' - for header in headers: - msg += header.pack() - self.commit(msg) - - def put_command(self, qID, command, read_notify=True, **kwargs): - """Puts a new command to be executed. - - If self.pend_messages is set to True, the messages are kept until flushing, - otherwise they are commited directly. - - Parameters - ---------- - qID: int - Id of the qubit to apply the command on - command: int - What command to be executed - read_notify : bool - Whether to listen to a notify message in this function or if this is handled - elsewhere (e.g. createEPR) - """ - headers = self.construct_command_headers(qID=qID, command=command, **kwargs) - str_of_headers = "".join(["\t{}\n".format(header) for header in headers]) - if self.pend_messages: - headers = self._update_headers_before_pending(headers) - logging.debug("App {} pends a command with headers:\n{}".format( - self.name, - str_of_headers, - )) - self.pend_headers(headers) - else: - logging.debug("App {} sends a command with headers:\n{}".format( - self.name, - str_of_headers, - )) - self.commit_headers(headers) - if read_notify: - notify = kwargs.get("notify", True) - if notify: - message = self.readMessage() - self._assert_done_message(message) - self.print_CQC_msg(message) - - def _update_headers_before_pending(self, headers): - # Don't include the CQC Headers since this is a sequence - return headers[1:] - - def _assert_done_message(self, message): - if message[0].tp != CQC_TP_DONE: - raise CQCUnsuppError( - "Unexpected message sent back from the server. Message: {}".format(message[0]) - ) - - def pend_headers(self, headers): - """Pends the given headers""" - for header in headers: - self.pend_header(header) - - def pend_header(self, header: Header) -> None: - self._pending_headers.append(header) - - def construct_command(self, qID, command, **kwargs): - """Construct a commmand and packs it in it's binary form. - - Extra arguments are only used if the command if of a type that - needs them. - - - **Arguments** - - :qID: qubit ID - :command: Command to be executed, eg CQC_CMD_H - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - headers = self.construct_command_headers(qID, command, **kwargs) - msg = b'' - for header in headers: - msg += header.pack() - return msg - - def construct_command_headers(self, qID, command, **kwargs): - """Construct a commmand consisting of a list of header objects. - - Extra arguments are only used if the command if of a type that - needs them. - - - **Arguments** - - :qID: qubit ID - :command: Command to be executed, eg CQC_CMD_H - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - # Construct extra header if needed. - xtra_hdr = None - if command == CQC_CMD_SEND or command == CQC_CMD_EPR: - xtra_hdr = CQCCommunicationHeader() - remote_appID = kwargs.get("remote_appID", 0) - remote_node = kwargs.get("remote_node", 0) - remote_port = kwargs.get("remote_port", 0) - xtra_hdr.setVals(remote_appID, remote_node, remote_port) - elif command == CQC_CMD_CNOT or command == CQC_CMD_CPHASE: - xtra_hdr = CQCXtraQubitHeader() - xtra_qID = kwargs.get("xtra_qID", 0) - xtra_hdr.setVals(xtra_qID) - elif (command == CQC_CMD_ROT_X or command == CQC_CMD_ROT_Y - or command == CQC_CMD_ROT_Z): - xtra_hdr = CQCRotationHeader() - step = kwargs.get("step", 0) - xtra_hdr.setVals(step) - elif command == CQC_CMD_MEASURE or command == CQC_CMD_MEASURE_INPLACE: - xtra_hdr = CQCAssignHeader() - ref_id = kwargs.get("ref_id", 0) - xtra_hdr.setVals(ref_id) - - # If xtra_hdr is None, we don't need an extra message. - if xtra_hdr is None: - header_length = CQCCmdHeader.HDR_LENGTH - else: - header_length = CQCCmdHeader.HDR_LENGTH + xtra_hdr.HDR_LENGTH - - # Construct Header - hdr = CQCHeader() - hdr.setVals(CQC_VERSION, CQC_TP_COMMAND, self._appID, header_length) - - # Construct Command - cmd_hdr = CQCCmdHeader() - notify = int(kwargs.get("notify", True)) - block = int(kwargs.get("block", True)) - action = int(kwargs.get("action", False)) - cmd_hdr.setVals(qID, command, notify, block, action) - - headers = [hdr, cmd_hdr] - if xtra_hdr is not None: - headers.append(xtra_hdr) - - return headers - - def construct_simple(self, tp): - """Construct simple message. - - For example a HELLO message if tp=CQC_TP_HELLO. - """ - hdr = CQCHeader() - hdr.setVals(CQC_VERSION, tp, self._appID, 0) - msg = hdr.pack() - return msg - - def sendSimple(self, tp): - """Construct and commit simple message.""" - msg = self.construct_simple(tp) - self.commit(msg) - - def close(self, release_qubits=True): - """Handle exiting of context.""" - - if release_qubits: - for q in list(self.active_qubits): - q.release() - - # Flush all remaining commands and the releases - self.flush() - - self._pop_app_id() - - def _pop_app_id(self): - """ - Removes the used appID from the list. - """ - try: - self._appIDs[self.name].remove(self._appID) - except ValueError: - pass # Already removed - - def create_qubits(self, num_qubits, block=True, notify=True): - """Requests the backend to reserve some qubits - - :param num_qubits: The amount of qubits to reserve - :return: A list of qubits - :param notify: Do we wish to be notified when done. - :param block: Do we want the qubit to be blocked - """ - notify = self.notify and notify - - # TODO how to handle pending headers? - headers = self.construct_command_headers( - qID=num_qubits, - command=CQC_CMD_ALLOCATE, - notify=notify, - block=block, - ) - self.commit_headers(headers) - - qubits = self._handle_create_qubits(num_qubits=num_qubits, notify=notify) - - return qubits - - def sendGetTime(self, qID, notify=1, block=1, action=0): - """Sends get-time message - - - **Arguments** - - :qID: qubit ID - :command: Command to be executed, eg CQC_CMD_H - :notify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - :action: Are there more commands to be executed - """ - # Send Header - hdr = CQCHeader() - hdr.setVals(CQC_VERSION, CQC_TP_GET_TIME, self._appID, CQCCmdHeader.HDR_LENGTH) - msg = hdr.pack() - self.commit(msg) - - # Send Command - cmd_hdr = CQCCmdHeader() - cmd_hdr.setVals(qID, 0, notify, block, action) - cmd_msg = cmd_hdr.pack() - self.commit(cmd_msg) - - def allocate_qubits(self, nb_of_qubits: int) -> List['qubit']: - """ - Creates (i.e. allocates) multiple qubits, and returns a list with qubit objects. - - :nb_of_qubits: The amount of qubits to be created. - """ - warnings.warn("allocate_qubits is deprecated, use create_qubits instead", - DeprecationWarning) - - return self.create_qubits(nb_of_qubits) - - def createEPR(self, name, remote_appID=0, notify=True, block=True, **kwargs): - """Creates epr with other host in the network. - - - **Arguments** - - :name: Name of the node as specified in the cqc network config file. - :remote_appID: The app ID of the application running on the receiving node. - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - remote_ip, remote_port = self.get_remote_from_directory_or_address(name, **kwargs) - - # print info - logging.debug( - "App {} puts message: 'Create EPR-pair with {} and appID {}'".format(self.name, name, remote_appID) - ) - notify = self.notify and notify - self.put_command( - 0, - CQC_CMD_EPR, - read_notify=False, - notify=notify, - block=block, - remote_appID=remote_appID, - remote_node=remote_ip, - remote_port=remote_port, - ) - if not self.pend_messages: - q = self._handle_epr_response(notify=notify) - return q - - def recvEPR(self, notify=True, block=True): - """Receives a qubit from an EPR-pair generated with another node. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - # print info - logging.debug("App {} puts message: 'Receive half of EPR'".format(self.name)) - notify = self.notify and notify - self.put_command( - qID=0, - command=CQC_CMD_EPR_RECV, - read_notify=False, - notify=notify, - block=block, - ) - - if not self.pend_messages: - q = self._handle_epr_response(notify=notify) - return q - - def sendQubit(self, q, name, remote_appID=0, notify=True, block=True, **kwargs): - """Sends qubit to another node in the cqc network. - - If this node is not in the network an error is raised. - - - **Arguments** - - :q: The qubit to send. - :Name: Name of the node as specified in the cqc network config file. - :remote_appID: The app ID of the application running on the receiving node. - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - remote_ip, remote_port = self.get_remote_from_directory_or_address(name, **kwargs) - - # print info - logging.debug( - "App {} puts message: 'Send qubit with ID {} to {} and appID {}'".format( - self.name, q._qID, name, remote_appID - ) - ) - notify = self.notify and notify - self.put_command( - qID=q._qID, - command=CQC_CMD_SEND, - notify=notify, - block=block, - remote_appID=remote_appID, - remote_node=remote_ip, - remote_port=remote_port, - ) - # Deactivate qubit - # TODO should this be done if pending messages? - q._set_active(False) - - def recvQubit(self, notify=True, block=True): - """Receives a qubit. - - - **Arguments** - - :q: The qubit to send. - :Name: Name of the node as specified in the cqc network config file. - :remote_appID: The app ID of the application running on the receiving node. - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - - # print info - logging.debug("App {} puts message: 'Receive qubit'".format(self.name)) - notify = self.notify and notify - self.put_command(0, CQC_CMD_RECV, read_notify=False, notify=notify, block=block) - if not self.pend_messages: - # Get qubit id - q_id = self.new_qubitID(print_cqc=True) - - # initialize the qubit - q = qubit(self, createNew=False) - q._qID = q_id - - # Activate and return qubit - q._set_active(True) - - # Read the notify message - if notify: - message = self.readMessage() - self._assert_done_message(message) - self.print_CQC_msg(message) - - return q - - def flush(self, do_sequence=False): - """Flush all pending messages to the backend. - - :param do_sequence: boolean to indicate if you want to send the pending messages as a sequence - :return: A list of things that are sent back from the server. Can be qubits, or outcomes - """ - return self.flush_factory(1, do_sequence) - - def flush_factory(self, num_iter, do_sequence=False, block_factory=False): - """ - Flushes the current pending sequence in a factory. It is performed multiple times - :param num_iter: The amount of times the current pending sequence is performed - :return: A list of outcomes/qubits that are produced by the commands - """ - if len(self._pending_headers) == 0: - return [] - - # Initialize should_notify to False - should_notify = False - - # Store how many of the headers we send will get a response message from the backend - response_amount = 0 - - # Loop over the pending_headers to determine the total length and set should_notify - for header in self._pending_headers: - - # Check if the current header is a Command header. It can also be a sub header - if isinstance(header, CQCCmdHeader): - # set should_notify to True if at least one of all command headers has notify to True - should_notify = should_notify or header.notify - - # Remember this header if we expect a return messge - if self.shouldReturn(header.instr): - response_amount += 1 - - # Determine the CQC Header type - if num_iter == 1: - cqc_type = CQC_TP_COMMAND - else: - # Build and insert the Factory header - cqc_type = CQC_TP_FACTORY - factory_header = CQCFactoryHeader() - factory_header.setVals(num_iter, should_notify, block_factory) - # Insert the factory header at the front - self._pending_headers.insert(0, factory_header) - - # Insert the cqc header - self.insert_cqc_header(cqc_type) - - # Send all pending headers - self.send_pending_headers() - - # Reset _pending_headers to an empty list after all headers are sent - self.reset_pending_headers() - - # Read out any returned messages from the backend - res = self._handle_factory_response(num_iter, response_amount, should_notify=should_notify) - - # Return information that the backend returned - return res - - def send_pending_headers(self) -> List[Any]: - """ - Sends all pending headers. - After sending, self._pending_headers is emptied. - """ - - # Send all pending headers - to_log = "App {} sends a message with the following headers:\n".format(self.name) - msg = b'' - for header in self._pending_headers: - to_log += "\t{}\n".format(header) - msg += header.pack() - logging.debug(to_log[:-1]) - self.commit(msg) - - def reset_pending_headers(self): - """Sets the list of pending headers to empty """ - self._pending_headers = [] - - def set_pending(self, pend_messages): - """Set the pend_messages flag. - - If true, flush() has to be called to send all self._pending_headers in sequence to the backend - If false, all commands are directly send to the back_end - :param pend_messages: Boolean to indicate if messages should pend or not - """ - # Check if the list is not empty, give a warning if it isn't - if self._pending_headers: - logging.warning("List of pending headers is not empty, flushing them") - self.flush() - self._pend_messages = pend_messages - - def insert_cqc_header(self, cqc_type: CQCType, version=CQC_VERSION) -> None: - """ - Inserts a CQC Header at index 0 of self._pending_headers. - Invoke this method *after* all other headers are pended, so that the correct message length is calculated. - """ - - # Count the total message length - message_length = 0 - for header in self._pending_headers: - message_length += header.HDR_LENGTH - - # Build the CQC Header - cqc_header = CQCHeader() - cqc_header.setVals(CQC_VERSION, cqc_type, self._appID, message_length) - - # Insert CQC Header at the front - self._pending_headers.insert(0, cqc_header) - - def _pend_type_header(self, cqc_type: CQCType, length: int) -> None: - """ - Creates a CQCTypeHeader and pends it. - """ - header = CQCTypeHeader() - header.setVals(cqc_type, length) - self.pend_header(header) - - def tomography(self, preparation, iterations, progress=True): - """ - Does a tomography on the output from the preparation specified. - The frequencies from X, Y and Z measurements are returned as a tuple (f_X,f_Y,f_Z). - - - **Arguments** - - :preparation: A function that takes a CQCConnection as input and prepares a qubit and returns this - :iterations: Number of measurements in each basis. - :progress_bar: Displays a progress bar - """ - accum_outcomes = [0, 0, 0] - if progress: - bar = ProgressBar(3 * iterations) - - # Measure in X - for _ in range(iterations): - # Progress bar - if progress: - bar.increase() - - # prepare and measure - q = preparation(self) - q.H() - m = q.measure() - accum_outcomes[0] += m - - # Measure in Y - for _ in range(iterations): - # Progress bar - if progress: - bar.increase() - - # prepare and measure - q = preparation(self) - q.K() - m = q.measure() - accum_outcomes[1] += m - - # Measure in Z - for _ in range(iterations): - # Progress bar - if progress: - bar.increase() - - # prepare and measure - q = preparation(self) - m = q.measure() - accum_outcomes[2] += m - - if progress: - bar.close() - del bar - - freqs = map(lambda x: x / iterations, accum_outcomes) - return list(freqs) - - def test_preparation(self, preparation, exp_values, conf=2, iterations=100, progress=True): - """Test the preparation of a qubit. - Returns True if the expected values are inside the confidence interval produced from the data received from - the tomography function - - - **Arguments** - - :preparation: A function that takes a CQCConnection as input and prepares a qubit and returns this - :exp_values: The expected values for measurements in the X, Y and Z basis. - :conf: Determines the confidence region (+/- conf/sqrt(iterations) ) - :iterations: Number of measurements in each basis. - :progress_bar: Displays a progress bar - """ - epsilon = conf / math.sqrt(iterations) - - freqs = self.tomography(preparation, iterations, progress=progress) - for i in range(3): - if abs(freqs[i] - exp_values[i]) > epsilon: - print(freqs, exp_values, epsilon) - return False - return True - - def print_CQC_msg(self, message): - """ - Prints messsage returned by the readMessage method of CQCConnection. - """ - # First check if there was an error - self.check_error(message[0]) - - hdr = message[0] - otherHdr = message[1] - entInfoHdr = message[2] - - if hdr.tp == CQC_TP_HELLO: - logging.debug("CQC tells App {}: 'HELLO'".format(self.name)) - elif hdr.tp == CQC_TP_EXPIRE: - logging.debug("CQC tells App {}: 'Qubit with ID {} has expired'".format(self.name, otherHdr.qubit_id)) - elif hdr.tp == CQC_TP_DONE: - logging.debug("CQC tells App {}: 'Done with command'".format(self.name)) - elif hdr.tp == CQC_TP_RECV: - logging.debug("CQC tells App {}: 'Received qubit with ID {}'".format(self.name, otherHdr.qubit_id)) - elif hdr.tp == CQC_TP_EPR_OK: - - # Lookup host name - remote_node = entInfoHdr.node_B - remote_port = entInfoHdr.port_B - remote_name = None - try: - for node in self._cqcNet.hostDict.values(): - if (node.ip == remote_node) and (node.port == remote_port): - remote_name = node.name - break - if remote_name is None: - raise RuntimeError("Remote node ({},{}) is not in config-file.".format(remote_node, remote_port)) - except AttributeError: - remote_name = "({}, {})".format(remote_node, remote_port) - - logging.debug( - "CQC tells App {}: 'EPR created with node {}, using qubit with ID {}'".format( - self.name, remote_name, otherHdr.qubit_id - ) - ) - elif hdr.tp == CQC_TP_MEASOUT: - logging.debug("CQC tells App {}: 'Measurement outcome is {}'".format(self.name, otherHdr.outcome)) - elif hdr.tp == CQC_TP_INF_TIME: - logging.debug("CQC tells App {}: 'Timestamp is {}'".format(self.name, otherHdr.datetime)) - - def parse_CQC_msg(self, message, q=None, is_factory=False): - """ - parses the cqc message and returns the relevant value of that measure - (qubit, measurement outcome) - - :param message: str - the cqc message to be parsed - :param q: :obj:`cqc.pythonLib.qubit` - the qubit object we should save the qubit to - :param is_factory: bool - whether the returned message came from a factory. If so, do not change the qubit, but create a new one - :return: the result of the message (either a qubit, or a measurement outcome. Otherwise None - """ - hdr = message[0] - otherHdr = message[1] - if len(message) < 3: - entInfoHdr = None - else: - entInfoHdr = message[2] - - if hdr.tp in {CQC_TP_RECV, CQC_TP_NEW_OK, CQC_TP_EPR_OK}: - if is_factory: - q._set_active(False) # Set qubit to inactive so it can't be used anymore - q = qubit(self, createNew=False) - if q is None: - q = qubit(self, createNew=False) - q._qID = otherHdr.qubit_id - q._set_entanglement_info(entInfoHdr) - q._set_active(True) - return q - if hdr.tp == CQC_TP_MEASOUT: - return otherHdr.outcome - if hdr.tp == CQC_TP_INF_TIME: - return otherHdr.datetime - - def check_error(self, hdr): - """Checks if there is an error returned.""" - - self._errorHandler(hdr.tp) - - def _errorHandler(self, cqc_err): - """Raises an error if there is an error-message.""" - - if cqc_err == CQC_ERR_GENERAL: - raise CQCGeneralError("General error") - if cqc_err == CQC_ERR_NOQUBIT: - raise CQCNoQubitError("No more qubits available") - if cqc_err == CQC_ERR_UNSUPP: - raise CQCUnsuppError("Sequence not supported") - if cqc_err == CQC_ERR_TIMEOUT: - raise CQCTimeoutError("Timeout") - if cqc_err == CQC_ERR_UNKNOWN: - raise CQCUnknownError("Unknown qubit ID") - - @staticmethod - def shouldReturn(command): - return command in { - CQC_CMD_NEW, - CQC_CMD_MEASURE, - CQC_CMD_MEASURE_INPLACE, - CQC_CMD_RECV, - CQC_CMD_EPR_RECV, - CQC_CMD_EPR, - } - - @staticmethod - def hasXtraHeader(command): - return command in { - CQC_CMD_CNOT, - CQC_CMD_SEND, - CQC_CMD_EPR, - CQC_CMD_ROT_X, - CQC_CMD_ROT_Y, - CQC_CMD_ROT_Z, - CQC_CMD_CPHASE, - } diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_mix.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_mix.py deleted file mode 100644 index f07157c..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_mix.py +++ /dev/null @@ -1,480 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from typing import Union -from anytree import NodeMixin - -from cqc.cqcHeader import ( - CQC_CMD_MEASURE, - CQC_CMD_MEASURE_INPLACE, - CQCIfHeader, - CQCTypeHeader, - CQCFactoryHeader, - CQCType, - CQCLogicalOperator, -) -from .util import CQCGeneralError, QubitNotActiveError -from .qubit import qubit -from .cqc_connection import CQCConnection - - -class CQCVariable: - """ - Instances of this class are returned by measure command, if executed inside a CQCMix context. - A CQCVariable holds a reference ID with which one can refer to the outcome of the measurement. - """ - _next_ref_id = 0 - - def __init__(self): - """ - Increments the reference ID, and assigns the new unique reference ID to this CQCVariable. - This system ensures no two CQCVariable instances have the same reference ID. - """ - self._ref_id = CQCVariable._next_ref_id - CQCVariable._next_ref_id += 1 - - # make ref_id a read-only variable - @property - def ref_id(self): - """ - Get the refernce ID of this CQCVariable. This is a read-only property. - """ - return self._ref_id - - # override the == operator - # other can be a CQCVariable or int - def __eq__(self, other: Union['CQCVariable', int]): - return _LogicalFunction(self, CQCLogicalOperator.EQ, other) - - # override the != operator - def __ne__(self, other: Union['CQCVariable', int]): - return _LogicalFunction(self, CQCLogicalOperator.NEQ, other) - - -class _LogicalFunction: - """ - Private helper class. This class should never be used outside this pythonLib. - """ - - def __init__( - self, - operand_one: CQCVariable, - operator: CQCLogicalOperator, - operand_two: Union[CQCVariable, int] - ): - """ - Stores all information necessary to create a logical comparison - - - **Arguments** - - :operand_one: The CQCVariable that stores the measurement outcome that must be compared - :operator: One of the CQCLogicalOperator types that CQC supports. - At present, equality and inequality are supported. - :operand_two: Either a CQCVariable or an integer. - If a CQCVariable, then the value behind this variable will be compared to operand_one. - If an integer, then the value behind operand_one will be compared to this integer. - """ - - self.operand_one = operand_one - self.operator = operator - self.operand_two = operand_two - - def get_negation(self) -> '_LogicalFunction': - return _LogicalFunction(self.operand_one, CQCLogicalOperator.opposite_of(self.operator), self.operand_two) - - def get_CQCIfHeader(self) -> CQCIfHeader: - """ - Builds the If header corresponding to this logical function. - """ - - if isinstance(self.operand_two, int): - type_of_operand_two = CQCIfHeader.TYPE_VALUE - operand_two = self.operand_two - else: - type_of_operand_two = CQCIfHeader.TYPE_REF_ID - operand_two = self.operand_two._ref_id - - header = CQCIfHeader() - header.setVals( - self.operand_one.ref_id, - self.operator, - type_of_operand_two, - operand_two, - length=0 - ) - return header - - -class CQCMixConnection(CQCConnection): - """Subclass of CQCconnection to be used with CQCMix""" - def __init__(self, name, socket_address=None, appID=None, pend_messages=False, - retry_connection=True, conn_retry_time=0.1, log_level=None, backend=None, - use_classical_communication=True, network_name=None): - super().__init__( - name=name, - socket_address=socket_address, - appID=appID, - pend_messages=pend_messages, - retry_connection=retry_connection, - conn_retry_time=conn_retry_time, - log_level=log_level, - backend=backend, - use_classical_communication=use_classical_communication, - network_name=network_name, - ) - - # Variable of type NodeMixin. This variable is used in CQCMix types to create a - # scoping mechanism. - self.current_scope = None - - self._inside_cqc_mix = False - - def _update_headers_before_pending(self, headers): - # Insert type headers if in cqc mix - if self._inside_cqc_mix: - length = sum([hdr.HDR_LENGTH for hdr in headers[1:]]) - tp_header = CQCTypeHeader() - tp_header.setVals(CQCType.COMMAND, length) - return [tp_header] + headers[1:] - else: - return headers[1:] - - def _enter_mix(self): - # Set the _inside_cqc_mix bool to True on the connection - self._inside_cqc_mix = True - - self.pend_messages = True - - -class mix_qubit(qubit): - def __init__(self, cqc: CQCMixConnection, notify=True, block=True, createNew=True, q_id=None, entInfo=None): - # This stores the scope (type NodeMixin) in which this qubit was deactivated - # If the qubit has not yet been deactivated, this is set to None - self.scope_of_deactivation = None - - super().__init__( - cqc=cqc, - notify=notify, - block=block, - createNew=createNew, - q_id=q_id, - entInfo=entInfo, - ) - - def check_active(self): - """ - Checks if the qubit is active - """ - if not self._active: - - # This conditional checks whether it is certain that the qubit is inactive at this - # point in the code. If such is the case, an error is raised. - # At this point, it is certain that self_active is False. However, this does not necessarily - # mean that the qubit is inactive due to the possibility to write cqc_if blocks. - # There are four options: - # 1) Control is currently not inside a CQCMix. In that case, the qubit is inactive. - # 2) The qubit was deactivated in the current scope. The qubit therefore is inactive. - # 3) The qubit was deactivated in an ancestor scope. The qubit therefore is inactive. - # 4) The qubit was deactivated in a descendent scope. The qubit is therefore inactive. - # The only possible way self_active can be False but the qubit is in fact active, is - # if the qubit was deactivated in a sibling scope, such as the sibling if-block of an else-block. - if ( - not self._cqc._inside_cqc_mix - or self.scope_of_deactivation == self._cqc.current_scope - or self.scope_of_deactivation in self._cqc.current_scope.ancestors - or self.scope_of_deactivation in self._cqc.current_scope.descendants - ): - - raise QubitNotActiveError( - "Qubit is not active. Possible causes:\n" - "- Qubit is sent to another node\n" - "- Qubit is measured (with inplace=False)\n" - "- Qubit is released\n" - "- Qubit is not received\n" - "- Qubit is used and created in the same factory\n" - "- Qubit is measured (with inplace=False) inside a cqc_if block earlier in the code\n" - ) - - def _set_active(self, be_active): - - # Set the scope of deactivation to the current scope, if inside a CQCMix. - if not be_active and self._cqc._inside_cqc_mix: - self.scope_of_deactivation = self._cqc.current_scope - - super()._set_active(be_active) - - def measure(self, inplace=False, block=True): - """ - Measures the qubit in the standard basis and returns the measurement outcome. - If now MEASOUT message is received, None is returned. - If inplace=False, the measurement is destructive and the qubit is removed from memory. - If inplace=True, the qubit is left in the post-measurement state. - - - **Arguments** - - :inplace: If false, measure destructively. - :block: Do we want the qubit to be blocked - """ - # check if qubit is active - self.check_active() - - if inplace: - command = CQC_CMD_MEASURE_INPLACE - else: - command = CQC_CMD_MEASURE - # Set qubit to non active so the user can receive helpful errors during compile time - # if this qubit is used after this measurement - self._set_active(False) - - if self._cqc.pend_messages: - cqc_variable = CQCVariable() - ref_id = cqc_variable.ref_id - else: - ref_id = 0 - - self._cqc.put_command( - qID=self._qID, - command=command, - notify=False, - block=block, - ref_id=ref_id, - ) - - if self._cqc.pend_messages: - return cqc_variable - else: - return self._cqc.return_meas_outcome() - - -class CQCMix(NodeMixin): - """ - This Python Context Manager Type can be used to create CQC programs that consist of more than a single type. - Hence the name CQC Mix. Programs of this type can consist of any number and mix of the other CQC types. - """ - - def __init__(self, cqc_connection: CQCMixConnection): - """ - Initializes the Mix context. - - - **Arguments** - - :cqc_connection: The CQCConnection to which this CQC Program must be sent. - """ - if not isinstance(cqc_connection, CQCMixConnection): - raise TypeError("To use CQCMix the connection needs to be of type CQCMixConnection, " - "not {}".format(type(cqc_connection))) - - self._conn = cqc_connection - - # Set the current scope to self - self._conn.current_scope = self - - def __enter__(self): - # Update the connection to be compatible with mixing - self._conn._enter_mix() - - # Return self so that this instance is bound to the variable after "as", i.e.: "with CQCMix() as pgrm" - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - - # Only do these things if there was no exception. - if exc_type is None: - # Build and insert the CQC Header - self._conn.insert_cqc_header(CQCType.MIX) - - # Send this program to the backend - self._conn.send_pending_headers() - self._conn.reset_pending_headers() - - # We expect one message back, which can be an error or TP_DONE - # This also blocks the program until we have received a message from the backend, - # which is important because it avoids that we send more messages before the backend is finished. - message = self._conn.readMessage() - - # Check if it is an error and assume it is a TP_DONE if it is not an error - self._conn.check_error(message[0]) - - # We are no longer in a TP_MIX - self._conn._inside_cqc_mix = False - - self._conn.pend_messages = False - - # Set the current scope to None, since we exit the CQCMix context - # current_scope is only used inside CQCMix contexts - self._conn.current_scope = None - - def cqc_if(self, logical_function: _LogicalFunction): - """ - Open a Python Context Manager Type to start an if-statement block. - - - **Arguments** - - :logical_function: A _LogicalFunction instance. Never instantiate this explicitely; instead - use the following: CQCVariable == 1 OR CQCVariable == CQCVariable. - CQCVariable can be any instance that you want to test to a value, or to another - CQCVariable. The operator can be == or !=. - The value can be any integer (though only 1 and 0 make sense). - - """ - return _CQCConditional(self._conn, False, logical_function) - - def cqc_else(self): - """ - Open a Python Context Manager Type to start an else-statement block. - This will be an else-block of the last closed cqc_if-block. - """ - # Find out to which if this else belongs - return _CQCConditional(self._conn, True) - - def loop(self, times: int): - """ - Open a Python Context Manager Type to start a factory (i.e. repeated sequence of commands). - - - **Arguments** - - :times: The number of times the commands inside body of this context should be repeated. - - """ - return _CQCFactory(self._conn, times) - - -class _CQCFactory: - """ - Private class to create factories inside CQCMix contexts. Never explicitely instantiate this class outside - the source code of this library. - Instead, use CQCMix.loop(x), where x is the amount of times to repeat. - """ - - def __init__(self, cqc_connection, repetition_amount: int): - self._conn = cqc_connection - self._repetition_amount = repetition_amount - - def __enter__(self): - - # Inside a TP_FACTORY, we don't want CQCType headers before every instruction. - # Therefore, we set this bool to False - self._conn._inside_cqc_mix = False - - # Create the CQC Type header, and store it so that we can modify its length at __exit__ - self.type_header = CQCTypeHeader() - self.type_header.setVals(CQCType.FACTORY, length=0) - - # Build the Factory header - factory_header = CQCFactoryHeader() - factory_header.setVals(self._repetition_amount) - - # Pend the headers - self._conn.pend_header(self.type_header) - self._conn.pend_header(factory_header) - - def __exit__(self, exc_type, exc_val, exc_tb): - - # Outside a TP_FACTORY, we want CQCType headers before every instruction. - # Therefore, we set this bool to True - self._conn._inside_cqc_mix = True - - # Calculate the length of the body of the factory - # Loop in reverse through all pending_headers to calculate the length of all headers - index = len(self._conn._pending_headers) - 1 - body_length = 0 - while self._conn._pending_headers[index] is not self.type_header: - body_length += self._conn._pending_headers[index].HDR_LENGTH - index -= 1 - - # Set the correct length - self.type_header.length = body_length - - -class _CQCConditional(NodeMixin): - """ - Private helper class. Never explicitely instantiate this class outside the source code of this library. - This Context Manager class is instantiated by CQCMix.cqc_if() and CQCMix.cqc_else(). Its - function is to build and pend CQC If headers. - """ - - # This private class variable holds the last _CQCConditional that - # functioned as an IF (as opposed to an ELSE) on which __exit__ is invoked. - # In other words, it is the last closed IF statement. - # This is important so that ELSE statements can find out to which IF statement they belong. - # If this variable is None, then there either has not been aan IF statement yet, or the last - # _CQCConditional was an ELSE. - _last_closed_conditional = None - - def __init__(self, cqc_connection, is_else: bool, logical_function: _LogicalFunction = None): - self._conn = cqc_connection - self.is_else = is_else - - if is_else: - # If _last_closed_conditional is None, then there either has not been aan IF statement yet, or the last - # _CQCConditional was an ELSE. - if _CQCConditional._last_closed_conditional is None: - raise CQCGeneralError('Cannot use an ELSE if there is no IF directly before it.') - else: - # Get the negation of the logical function of the IF, - # which will be the logical function for this ELSE statement - logical_function = _CQCConditional._last_closed_conditional._logical_function.get_negation() - - self._logical_function = logical_function - - def __enter__(self): - # Pend CQC Type header - self._conn._pend_type_header(CQCType.IF, CQCIfHeader.HDR_LENGTH) - - # Build the IF header, and store it so we can modify its length at __exit__ - self.header = self._logical_function.get_CQCIfHeader() - - # Pend the IF header - self._conn.pend_header(self.header) - - # Register the parent scope, and set the current scope to self - self.parent = self._conn.current_scope - self._conn.current_scope = self - - def __exit__(self, exc_type, exc_val, exc_tb): - - # Set _last_closed_conditional to the correct value - if (self.is_else): - _CQCConditional._last_closed_conditional = None - else: - _CQCConditional._last_closed_conditional = self - - # Calculate the length of the body of the conditional - # Loop in reverse through all pending_headers to calculate the lenght of all headers - index = len(self._conn._pending_headers) - 1 - body_length = 0 - while self._conn._pending_headers[index] is not self.header: - body_length += self._conn._pending_headers[index].HDR_LENGTH - index -= 1 - - # Set the correct length - self.header.length = body_length - - # Set the scope to the parent scope - self._conn.current_scope = self.parent diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_to_file.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_to_file.py deleted file mode 100644 index eecc8f8..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/cqc_to_file.py +++ /dev/null @@ -1,169 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import os - -from cqc.cqcHeader import CQCCmdHeader, CQC_CMD_MEASURE, CQC_CMD_MEASURE_INPLACE -from .qubit import qubit -from .cqc_handler import CQCHandler - - -class CQCToFile(CQCHandler): - """Handler to be used when writing the CQC commands to a file.""" - - def __init__(self, name=None, file='CQC_File', pend_messages=False, - overwrite=False, binary=True): - - if name is None: - name = file - - # Call init of CQCHandler - super().__init__(file, pend_messages=pend_messages) - - self.next_qubitID = 0 - - self.binary = binary - - self.file = file - - # Check if file exists - if overwrite: - # Remove file if we can overwrite - try: - os.remove(self.file) - except FileNotFoundError: - pass - else: - if not os.path.isfile(self.file): - pass - else: - # Append number to filename if can't overwrite - num = 0 - while True: - if os.path.isfile(self.file + str(num)): - num += 1 - else: - self.file = self.file + str(num) - break - - # Don't want notify when writing to file - self.notify = False - - def commit(self, msg): - """Write a message to file. - - Message is written as string or as bytes depending on - self.binary - """ - - if self.binary is True: - with open(self.file, 'ab') as f: - f.write(msg) - else: - with open(self.file, 'a') as f: - f.write(str(msg) + '\n') - - def _handle_create_qubits(self, num_qubits): - qubits = [] - for _ in range(num_qubits): - q = qubit(self, createNew=False) - q._qID = self.new_qubitID() - q._set_active(True) - qubits.append(q) - - return qubits - - def new_qubitID(self, print_cqc=False): - """Provice new qubit ID. - - For CQCToFile we simply increase the qubit ID by one for each - new qubit. - """ - - qubitID = self.next_qubitID - - self.next_qubitID += 1 - - return qubitID - - def get_remote_from_directory_or_address(self, name): - # Only return fixed address and port for now - return 0, 0 - - def _handle_epr_response(self, notify): - # Initialize the qubit - q = qubit(self, createNew=False) - - entInfoHdr = None # TODO: create function that returns some fake entanglement info - q_id = self.new_qubitID() - - q._set_entanglement_info(entInfoHdr) - q._qID = q_id - - # Activate and return qubit - q._set_active(True) - - return q - - def return_meas_outcome(self): - """Return measurement outcome.""" - - return 0 - - def readMessage(self): - """For now returns nothing""" - return None - - def _handle_factory_response(self, num_iter, response_amount, should_notify=False): - """Handles the responses from a factory command and returns a list of results""" - res = [] - # Loop over the pending_headers to determine the total length and set should_notify - for header in self._pending_headers: - - # Check if the current header is a Command header. It can also be a sub header - if isinstance(header, CQCCmdHeader): - - if self.shouldReturn(header.instr): - # Build artificial responses - if header.instr in (CQC_CMD_MEASURE, CQC_CMD_MEASURE_INPLACE): - res.append(self.return_meas_outcome()) - # TODO entanglement information etc - else: - q = None - if num_iter != 1: - q._set_active(False) - q = qubit(self, createNew=False) - if q is None: - q = qubit(self, createNew=False) - q._qID = self.new_qubitID() - q._set_entanglement_info(None) - q._set_active(True) - res.append(q) - - return res diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/qubit.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib/qubit.py deleted file mode 100644 index 1f3e5fc..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/qubit.py +++ /dev/null @@ -1,523 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import logging -import warnings -from cqc.cqcHeader import ( - CQC_CMD_NEW, - CQC_CMD_I, - CQC_CMD_X, - CQC_CMD_Y, - CQC_CMD_Z, - CQC_CMD_T, - CQC_CMD_H, - CQC_CMD_K, - CQC_CMD_ROT_X, - CQC_CMD_ROT_Y, - CQC_CMD_ROT_Z, - CQC_CMD_CNOT, - CQC_CMD_CPHASE, - CQC_CMD_MEASURE, - CQC_CMD_MEASURE_INPLACE, - CQC_CMD_RESET, - CQC_CMD_RELEASE, -) -from .util import ( - CQCGeneralError, - CQCUnsuppError, - QubitNotActiveError, -) - - -class qubit: - """ - A qubit. - """ - - def __init__(self, cqc, notify=True, block=True, createNew=True, q_id=None, entInfo=None): - """ - Initializes the qubit. The cqc connection must be given. - If notify, the return message is received before the method finishes. - createNew is set to False when we receive a qubit. - - - **Arguments** - - :cqc: The CQCconnection used - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - :createNew: If NEW-message should be sent, used internally - :q_id: Qubit id, used internally if createNew - :entInfo: Entanglement information, if qubit is part of EPR-pair - """ - # Cqc connection - self._cqc = cqc - - self.notify = cqc.notify - - # Check if the cqc connection was openened using a 'with' statement - # If not, raise a deprecation warning - if not self._cqc._opened_with_with: - logging.info( - "You should open CQCConnection in a context, i.e. using 'with CQCConnection(...) as cqc:'. " - "Then qubits will be automatically released by the end of the program, independently of what happens. " - "For more information, see https://softwarequtech.github.io/SimulaQron/html/PythonLib.html" - ) - - # Whether the qubit is active. Will be set in the first run - self._active = None - - if createNew: - # print info - logging.debug("App {} tells CQC: 'Create qubit'".format(self._cqc.name)) - - # Create new qubit at the cqc server - # TODO how to handle pending headers - self._cqc.commit_command(0, CQC_CMD_NEW, notify=notify, block=block) - - # Get qubit id - try: - self._qID = self._cqc.new_qubitID() - except AttributeError: - raise CQCGeneralError("Didn't receive the qubit id") - - # Activate qubit - self._set_active(True) - if notify and self.notify: - message = self._cqc.readMessage() - self._cqc.print_CQC_msg(message) - - else: - self._qID = q_id - self._set_active(False) # Why? - - # Entanglement information - self._set_entanglement_info(entInfo) - - def __str__(self): - if self.active: - return "Qubit at the node {}".format(self._cqc.name) - else: - return "Not active qubit" - - @property - def entanglement_info(self): - return self._entInfo - - def _set_entanglement_info(self, ent_info): - self._entInfo = ent_info - - # Lookup remote entangled node - self._remote_entNode = None - if self._entInfo: - ip = self._entInfo.node_B - port = self._entInfo.port_B - try: - for node in self._cqc._cqcNet.hostDict.values(): - if (node.ip == ip) and (node.port == port): - self._remote_entNode = node.name - break - except AttributeError: - self._remote_entNode = None - - @property - def active(self): - return self._active - - @property - def remote_entangled_node(self): - return self._remote_entNode - - def get_entInfo(self): - warnings.warn("get_entInfo is deprecated, use the property entanglement_info instead", - DeprecationWarning) - return self._entInfo - - def print_entInfo(self): - warnings.warn("print_entInfo is deprecated", - DeprecationWarning) - if self.entanglement_info: - print(self.entanglement_info) - else: - print("No entanglement information") - - def set_entInfo(self, entInfo): - warnings.warn("set_entInfo is deprecated, use _set_entanglement_info instead", - DeprecationWarning) - self._set_entanglement_info(entInfo) - - def is_entangled(self): - if self._entInfo: - return True - return False - - def get_remote_entNode(self): - warnings.warn("get_remote_entNode is deprecated, use the propery remote_entangled_node instead", - DeprecationWarning) - return self.remote_entangled_node - - def check_active(self): - """ - Checks if the qubit is active - """ - if not self.active: - raise QubitNotActiveError("Qubit is not active") - - def _set_active(self, be_active): - - # Check if not already new state - if self._active == be_active: - return - - if be_active: - self._cqc.active_qubits.append(self) - else: - if self in self._cqc.active_qubits: - self._cqc.active_qubits.remove(self) - self._active = be_active - - def _single_qubit_gate(self, command, notify, block): - """ - Performs a single qubit gate specified by the command, called in I(), X(), Y() etc - :param command: the identifier of the command, as specified in cqcHeader.py - :param notify: Do we wish to be notified when done - :param block: Do we want the qubit to be blocked - """ - # check if qubit is active - self.check_active() - - notify = notify and self.notify - - self._cqc.put_command( - qID=self._qID, - command=command, - notify=notify, - block=block, - ) - - def I(self, notify=True, block=True): - """ - Performs an identity gate on the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_qubit_gate(CQC_CMD_I, notify, block) - - def X(self, notify=True, block=True): - """ - Performs a X on the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_qubit_gate(CQC_CMD_X, notify, block) - - def Y(self, notify=True, block=True): - """ - Performs a Y on the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_qubit_gate(CQC_CMD_Y, notify, block) - - def Z(self, notify=True, block=True): - """ - Performs a Z on the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_qubit_gate(CQC_CMD_Z, notify, block) - - def T(self, notify=True, block=True): - """ - Performs a T gate on the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_qubit_gate(CQC_CMD_T, notify, block) - - def H(self, notify=True, block=True): - """ - Performs a Hadamard on the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_qubit_gate(CQC_CMD_H, notify, block) - - def K(self, notify=True, block=True): - """ - Performs a K gate on the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_qubit_gate(CQC_CMD_K, notify, block) - - def _single_gate_rotation(self, command, step, notify, block): - """ - Perform a rotation on a qubit - :param command: the rotation qubit command as specified in cqcHeader.py - :param step: Determines the rotation angle in steps of 2*pi/256 - :param notify: Do we wish to be notified when done - :param block: Do we want the qubit to be blocked - :return: - """ - # check if qubit is active - self.check_active() - - notify = notify and self.notify - - self._cqc.put_command( - qID=self._qID, - command=command, - step=step, - notify=notify, - block=block, - ) - - def rot_X(self, step, notify=True, block=True): - """ - Applies rotation around the x-axis with the angle of step*2*pi/256 radians. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :step: Determines the rotation angle in steps of 2*pi/256 - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_gate_rotation(CQC_CMD_ROT_X, step, notify, block) - - def rot_Y(self, step, notify=True, block=True): - """ - Applies rotation around the y-axis with the angle of step*2*pi/256 radians. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :step: Determines the rotation angle in steps of 2*pi/256 - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_gate_rotation(CQC_CMD_ROT_Y, step, notify, block) - - def rot_Z(self, step, notify=True, block=True): - """ - Applies rotation around the z-axis with the angle of step*2*pi/256 radians. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :step: Determines the rotation angle in steps of 2*pi/256 - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._single_gate_rotation(CQC_CMD_ROT_Z, step, notify, block) - - def _two_qubit_gate(self, command, target, notify, block): - """ - Perform a two qubit gate on the qubit - :param command: the two qubit gate command as specified in cqcHeader.py - :param target: The target qubit - :param notify: Do we wish to be notified when done - :param block: Do we want the qubit to be blocked - """ - # check if qubit is active - self.check_active() - target.check_active() - - if self._cqc != target._cqc: - raise CQCUnsuppError("Multi qubit operations can only operate on qubits in the same process") - - if self == target: - raise CQCUnsuppError("Cannot perform multi qubit operation where control and target are the same") - - notify = notify and self.notify - - self._cqc.put_command( - qID=self._qID, - command=command, - notify=notify, - block=block, - xtra_qID=target._qID, - ) - - def cnot(self, target, notify=True, block=True): - """ - Applies a cnot onto target. - Target should be a qubit-object with the same cqc connection. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :target: The target qubit - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._two_qubit_gate(CQC_CMD_CNOT, target, notify, block) - - def cphase(self, target, notify=True, block=True): - """ - Applies a cphase onto target. - Target should be a qubit-object with the same cqc connection. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :target: The target qubit - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - self._two_qubit_gate(CQC_CMD_CPHASE, target, notify, block) - - def measure(self, inplace=False, block=True): - """ - Measures the qubit in the standard basis and returns the measurement outcome. - If now MEASOUT message is received, None is returned. - If inplace=False, the measurement is destructive and the qubit is removed from memory. - If inplace=True, the qubit is left in the post-measurement state. - - - **Arguments** - - :inplace: If false, measure destructively. - :block: Do we want the qubit to be blocked - """ - # check if qubit is active - self.check_active() - - if inplace: - command = CQC_CMD_MEASURE_INPLACE - else: - command = CQC_CMD_MEASURE - # Set qubit to non active so the user can receive helpful errors during compile time - # if this qubit is used after this measurement - self._set_active(False) - - self._cqc.put_command( - qID=self._qID, - command=command, - notify=False, - block=block, - ) - - if self._cqc.pend_messages: - return None - else: - return self._cqc.return_meas_outcome() - - def reset(self, notify=True, block=True): - """ - Resets the qubit. - If notify, the return message is received before the method finishes. - - - **Arguments** - - :nofify: Do we wish to be notified when done. - :block: Do we want the qubit to be blocked - """ - # check if qubit is active - self.check_active() - - notify = notify and self.notify - - self._cqc.put_command( - qID=self._qID, - command=CQC_CMD_RESET, - notify=notify, - block=block, - ) - - def release(self, notify=True, block=True): - """ - Release the current qubit - :param notify: Do we wish to be notified when done - :param block: Do we want the qubit to be blocked - :return: - """ - - notify = notify and self.notify - - self._set_active(False) - - self._cqc.put_command( - qID=self._qID, - command=CQC_CMD_RELEASE, - notify=notify, - block=block, - ) - - def getTime(self, block=True): - """ - Returns the time information of the qubit. - If no INF_TIME message is received, None is returned. - - - **Arguments** - - :block: Do we want the qubit to be blocked - """ - # check if qubit is active - self.check_active() - - # print info - logging.debug("App {} tells CQC: 'Return time-info of qubit with ID {}'".format(self._cqc.name, self._qID)) - - self._cqc.sendGetTime(self._qID, notify=0, block=int(block)) - - # Return time-stamp - message = self._cqc.readMessage() - try: - otherHdr = message[1] - return otherHdr.datetime - except AttributeError: - return None diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/util.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib/util.py deleted file mode 100644 index 994632a..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib/util.py +++ /dev/null @@ -1,90 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -import os -import sys - - -class ProgressBar: - def __init__(self, maxitr): - self.maxitr = maxitr - self.itr = 0 - try: - self.cols = os.get_terminal_size().columns - except (OSError, AttributeError): - self.cols = 60 - print("") - self.update() - - def increase(self): - self.itr += 1 - self.update() - - def update(self): - cols = self.cols - 8 - assert self.itr <= self.maxitr - ratio = float(self.itr) / self.maxitr - procent = int(ratio * 100) - progress = "=" * int(cols * ratio) - sys.stdout.write("\r") - sys.stdout.write("[%*s] %d%%" % (-cols, progress, procent)) - sys.stdout.flush() - pass - - def close(self): - print("") - - -class CQCGeneralError(Exception): - pass - - -class CQCNoQubitError(CQCGeneralError): - pass - - -class CQCUnsuppError(CQCGeneralError): - pass - - -class CQCTimeoutError(CQCGeneralError): - pass - - -class CQCInuseError(CQCGeneralError): - pass - - -class CQCUnknownError(CQCGeneralError): - pass - - -class QubitNotActiveError(CQCGeneralError): - pass diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/__init__.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/coinflip_leader.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/coinflip_leader.py deleted file mode 100644 index 9323075..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/coinflip_leader.py +++ /dev/null @@ -1,63 +0,0 @@ -from cqc.pythonLib import CQCConnection, qubit -import math - - -class CoinflipConsensus: - def __init__(self, queue): - """ - Inits the algo with the list of candidates ids. - :param queue: the list of candidates ids. - """ - self.queue = queue - - def _atomic_flip(self, candidate1, candidate2, coeff): - """ - Performs the basic biased coinflip between two parties. - :param candidate1: the first party id. - :param candidate2: the second party id. - :param coeff: bias. - :return: the winner id. - """ - with CQCConnection(candidate1) as Alice: - qA = qubit(Alice) - qB = qubit(Alice) - - # Bias - angle = 2 * math.acos(coeff) - step = int(angle * 256 / (2 * math.pi)) - qA.rot_Y(step) - qA.cnot(qB) - qB.X() - - # Send qubit qB to Bob. - Alice.sendQubit(qB, candidate2) - - # Measure the qubits. - measured_value = qA.measure() - - with CQCConnection(candidate2) as Bob: - qB = Bob.recvQubit() - bob_value = qB.measure() - assert measured_value + bob_value == 1 - - if measured_value == 1: # `candidate1` is a winner. - return candidate1 - else: - return candidate2 - - def leader(self): - """ - Executes the coinflip leader election algo. - :return: the selected leader id. - """ - assert len(self.queue) >= 2 - - winner = self.queue[0] - - for i in range(2, len(self.queue) + 1): - # This is calculated to bias the every next coinflip to - # equalize candidates' chances to win. - coeff = math.sqrt(1 / i) - winner = self._atomic_flip(winner, self.queue[i - 1], coeff) - - return winner diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/measurements.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/measurements.py deleted file mode 100644 index c40d0cd..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/measurements.py +++ /dev/null @@ -1,128 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import qubit - - -def parity_meas(qubits, bases, node, negative=False): - """ - Performs a parity measurement on the provided qubits in the Pauli bases specified by 'bases'. - 'bases' should be a string with letters in "IXYZ" and have the same length as the number of qubits provided. - If 'negative' is true the measurement outcome is flipped. - If more than one letter of 'bases' is not identity, then an ancilla qubit will be used, which is created using the - provided 'node'. - - :param qubits: List of qubits to be measured. - :type qubits: list of :obj: `cqc.pythonLib.qubit` - :param bases: String specifying the Pauli-bases of the measurement. Example bases="IXY" for three qubits. - :type bases: str - :param node: The node storing the qubits. Used for creating an ancilla qubit. - :type node: :obj: `cqc.pythonLib.CQCConnection` - :param negative: If the measurement outcome should be flipped or not. - :type negative: bool - :return: The measurement outcome 0 or 1, where 0 correspond to the +1 eigenvalue of the measurement operator. - """ - - if not (len(qubits) == len(bases)): - raise ValueError("Number of bases needs to be the number of qubits.") - if not all([(B in "IXYZ") for B in bases]): - raise ValueError("All elements of bases need to be in 'IXYZ'.") - - num_qubits = len(qubits) - - flip_basis = ["I"] * num_qubits - non_identity_bases = [] - - # Check if we need to flip the bases of the qubits - for i in range(len(bases)): - B = bases[i] - if B == "X": - flip_basis[i] = "H" - non_identity_bases.append(i) - elif B == "Y": - flip_basis[i] = "K" - non_identity_bases.append(i) - elif B == "Z": - non_identity_bases.append(i) - else: - pass - - if len(non_identity_bases) == 0: - # Trivial measurement - m = 0 - - elif len(non_identity_bases) == 1: - # Single_qubit measurement - q_index = non_identity_bases[0] - q = qubits[q_index] - - # Flip to correct basis - if flip_basis[q_index] == "H": - q.H() - if flip_basis[q_index] == "K": - q.K() - - m = q.measure(inplace=True) - - # Flip the qubit back - if flip_basis[q_index] == "H": - q.H() - if flip_basis[q_index] == "K": - q.K() - - else: - # Parity measurement, ancilla needed - - # Initialize ancilla qubit - anc = qubit(node) - - # Flip to correct basis - for i in range(len(bases)): - if flip_basis[i] == "H": - qubits[i].H() - if flip_basis[i] == "K": - qubits[i].K() - - # Transfer parity information to ancilla qubit - for i in non_identity_bases: - qubits[i].cnot(anc) - - # Measure ancilla qubit - m = anc.measure() - - # Flip to correct basis - for i in range(len(bases)): - if flip_basis[i] == "H": - qubits[i].H() - if flip_basis[i] == "K": - qubits[i].K() - if negative: - return (m + 1) % 2 - else: - return m diff --git a/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/wstate.py b/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/wstate.py deleted file mode 100644 index e61c413..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/pythonLib_protocols/wstate.py +++ /dev/null @@ -1,54 +0,0 @@ -from cqc.pythonLib import qubit -import numpy as np - - -def initialize_Qubit_register(num_qubit, Owner): - - """ - Initialize quantum registers. Multiple qubits are stored and returned as an array. - Returns an array of initialized qubits. - - :param num_qubit: Number of qubits to initialize - :param Owner: The owner of the qubit / CQCConnection. - """ - - qubits = [] - for x in range(0, num_qubit): - one_more_qubit = qubit(Owner) - qubits.append(one_more_qubit) - return qubits - - -def create_Nqubit_Wstate(num_qubit, Owner): - """ - Initializes multiple qubits, and entangles them as W state. - Returns an array of qubits (W state). - - :param num_qubit: Number of qubits to initialize for the W state - :param Owner: The owner of the qubit / CQCConnection. - """ - qubits = initialize_Qubit_register(num_qubit, Owner) - num_qubit = len(qubits) - qubits[0].X() - for x in range(1, num_qubit): - qubit1 = qubits[x - 1] - qubit2 = qubits[x] - ControlledG(qubit1, qubit2, num_qubit - x + 1) - return qubits - - -def ControlledG(controlled_qubit, target_qubit, index): - """ - Controlled-G(p)/Controlled-Ry(θ) gate - - :param contolled_qubit: Controlled qubit for this operation - :param target_qubit: Target qubit for this operation - :param index: Index to calculate the p value. The p value is an integer between 0 and 1. - """ - p = np.sqrt(1 - 1 / index) - x = int(np.arcsin(p) * 256 / (2 * np.pi)) - controlled_qubit.cnot(target_qubit) - target_qubit.rot_Y(256 - x) - controlled_qubit.cnot(target_qubit) - target_qubit.rot_Y(x) - target_qubit.cnot(controlled_qubit) diff --git a/data/examples/simulaqron/CQC-Python/cqc/util.py b/data/examples/simulaqron/CQC-Python/cqc/util.py deleted file mode 100644 index 9d83a4b..0000000 --- a/data/examples/simulaqron/CQC-Python/cqc/util.py +++ /dev/null @@ -1,100 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES -# LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.cqcHeader import ( - CQCCmdHeader, - CQCHeader, - CQCTypeHeader, - CQCAssignHeader, - CQCFactoryHeader, - CQCIfHeader, - CQCXtraQubitHeader, - CQCType, - CQC_CMD_CNOT, - CQC_CMD_CPHASE, - CQC_CMD_MEASURE, - CQC_CMD_MEASURE_INPLACE, -) - - -def parse_cqc_message(msg): - # TODO finish parser - hdr_map = { - CQCType.HELLO: None, - CQCType.COMMAND: CQCCmdHeader, - CQCType.MIX: CQCTypeHeader, - CQCType.IF: CQCIfHeader, - CQCType.FACTORY: CQCFactoryHeader, - } - headers = [] - next_hdr = CQCHeader - bits_to_next_first_hdr = 0 - is_mix = False - while len(msg) > 0: - hdr = extract_header(msg, next_hdr) - headers.append(hdr) - next_hdr = None - msg = msg[hdr.HDR_LENGTH:] - if isinstance(hdr, CQCHeader): - bits_to_next_first_hdr = hdr.length - next_hdr = hdr_map[hdr.tp] - is_mix = hdr.tp == CQCType.MIX - else: - if isinstance(hdr, CQCCmdHeader): - if hdr.instr in [CQC_CMD_MEASURE, CQC_CMD_MEASURE_INPLACE]: - next_hdr = CQCAssignHeader - if hdr.instr in [CQC_CMD_CNOT, CQC_CMD_CPHASE]: - next_hdr = CQCXtraQubitHeader - elif isinstance(hdr, CQCTypeHeader): - next_hdr = hdr_map[hdr.type] - elif isinstance(hdr, CQCAssignHeader): - pass - elif isinstance(hdr, CQCIfHeader): - pass - elif isinstance(hdr, CQCXtraQubitHeader): - pass - elif isinstance(hdr, CQCFactoryHeader): - next_hdr = CQCCmdHeader - else: - raise NotImplementedError("for {}".format(hdr)) - bits_to_next_first_hdr -= hdr.HDR_LENGTH - if bits_to_next_first_hdr <= 0: - next_hdr = CQCHeader - if next_hdr is None: - if is_mix: - next_hdr = CQCTypeHeader - else: - next_hdr = CQCCmdHeader - - return headers - - -def extract_header(msg, hdr_class): - hdr = hdr_class(msg[:hdr_class.HDR_LENGTH]) - return hdr diff --git a/data/examples/simulaqron/CQC-Python/examples/python/.DS_Store b/data/examples/simulaqron/CQC-Python/examples/python/.DS_Store deleted file mode 100644 index 4bfde4ddea7ae0546c734203bb3322fff516fc7a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK!A>GU5UmDW8;DsBo9MAG-iSev<+RBx>cParCS&yA8k||kGRZh?V2~(c<~Q_@ z`~pA6t?F)whUL0TOckkqMRirr^qWc76aa|!sJjbL0RV|gm@DG&7omC51<5&29#NPz zG;|;V4aX2IM6+WR8K7rZhCcKl#^2lL7aqm>R~YLMBk1+`j=J+|1g)i6;dprMvYx~1 zI2xw4+Kb5L3u~X&r7X$PM(M)u>#?5(>1fyv2IuteN09bIXP;;t&+Q;Qje6rw<;%WK z(jZED1Ctzedl>TbEK0h1+}5L{J2dO~c0$UcEOshelS#eVtg3peF|Ddet5vJ2y~fw+ zv?w>XcfTE7UfteJ?xzorW%uOn)+*FXR1%8IEY4HVFr^q{sT6Oa8bQAz1JQGsSws&C Pe+U>Fcwh$pDFc51=z?N` diff --git a/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/README.txt b/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/README.txt deleted file mode 100644 index c2723ad..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/README.txt +++ /dev/null @@ -1 +0,0 @@ -In this example Alice connects to the cqc-server, sends a hello message and prints the return message diff --git a/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/aliceTest.py b/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/aliceTest.py deleted file mode 100644 index da80709..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/aliceTest.py +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import logging -import os -import socket - -from simulaqron.general.hostConfig import networkConfig -from cqc.cqcHeader import CQCHeader, CQC_TP_HELLO, CQC_VERSION -from simulaqron.toolbox import get_simulaqron_path - - -##################################################################################################### -# -# init -# -def init(name, cqcFile=None): - """ - Initialize a connection to the cqc server with the name given as input. - A path to a configure file for the cqc network can be given, - if it's not given the config file 'config/cqcNodes.cfg' will be used. - Returns a socket object. - """ - - # This file defines the network of CQC servers interfacing to virtual quantum nodes - if cqcFile is None: - simulaqron_path = get_simulaqron_path.main() - cqcFile = os.path.join(simulaqron_path, "config/cqcNodes.cfg") - - # Read configuration files for the cqc network - cqcNet = networkConfig(cqcFile) - - # Host data - if name in cqcNet.hostDict: - myHost = cqcNet.hostDict[name] - else: - logging.error("The name '{}' is not in the cqc network.".format(name)) - raise LookupError("The name '{}' is not in the cqc network.".format(name)) - - addr = myHost.addr - - # Connect to cqc server and run protocol - cqc = None - try: - cqc = socket.socket(addr[0], addr[1], addr[2]) - except socket.error: - logging.error("Could not connect to cqc server: %s", name) - try: - cqc.connect(addr[4]) - except socket.error: - cqc.close() - logging.error("Could not connect to cqc server: %s", name) - return cqc - - -##################################################################################################### -# -# main -# -def main(): - - # In this example, we are Alice. - myName = "Alice" - - # Initialize the connection - cqc = init(myName) - - # Send Hello message - print("App {} tells CQC: 'HELLO'".format(myName)) - hdr = CQCHeader() - hdr.setVals(CQC_VERSION, CQC_TP_HELLO, 0, 0) - msg = hdr.pack() - cqc.send(msg) - - # Receive return message - data = cqc.recv(192) - hdr = CQCHeader(data) - if hdr.tp == CQC_TP_HELLO: - print("CQC tells App {}: 'HELLO'".format(myName)) - else: - print("Did not receive a hello message, but rather: {}".format(hdr.printable())) - - # Close the connection - cqc.close() - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/run.sh b/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/run.sh deleted file mode 100755 index 2ce0ba1..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/python/hello_noLib/run.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -python3 aliceTest.py & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/.DS_Store b/data/examples/simulaqron/CQC-Python/examples/pythonLib/.DS_Store deleted file mode 100644 index 76df1aecde24f25c63bf8ccd3b6594c08a993c29..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%We}f6uoZKb`oA$fG7*3*|3XH`XVc&5L%T;2tk8D;-Pe=3CW1*I80^;B?M*9 z7r-|l@f~~t-@*#cwM~_olm#1vsPD)=e%x~tAA9UE5s60HStBYFk%PooC?Pw+xS!LU zEtrMAIeZ7 zI!^~ADWFKb?EwwwF1Q|bI6^bbaKGfZD~cOqr`V%=w43!7S99J)M0}(ES%m1jbcdeg z7$0(sCF+9{;*mMe?>Wy)_}?+c(L?UhAs!x4kJ|JKDMFNlM(B^}Wj2!1c~+;rcr08;> z-HM}7Mm@B#{}o7@LgWaNrVyItW%PN$pwxl0v zcM^4tHn$2`1+oe(>S~$K|DE68|Fa}pvkF)R{woDUVY{{6z>v(@IyX2zYh9#$BsTV& nYE%?t<~UXbK8jb7l%db%0 1000: - raise ValueError("Number of EPR pairs for this example is currently restricted to less than 1000") - main(nr_runs) diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/bobTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/bobTest.py deleted file mode 100644 index 16629ec..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/bobTest.py +++ /dev/null @@ -1,76 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import sys -import json -from cqc.pythonLib import CQCConnection - - -def main(nr_runs): - meas_outcomes = {} - - # Initialize the connection - with CQCConnection("Bob") as Bob: - - for _ in range(nr_runs): - - # Create an EPR pair - q = Bob.recvEPR() - - # Get the identifier of this EPR pair such that Alice can relate the measuement outcomes to hers - sequence_nr = q.get_entInfo().id_AB - - if (sequence_nr % 3) == 0: - # Measure in Z - pass - elif (sequence_nr % 3) == 1: - # Measure in X - q.H() - else: - # Measure in Y - q.K() - - m = q.measure() - meas_outcomes[sequence_nr] = m - - # Encode the measurement outcomes to bytes, such that we can send them - msg = json.dumps(meas_outcomes).encode("utf-8") - - # Send the measurement outcomes to Alice - Bob.sendClassical(name="Alice", msg=msg) - - -if __name__ == "__main__": - try: - nr_runs = int(sys.argv[1]) - except Exception: - nr_runs = 500 - if nr_runs > 1000: - raise ValueError("Number of EPR pairs for this example is currently restricted to less than 1000") - main(nr_runs) diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/run.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/run.sh deleted file mode 100755 index 98bdd83..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/QBER/run.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -python3 aliceTest.py $@ & -python3 bobTest.py $@ & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R1.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R1.py deleted file mode 100644 index 0deb657..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R1.py +++ /dev/null @@ -1,101 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("R1") as R1: - - # Make EPR-pairs with S1,S2 and R2 - qtmp1 = R1.recvEPR() - qtmp2 = R1.recvEPR() - q8 = R1.createEPR("R2") - - # Check where qubit are sent from - if qtmp1.get_remote_entNode() == "S1": - q3 = qtmp1 - q7 = qtmp2 - else: - q3 = qtmp2 - q7 = qtmp1 - - # Receive corrections - msg1 = R1.recvClassical() - msg2 = R1.recvClassical() - - # Do corrections - if msg1[:2].decode("utf-8") == "S1": - if msg1[2] == 1: - q3.X() - if msg2[2] == 1: - q7.X() - else: - if msg1[2] == 1: - q7.X() - if msg2[2] == 1: - q3.X() - - # Entangle and measure (step 2) - q3.cnot(q8) - q7.cnot(q8) - m = q8.measure() - - # Send corrections to R2 (including sender) (step 2) - msg = "R1".encode("utf-8") + bytes([m]) - R1.sendClassical("R2", msg) - - # Get correction from R2 (step 6) - msg = R1.recvClassical() - if msg[2] == 1: - q3.Z() - q7.Z() - - # H and measure qubits (step 7) - q3.H() - m1 = q3.measure() - q7.H() - m2 = q7.measure() - - # Send corrections to S1 and S2 (step 7) - msg1 = "R1".encode("utf-8") + bytes([m1]) - R1.sendClassical("S1", msg1) - msg2 = "R1".encode("utf-8") + bytes([m2]) - R1.sendClassical("S2", msg2) - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R2.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R2.py deleted file mode 100644 index ce03a34..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_R2.py +++ /dev/null @@ -1,81 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("R2") as R2: - - # Make EPR-pairs with T1,T2 and R1 - q9 = R2.recvEPR() - q10 = R2.createEPR("T2") - q12 = R2.createEPR("T1") - - # Receive corrections from R1 (step 2) - msg = R2.recvClassical() - if msg[2] == 1: - q9.X() - - # Entangle and measure (step 3) - q9.cnot(q10) - q9.cnot(q12) - m1 = q10.measure() - m2 = q12.measure() - - # Send corrections to T1 and T2 (step 3) - msg1 = "R2".encode("utf-8") + bytes([m1]) - R2.sendClassical("T2", msg1) - msg2 = "R2".encode("utf-8") + bytes([m2]) - R2.sendClassical("T1", msg2) - - # Receive corrections from T1 and T2 (step 5) - m1 = R2.recvClassical()[2] - m2 = R2.recvClassical()[2] - if (m1 + m2) % 2 == 1: - q9.Z() - - # H and measure (step 6) - q9.H() - m = q9.measure() - - # Send corrections to R1 (step 6) - msg = "R1".encode("utf-8") + bytes([m]) - R2.sendClassical("R1", msg) - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S1.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S1.py deleted file mode 100644 index 23bf571..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S1.py +++ /dev/null @@ -1,69 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("S1") as S1: - - # Make EPR-pairs with R1 and T2 - q2 = S1.createEPR("R1") - q0 = S1.createEPR("T2") - - # Make Bell measurement (step 1) - q0.cnot(q2) - m = q2.measure() - - # Send corrections to R1 (including sender) (step 1) - msg = "S1".encode("utf-8") + bytes([m]) - S1.sendClassical("R1", msg) - - # Receive correction from R1 (step 7) - m = S1.recvClassical() - if m == 1: - q0.Z() - - # Measure out - m = q0.measure() - to_print = "S1: Measurement outcome: {}".format(m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S2.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S2.py deleted file mode 100644 index 6b410ef..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_S2.py +++ /dev/null @@ -1,69 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("S2") as S2: - - # Make EPR-pairs with R1 and T1 - q6 = S2.createEPR("R1") - q4 = S2.createEPR("T1") - - # Make Bell measurement (step 1) - q4.cnot(q6) - m = q6.measure() - - # Send corrections to R1 (including sender) (step 1) - msg = "S2".encode("utf-8") + bytes([m]) - S2.sendClassical("R1", msg) - - # Receive correction from R1 (step 7) - m = S2.recvClassical() - if m == 1: - q4.Z() - - # Measure out - m = q4.measure() - to_print = "S2: Measurement outcome: {}".format(m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T1.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T1.py deleted file mode 100644 index 97d5ae6..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T1.py +++ /dev/null @@ -1,80 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("T1") as T1: - - # Make EPR-pairs with S2 and R2 - qtmp1 = T1.recvEPR() - qtmp2 = T1.recvEPR() - - # Check where qubit are sent from - if qtmp1.get_remote_entNode() == "R2": - q13 = qtmp1 - q5 = qtmp2 - else: - q13 = qtmp2 - q5 = qtmp1 - - # Receive corrections from R2 (step 3) - msg = T1.recvClassical() - if msg[2] == 1: - q13.X() - - # Entangle (step 4) - q13.cnot(q5) - - # H and measure (step 5) - q13.H() - m = q13.measure() - - # Send corrections to R2 (step 5) - msg = "T1".encode("utf-8") + bytes([m]) - T1.sendClassical("R2", msg) - - # Measure out - m = q5.measure() - to_print = "T1: Measurement outcome: {}".format(m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T2.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T2.py deleted file mode 100644 index 177d793..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/node_T2.py +++ /dev/null @@ -1,80 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("T2") as T2: - - # Make EPR-pairs with S1 and R2 - qtmp1 = T2.recvEPR() - qtmp2 = T2.recvEPR() - - # Check where qubit are sent from - if qtmp1.get_remote_entNode() == "R2": - q11 = qtmp1 - q1 = qtmp2 - else: - q11 = qtmp2 - q1 = qtmp1 - - # Receive corrections from R2 (step 3) - msg = T2.recvClassical() - if msg[2] == 1: - q11.X() - - # Entangle (step 4) - q11.cnot(q1) - - # H and measure (step 5) - q11.H() - m = q11.measure() - - # Send corrections to R2 (step 5) - msg = "T2".encode("utf-8") + bytes([m]) - T2.sendClassical("R2", msg) - - # Measure out - m = q1.measure() - to_print = "T2: Measurement outcome: {}".format(m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/run.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/run.sh deleted file mode 100755 index 6c31422..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/butterfly/run.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -python3 node_S1.py & -python3 node_S2.py & -python3 node_R1.py & -python3 node_R2.py & -python3 node_T1.py & -python3 node_T2.py & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/README.txt b/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/README.txt deleted file mode 100644 index 6b17bec..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/README.txt +++ /dev/null @@ -1,32 +0,0 @@ -# Coin Flip Leader Election - -## How to run - -First make sure that simulaqron is started with the nodes you'd want to include. -This can be done with for example `simulaqron start` which by default starts a network -with the nodes Alice, Bob, Charlie, David and Eve. -Note that you need to be using either the qutip or projectq backend, since single-qubit -rotations are used which are not supported in stabilizer formalism. -To change the backend do `simulaqron set backend projectq`, which of course requires projectq -to be installed (`pip install projectq`). - -In this folder there is both an example with the four nodes Alice, Bob, Charlie and David -and one where you can dynamically choose the nodes that the example uses. - -To start either of the examples do -``` -python3 fourPartyCoinFlip.py -``` -or -``` -python3 nPartyCoinFlip.py -``` - -When running `nPartyCoinFlip.py` fill in the names you want to use (note that these needs to -be in the current running network) and press enter when you're finished. - -## Explanation - -It is possible to elect a leader from a collection of N nodes by performing a -series of coin flips as explained in [this -paper](https://arxiv.org/abs/0910.4952v2). diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/fourPartyCoinFlip.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/fourPartyCoinFlip.py deleted file mode 100644 index 1f2258b..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/fourPartyCoinFlip.py +++ /dev/null @@ -1,24 +0,0 @@ -from cqc.pythonLib_protocols.coinflip_leader import CoinflipConsensus - - -def main(): - """ - Creates array of four people and elects a leader among them using - the CoinFlipConsensus protocol. - """ - arr = ["Alice", "Bob", "Charlie", "David"] - leaderChooser = CoinflipConsensus(arr) - return leaderChooser.leader() - - -# Runs 20 rounds of leader election and prints the results. -d = dict() -d["Alice"] = 0 -d["Bob"] = 0 -d["Charlie"] = 0 -d["David"] = 0 -for i in range(0, 20): - if i % 10 == 0: - print(i) - d[main()] += 1 -print(d) diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/nPartyCoinFlip.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/nPartyCoinFlip.py deleted file mode 100644 index ddaf805..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/coinflipLeader/nPartyCoinFlip.py +++ /dev/null @@ -1,34 +0,0 @@ -from cqc.pythonLib_protocols.coinflip_leader import CoinflipConsensus - - -def main(): - - leaderChooser = CoinflipConsensus(arr) # Elects a leader from array that you declared - return leaderChooser.leader() - - -# For 12-13-14-15 lines: After seeing "Add person" sentence, you can add person that how many person you want to add. -# After adding one person you should press "enter" and then you can continue to add person with press enter -# If you want to cancel from adding person you should press enter again -# After enter the all name that you wanted to add you should press "enter" -# Note that: you should use names configure in the network -arr = [] # Here an empty array was defined -veri = input("Add person") -while veri: - arr.append(veri) - veri = input("Add person") - - -# giving a value for each leader -d = dict() -for veri in arr: - d[veri] = 0 - -# Runs 20 rounds of leader election and prints the results. -for i in range(0, 20): - if i % 10 == 0: - print(i) - d[main()] += 1 - - -print(d) diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/README.txt b/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/README.txt deleted file mode 100644 index 9bc0691..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -In this example Alice and Bob generate correlated randomness by sharing an EPR pair and measuring. - -Alice creates two qubits and puts these into an EPR pair by performing a Hadamard and CNOT operation. She sends one of the qubit to Bob and measures the one she keeps in the standard-basis. Bob receives the qubit that Alice sent and measures it. Both print their measurement outcomes. diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/aliceTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/aliceTest.py deleted file mode 100644 index 76f4084..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/aliceTest.py +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Alice") as Alice: - - # Create an EPR pair - q = Alice.createEPR("Bob") - - # Measure qubit - m = q.measure() - to_print = "App {}: Measurement outcome is: {}".format(Alice.name, m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/bobTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/bobTest.py deleted file mode 100644 index 2fd034e..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/bobTest.py +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Bob") as Bob: - - # Receive qubit - q = Bob.recvEPR() - - # Measure qubit - m = q.measure() - to_print = "App {}: Measurement outcome is: {}".format(Bob.name, m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/run.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/run.sh deleted file mode 100755 index d5aa342..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/corrRNG/run.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -python3 aliceTest.py & -python3 bobTest.py & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/README.txt b/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/README.txt deleted file mode 100644 index 14f6aac..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -In this example Alice, Bob and Charlie will produce a GHZ state between them and measure their qubits. - -Alice and Bob creates an EPR pair between them and Alice measures her qubit in the standard-basis. Bob creates a fresh qubit which he entangles with the qubit which is part of the EPR pair with Alice. Bob sends one of his qubits to Charlie and both Bob and Charlie measures their qubits in the standard-basis. diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/aliceTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/aliceTest.py deleted file mode 100644 index 37cb1cb..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/aliceTest.py +++ /dev/null @@ -1,55 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Alice") as Alice: - - # Make an EPR pair with Bob - qA = Alice.createEPR("Bob") - - # Measure qubit - m = qA.measure() - to_print = "App {}: Measurement outcome is: {}".format(Alice.name, m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/bobTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/bobTest.py deleted file mode 100644 index 393309e..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/bobTest.py +++ /dev/null @@ -1,63 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection, qubit - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Bob") as Bob: - - # Make an EPR pair with Alice - qB = Bob.recvEPR() - - # Create a fresh qubit - qC = qubit(Bob) - - # Entangle the new qubit - qB.cnot(qC) - - # Send qubit to Charlie - Bob.sendQubit(qC, "Charlie") - - # Measure qubit - m = qB.measure() - to_print = "App {}: Measurement outcome is: {}".format(Bob.name, m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/charlieTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/charlieTest.py deleted file mode 100644 index 699cefb..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/charlieTest.py +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Charlie") as Charlie: - - # Receive qubit - qC = Charlie.recvQubit() - - # Measure qubit - m = qC.measure() - to_print = "App {}: Measurement outcome is: {}".format(Charlie.name, m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/run.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/run.sh deleted file mode 100755 index e5223a6..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/extendGHZ/run.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -python3 aliceTest.py & -python3 bobTest.py & -python3 charlieTest.py & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/README.txt b/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/README.txt deleted file mode 100644 index c2723ad..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/README.txt +++ /dev/null @@ -1 +0,0 @@ -In this example Alice connects to the cqc-server, sends a hello message and prints the return message diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/aliceTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/aliceTest.py deleted file mode 100644 index 1b9b0dc..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/aliceTest.py +++ /dev/null @@ -1,58 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection -from cqc.cqcHeader import CQC_TP_HELLO - - -##################################################################################################### -# -# main -# -def main(): - - # In this example, we are Alice. - myName = "Alice" - - # Initialize the connection - with CQCConnection(myName) as cqc: - - # Send Hello message - print("{} says HELLO to CQC server".format(myName)) - cqc.sendSimple(CQC_TP_HELLO) - - # Get return message - message = cqc.readMessage() - cqc_header = message[0] - if cqc_header.tp == CQC_TP_HELLO: - print("CQC server says HELLO back :)") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/run.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/run.sh deleted file mode 100755 index 2ce0ba1..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/hello/run.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -python3 aliceTest.py & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/README.txt b/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/README.txt deleted file mode 100644 index 4be398f..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -Alice and Bob will in this example generate a key and use this to send a message. All the communication will pass through Eve who will try to intercept the message. Alice and Bob don't know distribute a key securely using QKD, so Alice just generates a key and sends this to Bob by encoding the key in a qubit. Alice encodes the key by applying an Pauli-X operation depending on the value of the key. - -Can you help Alice and Bob with a better scheme? diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/aliceTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/aliceTest.py deleted file mode 100644 index 12e5f5d..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/aliceTest.py +++ /dev/null @@ -1,66 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection, qubit - -import random - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Alice") as Alice: - - # Generate a key - k = random.randint(0, 1) - - # Create a qubit - q = qubit(Alice) - - # Encode the key in the qubit - if k == 1: - q.X() - - # Send qubit to Bob (via Eve) - Alice.sendQubit(q, "Eve") - - # Encode and send a classical message m to Bob - m = 0 - enc = (m + k) % 2 - Alice.sendClassical("Bob", enc) - - print("Alice send the message m={} to Bob".format(m)) - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/bobTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/bobTest.py deleted file mode 100644 index a2f7aa5..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/bobTest.py +++ /dev/null @@ -1,58 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Bob") as Bob: - - # Receive qubit from Alice (via Eve) - q = Bob.recvQubit() - - # Retreive key - k = q.measure() - - # Receive classical encoded message from Alice - enc = Bob.recvClassical()[0] - - # Calculate message - m = (enc + k) % 2 - - print("Bob retrived the message m={} from Alice.".format(m)) - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/eveTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/eveTest.py deleted file mode 100644 index 1973574..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/eveTest.py +++ /dev/null @@ -1,50 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Eve") as Eve: - - # Receive qubit from Alice - q = Eve.recvQubit() - - # Forward the qubit to Bob - Eve.sendQubit(q, "Bob") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/run_example.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/run_example.sh deleted file mode 100755 index 6dda9d1..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/programming_q_network/run_example.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env sh - -python3 aliceTest.py & -python3 bobTest.py & -python3 eveTest.py & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/README.md b/data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/README.md deleted file mode 100644 index ab6afaf..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/README.md +++ /dev/null @@ -1,4 +0,0 @@ -We connect a node (Alice) and create a fresh qubit then apply a Hadamard gate. -After measuring the qubit, we repeat the process 10 times(in the for loop)and -finally we create an empty list in order to saving the quantum numbers or coins -and the quantum numbers/coins are printed in the screen diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/quantum_number_generation.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/quantum_number_generation.py deleted file mode 100644 index e867548..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/quantum_number_generation/quantum_number_generation.py +++ /dev/null @@ -1,29 +0,0 @@ -from cqc.pythonLib import CQCConnection, qubit - -##################################################################################################### -#In this example, we produce fresh coin/random number with using quantum logical gates. -# While creating quantum random generator, steps of coin analogy was used.For this -# 1) a new qubit was produced and this stpe similar to fishing coin -# 2) applied hadamard gate, this step can be equal that tossing a coin in air -# 3)Finally measured qubit and this is like that we can learn now the coin's result like head or tail - - -def main(): - - # Initialize the connection - with CQCConnection("Alice") as Alice: # Here 1)we connect a node (ALice) - q = qubit(Alice) # 2)produced a fresh qubit - q.H() # 3)applied Hadamard gate - coin = q.measure() # 4)mesaured the qubit and the result printed - to_print = "{}".format(coin) - print("| " + to_print + " |") - return coin - - -if __name__ == '__main__': - coin_list = [] # here we defined an empty list for saving our generated numbers/coins - for i in range(10): # for producing 10random numbers/coin used for loop - coin_list.append(main()) # generated coins/number added in the list - print('Quantum Coin', coin_list) # printed on the secreen - -################################################################################################## diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/README.txt b/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/README.txt deleted file mode 100644 index e6f909f..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/README.txt +++ /dev/null @@ -1,4 +0,0 @@ -In this example Alice teleports a qubit to Bob. - -Alice and Bob starts by creating a shared EPR pair. Alice creates a fresh qubit which she wants to teleport. In this case she puts it in the |+> state by performing a Hadamard operation. She performes the local teleportation operations and measures her qubits. She sends her measurement outcomes using a classical channel. Bob receives the measurement outcomes and performs corrections if needed. He finally measures his qubit in the standard basis and prints the measurement -outcome. diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/aliceTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/aliceTest.py deleted file mode 100644 index 990dc22..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/aliceTest.py +++ /dev/null @@ -1,69 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from cqc.pythonLib import CQCConnection, qubit - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Alice") as Alice: - - # Make an EPR pair with Bob - qA = Alice.createEPR("Bob") - - # Create a qubit to teleport - q = qubit(Alice) - - # Prepare the qubit to teleport in |+> - q.H() - - # Apply the local teleportation operations - q.cnot(qA) - q.H() - - # Measure the qubits - a = q.measure() - b = qA.measure() - to_print = "App {}: Measurement outcomes are: a={}, b={}".format(Alice.name, a, b) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - # Send corrections to Bob - Alice.sendClassical("Bob", [a, b]) - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/bobTest.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/bobTest.py deleted file mode 100644 index 39ef46e..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/bobTest.py +++ /dev/null @@ -1,66 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from cqc.pythonLib import CQCConnection - - -##################################################################################################### -# -# main -# -def main(): - - # Initialize the connection - with CQCConnection("Bob") as Bob: - - # Make an EPR pair with Alice - qB = Bob.recvEPR() - - # Receive info about corrections - data = Bob.recvClassical() - message = list(data) - a = message[0] - b = message[1] - - # Apply corrections - if b == 1: - qB.X() - if a == 1: - qB.Z() - - # Measure qubit - m = qB.measure() - to_print = "App {}: Measurement outcome is: {}".format(Bob.name, m) - print("|" + "-" * (len(to_print) + 2) + "|") - print("| " + to_print + " |") - print("|" + "-" * (len(to_print) + 2) + "|") - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/run.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/run.sh deleted file mode 100755 index d5aa342..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/teleport/run.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -python3 aliceTest.py & -python3 bobTest.py & diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/README.txt b/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/README.txt deleted file mode 100644 index 3facdd8..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/README.txt +++ /dev/null @@ -1,21 +0,0 @@ -# W State Leader Election - -## How to run - -``` -sh $NETSIM/run/startAll.sh --nrnodes 7 -./run.sh -``` - -Note that you need to give the nodes a few seconds to start up after running -the first command. - -## Explanation - -A conceptually simple way to elect a leader of N nodes is to prepare a W state -of N qubits and distribute one qubit to each node. Each node measures their -qubit and the node that measures `1` becomes the leader. The idea comes from -[this presentation](https://ww2.chemistry.gatech.edu/pradeep/talks/qle.pdf). - -In order to run this protocol, it is necessary to prepare a W state. The W -state preparation is based on [this paper](https://arxiv.org/abs/1807.05572). diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/additional_functions.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/additional_functions.py deleted file mode 100644 index 0428c83..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/additional_functions.py +++ /dev/null @@ -1,34 +0,0 @@ -def string_to_int(message): - """ - Converts string message into integer. - - **Arguments** - :message: String message - """ - ord_list = [] - for x in range(0, len(message)): - ord_list.append(ord(message[x])) - return ord_list - - -def int_to_string(message): - """ - Converts integer message into string. - - **Arguments** - :message: integer message - """ - char_list = "" - for x in range(0, len(message)): - char_list += chr(message[x]) - return char_list - - -def broadcastClassical(message, Owner): - """ - Broadcasts the same classical message. - - **Arguments** - :message: Integer message - """ - print("Broadcasting leader election result") - for key in Owner._cqcNet.hostDict.keys(): - if key != Owner.name: - Owner.sendClassical(key, message) diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_receiver.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_receiver.py deleted file mode 100644 index 41c4b6c..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_receiver.py +++ /dev/null @@ -1,67 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import sys - -from cqc.pythonLib import CQCConnection -from additional_functions import string_to_int, int_to_string, broadcastClassical - - -##################################################################################################### -# -# main -# -def main(): - if len(sys.argv) == 2: - nodename = sys.argv[1] - else: - print("Provide one argument for the node name") - - # Initialize the connection - with CQCConnection(nodename) as Node: - # Receive qubit - q = Node.recvQubit() - # Measure qubit - m = q.measure() - to_print = "(" + nodename + ") App {}: Measurement outcome is: {}".format(Node.name, m) - print("|" + "-" * (len(to_print) + 2) + "|\n", "| " + to_print + " |", "\n|" + "-" * (len(to_print) + 2) + "|") - - if m == 1: - print("| (", nodename, ") I'm the leader") - ordlist = string_to_int(nodename + " is the leader") - broadcastClassical(ordlist, Node) - - data = Node.recvClassical() - message = list(data) - msg = int_to_string(message) - print("(", nodename, ")", msg) - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_transmitter.py b/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_transmitter.py deleted file mode 100644 index 46fb7a7..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/default_Wstate_transmitter.py +++ /dev/null @@ -1,81 +0,0 @@ -# -# Copyright (c) 2017, Stephanie Wehner and Axel Dahlberg -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. All advertising materials mentioning features or use of this software -# must display the following acknowledgement: -# This product includes software developed by Stephanie Wehner, QuTech. -# 4. Neither the name of the QuTech organization nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import sys - -from cqc.pythonLib import CQCConnection -from cqc.pythonLib_protocols.wstate import create_Nqubit_Wstate -from additional_functions import string_to_int, broadcastClassical, int_to_string - -##################################################################################################### -# -# main -# - - -def main(): - - if len(sys.argv) == 2: - nodename = sys.argv[1] - else: - print("Provide one argument for the node name") - - # Initialize the connection - with CQCConnection(nodename) as Node: - # Create an EPR pair - Nodenames = Node._cqcNet.hostDict.keys() - print(Nodenames, " size = ", len(Nodenames)) - num_qubit = len(Nodenames) - qubits = create_Nqubit_Wstate(num_qubit, Node) - - print("Number of qubits as W state = ", len(qubits)) - index = 0 - for key in Node._cqcNet.hostDict.keys(): - if key != Node.name: - print("Sending qubit[", index, "] to ", key) - Node.sendQubit(qubits[index], key) - index = index + 1 - - m = qubits[len(qubits) - 1].measure() - to_print = "(" + nodename + ") App {}: Measurement outcome is: {}".format(Node.name, m) - print("|" + "-" * (len(to_print) + 2) + "|\n", "| " + to_print + " |", "\n|" + "-" * (len(to_print) + 2) + "|") - - if m == 1: - print("| (" + nodename + ") I'm the leader") - ordlist = string_to_int(nodename + " is the leader") - broadcastClassical(ordlist, Node) - - data = Node.recvClassical() - message = list(data) - msg = int_to_string(message) - print("(" + nodename + ")", msg) - - -################################################################################################## -main() diff --git a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/run.sh b/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/run.sh deleted file mode 100755 index 8c52260..0000000 --- a/data/examples/simulaqron/CQC-Python/examples/pythonLib/wstate/run.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh - -python3 default_Wstate_transmitter.py Node0 & -python3 default_Wstate_receiver.py Node1 & -python3 default_Wstate_receiver.py Node2 & -python3 default_Wstate_receiver.py Node3 & -python3 default_Wstate_receiver.py Node4 & -python3 default_Wstate_receiver.py Node5 & -python3 default_Wstate_receiver.py Node6 & diff --git a/data/examples/simulaqron/hello_simu.sh b/data/examples/simulaqron/hello_simu.sh deleted file mode 100755 index 91ab091..0000000 --- a/data/examples/simulaqron/hello_simu.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -# Start simulaqron and init qnodes -echo 'yes' | simulaqron start -# Run a simple EPR protocol between Alice and Bob (simple entanglement) -/opt/quantum_lab/data/CQC-Python/examples/pythonLib/corrRNG/run.sh - -# Wait time to the ERP finish and then stop and reset nodes -sleep 5 -simulaqron stop -echo 'yes' | simulaqron reset From 4d7da19085ec0f0296d2ae199d7d43b296d3e47d Mon Sep 17 00:00:00 2001 From: Mica Date: Tue, 28 May 2024 18:27:17 +0200 Subject: [PATCH 2/2] Connect to qat-computer --- Dockerfile | 3 +++ README.md | 17 +++++++++++++++++ data/start_jupyter.sh => start_jupyter.sh | 0 3 files changed, 20 insertions(+) rename data/start_jupyter.sh => start_jupyter.sh (100%) diff --git a/Dockerfile b/Dockerfile index 5e3c219..1d794ec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,6 +27,7 @@ RUN apt-get update -yq \ # Add script & data ADD build/* /opt/quantum_lab/build/ ADD data/ /opt/quantum_lab/data/ +ADD start_jupyter.sh /opt/quantum_lab/ # General & env requirements RUN pip install --upgrade pip setuptools @@ -35,4 +36,6 @@ RUN pip install -r /opt/quantum_lab/build/requirements.txt WORKDIR /opt/quantum_lab/data VOLUME /opt/quantum_lab/data/share +EXPOSE 8888 + CMD /bin/bash diff --git a/README.md b/README.md index b4d1393..09243e1 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,23 @@ The env is based on the image [qat-computer](https://github.com/mickahell/qat-co ### Volume The folder `data/share` is link to the host file and allow to register the modification in the host computer +### How to + +#### Build + +```bash +docker build . --file Dockerfile --tag quantum_lab_qiskit:main +``` + +#### Run + +```bash +docker run -d --name qiskit_lab \ + -v $PWD/YOUR_DATA_FOLDER:/opt/quantum_lab/data/share + -p 8888:8888 \ + mickahell/quantum_lab_qiskit:latest -c "/opt/quantum_lab/start_jupyter.sh" +``` + ### Jupyter To launch the Jupyter notebook instance : - be inside the `data`folder diff --git a/data/start_jupyter.sh b/start_jupyter.sh similarity index 100% rename from data/start_jupyter.sh rename to start_jupyter.sh