├── module ├── qml │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ └── meta.json │ └── module.py ├── vqe │ └── .cm │ │ ├── desc.json │ │ ├── info.json │ │ └── meta.json ├── .cm │ ├── alias-a-qml │ ├── alias-a-vqe │ ├── alias-u-1b0401c9d3f9db1e │ ├── alias-u-6b82fa71240ce99c │ ├── alias-a-challenge.vqe │ ├── alias-u-a44f5985526c2323 │ ├── alias-a-hackathon.20180615 │ ├── alias-a-hackathon.20181006 │ ├── alias-a-hackathon.20190127 │ ├── alias-a-hackathon.20190315 │ ├── alias-u-70fa4c547c1a1f1a │ ├── alias-u-905643d8991ad557 │ ├── alias-u-e485cb1137404d96 │ └── alias-u-f40e5947238264d1 ├── challenge.vqe │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ ├── updates.json │ │ └── meta.json │ ├── Rigetti -- Benchmarking License -- 18.12.16.pdf │ ├── README.md │ └── module.py ├── hackathon.20180615 │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ ├── meta.json │ │ └── updates.json │ └── README.md ├── hackathon.20181006 │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ ├── updates.json │ │ └── meta.json │ ├── README.md │ └── module.py ├── hackathon.20190127 │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ └── meta.json │ ├── module.py │ └── README.md └── hackathon.20190315 │ ├── .cm │ ├── desc.json │ ├── info.json │ └── meta.json │ └── module.py ├── .cm ├── alias-a-env ├── alias-a-soft ├── alias-u-5e1100048ab875d7 ├── alias-u-9b9b3208ac44b891 ├── alias-a-docker ├── alias-a-jnotebook ├── alias-a-module ├── alias-a-package ├── alias-a-program ├── alias-u-032630d041b4fd8a ├── alias-u-145039462db4f4d2 ├── alias-u-1dc07ee0f4742028 ├── alias-u-88eef0cd8c43b68a └── alias-u-b0ac08fe1d3c2615 ├── env ├── vqe_utils │ ├── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json │ ├── env.sh │ ├── env.bat │ └── vqe_utils.py └── .cm │ ├── alias-a-vqe_utils │ └── alias-u-b45019b647b129b0 ├── package ├── tool-hackathon │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ └── meta.json │ ├── hackathon-src │ │ ├── hackathon │ │ │ ├── __init__.py │ │ │ ├── hackathon.py │ │ │ ├── optimizers.py │ │ │ └── utils.py │ │ ├── __init__.py │ │ ├── hackathon_optimizers.py │ │ └── hackathon_utils.py │ ├── install.bat │ └── install.sh └── .cm │ ├── alias-a-tool-hackathon │ └── alias-u-e2bbefdc54d9cadd ├── soft ├── lib.hackathon │ ├── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json │ └── customize.py ├── vqe.hamiltonian │ ├── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json │ ├── python_code │ │ ├── helium │ │ │ └── vqe_hamiltonian.py │ │ ├── hydrogen │ │ │ └── vqe_hamiltonian.py │ │ └── qiskit_hydrogen │ │ │ └── vqe_hamiltonian.py │ └── customize.py ├── template.optimizer │ ├── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json │ ├── python_code │ │ ├── cobyla │ │ │ └── custom_optimizer.py │ │ ├── nelder_mead │ │ │ └── custom_optimizer.py │ │ ├── custom │ │ │ └── custom_optimizer.py │ │ └── random_sampler │ │ │ └── custom_optimizer.py │ └── customize.py └── .cm │ ├── alias-a-lib.hackathon │ ├── alias-a-vqe.hamiltonian │ ├── alias-u-4cef1a24219b2b67 │ ├── alias-u-f0a25d64c3891b4f │ ├── alias-a-template.optimizer │ └── alias-u-6acd94707a890d2a ├── docker ├── hackathon.20190127 │ ├── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json │ └── Dockerfile ├── hackathon.20190315 │ ├── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json │ └── Dockerfile └── .cm │ ├── alias-a-hackathon.20190127 │ ├── alias-a-hackathon.20190315 │ ├── alias-u-10d7491aaf9b6061 │ └── alias-u-887ebe1eb0bd7f83 ├── program ├── benchmark-helper │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ └── meta.json │ └── run.py ├── visualize-convergence │ ├── .cm │ │ ├── desc.json │ │ ├── info.json │ │ └── meta.json │ ├── README.md │ └── visualize_convergence.py └── .cm │ ├── alias-a-benchmark-helper │ ├── alias-u-89983c43e0ad01ac │ ├── alias-a-visualize-convergence │ └── alias-u-c707814bd9b2f9e3 ├── jnotebook ├── hackathon.20180615 │ └── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json ├── hackathon.20181006 │ └── .cm │ │ ├── desc.json │ │ ├── meta.json │ │ └── info.json └── .cm │ ├── alias-a-hackathon.20180615 │ ├── alias-a-hackathon.20181006 │ ├── alias-u-44ba791f37c2b826 │ └── alias-u-af711a439fb9bae3 ├── .ckr.json ├── README.md └── .gitignore /module/qml/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /module/vqe/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /.cm/alias-a-env: -------------------------------------------------------------------------------- 1 | 9b9b3208ac44b891 2 | -------------------------------------------------------------------------------- /.cm/alias-a-soft: -------------------------------------------------------------------------------- 1 | 5e1100048ab875d7 2 | -------------------------------------------------------------------------------- /.cm/alias-u-5e1100048ab875d7: -------------------------------------------------------------------------------- 1 | soft 2 | -------------------------------------------------------------------------------- /.cm/alias-u-9b9b3208ac44b891: -------------------------------------------------------------------------------- 1 | env 2 | -------------------------------------------------------------------------------- /env/vqe_utils/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /.cm/alias-a-docker: -------------------------------------------------------------------------------- 1 | 88eef0cd8c43b68a 2 | -------------------------------------------------------------------------------- /.cm/alias-a-jnotebook: -------------------------------------------------------------------------------- 1 | 145039462db4f4d2 2 | -------------------------------------------------------------------------------- /.cm/alias-a-module: -------------------------------------------------------------------------------- 1 | 032630d041b4fd8a 2 | -------------------------------------------------------------------------------- /.cm/alias-a-package: -------------------------------------------------------------------------------- 1 | 1dc07ee0f4742028 2 | -------------------------------------------------------------------------------- /.cm/alias-a-program: -------------------------------------------------------------------------------- 1 | b0ac08fe1d3c2615 2 | -------------------------------------------------------------------------------- /.cm/alias-u-032630d041b4fd8a: -------------------------------------------------------------------------------- 1 | module 2 | -------------------------------------------------------------------------------- /.cm/alias-u-145039462db4f4d2: -------------------------------------------------------------------------------- 1 | jnotebook 2 | -------------------------------------------------------------------------------- /.cm/alias-u-1dc07ee0f4742028: -------------------------------------------------------------------------------- 1 | package 2 | -------------------------------------------------------------------------------- /.cm/alias-u-88eef0cd8c43b68a: -------------------------------------------------------------------------------- 1 | docker 2 | -------------------------------------------------------------------------------- /.cm/alias-u-b0ac08fe1d3c2615: -------------------------------------------------------------------------------- 1 | program 2 | -------------------------------------------------------------------------------- /module/.cm/alias-a-qml: -------------------------------------------------------------------------------- 1 | 1b0401c9d3f9db1e 2 | -------------------------------------------------------------------------------- /module/.cm/alias-a-vqe: -------------------------------------------------------------------------------- 1 | 6b82fa71240ce99c 2 | -------------------------------------------------------------------------------- /module/.cm/alias-u-1b0401c9d3f9db1e: -------------------------------------------------------------------------------- 1 | qml 2 | -------------------------------------------------------------------------------- /module/.cm/alias-u-6b82fa71240ce99c: -------------------------------------------------------------------------------- 1 | vqe 2 | -------------------------------------------------------------------------------- /module/challenge.vqe/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /package/tool-hackathon/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /soft/lib.hackathon/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /soft/vqe.hamiltonian/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /docker/hackathon.20190127/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /docker/hackathon.20190315/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /env/.cm/alias-a-vqe_utils: -------------------------------------------------------------------------------- 1 | b45019b647b129b0 2 | -------------------------------------------------------------------------------- /env/.cm/alias-u-b45019b647b129b0: -------------------------------------------------------------------------------- 1 | vqe_utils 2 | -------------------------------------------------------------------------------- /module/hackathon.20180615/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /module/hackathon.20181006/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /module/hackathon.20190127/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /module/hackathon.20190315/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /program/benchmark-helper/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /soft/template.optimizer/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /jnotebook/hackathon.20180615/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /jnotebook/hackathon.20180615/.cm/meta.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /jnotebook/hackathon.20181006/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /jnotebook/hackathon.20181006/.cm/meta.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /module/.cm/alias-a-challenge.vqe: -------------------------------------------------------------------------------- 1 | a44f5985526c2323 2 | -------------------------------------------------------------------------------- /module/.cm/alias-u-a44f5985526c2323: -------------------------------------------------------------------------------- 1 | challenge.vqe 2 | -------------------------------------------------------------------------------- /program/visualize-convergence/.cm/desc.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /soft/.cm/alias-a-lib.hackathon: -------------------------------------------------------------------------------- 1 | f0a25d64c3891b4f 2 | -------------------------------------------------------------------------------- /soft/.cm/alias-a-vqe.hamiltonian: -------------------------------------------------------------------------------- 1 | 4cef1a24219b2b67 2 | -------------------------------------------------------------------------------- /soft/.cm/alias-u-4cef1a24219b2b67: -------------------------------------------------------------------------------- 1 | vqe.hamiltonian 2 | -------------------------------------------------------------------------------- /soft/.cm/alias-u-f0a25d64c3891b4f: -------------------------------------------------------------------------------- 1 | lib.hackathon 2 | -------------------------------------------------------------------------------- /docker/.cm/alias-a-hackathon.20190127: -------------------------------------------------------------------------------- 1 | 887ebe1eb0bd7f83 2 | -------------------------------------------------------------------------------- /docker/.cm/alias-a-hackathon.20190315: -------------------------------------------------------------------------------- 1 | 10d7491aaf9b6061 2 | -------------------------------------------------------------------------------- /docker/.cm/alias-u-10d7491aaf9b6061: -------------------------------------------------------------------------------- 1 | hackathon.20190315 2 | -------------------------------------------------------------------------------- /docker/.cm/alias-u-887ebe1eb0bd7f83: -------------------------------------------------------------------------------- 1 | hackathon.20190127 2 | -------------------------------------------------------------------------------- /module/.cm/alias-a-hackathon.20180615: -------------------------------------------------------------------------------- 1 | f40e5947238264d1 2 | -------------------------------------------------------------------------------- /module/.cm/alias-a-hackathon.20181006: -------------------------------------------------------------------------------- 1 | e485cb1137404d96 2 | -------------------------------------------------------------------------------- /module/.cm/alias-a-hackathon.20190127: -------------------------------------------------------------------------------- 1 | 70fa4c547c1a1f1a 2 | -------------------------------------------------------------------------------- /module/.cm/alias-a-hackathon.20190315: -------------------------------------------------------------------------------- 1 | 905643d8991ad557 2 | -------------------------------------------------------------------------------- /module/.cm/alias-u-70fa4c547c1a1f1a: -------------------------------------------------------------------------------- 1 | hackathon.20190127 2 | -------------------------------------------------------------------------------- /module/.cm/alias-u-905643d8991ad557: -------------------------------------------------------------------------------- 1 | hackathon.20190315 2 | -------------------------------------------------------------------------------- /module/.cm/alias-u-e485cb1137404d96: -------------------------------------------------------------------------------- 1 | hackathon.20181006 2 | -------------------------------------------------------------------------------- /module/.cm/alias-u-f40e5947238264d1: -------------------------------------------------------------------------------- 1 | hackathon.20180615 2 | -------------------------------------------------------------------------------- /package/.cm/alias-a-tool-hackathon: -------------------------------------------------------------------------------- 1 | e2bbefdc54d9cadd 2 | -------------------------------------------------------------------------------- /package/.cm/alias-u-e2bbefdc54d9cadd: -------------------------------------------------------------------------------- 1 | tool-hackathon 2 | -------------------------------------------------------------------------------- /package/tool-hackathon/hackathon-src/hackathon/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /program/.cm/alias-a-benchmark-helper: -------------------------------------------------------------------------------- 1 | 89983c43e0ad01ac 2 | -------------------------------------------------------------------------------- /program/.cm/alias-u-89983c43e0ad01ac: -------------------------------------------------------------------------------- 1 | benchmark-helper 2 | -------------------------------------------------------------------------------- /soft/.cm/alias-a-template.optimizer: -------------------------------------------------------------------------------- 1 | 6acd94707a890d2a 2 | -------------------------------------------------------------------------------- /soft/.cm/alias-u-6acd94707a890d2a: -------------------------------------------------------------------------------- 1 | template.optimizer 2 | -------------------------------------------------------------------------------- /jnotebook/.cm/alias-a-hackathon.20180615: -------------------------------------------------------------------------------- 1 | 44ba791f37c2b826 2 | -------------------------------------------------------------------------------- /jnotebook/.cm/alias-a-hackathon.20181006: -------------------------------------------------------------------------------- 1 | af711a439fb9bae3 2 | -------------------------------------------------------------------------------- /jnotebook/.cm/alias-u-44ba791f37c2b826: -------------------------------------------------------------------------------- 1 | hackathon.20180615 2 | -------------------------------------------------------------------------------- /jnotebook/.cm/alias-u-af711a439fb9bae3: -------------------------------------------------------------------------------- 1 | hackathon.20181006 2 | -------------------------------------------------------------------------------- /program/.cm/alias-a-visualize-convergence: -------------------------------------------------------------------------------- 1 | c707814bd9b2f9e3 2 | -------------------------------------------------------------------------------- /program/.cm/alias-u-c707814bd9b2f9e3: -------------------------------------------------------------------------------- 1 | visualize-convergence 2 | -------------------------------------------------------------------------------- /package/tool-hackathon/hackathon-src/hackathon/hackathon.py: -------------------------------------------------------------------------------- 1 | def hello(): 2 | return "Have a nice Hackathon" 3 | -------------------------------------------------------------------------------- /package/tool-hackathon/hackathon-src/__init__.py: -------------------------------------------------------------------------------- 1 | from .hackathon import utils 2 | from .hackathon import optimizers 3 | -------------------------------------------------------------------------------- /env/vqe_utils/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "tags": [ 3 | "quantum", 4 | "vqe", 5 | "utils", 6 | "lib" 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /module/challenge.vqe/Rigetti -- Benchmarking License -- 18.12.16.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dividiti/ck-quantum/master/module/challenge.vqe/Rigetti -- Benchmarking License -- 18.12.16.pdf -------------------------------------------------------------------------------- /soft/template.optimizer/python_code/cobyla/custom_optimizer.py: -------------------------------------------------------------------------------- 1 | import scipy.optimize 2 | 3 | 4 | def my_cobyla( func, x0, my_args=(), my_options=None ): 5 | "Stock COBYLA optimizer from SciPy library" 6 | 7 | return scipy.optimize.minimize( func, x0, method='COBYLA', options=my_options, args=my_args ) 8 | -------------------------------------------------------------------------------- /soft/template.optimizer/python_code/nelder_mead/custom_optimizer.py: -------------------------------------------------------------------------------- 1 | import scipy.optimize 2 | 3 | 4 | def my_nelder_mead( func, x0, my_args=(), my_options=None ): 5 | "Stock Nelder-Mead optimizer from SciPy library" 6 | 7 | return scipy.optimize.minimize( func, x0, method='Nelder-Mead', options=my_options, args=my_args ) 8 | -------------------------------------------------------------------------------- /module/hackathon.20180615/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "f40e5947238264d1", 3 | "backup_module_uid": "032630d041b4fd8a", 4 | "backup_module_uoa": "module", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-08-09T13:21:57.496563", 8 | "version": [ 9 | "1", 10 | "9", 11 | "4" 12 | ] 13 | }, 14 | "data_name": "hackathon.20180615" 15 | } 16 | -------------------------------------------------------------------------------- /module/challenge.vqe/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "a44f5985526c2323", 3 | "backup_module_uid": "032630d041b4fd8a", 4 | "backup_module_uoa": "module", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-11-19T16:10:43.841971", 8 | "version": [ 9 | "1", 10 | "9", 11 | "6", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "challenge.vqe" 16 | } 17 | -------------------------------------------------------------------------------- /module/hackathon.20181006/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "e485cb1137404d96", 3 | "backup_module_uid": "032630d041b4fd8a", 4 | "backup_module_uoa": "module", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-10-01T15:06:14.352381", 8 | "version": [ 9 | "1", 10 | "9", 11 | "6", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "hackathon.20181006" 16 | } 17 | -------------------------------------------------------------------------------- /module/hackathon.20190127/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "70fa4c547c1a1f1a", 3 | "backup_module_uid": "032630d041b4fd8a", 4 | "backup_module_uoa": "module", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-12-21T12:11:33.612621", 8 | "version": [ 9 | "1", 10 | "9", 11 | "6", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "hackathon.20190127" 16 | } 17 | -------------------------------------------------------------------------------- /module/hackathon.20190315/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "905643d8991ad557", 3 | "backup_module_uid": "032630d041b4fd8a", 4 | "backup_module_uoa": "module", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2019-03-08T10:01:04.457055", 8 | "version": [ 9 | "1", 10 | "9", 11 | "6", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "hackathon.20190315" 16 | } 17 | -------------------------------------------------------------------------------- /env/vqe_utils/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "b45019b647b129b0", 3 | "backup_module_uid": "9b9b3208ac44b891", 4 | "backup_module_uoa": "env", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-07-31T13:42:09.326052", 8 | "version": [ 9 | "1", 10 | "9", 11 | "5", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "VQE Python utility functions" 16 | } 17 | -------------------------------------------------------------------------------- /jnotebook/hackathon.20180615/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "44ba791f37c2b826", 3 | "backup_module_uid": "145039462db4f4d2", 4 | "backup_module_uoa": "jnotebook", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-06-08T11:55:42.800779", 8 | "version": [ 9 | "1", 10 | "9", 11 | "4", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "hackathon.20180615" 16 | } 17 | -------------------------------------------------------------------------------- /jnotebook/hackathon.20181006/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "af711a439fb9bae3", 3 | "backup_module_uid": "145039462db4f4d2", 4 | "backup_module_uoa": "jnotebook", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-10-04T10:37:48.078647", 8 | "version": [ 9 | "1", 10 | "9", 11 | "6", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "hackathon.20181006" 16 | } 17 | -------------------------------------------------------------------------------- /module/hackathon.20180615/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "actions": { 3 | "get_raw_config": { 4 | "desc": "get raw config for repo widget", 5 | "for_web": "yes" 6 | }, 7 | "get_raw_data": { 8 | "desc": "get raw data for repo-widget", 9 | "for_web": "yes" 10 | } 11 | }, 12 | "desc": "Raw data access (json)", 13 | "workflow": "yes", 14 | "workflow_type": "quantum hackathon workflow" 15 | } 16 | -------------------------------------------------------------------------------- /program/benchmark-helper/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "89983c43e0ad01ac", 3 | "backup_module_uid": "b0ac08fe1d3c2615", 4 | "backup_module_uoa": "program", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2019-01-24T15:27:45.128715", 8 | "version": [ 9 | "1", 10 | "9", 11 | "6", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "benchmark-helper" 16 | } 17 | -------------------------------------------------------------------------------- /program/visualize-convergence/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "c707814bd9b2f9e3", 3 | "backup_module_uid": "b0ac08fe1d3c2615", 4 | "backup_module_uoa": "program", 5 | "control": { 6 | "engine": "CK", 7 | "iso_datetime": "2018-10-05T10:10:15.610963", 8 | "version": [ 9 | "1", 10 | "9", 11 | "6", 12 | "1" 13 | ] 14 | }, 15 | "data_name": "visualize-convergence" 16 | } 17 | -------------------------------------------------------------------------------- /soft/template.optimizer/python_code/custom/custom_optimizer.py: -------------------------------------------------------------------------------- 1 | import random 2 | import numpy as np 3 | 4 | 5 | def my_minimizer( func, x0, my_args=(), my_options=None ): 6 | "Your own attempt at writing a stochastic minimizer" 7 | 8 | current_func_value = func(x0, my_args) 9 | 10 | minimizer_output = { 'fun' : current_func_value, 'nfev' : 1, 'nit' : 1, 'x' : x0 } 11 | 12 | return minimizer_output 13 | 14 | -------------------------------------------------------------------------------- /package/tool-hackathon/install.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | rem CK installation script 4 | rem 5 | rem Developer(s): 6 | rem * Grigori Fursin, dividiti/cTuning foundation 7 | rem 8 | 9 | ###################################################################################### 10 | echo Installing CK-QUANTUM HACKATHON MODULE 11 | echo. 12 | 13 | mkdir %INSTALL_DIR%\lib 14 | 15 | xcopy /s /e /y %PACKAGE_DIR%\hackathon-src\* %INSTALL_DIR%\lib 16 | 17 | exit /b 0 18 | -------------------------------------------------------------------------------- /module/challenge.vqe/.cm/updates.json: -------------------------------------------------------------------------------- 1 | { 2 | "control": [ 3 | { 4 | "engine": "CK", 5 | "iso_datetime": "2018-08-09T13:24:16.332179", 6 | "version": [ 7 | "1", 8 | "9", 9 | "4" 10 | ] 11 | }, 12 | { 13 | "engine": "CK", 14 | "iso_datetime": "2018-08-09T13:24:42.263686", 15 | "version": [ 16 | "1", 17 | "9", 18 | "4" 19 | ] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /module/hackathon.20180615/.cm/updates.json: -------------------------------------------------------------------------------- 1 | { 2 | "control": [ 3 | { 4 | "engine": "CK", 5 | "iso_datetime": "2018-08-09T13:24:16.332179", 6 | "version": [ 7 | "1", 8 | "9", 9 | "4" 10 | ] 11 | }, 12 | { 13 | "engine": "CK", 14 | "iso_datetime": "2018-08-09T13:24:42.263686", 15 | "version": [ 16 | "1", 17 | "9", 18 | "4" 19 | ] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /module/hackathon.20181006/.cm/updates.json: -------------------------------------------------------------------------------- 1 | { 2 | "control": [ 3 | { 4 | "engine": "CK", 5 | "iso_datetime": "2018-08-09T13:24:16.332179", 6 | "version": [ 7 | "1", 8 | "9", 9 | "4" 10 | ] 11 | }, 12 | { 13 | "engine": "CK", 14 | "iso_datetime": "2018-08-09T13:24:42.263686", 15 | "version": [ 16 | "1", 17 | "9", 18 | "4" 19 | ] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /soft/vqe.hamiltonian/python_code/helium/vqe_hamiltonian.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | Helium molecule in Ground State (sto, 3g) 5 | 6 | Originally used by River Lane Research for testing Rigetti VQE. 7 | """ 8 | 9 | label_to_hamiltonian_coeff = { 10 | "II": -1.6678202144537553, 11 | "ZI": 0.7019459893849936, 12 | "IZ": 0.7019459893849936, 13 | "ZZ": 0.263928235683768058, 14 | } 15 | 16 | classical_energy = -2.8077839575399746 17 | -------------------------------------------------------------------------------- /soft/lib.hackathon/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "auto_detect": "yes", 3 | "customize": { 4 | "check_that_exists": "yes", 5 | "ck_version": 10, 6 | "env_prefix": "CK_ENV_LIB_HACKATHON", 7 | "limit_recursion_dir_search": { 8 | "linux": 5, 9 | "win": 5 10 | }, 11 | "soft_file": { 12 | "linux": "hackathon/lib/hackathon.py" 13 | } 14 | }, 15 | "soft_name": "CK-Quantum Hackathon Module", 16 | "tags": [ 17 | "tool", 18 | "ck-quantum", 19 | "hackathon" 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /soft/vqe.hamiltonian/python_code/hydrogen/vqe_hamiltonian.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | Hydrogen molecule in Ground State (sto, 3g) 5 | 6 | Originally used by River Lane Research for testing Rigetti VQE. 7 | """ 8 | 9 | label_to_hamiltonian_coeff = { 10 | "ZZ": 0.011236585210827765, 11 | "II": -0.3399536172489041, 12 | "ZI": 0.39398367743432866, 13 | "IZ": 0.39398367743432866, 14 | "XX": 0.18128880839426165, 15 | } 16 | 17 | classical_energy = -1.137270174625326 18 | -------------------------------------------------------------------------------- /soft/vqe.hamiltonian/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "auto_detect": "yes", 3 | "customize": { 4 | "check_that_exists": "yes", 5 | "detect_in_soft_dir": "yes", 6 | "env_prefix": "CK_ENV_VQE_HAMILTONIAN", 7 | "limit_recursion_dir_search": { 8 | "linux": 2, 9 | "win": 2 10 | }, 11 | "soft_file_universal": "vqe_hamiltonian.py", 12 | "unsplit_version_to_tags_prefixed_with": "hamiltonian." 13 | }, 14 | "soft_name": "Hamiltonian for VQE", 15 | "tags": [ 16 | "quantum", 17 | "vqe", 18 | "hamiltonian", 19 | "lib" 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /soft/vqe.hamiltonian/python_code/qiskit_hydrogen/vqe_hamiltonian.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | Hydrogen molecule 5 | 6 | Originally packaged with Qiskit's VQE implementation: 7 | 8 | https://github.com/Qiskit/qiskit-terra/blob/master/test/performance/H2/H2Equilibrium.txt 9 | """ 10 | 11 | label_to_hamiltonian_coeff = { 12 | "ZZ": 0.011279956224107712, 13 | "II": -1.0523760606256514, 14 | "ZI": 0.39793570529466216, 15 | "IZ": 0.39793570529466216, 16 | "XX": 0.18093133934472627, 17 | } 18 | 19 | classical_energy = -1.8572746704950887 20 | -------------------------------------------------------------------------------- /docker/hackathon.20190315/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "cmd": { 3 | "default": { 4 | "build": "-t $#CK_DOCKER_ORGANIZATION#$/$#CK_DOCKER_NAME#$ $#CK_PATH#$", 5 | "push": "$#CK_DOCKER_ORGANIZATION#$/$#CK_DOCKER_NAME#$", 6 | "run": "--rm -it $#CK_DOCKER_ORGANIZATION#$/$#CK_DOCKER_NAME#$", 7 | "run_extra_cmd": "--env CK_HOST=0.0.0.0 --env WFE_HOST=localhost --env CK_PORT=$#CK_PORT#$ --env WFE_PORT=$#CK_PORT#$ -p $#CK_PORT#$:$#CK_PORT#$" 8 | } 9 | }, 10 | "convert_input_to_vars": { 11 | "port": { 12 | "default": "3344", 13 | "key": "CK_PORT" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /docker/hackathon.20190127/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "cmd": { 3 | "default": { 4 | "build": "-t $#CK_DOCKER_ORGANIZATION#$/$#CK_DOCKER_NAME#$ $#CK_PATH#$", 5 | "push": "$#CK_DOCKER_ORGANIZATION#$/$#CK_DOCKER_NAME#$", 6 | "run": "--rm -it $#CK_DOCKER_ORGANIZATION#$/$#CK_DOCKER_NAME#$", 7 | "run_extra_cmd": "--env CK_HOST=0.0.0.0 --env WFE_HOST=localhost --env CK_PORT=$#CK_PORT#$ --env WFE_PORT=$#CK_PORT#$ -p $#CK_PORT#$:$#CK_PORT#$" 8 | } 9 | }, 10 | "convert_input_to_vars": { 11 | "port": { 12 | "default": "3344", 13 | "key": "CK_PORT" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /soft/template.optimizer/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "auto_detect": "yes", 3 | "customize": { 4 | "check_that_exists": "yes", 5 | "deployed_name_infix": "optimizer.", 6 | "detect_in_soft_dir": "yes", 7 | "env_prefix": "CK_ENV_VQE_OPTIMIZER", 8 | "limit_recursion_dir_search": { 9 | "linux": 2, 10 | "win": 2 11 | }, 12 | "soft_file_universal": "custom_optimizer.py", 13 | "unsplit_version_to_tags_prefixed_with": "optimizer." 14 | }, 15 | "soft_name": "Optimizer for VQE", 16 | "tags": [ 17 | "quantum", 18 | "vqe", 19 | "optimizer", 20 | "lib" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /module/vqe/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "6b82fa71240ce99c", 3 | "backup_module_uid": "032630d041b4fd8a", 4 | "backup_module_uoa": "module", 5 | "control": { 6 | "author": "Grigori Fursin", 7 | "author_email": "Grigori.Fursin@cTuning.org", 8 | "author_webpage": "http://fursin.net", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2018-07-17T11:24:47.977960", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "4", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "vqe" 21 | } 22 | -------------------------------------------------------------------------------- /soft/lib.hackathon/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "f0a25d64c3891b4f", 3 | "backup_module_uid": "5e1100048ab875d7", 4 | "backup_module_uoa": "soft", 5 | "control": { 6 | "author": "cTuning foundation", 7 | "author_email": "admin@cTuning.org", 8 | "author_webpage": "http://cTuning.org", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2018-06-06T10:26:31.028090", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "1", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "lib.hackathon" 21 | } 22 | -------------------------------------------------------------------------------- /module/qml/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "1b0401c9d3f9db1e", 3 | "backup_module_uid": "032630d041b4fd8a", 4 | "backup_module_uoa": "module", 5 | "control": { 6 | "author": "Grigori Fursin", 7 | "author_email": "Grigori.Fursin@cTuning.org", 8 | "author_webpage": "http://fursin.net", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2019-01-21T11:28:34.095833", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "6", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "qml" 21 | } 22 | -------------------------------------------------------------------------------- /soft/vqe.hamiltonian/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "4cef1a24219b2b67", 3 | "backup_module_uid": "5e1100048ab875d7", 4 | "backup_module_uoa": "soft", 5 | "control": { 6 | "author": "cTuning foundation", 7 | "author_email": "admin@cTuning.org", 8 | "author_webpage": "http://cTuning.org", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2018-10-10T12:06:18.321612", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "5", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "vqe.hamiltonian" 21 | } 22 | -------------------------------------------------------------------------------- /package/tool-hackathon/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "e2bbefdc54d9cadd", 3 | "backup_module_uid": "1dc07ee0f4742028", 4 | "backup_module_uoa": "package", 5 | "control": { 6 | "author": "cTuning foundation", 7 | "author_email": "admin@cTuning.org", 8 | "author_webpage": "http://cTuning.org", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2018-06-06T10:35:42.370248", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "1", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "tool-hackathon" 21 | } 22 | -------------------------------------------------------------------------------- /soft/template.optimizer/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "6acd94707a890d2a", 3 | "backup_module_uid": "5e1100048ab875d7", 4 | "backup_module_uoa": "soft", 5 | "control": { 6 | "author": "cTuning foundation", 7 | "author_email": "admin@cTuning.org", 8 | "author_webpage": "http://cTuning.org", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2018-08-22T16:18:30.115604", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "5", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "template.optimizer" 21 | } 22 | -------------------------------------------------------------------------------- /docker/hackathon.20190127/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "887ebe1eb0bd7f83", 3 | "backup_module_uid": "88eef0cd8c43b68a", 4 | "backup_module_uoa": "docker", 5 | "control": { 6 | "author": "Grigori Fursin", 7 | "author_email": "Grigori.Fursin@cTuning.org", 8 | "author_webpage": "http://fursin.net", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2019-01-24T13:21:18.258175", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "6", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "hackathon.20190127" 21 | } 22 | -------------------------------------------------------------------------------- /docker/hackathon.20190315/.cm/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "10d7491aaf9b6061", 3 | "backup_module_uid": "88eef0cd8c43b68a", 4 | "backup_module_uoa": "docker", 5 | "control": { 6 | "author": "Grigori Fursin", 7 | "author_email": "Grigori.Fursin@cTuning.org", 8 | "author_webpage": "http://fursin.net", 9 | "copyright": "See CK COPYRIGHT.txt for copyright details", 10 | "engine": "CK", 11 | "iso_datetime": "2019-03-13T10:01:00.313077", 12 | "license": "See CK LICENSE.txt for licensing details", 13 | "version": [ 14 | "1", 15 | "9", 16 | "6", 17 | "1" 18 | ] 19 | }, 20 | "data_name": "hackathon.20190315" 21 | } 22 | -------------------------------------------------------------------------------- /env/vqe_utils/env.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Finding the path to the directory that contains THIS bash script, 4 | # the solution borrowed from here: 5 | # https://stackoverflow.com/questions/4774054/reliable-way-for-a-bash-script-to-get-the-full-path-to-itself 6 | 7 | PATH_TO_THIS_ENTRY_DIR="$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )" 8 | ALREADY_LOADED_NAME=CK_STATIC_ENV_`basename $PATH_TO_THIS_ENTRY_DIR | tr -cd '[:alnum:]_'` 9 | ALREADY_LOADED_FLAG=${ALREADY_LOADED_NAME} 10 | 11 | if [ "$1" != "1" ] && [ "$ALREADY_LOADED_FLAG" == "1" ]; then return; fi; 12 | 13 | echo Adding $PATH_TO_THIS_ENTRY_DIR to the PYTHONPATH ... 14 | 15 | export PYTHONPATH=${PATH_TO_THIS_ENTRY_DIR}:${PYTHONPATH} 16 | 17 | export ${ALREADY_LOADED_NAME}=1 18 | -------------------------------------------------------------------------------- /env/vqe_utils/env.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | rem Finding the path to the directory that contains THIS batch script, 4 | rem the solution borrowed from here: 5 | rem https://stackoverflow.com/questions/8797983/can-a-windows-batch-file-determine-its-own-file-name 6 | rem https://stackoverflow.com/questions/778135/how-do-i-get-the-equivalent-of-dirname-in-a-batch-file/778147 7 | 8 | set PATH_TO_THIS_ENTRY_DIR=%~dp0 9 | for /f %%j in ("%PATH_TO_THIS_ENTRY_DIR:~0,-1%") do set ALREADY_LOADED_NAME=CK_STATIC_ENV_%%~nxj 10 | 11 | if not [%1] == [1] (if defined %ALREADY_LOADED_NAME% exit /b 0) 12 | 13 | echo Adding %PATH_TO_THIS_ENTRY_DIR% to the PYTHONPATH ... 14 | 15 | set PYTHONPATH=%PATH_TO_THIS_ENTRY_DIR%;%PYTHONPATH% 16 | 17 | set %ALREADY_LOADED_NAME%=1 18 | 19 | exit /b 0 20 | -------------------------------------------------------------------------------- /program/benchmark-helper/run.py: -------------------------------------------------------------------------------- 1 | # 2 | # CK program template 3 | # 4 | # See CK LICENSE.txt for licensing details 5 | # See CK COPYRIGHT.txt for copyright details 6 | # 7 | # Developer: Grigori Fursin, 2018, Grigori.Fursin@cTuning.org, http://fursin.net 8 | # 9 | 10 | import os 11 | import json 12 | 13 | def run(): 14 | 15 | print("CK_ENV_COMPILER_PYTHON_FILE=" + os.environ.get('CK_ENV_COMPILER_PYTHON_FILE','')) 16 | print("CK_QUANTUM_PARIS_DIR=" + os.environ.get('CK_QUANTUM_PARIS_DIR','')) 17 | 18 | output_path = os.environ.get('CK_QUANTUM_PARIS_OUTPUT') 19 | print("CK_QUANTUM_PARIS_OUTPUT=" + output_path) 20 | with open(output_path) as output_file: 21 | print(output_file.read()) 22 | 23 | return 0 24 | 25 | if __name__ == '__main__': 26 | exit(run()) 27 | -------------------------------------------------------------------------------- /.ckr.json: -------------------------------------------------------------------------------- 1 | { 2 | "data_uoa": "ck-quantum", 3 | "data_uid": "de640faafc01c0a0", 4 | "data_alias": "ck-quantum", 5 | "data_name": "ck-quantum", 6 | "dict": { 7 | "repo_deps": [ 8 | { 9 | "repo_uoa": "ck-env", 10 | "repo_url": "https://github.com/ctuning/ck-env" 11 | }, 12 | { 13 | "repo_uoa": "ck-docker", 14 | "repo_url": "https://github.com/ctuning/ck-docker" 15 | }, 16 | { 17 | "repo_uoa": "ck-rigetti", 18 | "repo_url": "https://github.com/ctuning/ck-rigetti" 19 | }, 20 | { 21 | "repo_uoa": "ck-qiskit", 22 | "repo_url": "https://github.com/ctuning/ck-qiskit" 23 | } 24 | ], 25 | "shared": "git", 26 | "url": "https://github.com/ctuning/ck-quantum" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /package/tool-hackathon/install.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # CK installation script 4 | # 5 | # Developer(s): 6 | # * Grigori Fursin, dividiti/cTuning foundation 7 | # 8 | 9 | # PACKAGE_DIR 10 | # INSTALL_DIR 11 | ###################################################################################### 12 | echo "Installing CK-QUANTUM HACKATHON MODULE" 13 | echo "" 14 | 15 | 16 | 17 | if [ ! -d "${INSTALL_DIR}/lib" ]; then 18 | # Control will enter here if $DIRECTORY doesn't exist. 19 | mkdir -p ${INSTALL_DIR}/lib 20 | fi 21 | 22 | cp -r ${PACKAGE_DIR}/hackathon-src/* ${INSTALL_DIR}/lib/ 23 | 24 | 25 | if [ "${?}" != "0" ] ; then 26 | echo "Error: installation failed!" 27 | exit 1 28 | fi 29 | 30 | ###################################################################################### 31 | 32 | -------------------------------------------------------------------------------- /program/visualize-convergence/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "c707814bd9b2f9e3", 3 | "build_compiler_vars": {}, 4 | "compile_deps": { 5 | "compiler": { 6 | "local": "yes", 7 | "name": "Python 3", 8 | "tags": "compiler,python", 9 | "version_from": [ 10 | 3, 11 | 5, 12 | 0 13 | ] 14 | } 15 | }, 16 | "data_name": "visualize-convergence", 17 | "main_language": "python", 18 | "no_compile": "yes", 19 | "no_target_file": "yes", 20 | "process_in_tmp": "yes", 21 | "program": "yes", 22 | "run_cmds": { 23 | "default": { 24 | "ignore_return_code": "no", 25 | "run_time": { 26 | "run_cmd_main": "$<>$ ..$#dir_sep#$visualize_convergence.py" 27 | } 28 | } 29 | }, 30 | "run_vars": { 31 | "CK_VAR1": 123, 32 | "CK_VAR2": 666 33 | }, 34 | "tags": [ 35 | "program", 36 | "lang-python", 37 | "quantum", 38 | "visualize-convergence" 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /program/visualize-convergence/README.md: -------------------------------------------------------------------------------- 1 | # A progress monitoring tool for ck run vqe 2 | 3 | This tool provides a text-mode graph for showing the progress of CK VQE optimisation runs. 4 | 5 | ## USAGE 6 | 7 | ``` 8 | ck run program:visualize-convergence 9 | ``` 10 | 11 | This program helps to visually monitor the convergence of your `ck run vqe` runs. 12 | It can be run before or after your `ck run vqe` command, and does not need to be restarted for new runs. 13 | 14 | 15 | ## UI 16 | 17 | The top half displays the energy that your optimiser has achieved as a function of iteration. The current run is shown as a filled dot, and prior runs are shown as unfilled dots. 18 | 19 | The stats window shows some relatively self-explanatory metastatistics about your optimisation progress. 20 | 21 | To exit the program, press 'q'. 22 | 23 | # Software used 24 | 25 | This program uses asciiplot/AP by mfouesneau, available at https://github.com/mfouesneau/asciiplot. The version contained here has been ported to Pytohn3 using the 2to3 tool. 26 | -------------------------------------------------------------------------------- /soft/template.optimizer/python_code/random_sampler/custom_optimizer.py: -------------------------------------------------------------------------------- 1 | import random 2 | import numpy as np 3 | 4 | 5 | def my_random_sampler( func, x0, my_args=(), my_options=None ): 6 | "Simple optimiser: samples randomly and returns the minimum - used here as an example" 7 | 8 | my_options = my_options or {} 9 | points = my_options.get('maxfev', 30) # by default perform 30 function evaluations 10 | num_parameters = len(x0) # get number of parameters needed for objective function 11 | 12 | flist = [] 13 | xlist = [] 14 | for i in range(points): 15 | x = [random.random() for i in range(num_parameters)] # initialise parameters randomly from uniform distribution 16 | fnew = func(x, my_args) 17 | flist.append(fnew) 18 | xlist.append(x) 19 | 20 | min_idx = np.argmin(flist) 21 | best_x = xlist[min_idx] 22 | fmin = flist[min_idx] 23 | 24 | minimizer_output = { 'fun' : fmin, 'nfev' : points, 'nit' : points, 'x' : best_x } 25 | 26 | return minimizer_output 27 | -------------------------------------------------------------------------------- /package/tool-hackathon/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "customize": { 3 | "extra_dir": "", 4 | "install_env": { 5 | "PACKAGE_SUB_DIR1": "lib" 6 | }, 7 | "supported_python_ver2_on_linux": [ 8 | 4, 9 | 5 10 | ], 11 | "supported_python_ver2_on_mac": [ 12 | 4, 13 | 5 14 | ], 15 | "supported_python_ver2_on_win": [ 16 | 5 17 | ], 18 | "version": "1.0" 19 | }, 20 | "deps": { 21 | "lib-python-scipy": { 22 | "local": "yes", 23 | "name": "SciPy Python library", 24 | "sort": 10, 25 | "tags": "lib,scipy,python-package" 26 | } 27 | }, 28 | "end_full_path_universal": "lib$#sep#$__init__.py", 29 | "need_cpu_info": "yes", 30 | "only_for_host_os_tags": [ 31 | "linux", 32 | "windows" 33 | ], 34 | "only_for_target_os_tags": [ 35 | "linux", 36 | "windows" 37 | ], 38 | "process_script": "install", 39 | "soft_uoa": "f0a25d64c3891b4f", 40 | "suggested_path": "hackathon", 41 | "tags": [ 42 | "tool", 43 | "hackathon", 44 | "ck-quantum", 45 | "quantum", 46 | "v1" 47 | ] 48 | } 49 | -------------------------------------------------------------------------------- /module/qml/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "actions": { 3 | "list_experiments": { 4 | "desc": "Returns a list of all VQE-relevant CK experiment entries" 5 | }, 6 | "pick_a_filename": { 7 | "desc": "Select a filename from the given directory (interactive helper function)" 8 | }, 9 | "pick_an_experiment": { 10 | "desc": "Select an experiment from the list (interactive helper function)" 11 | }, 12 | "store_experiment": { 13 | "desc": "Store the JSON output in a CK experiment entry for further analysis and upload" 14 | }, 15 | "upload": { 16 | "desc": "Upload the best experimental results on the server for visualization and comparison" 17 | } 18 | }, 19 | "copyright": "See CK COPYRIGHT.txt for copyright details", 20 | "desc": "simplify running the qml experiments and recording/viewing the results", 21 | "developer": "Leo Gordon", 22 | "developer_email": "leo@dividiti.com", 23 | "developer_webpage": "http://fursin.net", 24 | "license": "See CK LICENSE.txt for licensing details", 25 | "module_deps": { 26 | "env": "9b9b3208ac44b891" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /program/benchmark-helper/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "backup_data_uid": "89983c43e0ad01ac", 3 | "build_compiler_vars": {}, 4 | "compile_deps": { 5 | "python": { 6 | "local": "yes", 7 | "name": "Python v3", 8 | "tags": "compiler,lang-python", 9 | "version_from": [ 10 | 3, 11 | 6, 12 | 0 13 | ] 14 | } 15 | }, 16 | "data_name": "benchmark-helper", 17 | "main_language": "python", 18 | "no_compile": "yes", 19 | "no_target_file": "yes", 20 | "print_files_after_run": [ 21 | "stderr.log", 22 | "stdout.log" 23 | ], 24 | "process_in_tmp": "yes", 25 | "program": "yes", 26 | "run_cmds": { 27 | "default": { 28 | "ignore_return_code": "no", 29 | "run_time": { 30 | "fine_grain_timer_file": "../solution_output.json", 31 | "run_cmd_main": "$<>$ ..$#dir_sep#$run.py", 32 | "run_cmd_out1": "stdout.log", 33 | "run_cmd_out2": "stderr.log", 34 | "run_output_files": [ 35 | "stdout.log", 36 | "stderr.log" 37 | ] 38 | } 39 | } 40 | }, 41 | "run_vars": { 42 | "CK_QUANTUM_PARIS_DIR": "$<>$/projects/qck-paris", 43 | "CK_QUANTUM_PARIS_OUTPUT": "../solution_output.json" 44 | }, 45 | "tags": [ 46 | "program", 47 | "lang-python" 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![compatibility](https://github.com/ctuning/ck-guide-images/blob/master/ck-compatible.svg)](https://github.com/ctuning/ck) 2 | [![automation](https://github.com/ctuning/ck-guide-images/blob/master/ck-artifact-automated-and-reusable.svg)](http://cTuning.org/ae) 3 | [![workflow](https://github.com/ctuning/ck-guide-images/blob/master/ck-workflow.svg)](http://cKnowledge.org) 4 | 5 | [![DOI](https://zenodo.org/badge/131708254.svg)](https://zenodo.org/badge/latestdoi/131708254) 6 | [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause) 7 | 8 | # Quantum Collective Knowledge (QCK) repository 9 | 10 | *Powered by the [Collective Knowledge](https://github.com/ctuning/ck) platform.* 11 | 12 | ## Competitions 13 | 14 | - [1st Open QCK Challenge](https://github.com/ctuning/ck-quantum/tree/master/module/challenge.vqe) 15 | 16 | ## Hackathons 17 | 18 | - 5th QCK Hackathon, London (**TBC**) 19 | - [4th QCK Hackathon, Oxford, 2019-03-15](https://github.com/ctuning/ck-quantum/tree/master/module/hackathon.20190315) 20 | - [3nd QCK Hackathon, Paris, 2019-01-27](https://github.com/ctuning/ck-quantum/tree/master/module/hackathon.20190127) 21 | - [2nd QCK Hackathon, London, 2018-10-06](https://github.com/ctuning/ck-quantum/tree/master/module/hackathon.20181006) 22 | - [1st QCK Hackathon, Cambridge, 2018-06-15](https://github.com/ctuning/ck-quantum/tree/master/module/hackathon.20180615) 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # CK-specific. 2 | *tmp/ 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # dotenv 86 | .env 87 | 88 | # virtualenv 89 | .venv 90 | venv/ 91 | ENV/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /module/hackathon.20180615/README.md: -------------------------------------------------------------------------------- 1 | # 1st Quantum Computing Hackathon, Cambridge, 15 June 2018 2 | 3 | ## Installation (on Ubuntu) 4 | 5 | ### Install global prerequisites, Python3 and its pip (Python2 is also supported) 6 | 7 | ``` 8 | $ sudo apt-get install python3 python3-pip 9 | ``` 10 | 11 | ### Install Collective Knowledge 12 | 13 | ``` 14 | $ sudo pip3 install ck 15 | ``` 16 | 17 | 18 | ## Installation (on MacOS) 19 | 20 | ### Install Python3 and its pip (Python2 is also supported) 21 | 22 | ``` 23 | $ brew update 24 | $ brew reinstall python 25 | ``` 26 | 27 | ``` 28 | $ pip install ck 29 | ``` 30 | 31 | ## Non-root CK installation 32 | 33 | You can install CK in your local user space as follows: 34 | 35 | ``` 36 | $ git clone http://github.com/ctuning/ck 37 | $ export PATH=$PWD/ck/bin:$PATH 38 | $ export PYTHONPATH=$PWD/ck:$PYTHONPATH 39 | ``` 40 | 41 | ## Test CK installation 42 | 43 | ``` 44 | $ ck version 45 | ``` 46 | 47 | ## Common part of the workflow installation 48 | 49 | ### Pull CK repositories 50 | 51 | ``` 52 | $ ck pull repo:ck-quantum 53 | $ ck pull repo:ck-env 54 | $ ck pull repo:ck-rigetti 55 | $ ck pull repo:ck-qiskit 56 | ``` 57 | 58 | ### Detect a Python interpreter (interactively choose one if there are several options) 59 | ``` 60 | $ ck detect soft:compiler.python 61 | ``` 62 | 63 | 64 | ### Install this CK repository with all its dependencies (other CK repos to reuse artifacts) 65 | 66 | ``` 67 | $ ck install package:tool-hackathon 68 | ``` 69 | 70 | ### Install pyQuil 71 | 72 | ``` 73 | $ ck install package:lib-pyquil-1.9.0 74 | ``` 75 | 76 | ### Run a demo program (press Enter if prompted) 77 | 78 | ``` 79 | $ ck run program:pyquil-demo 80 | ... 81 | 82 | * tmp-stdout.tmp 83 | 84 | Number of games: 10 85 | Q's winning average: 1.0 86 | Picard's flip-decision average: 0.5 87 | ``` 88 | 89 | ### Run VQE 90 | 91 | ``` 92 | $ ck run program:rigetti-vqe 93 | ``` 94 | -------------------------------------------------------------------------------- /package/tool-hackathon/hackathon-src/hackathon/optimizers.py: -------------------------------------------------------------------------------- 1 | from scipy.optimize import minimize 2 | import random 3 | import numpy as np 4 | 5 | def my_nelder_mead( func, x0, my_args=(), my_options=None ): # a non-stochastic minimizer for comparison 6 | "Nelder-Mead optimizer from SciPy library" 7 | 8 | return minimize( func, x0, method='Nelder-Mead', options=my_options, args=my_args ) 9 | 10 | 11 | def my_cobyla( func, x0, my_args=(), my_options=None ): # another non-stochastic minimizer for comparison 12 | "COBYLA optimizer from SciPy library" 13 | 14 | return minimize( func, x0, method='COBYLA', options=my_options, args=my_args ) 15 | 16 | 17 | def my_random_sampler( func, x0, my_args=(), my_options=None ): 18 | "Simple optimiser: samples randomly and returns the minimum - used here as an example" 19 | 20 | my_options = my_options or {} 21 | points = my_options.get('maxfev', 30) # by default perform 30 function evaluations 22 | num_parameters = len(x0) # get number of parameters needed for objective function 23 | 24 | flist = [] 25 | xlist = [] 26 | for i in range(points): 27 | x = [random.random() for i in range(num_parameters)] # initialise parameters randomly from uniform distribution 28 | fnew = func(x, my_args) 29 | flist.append(fnew) 30 | xlist.append(x) 31 | 32 | min_idx = np.argmin(flist) 33 | best_x = xlist[min_idx] 34 | fmin = flist[min_idx] 35 | 36 | minimizer_output = { 'fun' : fmin, 'nfev' : points, 'nit' : points, 'x' : best_x } 37 | 38 | return minimizer_output 39 | 40 | 41 | def my_minimizer( func, x0, my_args=(), my_options=None ): 42 | "Your own attempt at writing a stochastic minimizer" 43 | 44 | current_func_value = func(x0, my_args) 45 | 46 | minimizer_output = { 'fun' : current_func_value, 'nfev' : 1, 'nit' : 1, 'x' : x0 } 47 | 48 | return minimizer_output 49 | 50 | -------------------------------------------------------------------------------- /package/tool-hackathon/hackathon-src/hackathon_optimizers.py: -------------------------------------------------------------------------------- 1 | from scipy.optimize import minimize 2 | import random 3 | import numpy as np 4 | 5 | def my_nelder_mead( func, x0, my_args=(), my_options=None ): # a non-stochastic minimizer for comparison 6 | "Nelder-Mead optimizer from SciPy library" 7 | 8 | return minimize( func, x0, method='Nelder-Mead', options=my_options, args=my_args ) 9 | 10 | 11 | def my_cobyla( func, x0, my_args=(), my_options=None ): # another non-stochastic minimizer for comparison 12 | "COBYLA optimizer from SciPy library" 13 | 14 | return minimize( func, x0, method='COBYLA', options=my_options, args=my_args ) 15 | 16 | 17 | def my_random_sampler( func, x0, my_args=(), my_options=None ): 18 | "Simple optimiser: samples randomly and returns the minimum - used here as an example" 19 | 20 | my_options = my_options or {} 21 | points = my_options.get('maxfev', 30) # by default perform 30 function evaluations 22 | num_parameters = len(x0) # get number of parameters needed for objective function 23 | 24 | flist = [] 25 | xlist = [] 26 | for i in range(points): 27 | x = [random.random() for i in range(num_parameters)] # initialise parameters randomly from uniform distribution 28 | fnew = func(x, my_args) 29 | flist.append(fnew) 30 | xlist.append(x) 31 | 32 | min_idx = np.argmin(flist) 33 | best_x = xlist[min_idx] 34 | fmin = flist[min_idx] 35 | 36 | minimizer_output = { 'fun' : fmin, 'nfev' : points, 'nit' : points, 'x' : best_x } 37 | 38 | return minimizer_output 39 | 40 | 41 | def my_minimizer( func, x0, my_args=(), my_options=None ): 42 | "Your own attempt at writing a stochastic minimizer" 43 | 44 | current_func_value = func(x0, my_args) 45 | 46 | minimizer_output = { 'fun' : current_func_value, 'nfev' : 1, 'nit' : 1, 'x' : x0 } 47 | 48 | return minimizer_output 49 | 50 | -------------------------------------------------------------------------------- /module/vqe/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "actions": { 3 | "cleanup": { 4 | "desc": "Remove env and soft entries that make up deployed plugin(s)" 5 | }, 6 | "deploy": { 7 | "desc": "Install the necessary plugin (optimizer or ansatz) and the corresponding environment for the 'run' method to work (helper function)" 8 | }, 9 | "deploy_ansatz": { 10 | "desc": "Deploy one ansatz plugin" 11 | }, 12 | "deploy_optimizer": { 13 | "desc": "Deploy one optimizer plugin" 14 | }, 15 | "list_deployables": { 16 | "desc": "Get the list of all deployables of a template code-containing soft entry (helper function)" 17 | }, 18 | "list_experiments": { 19 | "desc": "Returns a list of all VQE-relevant CK experiment entries" 20 | }, 21 | "list_registered_emails": { 22 | "desc": "Get the list of emails of the users that have successfully recorded the quantum_coin_flip experiment (helper function)" 23 | }, 24 | "pick_an_experiment": { 25 | "desc": "Select an experiment from the list (interactive helper function)" 26 | }, 27 | "plugin_path": { 28 | "desc": "Get the path to the plugin's editable python file" 29 | }, 30 | "run": { 31 | "desc": "Run several repetitions and record the results locally" 32 | }, 33 | "time_to_solution": { 34 | "desc": "Calculate the Time-to-Solution metric for a given experiment" 35 | }, 36 | "upload": { 37 | "desc": "Upload the best experimental results on the server for visualization and comparison" 38 | } 39 | }, 40 | "copyright": "See CK COPYRIGHT.txt for copyright details", 41 | "desc": "simplify running the vqe pipeline and recording the results", 42 | "developer": "Leo Gordon", 43 | "developer_email": "leo@dividiti.com", 44 | "developer_webpage": "http://fursin.net", 45 | "license": "See CK LICENSE.txt for licensing details", 46 | "module_deps": { 47 | "env": "9b9b3208ac44b891" 48 | }, 49 | "workflow": "yes", 50 | "workflow_type": "VQE quantum competition pipeline" 51 | } 52 | -------------------------------------------------------------------------------- /docker/hackathon.20190127/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | MAINTAINER Leo Gordon 3 | MAINTAINER Anton Lokhmotov 4 | 5 | ## Install all packages and immediately clean up to make the image smaller 6 | # 7 | RUN apt-get update -y \ 8 | && apt-get install -y python3 python3-pip git zip bzip2 sudo wget vi daemonize \ 9 | libjpeg8 libjpeg62-dev libfreetype6 libfreetype6-dev python-pillow build-essential 10 | 11 | # Install the core Collective Knowledge (CK) module. 12 | ENV CK_ROOT=/ck-master \ 13 | CK_REPOS=/CK \ 14 | CK_TOOLS=/CK-TOOLS \ 15 | PATH=${CK_ROOT}/bin:${PATH} \ 16 | PARIS=/paris \ 17 | CK_PYTHON=python3 \ 18 | LANG=C.UTF-8 19 | 20 | RUN mkdir -p ${CK_ROOT} ${CK_REPOS} ${CK_TOOLS} 21 | RUN git clone https://github.com/ctuning/ck.git ${CK_ROOT} 22 | RUN cd ${CK_ROOT} && ${CK_PYTHON} setup.py install && ${CK_PYTHON} -c "import ck.kernel as ck" 23 | 24 | # Install other CK modules. 25 | RUN ck pull repo:ck-quantum 26 | 27 | # Dependencies of this particular Hackathon: 28 | RUN ${CK_PYTHON} -m pip install marshmallow==2.15.0 qiskit==0.7 pandas==0.23.4 sklearn 29 | RUN git clone https://github.com/riverlane/paris ${PARIS} 30 | 31 | 32 | # -------------------------------------------------------------------------------------------------- 33 | 34 | ## This is how do build this image (host machine) : 35 | # 36 | # docker build --tag hackathon.20190127 ck-quantum/docker/hackathon.20190127 37 | 38 | 39 | ## This is how to run this image with proper port mapping (host machine) : 40 | # 41 | # docker run -it --publish 3355:3344 hackathon.20190127 42 | 43 | 44 | ## This is where to point your browser to connect to the dashboard visualization server (host machine) : 45 | # 46 | # http://localhost:3355/?template=dashboard&scenario=hackathon.20190127 47 | 48 | # -------------------------------------------------------------------------------------------------- 49 | 50 | 51 | WORKDIR ${PARIS} 52 | 53 | ## This command spawns the server in background (daemon) mode 54 | ## and also brings up an interactive shell in the same container 55 | # 56 | CMD daemonize -o ${HOME}/ck_server.out -e ${HOME}/ck_server.err /usr/local/bin/ck display dashboard --scenario=hackathon.20190127 --host=0.0.0.0 --wfe_host=localhost --wfe_port=3355 && /bin/bash 57 | -------------------------------------------------------------------------------- /docker/hackathon.20190315/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | MAINTAINER Leo Gordon 3 | MAINTAINER Anton Lokhmotov 4 | 5 | ## Install all packages and immediately clean up to make the image smaller 6 | # 7 | RUN apt-get update -y \ 8 | && apt-get install -y python3 python3-pip git zip bzip2 sudo wget vim daemonize \ 9 | libjpeg8 libjpeg62-dev libfreetype6 libfreetype6-dev python-pillow build-essential 10 | 11 | # Install the core Collective Knowledge (CK) module. 12 | ENV CK_ROOT=/ck-master \ 13 | CK_REPOS=/CK \ 14 | CK_TOOLS=/CK-TOOLS \ 15 | PATH=${CK_ROOT}/bin:${PATH} \ 16 | HACKATHON=/HiddenState \ 17 | CK_PYTHON=python3 \ 18 | LANG=C.UTF-8 19 | 20 | RUN mkdir -p ${CK_ROOT} ${CK_REPOS} ${CK_TOOLS} 21 | RUN git clone https://github.com/ctuning/ck.git ${CK_ROOT} 22 | RUN cd ${CK_ROOT} && ${CK_PYTHON} setup.py install && ${CK_PYTHON} -c "import ck.kernel as ck" 23 | 24 | # Install other CK modules. 25 | RUN ck pull repo:ck-quantum 26 | 27 | # Dependencies of this particular Hackathon. 28 | RUN ${CK_PYTHON} -m pip install marshmallow==2.15.0 qiskit==0.7 pandas==0.23.4 sklearn 29 | RUN git clone https://github.com/riverlane/HiddenStateHackathon ${HACKATHON} 30 | 31 | 32 | # -------------------------------------------------------------------------------------------------- 33 | 34 | ## This is how do build this image (host machine) : 35 | # 36 | # docker build --tag hackathon.20190315 ck-quantum/docker/hackathon.20190315 37 | 38 | 39 | ## This is how to run this image with proper port mapping (host machine) : 40 | # 41 | # docker run -it --publish 3355:3344 hackathon.20190315 42 | 43 | 44 | ## This is where to point your browser to connect to the dashboard visualization server (host machine) : 45 | # 46 | # http://localhost:3355/?template=dashboard&scenario=hackathon.20190315 47 | 48 | # -------------------------------------------------------------------------------------------------- 49 | 50 | 51 | WORKDIR ${HACKATHON} 52 | 53 | ## This command spawns the server in background (daemon) mode 54 | ## and also brings up an interactive shell in the same container 55 | # 56 | CMD daemonize -o ${HOME}/ck_server.out -e ${HOME}/ck_server.err /usr/local/bin/ck display dashboard --scenario=hackathon.20190315 --host=0.0.0.0 --wfe_host=localhost --wfe_port=3355 && /bin/bash 57 | -------------------------------------------------------------------------------- /soft/template.optimizer/customize.py: -------------------------------------------------------------------------------- 1 | # 2 | # Collective Knowledge (individual environment - setup) 3 | # 4 | # See CK LICENSE.txt for licensing details 5 | # See CK COPYRIGHT.txt for copyright details 6 | # 7 | 8 | import os 9 | 10 | ############################################################################## 11 | 12 | def version_cmd(i): 13 | 14 | full_path = i.get('full_path') 15 | plugin_name = os.path.basename( os.path.dirname( full_path ) ) 16 | 17 | return {'return':0, 'cmd':'', 'version': plugin_name } 18 | 19 | 20 | ############################################################################## 21 | 22 | def setup(i): 23 | """ 24 | Input: { 25 | cus/full_path - the path of the found python file (or directory if "soft_can_be_dir") 26 | 27 | cus/soft_can_be_dir - set to "yes" if you are looking for a directory, not a regular file 28 | 29 | cus/required_depth - how many EXTRA STEPS to ascend (in addition to the 1 for a regular file and 0 for a directory) 30 | 31 | env - environment variables that we are supposed to fill in (passed by reference) 32 | } 33 | 34 | Output: { 35 | return - return code = 0, if successful 36 | > 0, if error 37 | (error) - error text if return > 0 38 | 39 | bat - prepared string for bat file 40 | } 41 | 42 | """ 43 | 44 | cus = i.get('customize',{}) 45 | full_path = cus.get('full_path','') 46 | soft_can_be_dir_bool = cus.get('soft_can_be_dir', '')=='yes' 47 | type_dependent_depth = 0 if soft_can_be_dir_bool else 1 48 | total_depth = cus.get('required_depth', 0) + type_dependent_depth 49 | 50 | # Ascend as many steps as required: 51 | # 52 | path_lib = full_path 53 | for _ in range(total_depth): 54 | path_lib = os.path.dirname( path_lib ) 55 | 56 | # Detect the platform: 57 | # 58 | hosd = i['host_os_dict'] 59 | tosd = i['target_os_dict'] 60 | winh = hosd.get('windows_base','') 61 | 62 | # Extend PYTHONPATH depending on the platform: 63 | # 64 | env = i['env'] 65 | env['PYTHONPATH'] = path_lib + ( ';%PYTHONPATH%' if winh=='yes' else ':${PYTHONPATH}') 66 | 67 | return {'return':0, 'bat':''} 68 | -------------------------------------------------------------------------------- /soft/vqe.hamiltonian/customize.py: -------------------------------------------------------------------------------- 1 | # 2 | # Collective Knowledge (individual environment - setup) 3 | # 4 | # See CK LICENSE.txt for licensing details 5 | # See CK COPYRIGHT.txt for copyright details 6 | # 7 | 8 | import os 9 | 10 | ############################################################################## 11 | 12 | def version_cmd(i): 13 | 14 | full_path = i.get('full_path') 15 | plugin_name = os.path.basename( os.path.dirname( full_path ) ) 16 | 17 | return {'return':0, 'cmd':'', 'version': plugin_name } 18 | 19 | 20 | ############################################################################## 21 | 22 | def setup(i): 23 | """ 24 | Input: { 25 | cus/full_path - the path of the found python file (or directory if "soft_can_be_dir") 26 | 27 | cus/soft_can_be_dir - set to "yes" if you are looking for a directory, not a regular file 28 | 29 | cus/required_depth - how many EXTRA STEPS to ascend (in addition to the 1 for a regular file and 0 for a directory) 30 | 31 | env - environment variables that we are supposed to fill in (passed by reference) 32 | } 33 | 34 | Output: { 35 | return - return code = 0, if successful 36 | > 0, if error 37 | (error) - error text if return > 0 38 | 39 | bat - prepared string for bat file 40 | } 41 | 42 | """ 43 | 44 | cus = i.get('customize',{}) 45 | full_path = cus.get('full_path','') 46 | soft_can_be_dir_bool = cus.get('soft_can_be_dir', '')=='yes' 47 | type_dependent_depth = 0 if soft_can_be_dir_bool else 1 48 | total_depth = cus.get('required_depth', 0) + type_dependent_depth 49 | 50 | # Ascend as many steps as required: 51 | # 52 | path_lib = full_path 53 | for _ in range(total_depth): 54 | path_lib = os.path.dirname( path_lib ) 55 | 56 | # Detect the platform: 57 | # 58 | hosd = i['host_os_dict'] 59 | tosd = i['target_os_dict'] 60 | winh = hosd.get('windows_base','') 61 | 62 | # Extend PYTHONPATH depending on the platform: 63 | # 64 | env = i['env'] 65 | env['PYTHONPATH'] = path_lib + ( ';%PYTHONPATH%' if winh=='yes' else ':${PYTHONPATH}') 66 | 67 | return {'return':0, 'bat':''} 68 | -------------------------------------------------------------------------------- /module/hackathon.20190127/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "actions": { 3 | "get_raw_config": { 4 | "desc": "get raw config for repo widget", 5 | "for_web": "yes" 6 | }, 7 | "get_raw_data": { 8 | "desc": "get raw data for repo-widget", 9 | "for_web": "yes" 10 | } 11 | }, 12 | "desc": "Raw data access (json)", 13 | "data_config": { 14 | "selector": [], 15 | "selector2": [ 16 | { "key": "problem_name", "name": "Which problem" }, 17 | { "key": "team", "name": "Which team" }, 18 | { "key": "solution_function_name", "name": "Which method" } 19 | ], 20 | "selector3": [], 21 | 22 | "dimensions": [ 23 | {"key":"problem_index", "name":"Problem index", "view_key":"problem_index"}, 24 | {"key":"hours_since_start", "name":"Hours since start", "view_key":"hours_since_start"}, 25 | {"key":"team", "name":"Team name", "view_key":"team"}, 26 | {"key":"training_vectors_limit","name":"Training vectors limit", "view_key":"training_vectors_limit"}, 27 | {"key":"training_time", "name":"Training time", "view_key":"training_time"}, 28 | {"key":"training_accuracy", "name":"Training accuracy", "view_key":"training_accuracy"}, 29 | {"key":"test_accuracy", "name":"Test accuracy", "view_key":"test_accuracy"}, 30 | {"key":"rank", "name":"Solution's rank", "view_key":"rank"}, 31 | {"key":"solution_function_name","name":"Solution function name", "view_key":"solution_function_name"} 32 | ], 33 | 34 | "table_view": [ 35 | {"key":"problem_index", "name":"Problem index"}, 36 | {"key":"timestamp_utc_human", "name":"Timestamp (UTC)"}, 37 | {"key":"team", "name":"Team name"}, 38 | {"key":"training_time", "name":"Training time (sec)", "format":"%.2f"}, 39 | {"key":"training_accuracy", "name":"Training accuracy", "format":"%.1f"}, 40 | {"key":"test_accuracy", "name":"Test accuracy", "format":"%.1f"}, 41 | {"key":"rank", "name":"Solution's rank"}, 42 | {"key":"source_code", "name":"Source code"}, 43 | {"key":"circuit_str", "name":"Quantum circuit"} 44 | ] 45 | }, 46 | "workflow": "yes", 47 | "workflow_type": "quantum hackathon workflow" 48 | } 49 | -------------------------------------------------------------------------------- /module/hackathon.20190315/.cm/meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "actions": { 3 | "get_raw_config": { 4 | "desc": "get raw config for repo widget", 5 | "for_web": "yes" 6 | }, 7 | "get_raw_data": { 8 | "desc": "get raw data for repo-widget", 9 | "for_web": "yes" 10 | } 11 | }, 12 | "data_config": { 13 | "dimensions": [ 14 | { 15 | "key": "problem_index", 16 | "name": "Problem index", 17 | "view_key": "problem_index" 18 | }, 19 | { 20 | "key": "hours_since_start", 21 | "name": "Hours since start", 22 | "view_key": "hours_since_start" 23 | }, 24 | { 25 | "key": "team", 26 | "name": "Team name", 27 | "view_key": "team" 28 | }, 29 | { 30 | "key": "training_vectors_limit", 31 | "name": "Training vectors limit", 32 | "view_key": "training_vectors_limit" 33 | }, 34 | { 35 | "key": "training_time", 36 | "name": "Training time", 37 | "view_key": "training_time" 38 | }, 39 | { 40 | "key": "training_accuracy", 41 | "name": "Training accuracy", 42 | "view_key": "training_accuracy" 43 | }, 44 | { 45 | "key": "test_accuracy", 46 | "name": "Test accuracy", 47 | "view_key": "test_accuracy" 48 | }, 49 | { 50 | "key": "rank", 51 | "name": "Solution's rank", 52 | "view_key": "rank" 53 | }, 54 | { 55 | "key": "solution_function_name", 56 | "name": "Solution function name", 57 | "view_key": "solution_function_name" 58 | } 59 | ], 60 | "selector": [], 61 | "selector2": [ 62 | { 63 | "key": "problem_name", 64 | "name": "Which problem" 65 | }, 66 | { 67 | "key": "team", 68 | "name": "Which team" 69 | }, 70 | { 71 | "key": "solution_function_name", 72 | "name": "Which method" 73 | } 74 | ], 75 | "selector3": [], 76 | "table_view": [ 77 | { 78 | "key": "problem_index", 79 | "name": "Problem index" 80 | }, 81 | { 82 | "key": "timestamp_utc_human", 83 | "name": "Timestamp (UTC)" 84 | }, 85 | { 86 | "key": "team", 87 | "name": "Team name" 88 | }, 89 | { 90 | "format": "%.2f", 91 | "key": "training_time", 92 | "name": "Training time (sec)" 93 | }, 94 | { 95 | "format": "%.1f", 96 | "key": "training_accuracy", 97 | "name": "Training accuracy" 98 | }, 99 | { 100 | "format": "%.1f", 101 | "key": "test_accuracy", 102 | "name": "Test accuracy" 103 | }, 104 | { 105 | "key": "rank", 106 | "name": "Solution's rank" 107 | }, 108 | { 109 | "key": "source_code", 110 | "name": "Source code" 111 | }, 112 | { 113 | "key": "circuit_str", 114 | "name": "Quantum circuit" 115 | } 116 | ] 117 | }, 118 | "desc": "Raw data access (json)", 119 | "workflow": "yes", 120 | "workflow_type": "quantum hackathon workflow" 121 | } 122 | -------------------------------------------------------------------------------- /soft/lib.hackathon/customize.py: -------------------------------------------------------------------------------- 1 | # 2 | # Collective Knowledge (individual environment - setup) 3 | # 4 | # See CK LICENSE.txt for licensing details 5 | # See CK COPYRIGHT.txt for copyright details 6 | # 7 | # Author(s): 8 | # - Grigori Fursin, cTuning foundation/dividiti 9 | # - Flavio Vella, dividiti 10 | # - Anton Lokhmotov, dividiti 11 | # 12 | 13 | import os 14 | 15 | ############################################################################## 16 | # setup environment setup 17 | 18 | def setup(i): 19 | """ 20 | Input: { 21 | cfg - meta of this soft entry 22 | self_cfg - meta of module soft 23 | ck_kernel - import CK kernel module (to reuse functions) 24 | 25 | host_os_uoa - host OS UOA 26 | host_os_uid - host OS UID 27 | host_os_dict - host OS meta 28 | 29 | target_os_uoa - target OS UOA 30 | target_os_uid - target OS UID 31 | target_os_dict - target OS meta 32 | 33 | target_device_id - target device ID (if via ADB) 34 | 35 | tags - list of tags used to search this entry 36 | 37 | env - updated environment vars from meta 38 | customize - updated customize vars from meta 39 | 40 | deps - resolved dependencies for this soft 41 | 42 | interactive - if 'yes', can ask questions, otherwise quiet 43 | } 44 | 45 | Output: { 46 | return - return code = 0, if successful 47 | > 0, if error 48 | (error) - error text if return > 0 49 | 50 | bat - prepared string for bat file 51 | } 52 | 53 | """ 54 | 55 | import os 56 | 57 | # Get variables 58 | ck=i['ck_kernel'] 59 | 60 | iv=i.get('interactive','') 61 | 62 | cus=i.get('customize',{}) 63 | fp=cus.get('full_path','') 64 | 65 | hosd=i['host_os_dict'] 66 | tosd=i['target_os_dict'] 67 | 68 | winh=hosd.get('windows_base','') 69 | 70 | ienv=cus.get('install_env',{}) 71 | 72 | env=i['env'] 73 | ep=cus['env_prefix'] 74 | 75 | p1=os.path.dirname(fp) 76 | pl=os.path.dirname(p1) 77 | pi=os.path.dirname(pl) 78 | env[ep]=pl 79 | #ppath=os.path.join(pi, ienv['INSTALL_DIR']) 80 | ppath=os.path.join(pl, ienv['PACKAGE_SUB_DIR1']) 81 | env[ep+'_LIB']=ppath 82 | # Using a generic script to prepend the library search path 83 | # with the value expected to be set in $CK_ENV_COMPILER_GCC_LIB . 84 | # 85 | # GCC's dynamic library is an implicit dependency of Python's scipy package. 86 | # If this library is not found, dlopen() call buried deep in scipy library 87 | # fails to import ___addtf3 symbol. 88 | # 89 | # See this discussion: 90 | # https://github.com/citwild/laugh-finder/issues/11#issuecomment-377997186 91 | # 92 | r = ck.access({'action': 'lib_path_export_script', 93 | 'module_uoa': 'os', 94 | 'host_os_dict': hosd, 95 | 'lib_path': '$CK_ENV_COMPILER_GCC_LIB' }) 96 | if r['return']>0: return r 97 | shell_setup_script_contents = r['script'] 98 | 99 | # FIXME: Fix for Windows. 100 | # FIXME: Should have no explicit exports. 101 | # FGG (20180617 - I checked this code and substituted pl to ppath in below code for Windows 102 | # it now works, so now sure about above comment) 103 | if winh=='yes': 104 | shell_setup_script_contents += '\nset PYTHONPATH='+ppath+';%PYTHONPATH%\n' 105 | else: 106 | shell_setup_script_contents += '\nexport PYTHONPATH='+ppath+':${PYTHONPATH}\n' 107 | 108 | for k in ienv: 109 | if k.startswith('HACKATHON_') or k=='CK_PYTHON_IPYTHON_BIN_FULL' or k=='CK_ENV_COMPILER_PYTHON_FILE': 110 | env[k]=ienv[k] 111 | 112 | return {'return':0, 'bat':shell_setup_script_contents} 113 | -------------------------------------------------------------------------------- /module/hackathon.20181006/README.md: -------------------------------------------------------------------------------- 1 | # London Quantum Computing Hackathon, 6 October 2018 2 | 3 | * [Meeetup](https://www.meetup.com/London-Quantum-Computing-Meetup/events/254156028/) (**fully booked 5 weeks in advance!**) 4 | * [Slides](https://docs.google.com/presentation/d/13O5hqez88NVyR0Gn9q9pGdVlRtKOtEkwQO5kAUyVOLs/edit?usp=sharing) (check often for updates) 5 | 6 | ## Getting started 7 | 8 | 1. Please register at [Quantum Experience](https://quantumexperience.ng.bluemix.net/qx/signup) 9 | 1. Copy your API token from the ["Advanced"](https://quantumexperience.ng.bluemix.net/qx/account/advanced) tab (click on the "Regenerate" button first). 10 | 1. For the day, please also change your "Institution" to "QuantumHackers" in the ["Account"](https://quantumexperience.ng.bluemix.net/qx/account/profile) tab. 11 | 1. Follow [CK-QISKit instructions](https://github.com/ctuning/ck-qiskit). 12 | 13 | ## Run QISKit-VQE once 14 | 15 | First, deploy a VQE ansatz and optimizer plugins that should just work: 16 | ``` 17 | $ ck deploy_optimizer vqe --value=optimizer.cobyla 18 | $ ck deploy_ansatz vqe --value=ansatz.universal4 19 | ``` 20 | 21 | Then, launch VQE with the deployed optimizer and ansatz: 22 | ``` 23 | $ ck run vqe --device=local_qasm_simulator --repetitions=1 24 | ``` 25 | 26 | ## Monitor the convergence process (an ASCII-graphics program run in a separate Terminal window) 27 | ``` 28 | ck run program:visualize-convergence 29 | ``` 30 | 31 | 32 | ## Easy VQE exploration via optimizer parameters 33 | ``` 34 | $ ck run vqe --device= --sample_size= --max_iterations= --start_param_value= --repetitions= 35 | ``` 36 | where: 37 | - `device`: `local_qasm_simulator` (local simulator), `ibmq_qasm_simulator` (remote simulator), `ibmqx4` (remote hardware); by default, QCK will prompt to select one of these target quantum devices (0, 1, 2). 38 | - `sample_size`: the number of times to evaluate the Hamiltonian function on the quantum device ("sampling resolution") per optimizer iteration; by default, 100. 39 | - `max_iterations`: the maximum number of optimizer iterations ("iteration limit"); by default, 80. 40 | - `start_param_value`: the starting value of each optimizer's parameter (can be a float number or the word 'random') 41 | - `repetitions`: the number of times to repeat the experiment with the same parameters; by default, 3. 42 | 43 | **NB:** The aim is to minimize the [Time-To-Solution](https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/d9iysrawnprjy2w/ck-quantum-hackathon-20180615.ipynb#Time-to-solution-metric) metric (TTS). As TTS is proportional to `sample_size`, exploring lower values of `sample_size` may be sensible. 44 | 45 | At the same time, a low number of `repetitions` may make it hard to demonstrate solution convergence with a high probability. For experiments to be uploaded, we recommend using at least 10 repetitions on the simulators and 3-5 repetitions on the hardware. 46 | 47 | ## Advanced VQE exploration via plugins 48 | 49 | ### See which plugins are deployed (both `soft` and `env` entries) 50 | ``` 51 | $ ck search --tags=deployed 52 | ``` 53 | 54 | ### Removing plugins 55 | 56 | #### Removing an optimizer plugin 57 | ``` 58 | $ ck cleanup vqe --type=optimizer 59 | ``` 60 | 61 | #### Removing an ansatz plugin 62 | ``` 63 | $ ck cleanup vqe --type=ansatz 64 | ``` 65 | 66 | #### Removing both optimizer and ansatz plugins 67 | ``` 68 | $ ck cleanup vqe 69 | ``` 70 | 71 | ### Working with optimizer plugins 72 | 73 | #### Select an optimizer plugin to deploy 74 | ``` 75 | $ ck deploy_optimizer vqe 76 | ``` 77 | 78 | #### Locate and edit the deployed optimizer plugin (use your favourite text editor instead of `vi`) 79 | ``` 80 | $ ck plugin_path vqe --type=optimizer 81 | $ vi `ck plugin_path vqe --type=optimizer` 82 | ``` 83 | **NB:** The optimizer plugin is written in Python. 84 | It is expected to contain only one top-level function. 85 | If you need more, please define them within the top-level one. 86 | 87 | ### Working with ansatz plugins 88 | 89 | #### Select an ansatz plugin to deploy 90 | ``` 91 | $ ck deploy_ansatz vqe 92 | ``` 93 | 94 | #### Visualize the ansatz circuit (use your favourite image viewer instead of `display`) 95 | ``` 96 | $ ck run program:visualize-ansatz 97 | $ display `ck find program:visualize-ansatz`/ansatz_circuit.png 98 | ``` 99 | **NB:** If unsure about the image viewer, try `eog` or `eom` on Linux, `open` on macOS. 100 | 101 | #### Locate and edit the deployed ansatz plugin (use your favourite text editor instead of `vi`) 102 | ``` 103 | $ ck plugin_path vqe --type=ansatz 104 | $ vi `ck plugin_path vqe --type=ansatz` 105 | ``` 106 | **NB:** The ansatz plugin is written in Python with QISKit. 107 | It is expected to contain only one top-level function. 108 | If you need more, please define them within the top-level one. 109 | 110 | ## Locate the experimental results 111 | 112 | You can list all your experimental entries and locate them on disk as follows: 113 | ``` 114 | $ ck search local:experiment:* --tags=qck 115 | $ ck find local:experiment:* 116 | ``` 117 | 118 | ## View the TTS metric 119 | 120 | Run the following and select an experiment entry to compute TTS for: 121 | ``` 122 | $ ck time_to_solution vqe --delta=0.015 --prob=0.95 123 | ``` 124 | 125 | To compute TTS for a particular experiment, supply its entry e.g.: 126 | ``` 127 | $ ck time_to_solution vqe --delta=0.015 --prob=0.8 local:experiment:anton-2018_10_05T12_18_19-local_qasm_simulator-ansatz.universal4-optimizer.cobyla-samples.100-repetitions.1 128 | ``` 129 | 130 | ## Upload your experimental results to Quantum Collective Knowledge 131 | 132 | When you have an experiment you would like to share, run: 133 | ``` 134 | $ ck upload vqe --team=schroedinger-cat-herders 135 | ``` 136 | and select the experiment from the list. We recommend uploading all experiments on the hardware and most successful experiments on the simulators. 137 | 138 | Alternatively, upload one or more experiments by using their entries e.g.: 139 | ``` 140 | $ ck upload vqe --team=bell-state-ringers local:experiment:my_experiment_5 local:experiment:my_experiment_13 141 | ``` 142 | -------------------------------------------------------------------------------- /package/tool-hackathon/hackathon-src/hackathon/utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import numpy as np 3 | import optimizers as h_optimizers 4 | 5 | 6 | def cmdline_parse_and_report(num_params, q_device_name_default, q_device_name_help, minimizer_options_default='{}'): 7 | 8 | import argparse 9 | 10 | start_params_default = np.random.randn( num_params ) # Initial guess of ansatz 11 | 12 | arg_parser = argparse.ArgumentParser() 13 | 14 | arg_parser.add_argument('--start_params', '--start-params', 15 | default=start_params_default, type=float, nargs=num_params, help="Initial values of optimized parameters") 16 | 17 | arg_parser.add_argument('--sample_number', '--sample-number', '--shots', 18 | default=100, type=int, help="Number of repetitions of each individual quantum run") 19 | 20 | arg_parser.add_argument('--q_device_name', '--q-device-name', 21 | default=q_device_name_default, help=q_device_name_help) 22 | 23 | arg_parser.add_argument('--minimizer_method', '--minimizer-method', 24 | default='my_nelder_mead', help="SciPy-based: 'my_nelder_mead', 'my_cobyla' or the custom 'my_minimizer'") 25 | 26 | arg_parser.add_argument('--max_func_evaluations', '--max-func-evaluations', 27 | default=100, type=int, help="Minimizer's upper limit on the number of function evaluations") 28 | 29 | arg_parser.add_argument('--minimizer_options', '--minimizer-options', 30 | default=minimizer_options_default, help="A dictionary in JSON format to be passed to the minimizer function") 31 | 32 | args = arg_parser.parse_args() 33 | 34 | start_params = args.start_params 35 | sample_number = args.sample_number 36 | q_device_name = args.q_device_name 37 | minimizer_method = args.minimizer_method 38 | max_func_evaluations = args.max_func_evaluations 39 | minimizer_options = json.loads( args.minimizer_options ) 40 | 41 | # We only know how to limit the number of iterations for certain methods, 42 | # so will introduce this as a "patch" to their minimizer_options dictionary: 43 | # 44 | if max_func_evaluations: 45 | minimizer_options_update = { 46 | 'my_nelder_mead': {'maxfev': max_func_evaluations}, 47 | 'my_cobyla': {'maxiter': max_func_evaluations}, 48 | 'my_random_sampler':{'maxfev': max_func_evaluations}, 49 | 'my_minimizer': {'maxfev': max_func_evaluations}, 50 | }.get(minimizer_method, {}) 51 | 52 | minimizer_options.update( minimizer_options_update ) 53 | 54 | print("Using start_params = '%s'" % str(start_params) ) 55 | print("Using shots (sample_number) = %d" % sample_number) 56 | print("Using q_device_name = '%s'" % q_device_name) 57 | print("Using minimizer_method = '%s'" % minimizer_method) 58 | print("Using max_func_evaluations = %d" % max_func_evaluations) # this parameter may influence the next one 59 | print("Using minimizer_options = '%s'" % str(minimizer_options) ) 60 | 61 | minimizer_function = getattr(h_optimizers, minimizer_method) # minimizer_method is a string/name, minimizer_function is an imported callable 62 | 63 | return start_params, sample_number, q_device_name, minimizer_method, minimizer_options, minimizer_function 64 | 65 | 66 | def ttot(t,s,p): 67 | R = np.ceil(np.log(1-p)/np.log(1-s)) 68 | return t*R 69 | 70 | 71 | # Total time to solution (as defined in ttot(t,s,p)), calculated from data and returning errors 72 | def total_time(ts, n_succ, n_tot, p): 73 | if n_succ == 0: 74 | return np.nan, np.nan, np.nan, np.nan, 0, 0 75 | t_ave = np.mean(ts) 76 | t_err = np.std(ts)/len(ts)**0.5 # Standard error for t 77 | if n_succ == n_tot: 78 | return t_ave,t_err,t_ave,t_err,1,0 # Always works so return time per run. Also prevents np.log(0) in code that follows. 79 | s = float(n_succ)/n_tot 80 | s_err = (s*(1-s)/float(n_tot))**0.5 # Standard error for s (using binomial dist) 81 | Tave = ttot(t_ave,s,p) 82 | T_serr = ttot(t_ave,s+s_err,p) 83 | T_serr2 = ttot(t_ave,s-s_err,p) 84 | Terr = (( (T_serr2 - T_serr)/2.)**2 + (t_err*Tave/float(t_ave)) ** 2 ) ** 0.5 # Error in total error assuming t and s independent 85 | return Tave, Terr, t_ave, t_err, s, s_err 86 | 87 | 88 | def benchmark_code(vqe_entry, N = 100, solution = 0., delta = 1e-1, p=0.95): 89 | n_succ = 0 90 | out_list = [] 91 | n_samples_list = [] 92 | for i in range(N): 93 | out, n_samples = vqe_entry() # 'out' is the global minimum 'found' by the participant's code, 'n_samples' is the number of samples they used in total throughout the optimisation procedure 94 | if abs(out-solution) <= delta: 95 | n_succ += 1 96 | out_list.append(out) 97 | n_samples_list.append(n_samples) 98 | Tave, Terr, t_ave, t_err, s, s_err = total_time(n_samples_list, n_succ, N, p) 99 | # The key metric is is Tave (which has error +/- Terr to 1 stdev), but we'll return everything to be stored anyway 100 | return Tave, Terr, t_ave, t_err, s, s_err, out_list, n_samples_list 101 | 102 | 103 | def benchmark_list_of_runs(list_of_runs, delta, prob, which_fun_key, which_time_key, show_more=False, verbose=True): 104 | "Perform benchmarking on the already collected JSON file from an experiment: CK entry" 105 | 106 | if verbose: 107 | print("benchmark_list_of_runs: delta={}, prob={}, which_fun_key={}, which_time_key={}\n".format(delta, prob, which_fun_key, which_time_key)) 108 | 109 | num_repetitions = len(list_of_runs) 110 | if num_repetitions: 111 | first_run_input = list_of_runs[0]['vqe_input'] 112 | classical_energy = first_run_input['classical_energy'] 113 | minimizer_src = first_run_input['minimizer_src'] 114 | minimizer_method = first_run_input['minimizer_method'] 115 | 116 | n_succ = 0 117 | list_selected_times = [] 118 | 119 | if verbose: 120 | print("experiment_file: Goal={}, Minimizer={}, Source:\n{}\n\n{}\n{}\n".format(classical_energy, minimizer_method, '-'*100, minimizer_src, '='*100)) 121 | 122 | for run in list_of_runs: 123 | vqe_output = run['vqe_output'] 124 | report = run['report'] 125 | 126 | fun = vqe_output['fun'] 127 | fun_validated = vqe_output['fun_validated'] 128 | fun_exact = vqe_output['fun_exact'] 129 | fun_selected = vqe_output[which_fun_key] 130 | 131 | q_seconds = report['total_q_seconds'] 132 | q_shots = report['total_q_shots'] 133 | time_selected = report[which_time_key] 134 | 135 | if verbose: 136 | print("fun_participant={:.4f}, fun_validated={:.4f}, fun_exact={:.4f}, Qtime={:.2f}sec, Qshots={}".format(fun, fun_validated, fun_exact, q_seconds, q_shots)) 137 | 138 | if abs( fun_selected - classical_energy ) 0, if error 37 | (error) - error text if return > 0 38 | } 39 | 40 | """ 41 | return {'return':0} 42 | 43 | 44 | ############################################################################## 45 | # get raw data for repo-widget 46 | 47 | def get_raw_data(i): 48 | """ 49 | Input: { 50 | } 51 | 52 | Output: { 53 | return - return code = 0, if successful 54 | > 0, if error 55 | (error) - error text if return > 0 56 | } 57 | 58 | """ 59 | 60 | selected_repo_uoa = i.get('repo_uoa', default_repo_uoa) 61 | 62 | def get_experimental_results(repo_uoa=selected_repo_uoa, tags='qck,hackathon-20190127', module_uoa='experiment'): 63 | r = ck.access({'action':'search', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'tags':tags}) 64 | if r['return']>0: 65 | print('Error: %s' % r['error']) 66 | exit(1) 67 | experiments = r['lst'] 68 | 69 | index = [ 70 | 'team', 'problem_index' 71 | ] 72 | 73 | dfs = [] 74 | for experiment in experiments: 75 | data_uoa = experiment['data_uoa'] 76 | r = ck.access({'action':'list_points', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'data_uoa':data_uoa}) 77 | if r['return']>0: 78 | print('Error: %s' % r['error']) 79 | exit(1) 80 | 81 | # Get all the parameters from meta.json -> "meta" 82 | mmeta = r['dict']['meta'] 83 | team = mmeta.get('team', 'UNKNOWN_TEAM') 84 | 85 | experiment_entry_path = r['path'] 86 | entry_modification_epoch_secs = int( os.path.getmtime(experiment_entry_path) ) 87 | entry_modification_utc_human = time.asctime(time.gmtime( entry_modification_epoch_secs )) 88 | 89 | point_ids = r['points'] 90 | 91 | for point_id in point_ids: 92 | load_point_adict = { 'action': 'load_point', 93 | 'module_uoa': module_uoa, 94 | 'data_uoa': data_uoa, 95 | 'point': point_id, 96 | } 97 | r=ck.access( load_point_adict ) 98 | if r['return']>0: return r 99 | 100 | if i.get('out')=='con': 101 | ck.out( "Loading {}:experiment:{} point_id={} (recorded {})".format(repo_uoa, data_uoa, point_id, entry_modification_utc_human) ) 102 | 103 | point_data_raw = r['dict']['0001'] 104 | choices = point_data_raw['choices'] 105 | characteristics_list = point_data_raw['characteristics_list'] 106 | num_repetitions = len(characteristics_list) 107 | 108 | data = [ 109 | { 110 | # statistical repetition 111 | 'repetition_id': repetition_id, 112 | # runtime characteristics 113 | 'problem_name': characteristics['run'].get('problem_name','problem_x'), 114 | 'problem_index': characteristics['run'].get('problem_index',-1), 115 | 'training_accuracy': np.float64(characteristics['run'].get('training_accuracy',1e6)), 116 | 'training_time': np.float64(characteristics['run'].get('training_time',0.0)), 117 | 'training_vectors_limit': np.int64(characteristics['run'].get('training_vectors_limit') or -1), 118 | 'solution_function_name': characteristics['run'].get('solution_function_name',''), 119 | 'source_code': characteristics['run'].get('source_code',''), 120 | 'circuit_str': characteristics['run'].get('circuit_str',''), 121 | 'test_accuracy': np.float64(characteristics['run'].get('test_accuracy',0.0)), 122 | 123 | 'team': team, 124 | 'timestamp_epoch_secs': entry_modification_epoch_secs, 125 | 'timestamp_utc_human': entry_modification_utc_human, 126 | 127 | 'success?': characteristics['run'].get('run_success','N/A'), 128 | } 129 | for (repetition_id, characteristics) in zip(range(num_repetitions), characteristics_list) 130 | if len(characteristics['run']) > 0 131 | ] 132 | 133 | # Construct a DataFrame. 134 | df = pd.DataFrame(data) 135 | df = df.set_index(index, drop=False) 136 | # Append to the list of similarly constructed DataFrames. 137 | dfs.append(df) 138 | if dfs: 139 | # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). 140 | result = pd.concat(dfs) 141 | result.sort_index(ascending=True, inplace=True) 142 | else: 143 | # Construct a dummy DataFrame the success status of which can be safely checked. 144 | result = pd.DataFrame(columns=['success?']) 145 | 146 | return result 147 | 148 | 149 | # prepare table 150 | df = get_experimental_results() 151 | 152 | if not df.empty: 153 | df.reset_index(inplace=True, drop=True) # remove the index as it is in the way of complex grouping 154 | 155 | ## Sorting in place allows us to preserve this order as the initial order in the output 156 | df.sort_values(['problem_index', 'test_accuracy', 'timestamp_epoch_secs'], ascending=[True, False, True], inplace=True) 157 | df['rank'] = df.groupby('problem_index').cumcount()+1 158 | 159 | df['seconds_since_start'] = df['timestamp_epoch_secs']-df['timestamp_epoch_secs'].min() 160 | df['hours_since_start'] = df['seconds_since_start'] / 3600.0 161 | 162 | # from IPython.display import display 163 | # pd.options.display.max_columns = len(df.columns) 164 | # pd.options.display.max_rows = len(df.index) 165 | # display(df) 166 | 167 | table = [] 168 | 169 | def to_value(i): 170 | if type(i) is np.ndarray: 171 | return i.tolist() 172 | 173 | if isinstance(i, np.int64): 174 | return int(i) 175 | 176 | if isinstance(i, np.float64): 177 | return float(i) 178 | 179 | return i 180 | 181 | props = [ 182 | 'problem_name', 183 | 'problem_index', 184 | 'training_vectors_limit', 185 | 'training_time', 186 | 'training_accuracy', 187 | 'solution_function_name', 188 | 'source_code', 189 | 'circuit_str', 190 | 'test_accuracy', 191 | 'rank', 192 | 193 | 'team', 194 | 'timestamp_epoch_secs', 195 | 'timestamp_utc_human', 196 | 'seconds_since_start', 197 | 'hours_since_start', 198 | 199 | 'success?', 200 | ] 201 | 202 | for record in df.to_dict(orient='records'): 203 | row = {} 204 | for prop in props: 205 | row[prop] = to_value(record.get(prop, '')) 206 | 207 | # row['##data_uid'] = "{}:{}".format(record['_point'], record['_repetition_id']) 208 | 209 | row['source_code'] = { 210 | 'title': record.get('solution_function_name','Show source'), 211 | 'cmd': record['source_code'], 212 | } 213 | 214 | if record['circuit_str']: 215 | row['circuit_str'] = { 216 | 'title': record.get('solution_circuit_name', 'Show circuit'), 217 | 'cmd': record['circuit_str'], 218 | } 219 | else: 220 | row['circuit_str']='N/A' 221 | 222 | table.append(row) 223 | 224 | return {'return':0, 'table':table} 225 | 226 | 227 | ############################################################################## 228 | # get raw config for repo widget 229 | 230 | def get_raw_config(i): 231 | """ 232 | Input: { 233 | } 234 | 235 | Output: { 236 | return - return code = 0, if successful 237 | > 0, if error 238 | (error) - error text if return > 0 239 | } 240 | 241 | """ 242 | 243 | data_config = cfg['data_config'] 244 | data_config['return'] = 0 245 | 246 | return data_config 247 | -------------------------------------------------------------------------------- /module/hackathon.20190315/module.py: -------------------------------------------------------------------------------- 1 | # 2 | # Collective Knowledge () 3 | # 4 | # 5 | # 6 | # 7 | # Developer: 8 | # 9 | 10 | cfg={} # Will be updated by CK (meta description of this module) 11 | work={} # Will be updated by CK (temporal data) 12 | ck=None # Will be updated by CK (initialized CK kernel) 13 | 14 | import os 15 | import sys 16 | import time 17 | 18 | import pandas as pd 19 | import numpy as np 20 | 21 | #default_repo_uoa = '' 22 | #default_repo_uoa = 'local' 23 | default_repo_uoa = 'ck-quantum-hackathon-20190315' 24 | 25 | 26 | ############################################################################## 27 | # Initialize module 28 | 29 | def init(i): 30 | """ 31 | 32 | Input: {} 33 | 34 | Output: { 35 | return - return code = 0, if successful 36 | > 0, if error 37 | (error) - error text if return > 0 38 | } 39 | 40 | """ 41 | return {'return':0} 42 | 43 | 44 | ############################################################################## 45 | # get raw data for repo-widget 46 | 47 | def get_raw_data(i): 48 | """ 49 | Input: { 50 | } 51 | 52 | Output: { 53 | return - return code = 0, if successful 54 | > 0, if error 55 | (error) - error text if return > 0 56 | } 57 | 58 | """ 59 | 60 | selected_repo_uoa = i.get('repo_uoa', default_repo_uoa) 61 | 62 | def get_experimental_results(repo_uoa=selected_repo_uoa, tags='qck,hackathon-20190315', module_uoa='experiment'): 63 | r = ck.access({'action':'search', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'tags':tags}) 64 | if r['return']>0: 65 | print('Error: %s' % r['error']) 66 | exit(1) 67 | experiments = r['lst'] 68 | 69 | index = [ 70 | 'team', 'problem_index' 71 | ] 72 | 73 | dfs = [] 74 | for experiment in experiments: 75 | data_uoa = experiment['data_uoa'] 76 | r = ck.access({'action':'list_points', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'data_uoa':data_uoa}) 77 | if r['return']>0: 78 | print('Error: %s' % r['error']) 79 | exit(1) 80 | 81 | # Get all the parameters from meta.json -> "meta" 82 | mmeta = r['dict']['meta'] 83 | team = mmeta.get('team', 'UNKNOWN_TEAM') 84 | 85 | experiment_entry_path = r['path'] 86 | entry_modification_epoch_secs = int( os.path.getmtime(experiment_entry_path) ) 87 | entry_modification_utc_human = time.asctime(time.gmtime( entry_modification_epoch_secs )) 88 | 89 | point_ids = r['points'] 90 | 91 | for point_id in point_ids: 92 | load_point_adict = { 'action': 'load_point', 93 | 'module_uoa': module_uoa, 94 | 'data_uoa': data_uoa, 95 | 'point': point_id, 96 | } 97 | r=ck.access( load_point_adict ) 98 | if r['return']>0: return r 99 | 100 | if i.get('out')=='con': 101 | ck.out( "Loading {}:experiment:{} point_id={} (recorded {})".format(repo_uoa, data_uoa, point_id, entry_modification_utc_human) ) 102 | 103 | point_data_raw = r['dict']['0001'] 104 | choices = point_data_raw['choices'] 105 | characteristics_list = point_data_raw['characteristics_list'] 106 | num_repetitions = len(characteristics_list) 107 | 108 | data = [ 109 | { 110 | # statistical repetition 111 | 'repetition_id': repetition_id, 112 | # runtime characteristics 113 | 'problem_name': characteristics['run'].get('problem_name','problem_x'), 114 | 'problem_index': characteristics['run'].get('problem_index',-1), 115 | 'training_accuracy': np.float64(characteristics['run'].get('training_accuracy',1e6)), 116 | 'training_time': np.float64(characteristics['run'].get('training_time',0.0)), 117 | 'training_vectors_limit': np.int64(characteristics['run'].get('training_vectors_limit') or -1), 118 | 'solution_function_name': characteristics['run'].get('solution_function_name',''), 119 | 'source_code': characteristics['run'].get('source_code',''), 120 | 'circuit_str': characteristics['run'].get('circuit_str',''), 121 | 'test_accuracy': np.float64(characteristics['run'].get('test_accuracy',0.0)), 122 | 123 | 'team': team, 124 | 'timestamp_epoch_secs': entry_modification_epoch_secs, 125 | 'timestamp_utc_human': entry_modification_utc_human, 126 | 127 | 'success?': characteristics['run'].get('run_success','N/A'), 128 | } 129 | for (repetition_id, characteristics) in zip(range(num_repetitions), characteristics_list) 130 | if len(characteristics['run']) > 0 131 | ] 132 | 133 | # Construct a DataFrame. 134 | df = pd.DataFrame(data) 135 | df = df.set_index(index, drop=False) 136 | # Append to the list of similarly constructed DataFrames. 137 | dfs.append(df) 138 | if dfs: 139 | # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). 140 | result = pd.concat(dfs) 141 | result.sort_index(ascending=True, inplace=True) 142 | else: 143 | # Construct a dummy DataFrame the success status of which can be safely checked. 144 | result = pd.DataFrame(columns=['success?']) 145 | 146 | return result 147 | 148 | 149 | # prepare table 150 | df = get_experimental_results() 151 | 152 | if not df.empty: 153 | df.reset_index(inplace=True, drop=True) # remove the index as it is in the way of complex grouping 154 | 155 | ## Sorting in place allows us to preserve this order as the initial order in the output 156 | df.sort_values(['problem_index', 'test_accuracy', 'timestamp_epoch_secs'], ascending=[True, False, True], inplace=True) 157 | df['rank'] = df.groupby('problem_index').cumcount()+1 158 | 159 | df['seconds_since_start'] = df['timestamp_epoch_secs']-df['timestamp_epoch_secs'].min() 160 | df['hours_since_start'] = df['seconds_since_start'] / 3600.0 161 | 162 | # from IPython.display import display 163 | # pd.options.display.max_columns = len(df.columns) 164 | # pd.options.display.max_rows = len(df.index) 165 | # display(df) 166 | 167 | table = [] 168 | 169 | def to_value(i): 170 | if type(i) is np.ndarray: 171 | return i.tolist() 172 | 173 | if isinstance(i, np.int64): 174 | return int(i) 175 | 176 | if isinstance(i, np.float64): 177 | return float(i) 178 | 179 | return i 180 | 181 | props = [ 182 | 'problem_name', 183 | 'problem_index', 184 | 'training_vectors_limit', 185 | 'training_time', 186 | 'training_accuracy', 187 | 'solution_function_name', 188 | 'source_code', 189 | 'circuit_str', 190 | 'test_accuracy', 191 | 'rank', 192 | 193 | 'team', 194 | 'timestamp_epoch_secs', 195 | 'timestamp_utc_human', 196 | 'seconds_since_start', 197 | 'hours_since_start', 198 | 199 | 'success?', 200 | ] 201 | 202 | for record in df.to_dict(orient='records'): 203 | row = {} 204 | for prop in props: 205 | row[prop] = to_value(record.get(prop, '')) 206 | 207 | # row['##data_uid'] = "{}:{}".format(record['_point'], record['_repetition_id']) 208 | 209 | row['source_code'] = { 210 | 'title': record.get('solution_function_name','Show source'), 211 | 'cmd': record['source_code'], 212 | } 213 | 214 | if record['circuit_str']: 215 | row['circuit_str'] = { 216 | 'title': record.get('solution_circuit_name', 'Show circuit'), 217 | 'cmd': record['circuit_str'], 218 | } 219 | else: 220 | row['circuit_str']='N/A' 221 | 222 | table.append(row) 223 | 224 | return {'return':0, 'table':table} 225 | 226 | 227 | ############################################################################## 228 | # get raw config for repo widget 229 | 230 | def get_raw_config(i): 231 | """ 232 | Input: { 233 | } 234 | 235 | Output: { 236 | return - return code = 0, if successful 237 | > 0, if error 238 | (error) - error text if return > 0 239 | } 240 | 241 | """ 242 | 243 | data_config = cfg['data_config'] 244 | data_config['return'] = 0 245 | 246 | return data_config 247 | -------------------------------------------------------------------------------- /program/visualize-convergence/visualize_convergence.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import time 4 | import curses 5 | import sys, os 6 | import select 7 | from math import * 8 | from ast import literal_eval 9 | import ap 10 | import numpy as np 11 | from functools import partial 12 | import subprocess 13 | import json 14 | import threading 15 | import signal 16 | 17 | try: 18 | import inotify 19 | NOTIFY_AVAILABLE = True 20 | except ImportError: 21 | NOTIFY_AVAILABLE = False 22 | 23 | class DataSource(threading.Thread): 24 | """Class for obtaining data from the log saved by ck run. 25 | 26 | we (try) to open the file, stream in the data from it. 27 | if ck run is restarted, the file will be unlinked - we need to detect 28 | this and discard prev data. 29 | """ 30 | 31 | def __init__(self, fname, *args, **kwargs): 32 | super().__init__(*args, **kwargs) 33 | self.fname = fname 34 | self.logs = None 35 | self.running = False 36 | self.file = None 37 | self.Nruns = 0 38 | 39 | def run(self): 40 | """Loads data from a file, and monitors it for changes. 41 | 42 | if the file is removed, then a new ck run command has begun. 43 | we need to discard the current data, and begin monitoring the new file. 44 | """ 45 | self.running = True 46 | while self.running: 47 | # os.stat to see if the file is zero length 48 | # os.fstat(f.fileno()).st_nlink == 0? file anon, need to reopen 49 | if self.file is not None and os.fstat(self.file.fileno()).st_nlink == 0: 50 | # file has been unlinked 51 | self.file = None # kill it. 52 | 53 | elif self.file is not None: # have a file object, should be valid. try and read more data from it. 54 | line = self.file.readline() 55 | if line == '': #eof 56 | time.sleep(0.1) # wait a bit 57 | elif line.startswith('{'): # experimental iteration. 58 | d = literal_eval(line) 59 | self.logs[-1].append(d["energy"]) 60 | elif line.startswith('#'): 61 | self.logs.append([]) # new experiment run 62 | 63 | else: 64 | try: 65 | self.file = open(self.fname, "r") 66 | self.logs = [[]] 67 | except FileNotFoundError: 68 | time.sleep(0.1) 69 | 70 | 71 | class Colors(): 72 | 73 | end = '\x1b[0m' 74 | 75 | def __init__(self): 76 | # generate a style list 77 | self.styles = [] 78 | for style in range(8): 79 | for fg in range(30,38): 80 | s1 = '' 81 | for bg in range(40,48): 82 | format = ';'.join([str(style), str(fg), str(bg)]) 83 | self.styles.append(format) 84 | 85 | self.N = len(self.styles) 86 | 87 | 88 | 89 | class CURSESDisplay(threading.Thread): 90 | 91 | stats_format = """N runs = {nruns} 92 | Minimum energy seen = {mine} 93 | Final mean = {mean} 94 | Final variance = {var} 95 | """ 96 | 97 | def __init__(self, datasource, *args, **kwargs): 98 | super().__init__(*args, **kwargs) 99 | self.data = datasource 100 | self.running = False 101 | self.numerical_markers = True 102 | self.colors = Colors() 103 | self.color = False 104 | 105 | 106 | def run(self): 107 | curses.wrapper(self._main) 108 | 109 | def draw_stats(self, window): 110 | window.clear() 111 | 112 | if self.data.logs: 113 | final_es = [] 114 | min_ = 0 115 | for i, log in enumerate(self.data.logs): 116 | if log: 117 | min_ = min(min_, min(log)) 118 | if log and i != len(self.data.logs)-1: # for finished runs 119 | final_es.append(min(log)) 120 | 121 | window.addstr(self.stats_format.format( 122 | nruns = len(self.data.logs)-1, 123 | mine = min_, 124 | mean = np.mean(final_es) if len(final_es) > 1 else "Insufficent data", 125 | var = np.std(final_es) if len(final_es) > 1 else "Insufficent data" 126 | )) 127 | else: 128 | window.addstr("No data yet!") 129 | 130 | 131 | def getmarker(self, i): 132 | marker = '_,' if i == len(self.data.logs)-1 else \ 133 | str(i) if self.numerical_markers else \ 134 | '_.' 135 | if self.color: 136 | marker = self.colors.styles[i % self.colors.N] + marker + self.colors.end 137 | return marker 138 | 139 | 140 | 141 | 142 | def draw_graphs(self, window): 143 | """Draws data from self.datasource to a curses window. 144 | """ 145 | height,width = window.getmaxyx() 146 | 147 | if self.data.logs: 148 | min_, max_ = -1.7, -1.6 149 | p = ap.AFigure(shape=(width-2, height-3)) 150 | for i, log in enumerate(self.data.logs): 151 | if len(log) < 1: 152 | continue 153 | x = np.arange(len(log)) 154 | y = log 155 | _ = p.plot(x, y, marker=self.getmarker(i), plot_slope=False) 156 | min_ = min(min_, min(log)) 157 | max_ = max(max_, max(log)) 158 | 159 | p.ylim(min_, max_) 160 | plot_str = p.draw() 161 | 162 | for i, line in enumerate(plot_str.split("\n")): 163 | window.addstr(i,0,line) 164 | 165 | 166 | def _main(self, stdscr): 167 | """Draws the CURSES ui. 168 | """ 169 | 170 | graph_size = ceil(curses.LINES * (2/3)) 171 | echo_v_size = floor(curses.LINES * (1/3)) 172 | 173 | stats_h_size = ceil(curses.COLS * (2/3)) 174 | opts_h_size = floor(curses.COLS * (1/3)) 175 | 176 | stats_border = curses.newwin(echo_v_size, stats_h_size, graph_size, 0) 177 | stats = stats_border.derwin(echo_v_size-2, stats_h_size-2, 1, 1) 178 | 179 | options_border = curses.newwin(echo_v_size, opts_h_size, graph_size, stats_h_size) 180 | options = options_border.derwin(echo_v_size-2, opts_h_size-2, 1, 1) 181 | 182 | graph_border = curses.newwin(graph_size, curses.COLS, 0, 0) 183 | graphwin = graph_border.derwin(graph_size-2, curses.COLS-2, 1, 1) 184 | 185 | # graphwin.scrollok(True) 186 | stdscr.nodelay(True) 187 | stdscr.refresh() 188 | graph_border.border() 189 | stats_border.border() 190 | options_border.border() 191 | stats_border.addstr(0, 2, "stats") 192 | options_border.addstr(0, 2, "usage") 193 | options.addstr("Toggle numerical markers: n\nQuit: q") 194 | options_border.refresh() 195 | 196 | logs = [] 197 | self.running = True 198 | 199 | while self.running: 200 | 201 | stdscr.refresh() 202 | 203 | graphwin.refresh() 204 | graph_border.refresh() 205 | stats_border.refresh() 206 | stats.refresh() 207 | 208 | graphwin.move(0,0) 209 | 210 | # noblock 211 | cmd = stdscr.getch() 212 | if cmd == ord('q'): 213 | break 214 | elif cmd == ord('n'): 215 | self.numerical_markers = not self.numerical_markers 216 | elif cmd == ord('c') and False: 217 | self.color = not self.color 218 | 219 | 220 | self.draw_graphs(graphwin) 221 | self.draw_stats(stats) 222 | graph_border.addstr(0,20,"Optimiser iteration") 223 | for i,c in enumerate("Energy"): 224 | graph_border.addstr(10+i,0,c) 225 | 226 | # will ahve some kind of update polling mech, but not yet 227 | time.sleep(0.1) 228 | 229 | 230 | def get_fname(): 231 | """Uses CK to get the file that contains the live-updated iteration progress. 232 | """ 233 | 234 | if 'CK_ROOT' in os.environ: 235 | import sys 236 | sys.path.append( os.environ['CK_ROOT'] ) 237 | 238 | provider = os.environ.get('VQE_QUANTUM_PROVIDER', 'ibm') 239 | program = { 240 | 'ibm': 'qiskit-vqe', 241 | 'rigetti': 'rigetti-vqe2', 242 | }[provider] 243 | 244 | import ck.kernel as ck 245 | 246 | load_adict = { 'action': 'load', 247 | 'module_uoa': 'program', 248 | 'data_uoa': program, 249 | } 250 | r=ck.access( load_adict ) 251 | if r['return']>0: return r 252 | 253 | program_entry_path = r['path'] 254 | stream_file_path = os.path.join( program_entry_path, 'tmp', 'vqe_stream.json') 255 | 256 | return stream_file_path 257 | 258 | 259 | if __name__ == "__main__": 260 | 261 | # now we get input from a file, don't allow pipes to stdin 262 | if not sys.stdin.isatty(): 263 | print("please run interactively.") 264 | sys.exit(1) 265 | 266 | fname = sys.argv[1] if len(sys.argv) > 1 else get_fname() 267 | data = DataSource(fname) 268 | ui = CURSESDisplay(data) 269 | 270 | def die(_, __): 271 | ui.running = False 272 | data.running = False 273 | signal.signal(signal.SIGINT, signal.SIG_DFL) 274 | 275 | data.start() 276 | ui.start() 277 | signal.signal(signal.SIGINT, die) 278 | 279 | ui.join() 280 | data.running = False 281 | data.join() 282 | -------------------------------------------------------------------------------- /env/vqe_utils/vqe_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import json 3 | 4 | 5 | # See https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable 6 | # 7 | class NumpyEncoder(json.JSONEncoder): 8 | def default(self, obj): 9 | if isinstance(obj, np.ndarray): 10 | return obj.tolist() 11 | elif isinstance(obj, np.bool_): 12 | return bool(obj) 13 | return json.JSONEncoder.default(self, obj) 14 | 15 | 16 | def get_first_callable( namespace ): 17 | "return the first callable function in the given namespace" 18 | 19 | callable_names = [ attrib_name for attrib_name in dir(namespace) if callable(getattr(namespace, attrib_name)) ] 20 | 21 | top_level_methods = len(callable_names) 22 | 23 | if top_level_methods==1: 24 | return callable_names[0] 25 | else: 26 | raise Exception("Expecting exactly one top level function in '{}', but found {} ({}). Please refactor your code". \ 27 | format(namespace.__name__, top_level_methods, callable_names)) 28 | 29 | 30 | def cmdline_parse_and_report(num_params, q_device_name_default, q_device_name_help, minimizer_options_default='{}', start_param_value_default=0.0): 31 | 32 | import argparse 33 | import json 34 | import custom_optimizer # the file will be different depending on the plugin choice 35 | 36 | arg_parser = argparse.ArgumentParser() 37 | 38 | arg_parser.add_argument('--start_param_value', '--start-param-value', 39 | default=start_param_value_default, help="Initial value of each optimized parameter") 40 | 41 | arg_parser.add_argument('--start_params', '--start-params', 42 | type=float, nargs=num_params, help="Initial values of optimized parameters") 43 | 44 | arg_parser.add_argument('--sample_number', '--sample-number', '--shots', 45 | default=100, type=int, help="Number of repetitions of each individual quantum run") 46 | 47 | arg_parser.add_argument('--q_device_name', '--q-device-name', 48 | default=q_device_name_default, help=q_device_name_help) 49 | 50 | arg_parser.add_argument('--max_func_evaluations', '--max-func-evaluations', 51 | default=100, type=int, help="Minimizer's upper limit on the number of function evaluations") 52 | 53 | arg_parser.add_argument('--minimizer_options', '--minimizer-options', 54 | default=minimizer_options_default, help="A dictionary in JSON format to be passed to the minimizer function") 55 | 56 | args = arg_parser.parse_args() 57 | 58 | start_param_value = args.start_param_value 59 | start_params_default = np.random.randn( num_params ) if start_param_value == 'random' else [ float(start_param_value) ] * num_params 60 | 61 | start_params = args.start_params or start_params_default 62 | sample_number = args.sample_number 63 | q_device_name = args.q_device_name 64 | max_func_evaluations = args.max_func_evaluations 65 | minimizer_options = json.loads( args.minimizer_options ) 66 | minimizer_method = get_first_callable( custom_optimizer ) 67 | 68 | # We only know how to limit the number of iterations for certain methods, 69 | # so will introduce this as a "patch" to their minimizer_options dictionary: 70 | # 71 | if max_func_evaluations: 72 | minimizer_options_update = { 73 | 'my_nelder_mead': {'maxfev': max_func_evaluations}, 74 | 'my_cobyla': {'maxiter': max_func_evaluations}, 75 | 'my_random_sampler':{'maxfev': max_func_evaluations}, 76 | 'my_minimizer': {'maxfev': max_func_evaluations}, 77 | }.get(minimizer_method, {}) 78 | 79 | minimizer_options.update( minimizer_options_update ) 80 | 81 | print("Using start_params = '%s'" % str(start_params) ) 82 | print("Using shots (sample_number) = %d" % sample_number) 83 | print("Using q_device_name = '%s'" % q_device_name) 84 | print("Using minimizer_method = '%s'" % minimizer_method) 85 | print("Using max_func_evaluations = %d" % max_func_evaluations) # this parameter may influence the next one 86 | print("Using minimizer_options = '%s'" % str(minimizer_options) ) 87 | 88 | minimizer_function = getattr(custom_optimizer, minimizer_method) # minimizer_method is a string/name, minimizer_function is an imported callable 89 | 90 | return start_params, sample_number, q_device_name, minimizer_method, minimizer_options, minimizer_function 91 | 92 | 93 | def ttot(t,s,p): 94 | R = np.ceil(np.log(1-p)/np.log(1-s)) 95 | return t*R 96 | 97 | 98 | # Total time to solution (as defined in ttot(t,s,p)), calculated from data and returning errors 99 | def total_time(ts, n_succ, n_tot, p): 100 | if n_succ == 0: 101 | return np.nan, np.nan, np.nan, np.nan, 0, 0 102 | t_ave = np.mean(ts) 103 | t_err = np.std(ts)/len(ts)**0.5 # Standard error for t 104 | if n_succ == n_tot: 105 | return t_ave,t_err,t_ave,t_err,1,0 # Always works so return time per run. Also prevents np.log(0) in code that follows. 106 | s = float(n_succ)/n_tot 107 | s_err = (s*(1-s)/float(n_tot))**0.5 # Standard error for s (using binomial dist) 108 | Tave = ttot(t_ave,s,p) 109 | T_serr = ttot(t_ave,s+s_err,p) 110 | T_serr2 = ttot(t_ave,s-s_err,p) 111 | Terr = (( (T_serr2 - T_serr)/2.)**2 + (t_err*Tave/float(t_ave)) ** 2 ) ** 0.5 # Error in total error assuming t and s independent 112 | return Tave, Terr, t_ave, t_err, s, s_err 113 | 114 | 115 | def benchmark_code(vqe_entry, N = 100, solution = 0., delta = 1e-1, p=0.95): 116 | n_succ = 0 117 | out_list = [] 118 | n_samples_list = [] 119 | for i in range(N): 120 | out, n_samples = vqe_entry() # 'out' is the global minimum 'found' by the participant's code, 'n_samples' is the number of samples they used in total throughout the optimisation procedure 121 | if abs(out-solution) <= delta: 122 | n_succ += 1 123 | out_list.append(out) 124 | n_samples_list.append(n_samples) 125 | Tave, Terr, t_ave, t_err, s, s_err = total_time(n_samples_list, n_succ, N, p) 126 | # The key metric is is Tave (which has error +/- Terr to 1 stdev), but we'll return everything to be stored anyway 127 | return Tave, Terr, t_ave, t_err, s, s_err, out_list, n_samples_list 128 | 129 | 130 | def benchmark_list_of_runs(list_of_runs, delta, prob, which_fun_key, which_time_key, show_more=False, verbose=True): 131 | "Perform benchmarking on the already collected JSON file from an experiment: CK entry" 132 | 133 | if verbose: 134 | print("benchmark_list_of_runs: delta={}, prob={}, which_fun_key={}, which_time_key={}\n".format(delta, prob, which_fun_key, which_time_key)) 135 | 136 | num_repetitions = len(list_of_runs) 137 | if num_repetitions: 138 | first_run_input = list_of_runs[0]['vqe_input'] 139 | classical_energy = first_run_input['classical_energy'] 140 | minimizer_method = first_run_input['minimizer_method'] 141 | minimizer_src = first_run_input['minimizer_src'] 142 | ansatz_method = first_run_input.get('ansatz_method') 143 | ansatz_src = first_run_input.get('ansatz_src') 144 | 145 | n_succ = 0 146 | list_selected_times = [] 147 | 148 | if verbose: 149 | print("experiment_file: Goal={}, Minimizer={}, Minimizer_source:\n{}\n\n{}\n{}\n".format(classical_energy, minimizer_method, '-'*100, minimizer_src, '='*100)) 150 | if ansatz_method and ansatz_src: 151 | print("Ansatz={}, Ansatz_source:\n{}\n{}".format(ansatz_method, ansatz_src, '-'*100)) 152 | 153 | for run in list_of_runs: 154 | vqe_output = run['vqe_output'] 155 | report = run['report'] 156 | 157 | fun = float(vqe_output['fun']) 158 | fun_validated = float(vqe_output['fun_validated']) 159 | fun_exact_present = 'fun_exact' in vqe_output 160 | fun_exact = float(vqe_output['fun_exact']) if fun_exact_present else None # may not be defined for a particular implementation 161 | fun_selected = float(vqe_output[which_fun_key]) 162 | 163 | q_seconds = report['total_q_seconds'] 164 | q_shots = report['total_q_shots'] 165 | time_selected = report[which_time_key] 166 | 167 | if verbose: 168 | abs_diff = abs( fun_selected - classical_energy ) 169 | hit_bool = abs_diff < delta 170 | fun_exact_str = 'fun_exact={:.4f}, '.format(fun_exact) if fun_exact_present else '' 171 | print("fun_participant={:.4f}, fun_validated={:.4f}, {}Qtime={:.2f}sec, Qshots={}, abs_diff={:.4f} {}" \ 172 | .format(fun, fun_validated, fun_exact_str, q_seconds, q_shots, abs_diff, '(hit)' if hit_bool else '(miss)')) 173 | 174 | if hit_bool: 175 | n_succ += 1 176 | 177 | list_selected_times.append(time_selected) 178 | 179 | Tave, Terr, t_ave, t_err, s, s_err = total_time(list_selected_times, n_succ, num_repetitions, prob) 180 | if verbose: 181 | if show_more: 182 | print("\nn_succ={}, Tave={:.4f}, Terr={:.4f}, t_ave={:.4f}, t_err={:.4f}, s={:.4f}, s_err={:.4f}\n\n".format(n_succ, Tave, Terr, t_ave, t_err, s, s_err)) 183 | else: 184 | print("\nn_succ={}, Tave={:.4f}\n\n".format(n_succ, Tave)) 185 | 186 | return classical_energy, minimizer_method, minimizer_src, n_succ, Tave, Terr, t_ave, t_err, s, s_err 187 | 188 | -------------------------------------------------------------------------------- /module/hackathon.20181006/module.py: -------------------------------------------------------------------------------- 1 | # 2 | # Collective Knowledge () 3 | # 4 | # 5 | # 6 | # 7 | # Developer: 8 | # 9 | 10 | cfg={} # Will be updated by CK (meta description of this module) 11 | work={} # Will be updated by CK (temporal data) 12 | ck=None # Will be updated by CK (initialized CK kernel) 13 | 14 | import os 15 | import sys 16 | import json 17 | import re 18 | 19 | import pandas as pd 20 | import numpy as np 21 | 22 | 23 | ############################################################################## 24 | # Initialize module 25 | 26 | def init(i): 27 | """ 28 | 29 | Input: {} 30 | 31 | Output: { 32 | return - return code = 0, if successful 33 | > 0, if error 34 | (error) - error text if return > 0 35 | } 36 | 37 | """ 38 | return {'return':0} 39 | 40 | 41 | ############################################################################## 42 | # get raw data for repo-widget 43 | 44 | def get_raw_data(i): 45 | """ 46 | Input: { 47 | } 48 | 49 | Output: { 50 | return - return code = 0, if successful 51 | > 0, if error 52 | (error) - error text if return > 0 53 | } 54 | 55 | """ 56 | 57 | repo_uoa = 'ck-quantum-hackathon-20181006' 58 | 59 | def get_experimental_results(repo_uoa, tags='qck', module_uoa='experiment'): 60 | r = ck.access({'action':'search', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'tags':tags}) 61 | if r['return']>0: 62 | print('Error: %s' % r['error']) 63 | exit(1) 64 | experiments = r['lst'] 65 | 66 | dfs = [] 67 | for experiment in experiments: 68 | data_uoa = experiment['data_uoa'] 69 | r = ck.access({'action':'list_points', 'repo_uoa':repo_uoa, 'module_uoa':module_uoa, 'data_uoa':data_uoa}) 70 | if r['return']>0: 71 | print('Error: %s' % r['error']) 72 | exit(1) 73 | 74 | # Get all the parameters from meta.json -> "meta" 75 | mmeta = r['dict']['meta'] 76 | 77 | team = mmeta.get('team', r['dict'].get('team', 'team-default') ) 78 | molecule = mmeta.get('hamiltonian', 'Hydrogen') 79 | vendor = mmeta.get('provider', 'IBM') 80 | 81 | # For each point. 82 | for point in r['points']: 83 | point_file_path = os.path.join(r['path'], 'ckp-%s.0001.json' % point) 84 | with open(point_file_path) as point_file: 85 | point_data_raw = json.load(point_file) 86 | choices = point_data_raw['choices'] 87 | characteristics_list = point_data_raw['characteristics_list'] 88 | num_repetitions = len(characteristics_list) 89 | data = [ 90 | { 91 | # features 92 | 'platform': characteristics['run'].get('vqe_input', {}).get('q_device_name', 'unknown').lower(), 93 | 'molecule': molecule, 94 | 'vendor': vendor, 95 | # choices 96 | 'minimizer_method': characteristics['run'].get('vqe_input', {}).get('minimizer_method', 'n/a'), 97 | 'minimizer_options': characteristics['run'].get('vqe_input', {}).get('minimizer_options', {'maxfev':-1}), 98 | 'minimizer_src': characteristics['run'].get('vqe_input', {}).get('minimizer_src', ''), 99 | 'ansatz_method': characteristics['run'].get('vqe_input', {}).get('ansatz_method', ''), 100 | 'ansatz_src': characteristics['run'].get('vqe_input', {}).get('ansatz_src', ''), 101 | 'sample_number': characteristics['run'].get('vqe_input', {}).get('sample_number','n/a'), 102 | 'max_iterations': choices['env'].get('VQE_MAX_ITERATIONS', -1), 103 | # statistical repetition 104 | 'repetition_id': repetition_id, 105 | # runtime characteristics 106 | 'run': characteristics['run'], 107 | 'report': characteristics['run'].get('report', {}), 108 | 'vqe_output': characteristics['run'].get('vqe_output', {}), 109 | } 110 | for (repetition_id, characteristics) in zip(range(num_repetitions), characteristics_list) 111 | if len(characteristics['run']) > 0 112 | ] 113 | 114 | index = [ 115 | 'platform', 'team', 'minimizer_method', 'sample_number', 'max_iterations', 'point', 'repetition_id', 'molecule', 'ansatz_method', 'vendor' 116 | ] 117 | 118 | for datum in data: 119 | datum['team'] = team 120 | datum['point'] = point 121 | datum['success'] = datum.get('vqe_output',{}).get('success',False) 122 | datum['nfev'] = np.int64(datum.get('vqe_output',{}).get('nfev',-1)) 123 | datum['nit'] = np.int64(datum.get('vqe_output',{}).get('nit',-1)) 124 | datum['fun'] = np.float64(datum.get('vqe_output',{}).get('fun',0)) 125 | datum['fun_validated'] = np.float64(datum.get('vqe_output',{}).get('fun_validated',0)) 126 | datum['fun_exact'] = np.float64(datum.get('vqe_output',{}).get('fun_exact',0)) 127 | datum['total_seconds'] = np.float64(datum.get('report',{}).get('total_seconds',0)) 128 | datum['total_q_seconds'] = np.float64(datum.get('report',{}).get('total_q_seconds',0)) 129 | datum['total_q_shots'] = np.int64(datum.get('report',{}).get('total_q_shots',0)) 130 | datum['max_iterations'] = np.int64(datum.get('max_iterations',-1)) 131 | for key in index: 132 | datum['_' + key] = datum[key] 133 | datum['_ansatz_src'] = datum['ansatz_src'] 134 | datum['_minimizer_src'] = datum['minimizer_src'] 135 | 136 | # Construct a DataFrame. 137 | df = pd.DataFrame(data) 138 | df = df.set_index(index) 139 | # Append to the list of similarly constructed DataFrames. 140 | dfs.append(df) 141 | if dfs: 142 | # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). 143 | result = pd.concat(dfs) 144 | result.sort_index(ascending=True, inplace=True) 145 | else: 146 | # Construct a dummy DataFrame the success status of which can be safely checked. 147 | result = pd.DataFrame(columns=['success']) 148 | return result 149 | 150 | # Merge experimental results from the same team with the same parameters 151 | # (minimizer_method, sample_number, max_iterations) and minimizer source. 152 | def merge_experimental_results(df): 153 | dfs = [] 154 | df_prev = None 155 | for index, row in df.iterrows(): 156 | # Construct a DataFrame. 157 | df_curr = pd.DataFrame(row).T 158 | # Check if this row is similar to the previous row. 159 | if df_prev is not None: # if not the very first row 160 | if df_prev.index.levels[:5]==df_curr.index.levels[:5]: # if the indices match for all but the last two levels 161 | if df_prev.index.levels[5]!=df_curr.index.levels[5]: # if the experiments are different 162 | if df_prev['minimizer_src'].values==df_curr['minimizer_src'].values and df_prev['ansatz_src'].values==df_curr['ansatz_src'].values: # if the minimizer and ansatz sources are the same 163 | print('[Info] Merging experiment:') 164 | print(df_curr.index.levels) 165 | print('[Info] into:') 166 | print(df_prev.index.levels) 167 | print('[Info] as:') 168 | # df_curr.index = df_prev.index.copy() # TODO: increment repetition_id 169 | df_curr.index = pd.MultiIndex.from_tuples([(x[0],x[1],x[2],x[3],x[4],x[5],x[6]+1,x[7],x[8],x[9]) for x in df_prev.index]) 170 | print(df_curr.index.levels) 171 | print 172 | else: 173 | print('[Warning] Cannot merge experiments as the minimizer or ansatz sources are different (previous vs current):') 174 | print(df_prev.index.levels) 175 | print 176 | print(df_curr.index.levels) 177 | print 178 | # else: 179 | # print('[Info] Keeping experiments separate:') 180 | # print(df_prev.index.levels) 181 | # print(df_curr.index.levels) 182 | # print 183 | # Append to the list of similarly constructed DataFrames. 184 | dfs.append(df_curr) 185 | # Prepare for next iteration. 186 | df_prev = df_curr 187 | 188 | # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). 189 | result = pd.concat(dfs) 190 | result.index.names = df.index.names 191 | result.sort_index(ascending=True, inplace=True) 192 | 193 | return result 194 | 195 | # prepare table 196 | df = get_experimental_results(repo_uoa=repo_uoa) 197 | 198 | table = [] 199 | 200 | def to_value(i): 201 | if type(i) is np.ndarray: 202 | return i.tolist() 203 | 204 | if isinstance(i, np.int64): 205 | return int(i) 206 | 207 | return i 208 | 209 | props = [ 210 | '_platform', 211 | '_team', 212 | '_minimizer_method', 213 | '_sample_number', 214 | '_max_iterations', 215 | '_point', 216 | '_repetition_id', 217 | 'fun', 218 | 'fun_exact', 219 | 'fun_validated', 220 | 'nfev', 221 | 'nit', 222 | 'success', 223 | 'total_q_seconds', 224 | 'total_q_shots', 225 | 'total_seconds', 226 | '_ansatz_method', 227 | '_vendor', 228 | '_molecule', 229 | ] 230 | 231 | for record in df.to_dict(orient='records'): 232 | row = {} 233 | for prop in props: 234 | row[prop] = to_value(record.get(prop, '')) 235 | 236 | energies = [ iteration['energy'] for iteration in record['report']['iterations'] ] 237 | fevs = list(range(len(energies))) 238 | last_energy = energies[-1] 239 | minimizer_method = record.get('_minimizer_method', '') 240 | last_fev = row['nfev']-1 if minimizer_method=='my_cobyla' or 'my_nelder_mead' else row['nfev'] 241 | 242 | row['__energies'] = energies 243 | row['__fevs'] = fevs 244 | 245 | row['##data_uid'] = "{}:{}".format(record['_point'], record['_repetition_id']) 246 | 247 | row['_ansatz_src'] = { 248 | 'title': record.get('_ansatz_method','Show'), 249 | 'cmd': record['_ansatz_src'] 250 | } 251 | 252 | row['_minimizer_src'] = { 253 | 'title': record.get('_minimizer_method','Show'), 254 | 'cmd': record['_minimizer_src'] 255 | } 256 | 257 | table.append(row) 258 | 259 | # prepare metrics data 260 | df_m = merge_experimental_results(df) 261 | 262 | metrics_data = [] 263 | names_no_repetitions = [ n for n in df_m.index.names if n != 'repetition_id' ] 264 | 265 | for index, group in df_m.groupby(level=names_no_repetitions): 266 | runs = [] 267 | 268 | for run in group['run']: 269 | run_t = {} 270 | run_t['report'] = run['report'] 271 | run_t['vqe_input'] = run['vqe_input'] 272 | run_t['vqe_output'] = run['vqe_output'] 273 | runs.append(run_t) 274 | 275 | data = {} 276 | data['runs'] = runs 277 | data['num_repetitions'] = len(group) 278 | 279 | meta = {} 280 | meta.update({ k : v for (k, v) in zip(names_no_repetitions, index) }) 281 | 282 | for key in names_no_repetitions: 283 | data['_' + key] = to_value(meta[key]) 284 | 285 | data['##data_uid'] = to_value(meta['point']) 286 | 287 | metrics_data.append(data) 288 | 289 | return {'return':0, 'full_table':table, 'metrics_table':metrics_data} 290 | 291 | 292 | ############################################################################## 293 | # get raw config for repo widget 294 | 295 | def get_raw_config(i): 296 | """ 297 | Input: { 298 | } 299 | 300 | Output: { 301 | return - return code = 0, if successful 302 | > 0, if error 303 | (error) - error text if return > 0 304 | } 305 | 306 | """ 307 | 308 | data_config = cfg['data_config'] 309 | data_config['return'] = 0 310 | 311 | return data_config 312 | -------------------------------------------------------------------------------- /module/qml/module.py: -------------------------------------------------------------------------------- 1 | # 2 | # Collective Knowledge (checking and installing software) 3 | # 4 | # See CK LICENSE.txt for licensing details 5 | # See CK COPYRIGHT.txt for copyright details 6 | # 7 | # Developer: Leo Gordon, leo@dividiti.com 8 | # 9 | 10 | cfg={} # Will be updated by CK (meta description of this module) 11 | work={} # Will be updated by CK (temporal data) 12 | ck=None # Will be updated by CK (initialized CK kernel) 13 | 14 | hackathon_date = '20190315' 15 | 16 | hackathon_tag = 'hackathon-{}'.format(hackathon_date) 17 | hackathon_remote_repo = 'ck-quantum-hackathon-{}'.format(hackathon_date) 18 | hackathon_local_repo = hackathon_remote_repo # to simplify hackathon.20190315.get_raw_data() 19 | competition_tag = 'qck-hackathon-4' 20 | 21 | 22 | import getpass 23 | import os 24 | import shutil 25 | 26 | 27 | def init(i): 28 | """ 29 | Not to be called directly. 30 | """ 31 | 32 | return {'return':0} 33 | 34 | 35 | def store_experiment(i): 36 | """ 37 | Input: { 38 | json_file - filename/path of the JSON file that was generated by an experimental run 39 | team - your team name 40 | (experiment_name) - your preferred name for the experiment (auto-generated otherwise) 41 | } 42 | 43 | Output: { 44 | return - return code = 0, if successful 45 | > 0, if error 46 | (error) - error text if return > 0 47 | } 48 | """ 49 | 50 | json_input_filepath = i.get('json_file') 51 | if not json_input_filepath: 52 | pick_filepath_adict = { 'action': 'pick_a_filename', 53 | 'module_uoa': work['self_module_uoa'], 54 | 'directory': '.', 55 | 'file_suffix': '.json', 56 | } 57 | r=ck.access( pick_filepath_adict ) 58 | if r['return']==0: 59 | json_input_filepath = r['filepath'] 60 | else: 61 | r = ck.inp({'text': "Please provide the path to the experimental JSON output to be stored: "}) 62 | json_input_filepath = r['string'] 63 | 64 | team_name = i.get('team') 65 | if not team_name: 66 | r = ck.inp({'text': "Your team name: "}) 67 | team_name = r['string'] 68 | 69 | 70 | experiment_name = i.get('experiment_name') 71 | if not experiment_name: 72 | 73 | r=ck.get_current_date_time({}) 74 | if r['return']>0: return r 75 | timestamp = r['iso_datetime'].split('.')[0].replace(':', '_').replace('-', '_') # cut to seconds' resolution 76 | 77 | r = ck.load_json_file( {'json_file': json_input_filepath} ) 78 | if r['return']>0: return r 79 | json_contents = r['dict'] 80 | 81 | experiment_name = '-'.join( [team_name, timestamp, json_contents['problem_name'], json_contents['solution_function_name']] ) 82 | 83 | load_adict = { 'action': 'load', 84 | 'module_uoa': 'program', 85 | 'data_uoa': 'benchmark-helper', 86 | } 87 | r=ck.access( load_adict ) 88 | if r['return']>0: return r 89 | 90 | exp_generating_program_path = r['path'] 91 | 92 | json_output_filepath = os.path.join(exp_generating_program_path, 'solution_output.json') 93 | 94 | shutil.copyfile(json_input_filepath, json_output_filepath) 95 | 96 | 97 | ## Making sure hackathon_local_repo exists before we start recording there: 98 | # 99 | load_adict = { 'action': 'load', 100 | 'module_uoa': 'repo', 101 | 'data_uoa': hackathon_local_repo, 102 | } 103 | r=ck.access( load_adict ) 104 | if r['return']==16: # No hackathon_local_repo ? Create it then! 105 | add_adict = { 'action': 'add', 106 | 'module_uoa': 'repo', 107 | 'data_uoa': hackathon_local_repo, 108 | 'quiet': 'yes', 109 | } 110 | r=ck.access( add_adict ) 111 | if r['return']>0: return r 112 | 113 | ## The actual JSON data recording: 114 | # 115 | r = ck.access({ 'action': 'benchmark', 116 | 'module_uoa': 'program', 117 | 'data_uoa': 'benchmark-helper', 118 | 'cmd_key': 'default', 119 | 120 | 'repetitions': 1, 121 | 'iterations': 1, 122 | 'skip_stat_analysis': 'yes', 123 | 'process_multi_keys': [ '##choices#env#*' ], 124 | 'no_state_check': 'yes', 125 | 'no_compiler_description': 'yes', 126 | 'skip_calibration': 'yes', 127 | 'speed': 'no', 128 | 'energy': 'no', 129 | 'cpu_freq': '', 130 | 'gpu_freq': '', 131 | 'no_state_check': 'yes', 132 | 'skip_print_timers': 'yes', 133 | 134 | 'tags': ','.join(['qck', 'quantum', hackathon_tag, competition_tag]), 135 | 'meta': { 136 | 'team': team_name, 137 | 'hackathon': hackathon_tag, 138 | 'competition': competition_tag, 139 | }, 140 | 'record': 'yes', 141 | 'record_repo': hackathon_local_repo, 142 | 'record_uoa': experiment_name, 143 | }) 144 | if r['return']>0: return r 145 | 146 | record_cid = '{}:experiment:{}'.format(hackathon_local_repo, experiment_name) 147 | ck.out('The results have been recorded into {}\n'.format(record_cid)) 148 | 149 | return r 150 | 151 | 152 | def list_experiments(i): 153 | """ 154 | Input: { 155 | (repo_uoa) - experiment repository name (defaults to '*') 156 | (extra_tags) - extra tags to filter 157 | (add_meta) - request to return metadata with each experiment entry 158 | } 159 | 160 | Output: { 161 | return - return code = 0, if successful 162 | > 0, if error 163 | (error) - error text if return > 0 164 | } 165 | """ 166 | 167 | repo_uoa = i.get('repo_uoa', '*') 168 | extra_tags = i.get('extra_tags') 169 | all_tags = 'qck,' + hackathon_tag + ( ',' + extra_tags if extra_tags else '' ) 170 | add_meta = i.get('add_meta') 171 | 172 | search_adict = { 'action': 'search', 173 | 'repo_uoa': repo_uoa, 174 | 'module_uoa': 'experiment', 175 | 'data_uoa': '*', 176 | 'tags': all_tags, 177 | 'add_meta': add_meta, 178 | } 179 | r=ck.access( search_adict ) 180 | if r['return']>0: return r 181 | 182 | list_of_experiments = r['lst'] 183 | 184 | repo_to_names_list = {} 185 | for entry in list_of_experiments: 186 | repo_uoa = entry['repo_uoa'] 187 | data_uoa = entry['data_uoa'] 188 | if not repo_uoa in repo_to_names_list: 189 | repo_to_names_list[ repo_uoa ] = [] 190 | repo_to_names_list[ repo_uoa ] += [ data_uoa ] 191 | 192 | if i.get('out')=='con': 193 | for repo_uoa in repo_to_names_list: 194 | experiments_this_repo = repo_to_names_list[ repo_uoa ] 195 | ck.out( '{} ({}) :'.format(repo_uoa, len(experiments_this_repo) ) ) 196 | for data_uoa in experiments_this_repo: 197 | ck.out( '\t' + data_uoa ) 198 | ck.out( '' ) 199 | 200 | return {'return':0, 'lst': list_of_experiments, 'repo_to_names_list': repo_to_names_list} 201 | 202 | 203 | def pick_a_filename(i): 204 | """ 205 | Input: { 206 | (directory) - the directory name from which to pick a filename (defaults to '.' - current directory) 207 | (file_suffix) - the file type (defaults to '' - none) 208 | } 209 | 210 | Output: { 211 | return - return code = 0, if successful 212 | > 0, if error 213 | (error) - error text if return > 0 214 | } 215 | """ 216 | 217 | directory = i.get('directory', '.') 218 | file_suffix = i.get('file_suffix', '') 219 | 220 | 221 | filenames = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) and f.endswith(file_suffix)] 222 | 223 | select_adict = {'action': 'select_string', 224 | 'module_uoa': 'misc', 225 | 'options': filenames, 226 | 'question': 'Please select a filename', 227 | } 228 | r=ck.access( select_adict ) 229 | if r['return']>0: 230 | return r 231 | else: 232 | filename = r['selected_value'] 233 | filepath = os.path.join(directory, filename) 234 | 235 | return {'return':0, 'filename': filename, 'filepath': filepath} 236 | 237 | 238 | def pick_an_experiment(i): 239 | """ 240 | Input: { 241 | (repo_uoa) - experiment repository name (defaults to hackathon_local_repo, but can be overridden by '*') 242 | (extra_tags) - extra tags to filter 243 | } 244 | 245 | Output: { 246 | return - return code = 0, if successful 247 | > 0, if error 248 | (error) - error text if return > 0 249 | } 250 | """ 251 | 252 | repo_uoa = i.get('repo_uoa', hackathon_local_repo) 253 | extra_tags = i.get('extra_tags') 254 | 255 | list_exp_adict = { 'action': 'list_experiments', 256 | 'module_uoa': work['self_module_uoa'], 257 | 'repo_uoa': repo_uoa, 258 | 'extra_tags': extra_tags, 259 | } 260 | r=ck.access( list_exp_adict ) 261 | if r['return']>0: return r 262 | 263 | if len(r['lst'])==0: 264 | return {'return':1, 'error':'No experiments to choose from - please relax your filters'} 265 | 266 | all_experiment_names = [ '{repo_uoa}:{module_uoa}:{data_uoa}'.format(**entry_dict) for entry_dict in r['lst']] 267 | 268 | number_of_experiments = len(all_experiment_names) 269 | select_adict = {'action': 'select_string', 270 | 'module_uoa': 'misc', 271 | 'options': all_experiment_names, 272 | 'default': str(number_of_experiments-1), 273 | 'question': 'Please select the experiment entry', 274 | } 275 | r=ck.access( select_adict ) 276 | if r['return']>0: 277 | return r 278 | else: 279 | cid = r['selected_value'] 280 | 281 | return {'return':0, 'cid': cid} 282 | 283 | 284 | def upload(i): 285 | """ 286 | Input: { 287 | (cids[]) - CIDs of entries to upload (interactive by default) 288 | OR 289 | (repo_uoa) - experiment repository name (defaults to hackathon_local_repo, but can be overridden by '*') 290 | (extra_tags) - extra tags to filter 291 | } 292 | 293 | Output: { 294 | return - return code = 0, if successful 295 | > 0, if error 296 | (error) - error text if return > 0 297 | } 298 | """ 299 | 300 | cids = i.get('cids') 301 | 302 | if len(cids)==0: 303 | repo_uoa = i.get('repo_uoa', hackathon_local_repo) 304 | extra_tags = i.get('extra_tags') 305 | 306 | pick_exp_adict = { 'action': 'pick_an_experiment', 307 | 'module_uoa': work['self_module_uoa'], 308 | 'repo_uoa': repo_uoa, 309 | 'extra_tags': extra_tags, 310 | } 311 | r=ck.access( pick_exp_adict ) 312 | if r['return']>0: return r 313 | cids = [ r['cid'] ] 314 | 315 | target_server_uoa = 'remote-ck' 316 | transfer_adict = { 'action': 'transfer', 317 | 'module_uoa': 'misc', 318 | 'cids': cids, # 'ck transfer' will perform its own cids->xcids parsing 319 | 'target_server_uoa': target_server_uoa, 320 | 'target_repo_uoa': hackathon_remote_repo, 321 | } 322 | r=ck.access( transfer_adict ) 323 | if r['return']>0: return r 324 | 325 | ck.out('The entries {} have been uploaded to {}/{}'.format(cids, target_server_uoa, hackathon_remote_repo)) 326 | return {'return': 0} 327 | 328 | -------------------------------------------------------------------------------- /module/challenge.vqe/README.md: -------------------------------------------------------------------------------- 1 | # 1st Open Quantum Collective Knowledge Challenge 2 | 3 | We are excited to announce the 1st Open Quantum Collective Knowledge (QCK) 4 | Challenge! In this challenge, you are invited to find the closest 5 | approximation to the ground state energy of a chemical molecule by running the 6 | hybrid (quantum+classical) VQE algorithm on either a physical device or a 7 | software simulator. Please read our engaging [VQE and 8 | You](https://github.com/ctuning/ck-quantum/wiki/VQE-and-You) guide for more 9 | information on VQE. 10 | 11 | In each experiment, you can select the **target quantum device** to run 12 | the experiment on, the **molecule** to work with (the task), the **optimizer 13 | method** (the classical component of VQE), the **ansatz function** (the quantum 14 | component of VQE), and tune some parameters of the above. 15 | 16 | Once your experiment is completed, you can check the [Time-To-Solution 17 | evaluation metric](#measure) (the lower the better), [upload your 18 | results](#upload) to the QCK server and finally view them on the [interactive 19 | QCK dashboard](http://cknowledge.org/dashboard/challenge.vqe)! 20 | 21 | Importantly, via the dashboard you can quickly check solutions contributed by 22 | others and draw inspiration for further improvements. For example, you may 23 | notice that someone else has made significant progress by using an interesting 24 | quantum ansatz. You are invited, indeed encouraged, to combine that ansatz with 25 | your own ideas e.g. on designing a classical optimizer! That's what we mean by 26 | Quantum **Collective** Knowledge! (Please just provide a reference if you build 27 | upon another solution.) 28 | 29 | From our [QCK hackathon experience](https://riverlane.io/news/river-lane-research-and-dividiti-hold-western-europes-first-quantum-computing-hackathon/), you can start contributing in under an hour by [experimenting with VQE parameters](#explore_parameters) and make a valuable contribution in under a day by [experimenting with VQE plugins](#explore_plugins)! 30 | 31 | 32 | To the best of our knowledge, the 1st QCK Challenge is indeed the **first** 33 | challenge of its kind. Therefore, please treat it as work in progress, where 34 | all comments and contributions are very welcome and valuable! If anything at 35 | all is unclear or you spot a clear opportunity for improvement, please (please! 36 | please!!) open a [GitHub issue](https://github.com/ctuning/ck-quantum/issues), or 37 | join our [CK Slack workspace](https://collective-knowledge.slack.com) 38 | `#quantum` channel) and ask your question there! 39 | 40 | We are thrilled about collaboratively solving this and future challenges, and 41 | thus making practical and scalable Quantum Computing a reality. Thank you so 42 | much for joining us and... best of luck! 43 | 44 | ### Small print 45 | - The 1st Open QCK challenged is brought to you by [dividiti](http://dividiti.com) and [Riverlane](http://riverlane.io), with generous support from [Innovate UK](http://innovateuk.org). 46 | - All contributions to QCK are accepted under the [standard CK licence](https://github.com/ctuning/ck/blob/master/LICENSE.txt) (3-clause BSD). 47 | - We gratefully acknowledge support of [IBM](https://www.research.ibm.com/ibm-q/) and [Rigetti](https://www.rigetti.com/) in preparing and running this challenge. 48 | - You can use Rigetti's [Forest SDK](https://www.rigetti.com/forest) under their [terms](https://www.rigetti.com/sdk-terms) and [Quantum Cloud Services](https://www.rigetti.com/qcs) (QCS) under their [terms of service](https://www.rigetti.com/sites/default/files/2018-11/RigettiTermsOfService.pdf). In addition, Rigetti [kindly expand these terms](https://github.com/ctuning/ck-quantum/blob/master/module/challenge.vqe/Rigetti%20--%20Benchmarking%20License%20--%2018.12.16.pdf) to allow you to use QCK for the purpose of benchmarking and publicity in this challenge. 49 | - You can use IBM's [Qiskit SDK](https://qiskit.org/) and [QX platforms](https://quantumexperience.ng.bluemix.net/qx) under their respective terms. 50 | 51 | 52 | ## Getting started 53 | 54 | At the moment we are collaborating with IBM and Rigetti to provide access to their hardware and software platforms 55 | for your experiments. As the challenge goes on, we may be able to support more providers. 56 | 57 | ### Installation instructions 58 | | IBM Quantum Experience | Rigetti Forest | 59 | |-|-| 60 | | [Sign up](https://quantumexperience.ng.bluemix.net/qx/signup) and copy your API token from the ["Advanced"](https://quantumexperience.ng.bluemix.net/qx/account/advanced) tab (click on the "Regenerate" button first). | [Download the Forest SDK](https://www.rigetti.com/forest). | 61 | | Follow [CK-Qiskit instructions](https://github.com/ctuning/ck-qiskit) to complete and test your setup. | Follow [CK-Rigetti instructions](https://github.com/ctuning/ck-rigetti) to complete and test your setup. Once you are done, do not kill the local QVM server - you will need it during VQE experiments as well! | 62 | 63 | ### Supported values 64 | 65 | | Choice | IBM Quantum Experience | Rigetti Forest | 66 | |-|-|-| 67 | | `` | `ibm` | `rigetti` | 68 | | `` | `qasm_simulator` (local simulator),
`ibmq_qasm_simulator` (remote simulator),
`ibmqx4` (a 5-qubit remote device),
`ibmq_16_melbourne` (a 16-qubit remote device) | `QVM` (local simulator) | 69 | | `` | `tiny1`, `tiny2`,
`universal3`, `universal4`,
`reduced_universal5`, `universal6` | `tiny1`, `tiny2`
| 70 | | `` | `cobyla`, `nelder_mead`,
`random_sampler`, `custom` | `cobyla`, `nelder_mead`,
`random_sampler`, `custom` | 71 | 72 | ## Select the VQE problem to solve - the Hamiltonian 73 | 74 | The problem to be solved (Hydrogen or Helium) is defined by a Hamiltonian plugin, implemented as a standard CK environment. 75 | You can pre-install one or both of them. If more than one is pre-installed, CK will interactively ask you to resolve the ambiguity 76 | when launching the experiments. 77 | 78 | Check which Hamiltonians are installed: 79 | ``` 80 | $ ck show env --tags=quantum,hamiltonian 81 | ``` 82 | 83 | To install a Hamiltonian, run: 84 | ``` 85 | $ ck detect soft --tags=quantum,hamiltonian 86 | ``` 87 | and interactively select from the menu. 88 | 89 | Remove a Hamiltonian (Helium in this case): 90 | ``` 91 | $ ck clean env --tags=quantum,hamiltonian.helium 92 | ``` 93 | **NB:** Separate tags with commas, not spaces. Use dot in `hamiltoniam.helium` (a sigle tag). 94 | 95 | ## Run VQE once 96 | 97 | In order to run VQE we'll need point the system to one optimizer plugin and one ansatz plugin. 98 | While the optimizer (being a classical component of VQE) is provider-neutral, 99 | the ansatz function has to be written with a specific provider in mind. 100 | 101 | Here is how to do deploy one plugin of each kind to get VQE running: 102 | ``` 103 | $ ck deploy_ansatz vqe --provider= --value= 104 | $ ck deploy_optimizer vqe --value= 105 | ``` 106 | 107 | Then, launch VQE with the deployed optimizer and ansatz: 108 | ``` 109 | $ ck run vqe --provider= --device= --repetitions=1 110 | ``` 111 | 112 | For example, to run VQE on Rigetti's local simulator, try: 113 | ``` 114 | $ ck deploy_optimizer vqe --value=cobyla 115 | $ ck deploy_ansatz vqe --provider=rigetti --value=tiny2 116 | $ ck run vqe --provider=rigetti --device=QVM --repetitions=1 117 | ``` 118 | 119 | 120 | ## Easy VQE exploration via parameters 121 | 122 | You can start exploring VQE by varying one or more of the following parameters: 123 | ``` 124 | $ ck run vqe \ 125 | --provider= \ 126 | --device= \ 127 | --sample_size= \ 128 | --max_iterations= \ 129 | --start_param_value= \ 130 | --repetitions= 131 | ``` 132 | where: 133 | - consult the table above for the supported values of `` and ``. 134 | - ``: the number of times to evaluate the Hamiltonian function on the quantum device ("sampling resolution") per optimizer iteration; by default, `100`. 135 | - ``: the maximum number of optimizer iterations ("iteration limit"); by default, `80`. 136 | - ``: the starting value of each optimizer's parameter (can be a float number or the word `random`); by default, `random`. 137 | - ``: the number of times to repeat the experiment with the same parameters; by default, `3`. 138 | 139 | Once you start an experiment, you can [monitor its convergence](#monitor). (Check the [online dashboard](http://cknowledge.org/dashboard/challenge.vqe) for the exact ground state energy for your chosen molecule.) 140 | 141 | When it completes, you can [measure the Time-To-Solution metric](#measure), 142 | [locate the experimenal results on disk](#locate) and [upload them to the QCK server](#upload). 143 | 144 | **TODO:** We will soon provide instructions on how to launch the dashboard locally on your collected experimental data. 145 | 146 | 147 | ## Monitor the convergence process 148 | 149 | To monitor the convergence process, run an ASCII-graphics program in a separate terminal window: 150 | ``` 151 | $ ck run program:visualize-convergence --env.VQE_QUANTUM_PROVIDER= 152 | ``` 153 | 154 | 155 | ## Measure the Time-To-Solution metric 156 | 157 | The goal of the challenge is to minimize the [Time-To-Solution](https://github.com/ctuning/ck-quantum/wiki/Measuring-Performance) metric (TTS). 158 | As TTS is proportional to `sample_size`, exploring lower values of `sample_size` may be sensible. 159 | At the same time, a low number of `repetitions` may make it hard to demonstrate solution convergence with a high probability. 160 | For experiments to be uploaded, we recommend using at least 10 repetitions on the simulators and 3-5 repetitions on the hardware. 161 | 162 | Run the following and select an experiment entry to compute TTS for: 163 | ``` 164 | $ ck time_to_solution vqe --delta=0.015 --prob=0.95 165 | ``` 166 | 167 | To compute TTS for a particular experiment, supply its entry name e.g.: 168 | ``` 169 | $ ck time_to_solution vqe --delta=0.015 --prob=0.8 \ 170 | local:experiment:anton-2018_10_05T12_18_19-local_qasm_simulator-ansatz.universal4-optimizer.cobyla-samples.100-repetitions.1 171 | ``` 172 | 173 | 174 | ## Advanced VQE exploration via plugins 175 | 176 | Congratulations if you have reached this point in the challenge! Now that you know the basic mechanics, you may wish to design your own [classical optimizer](https://github.com/ctuning/ck-quantum/wiki/Classical-Optimisation) or [quantum ansatz circuit](https://github.com/ctuning/ck-quantum/wiki/Quantum-Ansatz-Circuits)! For this, you will need to learn a bit how to work with [plugins in general](#explore_plugins_basics), and then with [optimizer plugins](#explore_plugins_optimizer) and/or [ansatz plugins](#explore_plugins_ansatz), depending on your interests and available time. 177 | 178 | 179 | ### Check which plugins are deployed (both `soft` and `env` entries) 180 | ``` 181 | $ ck search --tags=deployed 182 | ``` 183 | 184 | ### Removing plugins 185 | 186 | #### Removing all deployed plugins (unrestricted) 187 | ``` 188 | $ ck cleanup vqe 189 | ``` 190 | 191 | #### Removing all deployed optimizer plugins 192 | ``` 193 | $ ck cleanup vqe --type=optimizer 194 | ``` 195 | 196 | #### Removing all deployed ansatz plugins 197 | ``` 198 | $ ck cleanup vqe --type=ansatz 199 | ``` 200 | 201 | #### Removing all deployed ansatz plugins for the given provider 202 | ``` 203 | $ ck cleanup vqe --type=ansatz --provider= 204 | ``` 205 | 206 | 207 | ### Working with optimizer plugins 208 | 209 | #### Select an optimizer plugin to deploy 210 | ``` 211 | $ ck deploy_optimizer vqe 212 | ``` 213 | 214 | #### Locate and edit the deployed optimizer plugin (use your favourite text editor instead of `vi`) 215 | ``` 216 | $ ck plugin_path vqe --type=optimizer 217 | $ vi `ck plugin_path vqe --type=optimizer` 218 | ``` 219 | **NB:** The optimizer plugin is written in Python. 220 | It is expected to contain only one top-level function. 221 | If you need more, please define them within the top-level one. 222 | 223 | 224 | ### Working with ansatz plugins 225 | 226 | #### Select an ansatz plugin to deploy 227 | ``` 228 | $ ck deploy_ansatz vqe 229 | ``` 230 | 231 | #### Locate and edit the deployed ansatz plugin (use your favourite text editor instead of `vi`) 232 | ``` 233 | $ ck plugin_path vqe --type=ansatz 234 | $ vi `ck plugin_path vqe --type=ansatz` 235 | ``` 236 | **NB:** The ansatz plugin is written in Python. 237 | It is expected to contain only one top-level function. 238 | If you need more, please define them within the top-level one. 239 | 240 | **TODO:** The ansatz plugin is vendor-specific. We will shortly provide IBM- and Rigetti-specific circuit templates. 241 | 242 | #### Visualize the ansatz circuit (use your favourite image viewer instead of `display`) 243 | 244 | **NB:** Currently only supported for IBM-compatible ansatz circuits. 245 | 246 | **NB:** If unsure about the image viewer, try `eog` or `eom` on Linux, `open` on macOS. 247 | 248 | ``` 249 | $ ck run program:visualize-ansatz 250 | $ display `ck find program:visualize-ansatz`/ansatz_circuit.png 251 | ``` 252 | 253 | 254 | ## Locate the experimental results 255 | 256 | You can list all your experimental entries and locate them on disk as follows: 257 | ``` 258 | $ ck search local:experiment:* --tags=qck 259 | $ ck find local:experiment:* 260 | ``` 261 | 262 | 263 | ## Upload your experimental results to Quantum Collective Knowledge 264 | 265 | When you have an experiment you would like to share, run: 266 | ``` 267 | $ ck upload vqe --team=schroedinger-cat-herders 268 | ``` 269 | and select the experiment from the list. We recommend uploading all experiments on the hardware and most successful experiments on the simulators. 270 | 271 | Alternatively, upload one or more experiments by using their entries e.g.: 272 | ``` 273 | $ ck upload vqe --team=bell-state-ringers \ 274 | local:experiment:my_experiment_5 local:experiment:my_experiment_13 275 | ``` 276 | -------------------------------------------------------------------------------- /module/challenge.vqe/module.py: -------------------------------------------------------------------------------- 1 | # 2 | # Collective Knowledge () 3 | # 4 | # 5 | # 6 | # 7 | # Developer: 8 | # 9 | 10 | cfg={} # Will be updated by CK (meta description of this module) 11 | work={} # Will be updated by CK (temporal data) 12 | ck=None # Will be updated by CK (initialized CK kernel) 13 | 14 | import os 15 | import sys 16 | import re 17 | 18 | import pandas as pd 19 | import numpy as np 20 | 21 | 22 | ############################################################################## 23 | # Initialize module 24 | 25 | def init(i): 26 | """ 27 | 28 | Input: {} 29 | 30 | Output: { 31 | return - return code = 0, if successful 32 | > 0, if error 33 | (error) - error text if return > 0 34 | } 35 | 36 | """ 37 | return {'return':0} 38 | 39 | 40 | ############################################################################## 41 | # get raw data for repo-widget 42 | 43 | def get_raw_data(i): 44 | """ 45 | Input: { 46 | } 47 | 48 | Output: { 49 | return - return code = 0, if successful 50 | > 0, if error 51 | (error) - error text if return > 0 52 | } 53 | 54 | """ 55 | 56 | def get_experimental_results(repo_uoa, remote_repo_uoa, tags='qck', module_uoa='experiment'): 57 | 58 | addr_part = { 59 | 'repo_uoa':repo_uoa, 60 | 'remote_repo_uoa':remote_repo_uoa, 61 | 'module_uoa':module_uoa, 62 | } 63 | 64 | search_adict = { 65 | 'action':'search', 66 | 'tags':tags, 67 | } 68 | search_adict.update( addr_part ) 69 | 70 | r = ck.access( search_adict ) 71 | if r['return']>0: 72 | print('Error: %s' % r['error']) 73 | exit(1) 74 | experiments = r['lst'] 75 | 76 | dfs = [] 77 | for experiment in experiments: 78 | 79 | list_points_adict = { 80 | 'action': 'list_points', 81 | 'data_uoa': experiment['data_uoa'], 82 | } 83 | list_points_adict.update( addr_part ) 84 | r = ck.access( list_points_adict ) 85 | if r['return']>0: 86 | print('Error: %s' % r['error']) 87 | exit(1) 88 | 89 | # Get all the parameters from meta.json -> "meta" 90 | mmeta = r['dict']['meta'] 91 | 92 | # Expecting all of this data to be present for the Open Challenge: 93 | team = mmeta.get('team', r['dict'].get('team', 'UNKNOWN_TEAM') ) 94 | molecule = mmeta.get('hamiltonian', 'UNKNOWN_MOLECULE') 95 | vendor = mmeta.get('provider', 'UNKNOWN_PROVIDER') 96 | 97 | # For each point. 98 | for point_id in r['points']: 99 | load_point_adict = { 'action': 'load_point', 100 | 'data_uoa': experiment['data_uoa'], 101 | 'point': point_id, 102 | } 103 | load_point_adict.update( addr_part ) 104 | r=ck.access( load_point_adict ) 105 | if r['return']>0: return r 106 | 107 | point_data_raw = r['dict']['0001'] 108 | choices = point_data_raw['choices'] 109 | characteristics_list = point_data_raw['characteristics_list'] 110 | num_repetitions = len(characteristics_list) 111 | data = [ 112 | { 113 | # features 114 | 'platform': characteristics['run'].get('vqe_input', {}).get('q_device_name', 'unknown').lower(), 115 | 'molecule': molecule, 116 | 'vendor': vendor, 117 | # choices 118 | 'minimizer_method': characteristics['run'].get('vqe_input', {}).get('minimizer_method', 'n/a'), 119 | 'minimizer_options': characteristics['run'].get('vqe_input', {}).get('minimizer_options', {'maxfev':-1}), 120 | 'minimizer_src': characteristics['run'].get('vqe_input', {}).get('minimizer_src', ''), 121 | 'ansatz_method': characteristics['run'].get('vqe_input', {}).get('ansatz_method', ''), 122 | 'ansatz_src': characteristics['run'].get('vqe_input', {}).get('ansatz_src', ''), 123 | 'sample_number': characteristics['run'].get('vqe_input', {}).get('sample_number','n/a'), 124 | 'max_iterations': choices['env'].get('VQE_MAX_ITERATIONS', -1), 125 | # statistical repetition 126 | 'repetition_id': repetition_id, 127 | # runtime characteristics 128 | 'run': characteristics['run'], 129 | 'report': characteristics['run'].get('report', {}), 130 | 'vqe_output': characteristics['run'].get('vqe_output', {}), 131 | } 132 | for (repetition_id, characteristics) in zip(range(num_repetitions), characteristics_list) 133 | if len(characteristics['run']) > 0 134 | ] 135 | 136 | index = [ 137 | 'platform', 'team', 'minimizer_method', 'sample_number', 'max_iterations', 'point', 'repetition_id', 'molecule', 'ansatz_method', 'vendor' 138 | ] 139 | 140 | for datum in data: 141 | datum['team'] = team 142 | datum['point'] = point_id 143 | datum['success'] = datum.get('vqe_output',{}).get('success',False) 144 | datum['nfev'] = np.int64(datum.get('vqe_output',{}).get('nfev',-1)) 145 | datum['nit'] = np.int64(datum.get('vqe_output',{}).get('nit',-1)) 146 | datum['fun'] = np.float64(datum.get('vqe_output',{}).get('fun',0)) 147 | datum['fun_validated'] = np.float64(datum.get('vqe_output',{}).get('fun_validated',0)) 148 | datum['fun_exact'] = np.float64(datum.get('vqe_output',{}).get('fun_exact',0)) 149 | datum['total_seconds'] = np.float64(datum.get('report',{}).get('total_seconds',0)) 150 | datum['total_q_seconds'] = np.float64(datum.get('report',{}).get('total_q_seconds',0)) 151 | datum['total_q_shots'] = np.int64(datum.get('report',{}).get('total_q_shots',0)) 152 | datum['max_iterations'] = np.int64(datum.get('max_iterations',-1)) 153 | for key in index: 154 | datum['_' + key] = datum[key] 155 | datum['_ansatz_src'] = datum['ansatz_src'] 156 | datum['_minimizer_src'] = datum['minimizer_src'] 157 | 158 | # Construct a DataFrame. 159 | df = pd.DataFrame(data) 160 | df = df.set_index(index) 161 | # Append to the list of similarly constructed DataFrames. 162 | dfs.append(df) 163 | if dfs: 164 | # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). 165 | result = pd.concat(dfs) 166 | result.sort_index(ascending=True, inplace=True) 167 | else: 168 | # Construct a dummy DataFrame the success status of which can be safely checked. 169 | result = pd.DataFrame(columns=['success']) 170 | return result 171 | 172 | # Merge experimental results from the same team with the same parameters 173 | # (minimizer_method, sample_number, max_iterations) and minimizer source. 174 | def merge_experimental_results(df): 175 | dfs = [] 176 | df_prev = None 177 | for index, row in df.iterrows(): 178 | # Construct a DataFrame. 179 | df_curr = pd.DataFrame(row).T 180 | # Check if this row is similar to the previous row. 181 | if df_prev is not None: # if not the very first row 182 | if df_prev.index.levels[:5]==df_curr.index.levels[:5]: # if the indices match for all but the last two levels 183 | if df_prev.index.levels[5]!=df_curr.index.levels[5]: # if the experiments are different 184 | if df_prev['minimizer_src'].values==df_curr['minimizer_src'].values and df_prev['ansatz_src'].values==df_curr['ansatz_src'].values: # if the minimizer and ansatz sources are the same 185 | print('[Info] Merging experiment:') 186 | print(df_curr.index.levels) 187 | print('[Info] into:') 188 | print(df_prev.index.levels) 189 | print('[Info] as:') 190 | # df_curr.index = df_prev.index.copy() # TODO: increment repetition_id 191 | df_curr.index = pd.MultiIndex.from_tuples([(x[0],x[1],x[2],x[3],x[4],x[5],x[6]+1,x[7],x[8],x[9]) for x in df_prev.index]) 192 | print(df_curr.index.levels) 193 | print 194 | else: 195 | print('[Warning] Cannot merge experiments as the minimizer or ansatz sources are different (previous vs current):') 196 | print(df_prev.index.levels) 197 | print 198 | print(df_curr.index.levels) 199 | print 200 | # else: 201 | # print('[Info] Keeping experiments separate:') 202 | # print(df_prev.index.levels) 203 | # print(df_curr.index.levels) 204 | # print 205 | # Append to the list of similarly constructed DataFrames. 206 | dfs.append(df_curr) 207 | # Prepare for next iteration. 208 | df_prev = df_curr 209 | 210 | # Concatenate all thus constructed DataFrames (i.e. stack on top of each other). 211 | result = pd.concat(dfs) 212 | result.index.names = df.index.names 213 | result.sort_index(ascending=True, inplace=True) 214 | 215 | return result 216 | 217 | 218 | debug_output = i.get('out')=='con' 219 | repo_uoa = i.get('repo_uoa', 'ck-quantum-challenge-vqe') 220 | remote_repo_uoa = i.get('remote_repo_uoa', '') 221 | 222 | # prepare table 223 | df = get_experimental_results(repo_uoa=repo_uoa, remote_repo_uoa=remote_repo_uoa) 224 | 225 | convergence_data = [] 226 | 227 | def to_value(i): 228 | if type(i) is np.ndarray: 229 | return i.tolist() 230 | 231 | if isinstance(i, np.int64): 232 | return int(i) 233 | 234 | return i 235 | 236 | props = [ 237 | '_platform', 238 | '_team', 239 | '_minimizer_method', 240 | '_sample_number', 241 | '_max_iterations', 242 | '_point', 243 | '_repetition_id', 244 | 'fun', 245 | 'fun_exact', 246 | 'fun_validated', 247 | 'nfev', 248 | 'nit', 249 | 'success', 250 | 'total_q_seconds', 251 | 'total_q_shots', 252 | 'total_seconds', 253 | '_ansatz_method', 254 | '_vendor', 255 | '_molecule', 256 | ] 257 | 258 | if debug_output: 259 | ck.out("Convergence data:") 260 | 261 | for record in df.to_dict(orient='records'): 262 | row = {} 263 | for prop in props: 264 | row[prop] = to_value(record.get(prop, '')) 265 | 266 | energies = [ iteration['energy'] for iteration in record['report']['iterations'] ] 267 | fevs = list(range(len(energies))) 268 | last_energy = energies[-1] 269 | minimizer_method = record.get('_minimizer_method', '') 270 | last_fev = row['nfev']-1 if minimizer_method=='my_cobyla' or 'my_nelder_mead' else row['nfev'] 271 | 272 | row['__energies'] = energies 273 | row['__fevs'] = fevs 274 | 275 | row['##data_uid'] = "{}:{}".format(record['_point'], record['_repetition_id']) 276 | 277 | row['_ansatz_src'] = { 278 | 'title': record.get('_ansatz_method','Show'), 279 | 'cmd': record['_ansatz_src'] 280 | } 281 | 282 | row['_minimizer_src'] = { 283 | 'title': record.get('_minimizer_method','Show'), 284 | 'cmd': record['_minimizer_src'] 285 | } 286 | 287 | convergence_data.append(row) 288 | if debug_output: 289 | ck.out(str(row)) 290 | 291 | # prepare metrics data 292 | df_m = merge_experimental_results(df) 293 | 294 | tts_data = [] 295 | names_no_repetitions = [ n for n in df_m.index.names if n != 'repetition_id' ] 296 | 297 | if debug_output: 298 | ck.out("\nTime-to-solution data:") 299 | 300 | for index, group in df_m.groupby(level=names_no_repetitions): 301 | runs = [] 302 | 303 | for run in group['run']: 304 | run_t = {} 305 | run_t['report'] = run['report'] 306 | run_t['vqe_input'] = run['vqe_input'] 307 | run_t['vqe_output'] = run['vqe_output'] 308 | runs.append(run_t) 309 | 310 | data = {} 311 | data['runs'] = runs 312 | data['num_repetitions'] = len(group) 313 | 314 | meta = {} 315 | meta.update({ k : v for (k, v) in zip(names_no_repetitions, index) }) 316 | 317 | for key in names_no_repetitions: 318 | data['_' + key] = to_value(meta[key]) 319 | 320 | data['##data_uid'] = to_value(meta['point']) 321 | 322 | tts_data.append(data) 323 | if debug_output: 324 | ck.out(str(data)) 325 | 326 | return {'return':0, 'full_table':convergence_data, 'metrics_table':tts_data} 327 | 328 | 329 | ############################################################################## 330 | # get raw config for repo widget 331 | 332 | def get_raw_config(i): 333 | """ 334 | Input: { 335 | } 336 | 337 | Output: { 338 | return - return code = 0, if successful 339 | > 0, if error 340 | (error) - error text if return > 0 341 | } 342 | 343 | """ 344 | 345 | data_config = cfg['data_config'] 346 | data_config['return'] = 0 347 | 348 | return data_config 349 | -------------------------------------------------------------------------------- /module/hackathon.20190127/README.md: -------------------------------------------------------------------------------- 1 | # 3rd Quantum Collective Knowledge Hackathon, Paris, 27 January 2019 2 | 3 | * [Meetup page](https://www.meetup.com/Paris-Quantum-Computing-Technologies/events/256367871) 4 | * [ Presentation slides](https://docs.google.com/presentation/d/1DGyu1EGJn8d3xS2VcgQlvthQGF7ytx9VoGV5xUmGlyk/edit?usp=sharing) 5 | 6 | 7 | 1. Getting started 8 | 1. [Option A : Dockerless installation](#getting_started) 9 | 1. [Option B : using a Docker container](#getting_started_docker) 10 | 1. [Workflow overview](#workflow_overview) 11 | 1. [Problems](#problems) 12 | 1. [Problem 0](#problem0) 13 | 1. [Problem 1](#problem1) 14 | 1. [Problem 2](#problem2) 15 | 1. [Problem 3](#problem3) 16 | 1. [Problem 4](#problem4) 17 | 1. [Problem 5](#problem5) 18 | 1. [Sharing solutions](#sharing_solutions) 19 | 20 | 21 | ## Getting started - option A (directly installing software on your computer) 22 | 23 | ### Installing Python 3.6 24 | 25 | ``` 26 | $ python3 --version # skip the following session if Python 3.6.x is already installed 27 | ``` 28 | 29 | #### Ubuntu/Debian 30 | ``` 31 | $ sudo apt-get install python3 python3-pip 32 | ``` 33 | 34 | #### MacOS X 35 | First, install **[brew](https://brew.sh)** if missing. Then: 36 | ``` 37 | $ brew update 38 | $ brew unlink python 39 | $ brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb 40 | $ export PATH=/usr/local/opt/python/bin:$PATH # we suggest to put this into your .bashrc config file to avoid repeating in every terminal window 41 | ``` 42 | 43 | #### Windows 44 | Use [the official downloads and instructions](https://www.python.org/downloads/windows). 45 | 46 | 47 | ### Installing Qiskit and other dependencies to userspace 48 | ``` 49 | $ python3 -m pip install marshmallow==2.15.0 qiskit==0.7 pandas==0.23.4 sklearn --user 50 | ``` 51 | 52 | ### Obtaining the hackathon repository 53 | 54 | Choose a directory where you would like to place [the hackathon repository](https://github.com/riverlane/paris), 55 | change to that directory and run: 56 | ``` 57 | $ git clone https://github.com/riverlane/paris 58 | ``` 59 | In what follows, we refer to files in this repository (e.g. `evaluate.py`), so make sure you stay in that directory. 60 | 61 | Alternatively, you can download this repository as a [zip](https://github.com/riverlane/paris/archive/master.zip) file. 62 | We suggest sticking to using `git`, however, as we may need to provide updates during the hackathon (which you will then be able to obtain via `git pull`). 63 | 64 | ### Playing with quantum circuit design 65 | 66 | To help you learn how quantum circuits work, we have provided 67 | [a primer Qiskit program](https://github.com/riverlane/paris/blob/master/qiskit_primer.py): 68 | ``` 69 | $ python3 qiskit_primer.py 70 | ``` 71 | Feel free to modify it to study the effects of applying quantum circuits to initial states. 72 | 73 | ### Installing the [Collective Knowledge](http://cknowledge.org) framework (CK) with the Quantum CK repository 74 | 75 | 1. Follow [these instructions](https://github.com/ctuning/ck#installation). 76 | 2. Pull the `ck-quantum` repository and its dependencies: 77 | ``` 78 | $ ck pull repo:ck-quantum 79 | ``` 80 | 81 | 82 | ## Getting started - option B (using a Docker container tailor-made for this hackathon) 83 | 84 | You can check how to install Docker on your system [here](https://docs.docker.com/install). 85 | 86 | ### Run a Docker container from the cTuning Docker Hub: 87 | ``` 88 | $ docker run -it --publish 3355:3344 ctuning/qck-hackathon.20190127 89 | ``` 90 | 91 | ### Build your own Docker image: 92 | ``` 93 | $ docker build --tag hackathon.20190127 https://raw.githubusercontent.com/ctuning/ck-quantum/master/docker/hackathon.20190127/Dockerfile 94 | ``` 95 | 96 | ### Run a Docker container from this image: 97 | ``` 98 | $ docker run -it --publish 3355:3344 hackathon.20190127 99 | ``` 100 | 101 | Please note that some functions will have to be run differently if you are using a Docker container. 102 | 103 | 104 | 105 | ## Workflow overview 106 | 107 | The task repository contains several `*.pyz` files specifying each problem to 108 | solve. Each of these contains a set of training data - quantum state vectors 109 | labelled by a parity (-1 or 1). For each problem, you are asked to compose a 110 | quantum circuit which, when applied to each state vector in a test set, can 111 | predict the correct parity label as accurately as possible. 112 | 113 | In the first session of the day, we will help you set up your computers and walk through solving [Problem 0](#problem0). 114 | We will also show you how to [share your solutions](#sharing_solutions) by using [Collective Knowledge](http://cknowledge.org). 115 | Next, you will be free to attempt the remaining Problems 1-5 on your own. Each problem is outlined below. 116 | 117 | To test your solutions, use `evaluate.py` e.g. as follows: 118 | ``` 119 | $ python3 evaluate.py --fun discrete_solver --stats --problem discrete_problem1 -n 4 120 | ``` 121 | This runs your function `discrete_solver` on `discrete_problem1`, using 4 vectors for the training set. 122 | Specific details are outlined below for each problem. 123 | 124 | If you use the non-quantum solutions like `classical_svm`, you may want to use more training examples. 125 | The parameter `-n` controls this. 126 | 127 | To build quantum circuits, we will use the [Qiskit](https://qiskit.org/) simulator. 128 | Further documentation and examples can be found [here](https://qiskit.org/documentation/summary_of_quantum_operations.html). 129 | 130 | For a good overview of quantum circuits and logic gates, check this 131 | [wikipedia page](https://en.wikipedia.org/wiki/Quantum_logic_gate). 132 | 133 | 134 | ## Problems 135 | 136 | 137 | ### Problem 0 (`discrete_problem0`) 138 | 139 | Number of qubits: 1 140 | 141 | There are two state vectors labelled by `1` and `-1`. We need to apply to the 142 | single qubit a quantum circuit that will transform its state to one that will 143 | retrieve the correct labels when measured. 144 | 145 | You can look at `manual_solver.py` in the 146 | [`example_solutions`](https://github.com/riverlane/paris/tree/master/example_solutions) 147 | directory, and try to come up with a circuit that does this. 148 | (**Hint:** Applying a [Hadamard gate](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_(H)_gate) to 149 | each state should do this.) 150 | 151 | To run the solver, type the command: 152 | ``` 153 | $ python3 evaluate.py --fun manual_solver --problem discrete_problem0 154 | ``` 155 | 156 | 157 | ### Problem 1 (`discrete_problem1`) 158 | 159 | Number of qubits: 2 160 | 161 | Now we have two qubits! 162 | The circuit consists of only two gates, one gate for each qubit. 163 | We promise the gates are combinations of [X](https://en.wikipedia.org/wiki/Quantum_logic_gate#Pauli-X_gate) and [H](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_(H)_gate). Your job is to work out which ones. 164 | 165 | You can look at `manual_solver.py`, and try to come up with a circuit that does this. 166 | To run this solver, type the command: 167 | ``` 168 | $ python3 evaluate.py --fun manual_solver --problem discrete_problem1 169 | ``` 170 | 171 | Alternatively, you could look at `discrete_solver.py`, which can help automate the decision. 172 | To run this solver, type the command: 173 | ``` 174 | $ python3 evaluate.py --fun discrete_solver --problem discrete_problem1 175 | ``` 176 | 177 | 178 | ### Problem 2 (`discrete_problem2`) 179 | 180 | Number of qubits: 2 181 | 182 | Now there are multiple gates for each qubit. You will need to try interacting the qubits with one another using 183 | [CNOT gates](https://en.wikipedia.org/wiki/Controlled_NOT_gate). 184 | CNOT gates are only applied to neighbouring qubits, e.g. `qubit_0` -> `qubit_1`, `qubit_1` -> `qubit_2`. 185 | You can also use H, X and Y gates. 186 | 187 | You can look at `manual_solver.py` and try to come up with a circuit which does this. 188 | To run the solver, type the command: 189 | ``` 190 | $ python3 evaluate.py --fun manual_solver --problem discrete_problem2 191 | ``` 192 | 193 | It will probably be too annoying and difficult to manually try all combinations. 194 | Try modifying `discrete_solver.py` to include the extra gates needed. 195 | To run this solver, type the command: 196 | ``` 197 | $ python3 evaluate.py --fun discrete_solver --problem discrete_problem2 198 | ``` 199 | 200 | 201 | ### Problem 3 (`discrete_problem3`) 202 | 203 | Number of qubits: 4 204 | 205 | A larger problem with a 2 qubit gate. 206 | There is a single 1-qubit gate (H, X, or Y) on each qubit to start, and then a single CNOT gate linking 2 207 | neighbouring qubits. 208 | 209 | You will need to restrict the search to only circuits with 5 gates that have this structure. 210 | 211 | You can modify `discrete_solver.py` to begin, but you will notice that the number of combinations is extremely large and so the solver will take a very long time to run. You should write your own solver which exploits the structure given above to reduce the number of circuit possibilities. 212 | 213 | In order to do so, you need to know how we have produced the training and test data. We began with a quantum state on which we made a measurement. For the initial states we have chosen, this measurement is always equal to +/-1, and so this gave us a label. We then applied some quantum circuit to the original state to give the quantum state that we are giving you as data. 214 | 215 | Therefore, the circuits you have been finding so far are 'undoing' the effect of the circuit we applied in order to get back to the original state. You can now use the information above about the circuit we applied to construct the inverse circuit. You will find it useful to know that all of H, X, Y and CNOT are self-inverse - the effect of each can be 'undone' by applying the same gate again. You will need to think carefully about how to invert a circuit which consists of multiple gates - in which order should the inverse gates be applied? 216 | 217 | To run this solver, type the command: 218 | ``` 219 | $ python3 evaluate.py --fun --problem discrete_problem3 220 | ``` 221 | substituting `` for your own. 222 | 223 | 224 | 225 | ### Problem 4 (`continuous_problem4`) 226 | 227 | Number of qubits: 4 228 | 229 | In this problem, we have used gates that we have not considered before – rotation gates. Each gate is parameterised by an angle, which can have any value from 0 to 2 pi. These gates perform rotations of the qubit state in the Bloch sphere. 230 | 231 | This problem is based on a "state preperation circuit" for [VQE](https://github.com/ctuning/ck-quantum/wiki/VQE-and-You) used in quantum chemistry. 232 | The circuit is called the [Hardware Efficient Ansatz](https://github.com/ctuning/ck-quantum/wiki/Quantum-Ansatz-Circuits#research-proposal-investigate-the-hardware-efficient-ansatz). 233 | You should use `continuous_solver.py` for this and larger continuous problems, since we are now trying to find a circuit which is a function of continuously varying parameters and not just discrete combinations of fixed gates. 234 | You can try to optimise some parameters, i.e. circuit depth and minimize parameters. 235 | 236 | To run this solver, type the command: 237 | ``` 238 | $ python3 evaluate.py --fun continuous_solver --problem continuous_problem4 239 | ``` 240 | 241 | 242 | ### Problem 5 (`continuous_problem5`) 243 | 244 | Number of qubits: 6 245 | 246 | In order to solve this problem you will need to invert the circuit we are giving explicitly: 247 | 248 | ![problem 5 circuit](https://i.ibb.co/DDLJcF8/Screen-Shot-2019-01-24-at-18-00-17.png) 249 | 250 | You need to optimise the rotation parameters. The angles are given above as 0, but it can be anything from 0 to 2pi. 251 | You can try and use `continuous_solver.py` but it will not be very efficient. You should make your own function that exploits the structure shown above. 252 | 253 | To run this solver, type the command: 254 | ``` 255 | $ python3 evaluate.py --fun --stats --problem continuous_problem5 256 | ``` 257 | substituting `` for your own. 258 | 259 | 260 | 261 | ## Using Collective Knowledge (CK) for viewing and sharing solutions 262 | 263 | The main type of objects that CK works with is called a "CK entry". 264 | A "CK entry" is a directory with metadata, optional data and optional code. 265 | 266 | You will use CK to: 267 | 1. Convert your solutions into CK experiment entries. 268 | 1. View your own experiment entries using "the CK dashboard" in the local mode. 269 | 1. Upload your CK experiment entries to the [cKnowledge.org](http://cKnowledge.org) server. 270 | 1. View everyone's solutions on the common CK dashboard on the server. 271 | 272 | ### Storing an experiment entry locally 273 | 274 | Each run of `evaluate.py` creates a `.json` output file in the current directory. 275 | In order to be counted as a solution, it will have to be first "stored" as a CK entry: 276 | ``` 277 | $ ck store_experiment qml [--json_file=] [--team=] 278 | ``` 279 | 280 | An experiment entry is stored together with the team name. 281 | If you do not specify the JSON file to upload, this command will prompt you to choose one from the current directory. 282 | You can either supply the team name from the command line using the `--team` option or enter it interactively when prompted. 283 | 284 | ### Viewing your solutions stored locally (WITHOUT DOCKER) 285 | 286 | To view your local experiment entries on a local dashboard: 287 | ``` 288 | $ ck display dashboard --scenario=hackathon.20190127 289 | ``` 290 | This command will open a browser page and turn itself into a server to that page. 291 | You can leave this server command running in its own terminal and open a new one. 292 | Or you can kill it when the page loads and reclaim the terminal - it's up to you. 293 | 294 | ### Viewing your solutions stored locally (WITH DOCKER) 295 | 296 | To view your local experiment entries on a local dashboard, just follow 297 | [the link to the local dashboard](http://localhost:3355/?template=dashboard&scenario=hackathon.20190127) . 298 | 299 | After some loading time you should see your local experiments displayed as data points in your browser. 300 | 301 | ### Uploading your solutions to the server 302 | 303 | In order for your solution to count in the competition, you will have to upload 304 | your best results to the server: 305 | ``` 306 | $ ck upload qml [ ] 307 | ``` 308 | 309 | If you do not specify the entries to upload, this command will prompt you to 310 | choose one from a list. Please note that your competition points will depend 311 | on who uploads their solution to the server faster. (It is the time on the 312 | server during the upload that counts, not the local time during the run on your 313 | machine.) So please upload as soon as you are ready. 314 | 315 | ### Viewing all the shared solutions on the server 316 | 317 | Visit the [common dashboard](http://cknowledge.org/dashboard/hackathon.20190127). 318 | 319 | ## That's all folks! 320 | 321 | ... but you are more than welcome to try our [1st open QCK challenge](https://www.linkedin.com/pulse/first-open-quantum-collective-knowledge-challenge-anton-lokhmotov/)! 322 | --------------------------------------------------------------------------------