From 0b5bb52dcbb0e9133a619cf1916dd8f3bccf8ddc Mon Sep 17 00:00:00 2001 From: israelferrazaraujo Date: Tue, 4 Aug 2020 18:51:55 -0300 Subject: [PATCH 1/2] quantum classifier --- .../DevideAndConquer_Pennylane.cpython-37.pyc | Bin 0 -> 3258 bytes .../Pennylane_Common.cpython-37.pyc | Bin 0 -> 9926 bytes quantum classifier/cin/__init__.py | 2 + .../cin/__pycache__/__init__.cpython-37.pyc | Bin 0 -> 264 bytes quantum classifier/cin/dataset/__init__.py | 8 + .../__pycache__/__init__.cpython-37.pyc | Bin 0 -> 574 bytes .../banknote_authentication.cpython-37.pyc | Bin 0 -> 913 bytes .../__pycache__/breast_cancer.cpython-37.pyc | Bin 0 -> 953 bytes .../__pycache__/haberman.cpython-37.pyc | Bin 0 -> 863 bytes .../dataset/__pycache__/iris.cpython-37.pyc | Bin 0 -> 955 bytes .../__pycache__/manipulate.cpython-37.pyc | Bin 0 -> 781 bytes .../dataset/__pycache__/pima.cpython-37.pyc | Bin 0 -> 865 bytes .../cin/dataset/banknote_authentication.py | 18 ++ .../cin/dataset/breast_cancer.py | 17 ++ quantum classifier/cin/dataset/haberman.py | 16 ++ quantum classifier/cin/dataset/iris.py | 19 ++ quantum classifier/cin/dataset/manipulate.py | 18 ++ quantum classifier/cin/dataset/pima.py | 17 ++ quantum classifier/cin/pennylane/__init__.py | 3 + .../__pycache__/__init__.cpython-37.pyc | Bin 0 -> 326 bytes .../__pycache__/common.cpython-37.pyc | Bin 0 -> 6741 bytes quantum classifier/cin/pennylane/common.py | 206 ++++++++++++++++++ .../cin/pennylane/encoding/__init__.py | 3 + .../__pycache__/__init__.cpython-37.pyc | Bin 0 -> 375 bytes .../devide_and_conquer.cpython-37.pyc | Bin 0 -> 3273 bytes .../divide_and_conquer.cpython-37.pyc | Bin 0 -> 3280 bytes .../pennylane/encoding/divide_and_conquer.py | 101 +++++++++ .../cin/pennylane/qml/__init__.py | 4 + .../qml/__pycache__/__init__.cpython-37.pyc | Bin 0 -> 368 bytes .../hierarchical_classifier.cpython-37.pyc | Bin 0 -> 862 bytes .../pennylane/qml/hierarchical_classifier.py | 24 ++ .../cin/pennylane/templates/__init__.py | 7 + .../__pycache__/__init__.cpython-37.pyc | Bin 0 -> 590 bytes .../__pycache__/amp_hqc.cpython-37.pyc | Bin 0 -> 987 bytes .../__pycache__/dc_hqc.cpython-37.pyc | Bin 0 -> 1041 bytes .../__pycache__/dc_onelayer.cpython-37.pyc | Bin 0 -> 1113 bytes .../onelayer_dc_hqc.cpython-37.pyc | Bin 0 -> 1156 bytes .../__pycache__/qubit_hqc.cpython-37.pyc | Bin 0 -> 958 bytes .../cin/pennylane/templates/amp_hqc.py | 20 ++ .../cin/pennylane/templates/dc_hqc.py | 19 ++ .../cin/pennylane/templates/qubit_hqc.py | 19 ++ quantum classifier/quantum_classifier.py | 74 +++++++ 42 files changed, 595 insertions(+) create mode 100644 quantum classifier/__pycache__/DevideAndConquer_Pennylane.cpython-37.pyc create mode 100644 quantum classifier/__pycache__/Pennylane_Common.cpython-37.pyc create mode 100755 quantum classifier/cin/__init__.py create mode 100644 quantum classifier/cin/__pycache__/__init__.cpython-37.pyc create mode 100755 quantum classifier/cin/dataset/__init__.py create mode 100644 quantum classifier/cin/dataset/__pycache__/__init__.cpython-37.pyc create mode 100644 quantum classifier/cin/dataset/__pycache__/banknote_authentication.cpython-37.pyc create mode 100644 quantum classifier/cin/dataset/__pycache__/breast_cancer.cpython-37.pyc create mode 100644 quantum classifier/cin/dataset/__pycache__/haberman.cpython-37.pyc create mode 100644 quantum classifier/cin/dataset/__pycache__/iris.cpython-37.pyc create mode 100644 quantum classifier/cin/dataset/__pycache__/manipulate.cpython-37.pyc create mode 100644 quantum classifier/cin/dataset/__pycache__/pima.cpython-37.pyc create mode 100644 quantum classifier/cin/dataset/banknote_authentication.py create mode 100644 quantum classifier/cin/dataset/breast_cancer.py create mode 100644 quantum classifier/cin/dataset/haberman.py create mode 100644 quantum classifier/cin/dataset/iris.py create mode 100644 quantum classifier/cin/dataset/manipulate.py create mode 100644 quantum classifier/cin/dataset/pima.py create mode 100755 quantum classifier/cin/pennylane/__init__.py create mode 100644 quantum classifier/cin/pennylane/__pycache__/__init__.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/__pycache__/common.cpython-37.pyc create mode 100755 quantum classifier/cin/pennylane/common.py create mode 100755 quantum classifier/cin/pennylane/encoding/__init__.py create mode 100644 quantum classifier/cin/pennylane/encoding/__pycache__/__init__.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/encoding/__pycache__/devide_and_conquer.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/encoding/__pycache__/divide_and_conquer.cpython-37.pyc create mode 100755 quantum classifier/cin/pennylane/encoding/divide_and_conquer.py create mode 100755 quantum classifier/cin/pennylane/qml/__init__.py create mode 100644 quantum classifier/cin/pennylane/qml/__pycache__/__init__.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/qml/__pycache__/hierarchical_classifier.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/qml/hierarchical_classifier.py create mode 100755 quantum classifier/cin/pennylane/templates/__init__.py create mode 100644 quantum classifier/cin/pennylane/templates/__pycache__/__init__.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/templates/__pycache__/amp_hqc.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/templates/__pycache__/dc_hqc.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/templates/__pycache__/dc_onelayer.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/templates/__pycache__/onelayer_dc_hqc.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/templates/__pycache__/qubit_hqc.cpython-37.pyc create mode 100644 quantum classifier/cin/pennylane/templates/amp_hqc.py create mode 100644 quantum classifier/cin/pennylane/templates/dc_hqc.py create mode 100644 quantum classifier/cin/pennylane/templates/qubit_hqc.py create mode 100755 quantum classifier/quantum_classifier.py diff --git a/quantum classifier/__pycache__/DevideAndConquer_Pennylane.cpython-37.pyc b/quantum classifier/__pycache__/DevideAndConquer_Pennylane.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64ebc3d9814d320b838e8ac254b4251d7713241d GIT binary patch literal 3258 zcma)8NpBp-6|U-SdU_VwGG&sHO$=f|$RLU5VjzZL*pekHmw*twfbalGqt#U!HrdNe zbq`GvHNMbS13nn=#Rn?4#1|t#eu4i$&W#)l!oZy;@$?dsT1w zs^07M0*3FKZ-4yD*ImZ`L!H%Uqj3wRd;>%1p z*#TU-z03e^!u;p#*9pUktddG*VYqcc-^Thx7bXll6mxl$$uO*gFw6=uPpRDvLxgnN zaFk02qWn^{Bh@ED!KPj$LUvOx5uvcXKq#0LMJE}mqy;{AxMTT_Z#Tc;#$c>JntltV zya#d#ayX&Z*qac{bPe$Eu`k;V^qg^kOanfhCHQoWdwRA1ejXPh$tSz@)hL^$Ni`QT zl*_?;u}L*3q?(Fx?*NSn>>n}>&^xr$EARy&k}a$+EDpRi=~Z77ad=rM^2|pPMfoI^ zz^EReW;(B6)dxvcs%^*~I!y|8lbkq5G6oopJ7!lhtWKs<{R-2bH7L2@HI$MZ!nntM zAjIl?ml1+y(Gqi{AJ70oATeJKQX77vB#>`xvwqFAHfltV;44Yj7ywdMflOABtg%xt;nghtKbb; zTlo}M#!OYU7fq)!7qvA_&{lDo4w?Rj;qKWRY0~;Qz8`OUS9|k!nN8Umy>B?aIDvT7sbTHM<+EmX?y>&X%IVk>( zp>6=81z$KYf_wb7=7{k(7M^ysw@D*6wTF?NMXRDDZy~lQ?oFa2?(ILobhE)8oAnWU zmTpW-Mz$Be_75;)i!IvPKX-K-rViGv&hcj&Z=XX~{fIG72jF(mYMEB=_#NHT?L)5q z1-+1@gKY-dHMF0>C-8&!d-M+7`!yjq@GQ84+0=a(NTg8*X!Up$l8b+Gr zGE$+z(Gpoocv{x3smHDC#JnYICyh$V=eWYHRlBJ?l4%{#g8?rpA&={hxyPH%ILPJk zlJRWN{T52!LoqLE=1{Iuo(2fN7p#DLC>Q@7^!niUdDnJ`^3zw>!TH<-uoT_O_l7-1 zFI`1X0`)SHA;`EN;~-@cM`@E;1RQEa#Mq61yzbH?Gl?@FCZT-S=Og5QB zB1ofzE9s^-SFph##|qr;Ro^!`JM`){u&{ZHs^60+dWM+PHlA%V`$>wf#n=AZ&9mVh NdIOnTiEypI^?!51#*Y91 literal 0 HcmV?d00001 diff --git a/quantum classifier/__pycache__/Pennylane_Common.cpython-37.pyc b/quantum classifier/__pycache__/Pennylane_Common.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0baa2e9a55aaa414dc0e443b1fcef1ae6d5be08 GIT binary patch literal 9926 zcmdT~-E$k)b>F)mzybt7kOV&^xv;DxhGUVc8r!X^$W~-4>7>Ibwi3&z6=b=0NiMbc z(A|Y3qKiJ1@(_H`#C^+5+ZnJ=Y2W<^bdtR1c^{k1q^#3Vwwj{?qq<^(965IbDo?8Y*w$@c#-0S2**OI>TA@ zl%`tO7`17h-ZbiltTQiD&&YAvdY0?lc&OA(p5a-XbKK-Pobx=-r*NL)1zyCtz+dFk zy!?>Wi~KB~<#VW&c!kfSZ<;UgMV!lgi7(?k!(Za3_-Txo$iKLbY=$2A;&2SuO^*`d-`LS;woGn86i4fLVG z8CM@FK_guxcXX;%YH*1gS-kK`t zBgt7vIf7Owi+}kMYHQo=rnBby!g9Q|x7&8N>9m5jzjoEO_>cdl>Dq0y zc7wLCczf+T*KfSDcFk?A-4xb_sNU^bt)Sbi`hgWVRk!5^uI0HsD{$MbwX5;aCMLb%v|78K)p8ow+RbLW zwc6SJG=JH1{lIQFJ68&j+b7**l-?J;w#6G8!m<3IVOuTR5v!NIwrzR-6;wvIJfBKQ zogB)o0K`kFN+-4Xm>wJJmGp?N3^fp9#)=gtUFJ}fa3qonGNi}%1NkCCB2^FQ**9i3c zY?Dc|Fr`_jp*CR_YG4l79y?Hj9GwSH@PQ)lQuf)tx~Xw888g%plc5>&IHp2%!en41 zJB3h($rSoVXoT9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1!8QfhU~+uc8LHGCQtkxG z((1XMBieFOY1nmh!?N$(w*;>lu_4G1b8H-hd4!|VJUHs(=#%!Q+kRI#pP<<%tDz0l zGOVL_wzG=_#NIxM$da3E8bA8cdgNM4s2~#200AP}Sn6@$1{ueabue~9WSS%1)V+b) z-_q5$QS@GVhAblj{*9CBa}m-{ApVF}zwpdee7=eGr{i^uiB-HuZ;0|%Nvz@~YM);Q8y(2MmmwN_<&Y=lyYS`*}&knpHzQbDGK9hQ?!ZR`i6pO9QR^8_}3gb5P1H0fgs_!3OXW>JHY0F%AS|)E5Fz0;AoRqvR ztoIi4`J2*)u6ynK$I0_a!UUZfJlO3xM4Y4V5)FZ`{6`!+!A7#oSyW`Uw1R(^z&}_7 zYML)$U*?dVxHF^0JC3^VZnchV(mYRY@vnH|$d$hwyN69I?IeDD%6|>~I)oSZA;y1M z_J148{{Pi|S7P^_A8Vdmc_Y}2U3V7m!U|shN@p@h=G{}rUDpGWjAFRR zAj$ma@%$(6`c=lt8^iYR2phDyhR_cQ4!QYqoE9ZcK9B1qm6D{BlcQs<{!cIyg5C3U z!d5?}+%CS3ViTGT;gBS?&K)HxCInwOhx-u0X-ARfghKSDVkZSZ6HC9`Z6=`UZ( P8>VUMW-k8~^U{9;Z^BCy literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/__init__.py b/quantum classifier/cin/__init__.py new file mode 100755 index 0000000..fe16459 --- /dev/null +++ b/quantum classifier/cin/__init__.py @@ -0,0 +1,2 @@ +__all__ = [] + diff --git a/quantum classifier/cin/__pycache__/__init__.cpython-37.pyc b/quantum classifier/cin/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68a8d7fd4903686b69d86919bde77465b58f3fa0 GIT binary patch literal 264 zcmXv}yG}zf49#VsLMq>owF_Ap5TfNVA%u7=3`8bzdo3j~&7%^04-4#kLI0vFpHQ*m z3*tz&kA3`*XXEjn5*%J`ANM7G4aq+`Atz#GByOP|lvlTE(p^ou&91c&g0=4|?}+&8 zzTbqIo+BD688DbLb}eG6T+GygUw=e$EY(&ygJ*MpaeZ!1DVe(rPY`t%yfThygOMNNq+L7-Qt#K}zmTB9s=a>Cj{xAx%q RWivX8>|4O&;lr(%`T^;0P+|Z8 literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/dataset/__init__.py b/quantum classifier/cin/dataset/__init__.py new file mode 100755 index 0000000..aaf1ceb --- /dev/null +++ b/quantum classifier/cin/dataset/__init__.py @@ -0,0 +1,8 @@ +__all__ = ["manipulate", "banknote_authentication", "breast_cancer", "haberman", "iris", "pima"] + +import cin.dataset.manipulate +import cin.dataset.banknote_authentication +import cin.dataset.breast_cancer +import cin.dataset.haberman +import cin.dataset.iris +import cin.dataset.pima diff --git a/quantum classifier/cin/dataset/__pycache__/__init__.cpython-37.pyc b/quantum classifier/cin/dataset/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b566db75cdaa5bb10c06026d3dd8aa4a30737b5 GIT binary patch literal 574 zcmZ`%xlRKy5OwY-A`%7S=vJbliAx%UxJ!gM8W&iTwaJd~5o|9K{1J$jFW@iIQc)v% zCSfBb1-3kIJoD^%9{H%>?=c#?7vHy=HO4-toB3#yb3iMekWoz4R9!VxQ?*8I!Bksy zOik2h*r>2sVXMM+g&o4q72D}fdKMgxO9M%ZjUl*u=aZIDrb4@fIVAK>^oK!1Ofmma%X40WJ`lO_g?qB%wjU!;kh(~TV|!5AsUdX8?OAVJh=uu!H!ak0Ia{IBlT5@|`p z+G1+1N31SJXWEt`Q=Km?v`Fd9{JfFJ3vV^Y7(g3-;`7qd%YEdBIjE0Ui@B$0nS21{ z`OVqIDL+QXuLBIh6vVsKj~GARHJ!*5KBCeYIF;qzJ(N0RU`9S*Dr|P=L-tUDOQp?X zqK0SaFd-Oxp0$}D{!uMmO7GxR>$sFto|J>})1F=@<-fL{ literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/dataset/__pycache__/banknote_authentication.cpython-37.pyc b/quantum classifier/cin/dataset/__pycache__/banknote_authentication.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14b2b7ac1d8837080827fc3defdf2c24cad031f5 GIT binary patch literal 913 zcmZ`$Pfrvv6mL7Te?TFaa6t4h9ygIK@t}zzLN1wt8luHU^pHkkNWtGROmAvVxRQW z3P+4nG9*4Zt5pP$(Fx%xubq%>ay!-~F~jS;ag6@vYcaQmjxglYDyfow9o{rg@f;e~ zD){=1v43amr`rTNoLE16*Ykeh9#hI}-jjQxEpyi{bJ-TWq=ljdgRmA0N-(RX-dW(x zvn}R?ql=3V9zLSc?`|>uUK=mEtn@vhz08@HMz{UGzr^=jI81P%WFft<7Q^Hhzd`bN zixMfVfo_0~Xx%{-dOJG=T0N@p5uOFA=Flgyn?lp%BGzBT#{is2?OP;}_F}-|3$k%> zzrKT^JyQrOon=DNHItVG^kp1f$r(TYTFBf$wDiU@Zs_ahFP_m=sp%^V!>JzBy%c-W zoqvNlS28a5Bo`UeJj;#VErrdP+A&u8UXg7Zo9&iN`?AQKXI^AdOD~y{ha(c`%DA)u z&>Vgd33I~J|8X`rxSU*4()rvJgXJ4Aii-o+(czpjjJKDR$(eG?aJeo59#Xb1U8@=D zrBzC9g@zT-r}Lo!0W%Of5IqQuhyY6oHD)b42uUF|7`ET4hXe{cP0K!XV~3r_Ri6QG z2K*+}H@n){V#M#*#Lhw*0n^yy3>bt{auZLJd7Py)c!t<{h_%vC(`7L@u(!ao)6vBE ZKTvULc7)elDhw}`SdQy;5x9w)TI5}%4=VW(%XL}cAqHdS!plfd!7hl4U8ANoJ7?!~i=5LdI;PXz0C#IPtKo?z_(DxZ_>hR` zia}>k)1y`$JSIo2aae~nJ79n=-p(l8i-xp9@E!0ewL^gMZW&+zxfP&!9Gehwwn9Fz zQ3!{F37+jRgC7%M!0Z#0JX?M0sWdon8h(C(EFI`Vrpg*F^K?sRRUu2KZMvRuas9ba znTBfRwBbUhZ(h85o^Gl#-8Fol=L6__El-ra{wm=_BGiczGU262GF^@;X%e0vYNOns zNDj0~MinnzRV3DNClggFr+BW;xKp}J*Kb-27@ENqvp7J)=eY@1Am@Dezy*?KHK?n2Tazt$JLm;$CV;Zw3Y>7Rh x_n29M8jOz0su-S{HmrILdz?#d$|?A1!=0H^?nv7=yM-22F4yqMS*$l<;2#%R<{|(9 literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/dataset/__pycache__/haberman.cpython-37.pyc b/quantum classifier/cin/dataset/__pycache__/haberman.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eaef9a64a28a8a2b888c7b5fe485d3f49ca01e6 GIT binary patch literal 863 zcmYjOy>1jS5VpO$cb7mSkSGp9u^l>z+)|@cL`a~Zh#~?~h=d|%?c^N!XJdOq675w< z$`rgoC_%J5K^}q5E!8~$O&Sz~%-7!c%%6T(2EkwUttAg|_9;nDe0x2~%+$h^|6AGWY`@ zGHNY742hx#y;ev76FQcD+Kk#YC) literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/dataset/__pycache__/iris.cpython-37.pyc b/quantum classifier/cin/dataset/__pycache__/iris.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0a378ff8c0e414893cda00a5a8dd039b7425eb9 GIT binary patch literal 955 zcmY*XOHUL*5bo-E>@Gs$>#&H2i6{5Mc<@MwD0(EuM}j0~(@xJq!_4&3-AjP%dRY>d zg9rZs+|0feeq>MkwJm>qHl5#nw9Dn^HJob7wQ4Cp-~K0|hfM`w_vh zQ#fNI7{WFmal~L0xbQSOh8{?e{HW<-*BJ6)Fy>=eWn(yl5qHfAjNyd47JVnY%}!YD z#g5^a_X6aDp2OhMK0trI-IAej*ZxtXB14orL@hzsWJC78P1Gct zXA`y)n-F!FXP^0Qh|c_i$}$9B@#gvBBM&*&-N*`IZEg+4`~3wW-O^>ADr-buq^mj` zlzHW}O;<7@&%c!_)A%}Y+6bxBw=Z5kPoJqOePhH2QEZ{zt9(z{^B*~SBvS1unJ1!> zNv5maL2eRJY-*$2R+;p)Np=UKa)UClPPjZ#m2yfH>QFePt8`^*T4K-)Q(R6cRYuvx z{=uJ_r9xSk>9W7vLf)3T60^g0p@m#rDs(0ayNt?}(SPlu>DKLgh)UhQgxWU&YMo@L z;iM+)9=nS>)V^*bB{8%Tb;CN`P#_Z{bOH~Vp^fpaQdQl$v9*iee8tU%$?^|-$%k2ao|HL$Onh2?*q((Aoe@aG;vtF!n%id zK3?xu+LTkCfw@5(h@F`wAW9et)6wAVZ3G5Qh#}?=coSyfet46c1$^y9KB@*~|G?bB kn{U{iA{VBr3D*YG8Y#?mwZ6GjYB?zKWm-8)KQSo(3%*L=-~a#s literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/dataset/__pycache__/manipulate.cpython-37.pyc b/quantum classifier/cin/dataset/__pycache__/manipulate.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d60d1ccd647be1fa8db8bc7b257debb498328d15 GIT binary patch literal 781 zcmZ8f&2AGh5VrR(n>1;IQ~|y1H5c{;5YQGlR)`-d*#nV@-NtCwPHk_Xm2)aQ1f1Xq z2W}jYxb-c3<$!nq&M+vcy~H1&=p)9+#1^07 zRbmnw+hiL7P60<3I1Ad;WHvbi{i&nD|N9ecJ)Ct>LTs|XiW2WSsIA+-fR{QC=paxNQIa;*rf%lmTHHcS|)%iS5F z=bsxslaOtVRD{a%*~3Q<%6%@%r;5BF^&E7M*^=w?uM8>*%9ot70{SmzQXIET6{J3r ziko>;97DKw0M6Y@-vu}ficixcH*104qOPZ$E>^4pE1 OZO!iZW7WPqkNyG==hN~4 literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/dataset/__pycache__/pima.cpython-37.pyc b/quantum classifier/cin/dataset/__pycache__/pima.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0c72cc0f5f3c86f711102fceead56f70f9ec54f GIT binary patch literal 865 zcmYjOJ#Q2-5VgG@cL@Z6lp+v{ZBHV*)F_Gw33Nn=fD}$bk#Ftfd|KNZ+nX=#RY}Se z{DaT|JuOXs1C3j%`vEj*V0=jsBh7g2d4Bum`NiDaEQ0v)6K%gH2>lA1+kicK4rw1l zVTj=h_3?BieZmNfPEkK%coX&F2_Vo$8ET01Cf8uKH57)&$e|IwAT9cg$Jj-qxW$3v zoQ#Q!E|Qi2Gdd$IX2}`ZArAvC3LTcR&MErWPeN}UonYw4ZPZ4i6z+7-@gf>0ZPLa& z1Qg9|9QTLL)%ICY7s|^?>vmI@+y@o2+$jmzGcqWu^f>z>~I-ymudJUC8TEZ`aF<{@+w!A*Nnq97h zbzpJ562#juU5btuDot6wTqRq#rMb~oW=KvS%i~b>=V_<`p7(hoe8Mv`F})VIx}VKE=$dtim!x6w1KvZyW}rr CaPHgy literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/dataset/banknote_authentication.py b/quantum classifier/cin/dataset/banknote_authentication.py new file mode 100644 index 0000000..4e15f9b --- /dev/null +++ b/quantum classifier/cin/dataset/banknote_authentication.py @@ -0,0 +1,18 @@ +import numpy as np +import urllib + +def load(): + url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00267/data_banknote_authentication.txt" + #url = "https://datahub.io/machine-learning/banknote-authentication/r/banknote-authentication.csv" + raw_data = urllib.request.urlopen(url) + dataset = np.loadtxt(raw_data, delimiter=",") # , skiprows=1) # pylint: disable=no-member + + X = np.array(dataset[:,0:-1]) + Y = np.array([2*int(e)-1 for e in dataset[:,-1]]) # +1 ou -1. + + #normalization = np.sqrt(np.sum(X ** 2, -1)) # pylint: disable=no-member + #X_norm = (X.T / normalization).T + X_norm = X - X.min(axis=0) # banknote possui valores negativos, então precisa deslocar os valores das colunas de acordo. + X_norm = X_norm / X_norm.max(axis=0) + + return X_norm, Y diff --git a/quantum classifier/cin/dataset/breast_cancer.py b/quantum classifier/cin/dataset/breast_cancer.py new file mode 100644 index 0000000..bd449fa --- /dev/null +++ b/quantum classifier/cin/dataset/breast_cancer.py @@ -0,0 +1,17 @@ +import numpy as np +from sklearn import datasets + +def load(): + dataset = datasets.load_breast_cancer() # load the breast cancer dataset. + X = dataset.data # separate the data from the target attributes. # pylint: disable=no-member + Y = dataset.target # # pylint: disable=no-member + + X = np.array([ e[0] for e in list(zip(X, Y)) if e[1] in [0, 1]]) # select intended classes. + + Y = np.array([ 2*e-1 for e in Y if e in [0, 1]]) # + + normalization = np.sqrt(np.sum(X ** 2, -1)) # pylint: disable=no-member + X_norm = (X.T / normalization).T + + return X_norm, Y + diff --git a/quantum classifier/cin/dataset/haberman.py b/quantum classifier/cin/dataset/haberman.py new file mode 100644 index 0000000..c06c96b --- /dev/null +++ b/quantum classifier/cin/dataset/haberman.py @@ -0,0 +1,16 @@ +import numpy as np +import urllib + +def load(): + url = "https://archive.ics.uci.edu/ml/machine-learning-databases/haberman/haberman.data" + raw_data = urllib.request.urlopen(url) + dataset = np.loadtxt(raw_data, delimiter=",") # pylint: disable=no-member + + X = np.array(dataset[:,0:-1]) + Y = np.array([2*(int(e)-1)-1 for e in dataset[:,-1]]) # +1 ou -1; + + #normalization = np.sqrt(np.sum(X ** 2, -1)) # pylint: disable=no-member + #X_norm = (X.T / normalization).T + X_norm = X / X.max(axis=0) # reescala as colunas para valores entre 0 e 1. + + return X_norm, Y diff --git a/quantum classifier/cin/dataset/iris.py b/quantum classifier/cin/dataset/iris.py new file mode 100644 index 0000000..a2007ca --- /dev/null +++ b/quantum classifier/cin/dataset/iris.py @@ -0,0 +1,19 @@ +import numpy as np +from sklearn import datasets + +def load(classes): + iris = datasets.load_iris() # load the iris dataset. + X = iris.data # separate the data from the target attributes. # pylint: disable=no-member + Y = iris.target # # pylint: disable=no-member + + X = np.array([ e[0] for e in list(zip(X, Y)) if e[1] in classes]) # select intended classes. + + min_class = min(classes) # + c = max(classes) - min_class # + Y = np.array([ 2*((e-min_class)//c)-1 for e in Y if e in classes]) # +1 ou -1. + + #normalization = np.sqrt(np.sum(X ** 2, -1)) # pylint: disable=no-member + #X_norm = (X.T / normalization).T + X_norm = X / X.max(axis=0) # reescala as colunas para valores entre 0 e 1. Há apenas valores positivos no Iris. + + return X_norm, Y diff --git a/quantum classifier/cin/dataset/manipulate.py b/quantum classifier/cin/dataset/manipulate.py new file mode 100644 index 0000000..a0c18ab --- /dev/null +++ b/quantum classifier/cin/dataset/manipulate.py @@ -0,0 +1,18 @@ +import numpy as np + +def split_data(X, Y, validation_size=0.1, test_size=0.1): + np.random.seed(0) # pylint: disable=no-member + num_data = len(Y) + num_test = int(test_size * num_data) + num_val = int(validation_size * num_data) + + index = np.random.permutation(range(num_data)) # pylint: disable=no-member + + X_test = X[index[:num_test]] + Y_test = Y[index[:num_test]] + X_val = X[index[num_test:num_val+num_test]] + Y_val = Y[index[num_test:num_val+num_test]] + X_train = X[index[num_val+num_test:]] + Y_train = Y[index[num_val+num_test:]] + + return X_train, Y_train, X_val, Y_val, X_test, Y_test diff --git a/quantum classifier/cin/dataset/pima.py b/quantum classifier/cin/dataset/pima.py new file mode 100644 index 0000000..926fc69 --- /dev/null +++ b/quantum classifier/cin/dataset/pima.py @@ -0,0 +1,17 @@ +import numpy as np +import urllib + +def load(): + url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv" + raw_data = urllib.request.urlopen(url) + dataset = np.loadtxt(raw_data, delimiter=",") # pylint: disable=no-member + + X = np.array(dataset[:,0:-1]) + Y = np.array([2*int(e)-1 for e in dataset[:,-1]]) # +1 ou -1. + + #normalization = np.sqrt(np.sum(X ** 2, -1)) # pylint: disable=no-member + #X_norm = (X.T / normalization).T + X_norm = X / X.max(axis=0) # reescala as colunas para valores entre 0 e 1. + + return X_norm, Y + diff --git a/quantum classifier/cin/pennylane/__init__.py b/quantum classifier/cin/pennylane/__init__.py new file mode 100755 index 0000000..3e30839 --- /dev/null +++ b/quantum classifier/cin/pennylane/__init__.py @@ -0,0 +1,3 @@ +__all__ = ["common"] + +import cin.pennylane.common diff --git a/quantum classifier/cin/pennylane/__pycache__/__init__.cpython-37.pyc b/quantum classifier/cin/pennylane/__pycache__/__init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VcjwdTi|P!WZ?vx;2G2UaJbn{^Nf)ld-|IN2WE+kx zTW+gfmAEGTieo3UQ7A(Ip&a`XU4sp{uT5Ts9q=PB!*q3U5!|}TgA^JBe>$ z`!By3riV$F^yGV_s|R}RF!Khyzl(eGi+0C}!zls;VujOor_#Ne_1Qo0zGht*elr!p~PSVQTdM09iq&)QBhuRo{k;S=}Q? wz^NdVvMU7|lBOF+j}xJ*wbpEl-G*}t0Kz=FI0i}qtJ0=rS%#HLpSDi^6V-UJ&Hw-a literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/common.py b/quantum classifier/cin/pennylane/common.py new file mode 100755 index 0000000..998030d --- /dev/null +++ b/quantum classifier/cin/pennylane/common.py @@ -0,0 +1,206 @@ +import pennylane as qml +from pennylane import numpy as np +import time + +def variational_classifier(node, var, state_vector=None, n=4): + weights = var[0:-1] + bias = var[-1] + return node(weights, state_vector=state_vector, n=n) + bias + +def square_loss(labels, predictions): + loss = 0 + for l, p in zip(labels, predictions): + loss = loss + ((l - p)/2) ** 2 + + loss = loss / len(labels) + return loss + +def cost(node, n, var, state_vectors, labels): + predictions = [variational_classifier(node, var, state_vector=state_vector, n=n) for state_vector in state_vectors] + return square_loss(labels, predictions) + +def accuracy(labels, predictions): + acc = 0 + for l, p in zip(labels, predictions): + if abs(l - p) < 1e-5: + acc = acc + 1 + acc = acc / len(labels) + + return acc + +def numpy_interface(init_node, init_var, n, lr, steps, batch_size, X_train, X_val, X_test, Y_train, Y_val, Y_test, show=False): + if (show): + print('\nNumPy interface:') + + X = [*X_train, *X_val] + Y = [*Y_train, *Y_val] + + best = [0, 1.0, 0.0, 0.0, 0.0, []] + + node = init_node + var = init_var + opt = qml.optimize.AdamOptimizer(stepsize=lr) + + time1 = time.time() + for it in range(steps): + + # Update the weights by one optimizer step + batch_index = np.random.randint(0, len(X_train), (batch_size,)) # pylint: disable=no-member + X_train_batch = X_train[batch_index] + Y_train_batch = Y_train[batch_index] + var = opt.step(lambda v: cost(node, n, v, X_train_batch, Y_train_batch), var) + + # Compute predictions on train and validation set + predictions_train = [2*(variational_classifier(node, var, state_vector=f, n=n)>0.0)-1 for f in X_train] + predictions_val = [2*(variational_classifier(node, var, state_vector=f, n=n)>0.0)-1 for f in X_val] + + # Compute accuracy on train and validation set + acc_train = accuracy(Y_train, predictions_train) + acc_val = accuracy(Y_val, predictions_val) + + # Compute cost on complete dataset + cost_set = cost(node, n, var, X, Y) + + #if (cost_set < best[1]): + if (acc_val > best[3] or (acc_val == best[3] and cost_set < best[1])): + best[0] = it + 1 + best[1] = cost_set + best[2] = acc_train + best[3] = acc_val + best[4] = 0.0 + best[5] = var + + if (show): + print( + "Iter:{:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " + "".format(it + 1, cost_set, acc_train, acc_val) + ) + + # Compute predictions on test set + predictions_test = [2*(variational_classifier(node, best[5], state_vector=f, n=n)>0.0)-1 for f in X_test] + # Compute accuracy on test set + acc_test = accuracy(Y_test, predictions_test) + best[4] = acc_test + + time2 = time.time() + + if (show): + print("Optimized rotation angles: {}".format(best[5][:-1])) + print("Optimized bias: {}".format(best[5][-1])) + print("Optimized test accuracy: {:0.7f}".format(acc_test)) + print(f'Run time={((time2-time1)*1000.0):.3f}') + + return best + +def pytorch_interface(init_node, init_var, n, lr, steps, batch_size, X, X_train, X_val, Y, Y_train, Y_val): + print('\n\nPyTorch interface:') + + import torch + from torch.autograd import Variable + + best = [0, 1.0, 0.0, 0.0, 0.0, []] + + node = init_node.to_torch() + var = Variable(torch.tensor(init_var), requires_grad=True) # noqa pylint: disable=not-callable + opt = torch.optim.Adam([var], lr = lr) + + time1 = time.time() + def closure(n, var, X_train_batch, Y_train_batch): + opt.zero_grad() + loss = cost(node, n, var, X_train_batch, Y_train_batch) + loss.backward() # noqa pylint: disable=no-member + + return loss + for it in range(steps): + # Update the weights by one optimizer step + batch_index = np.random.randint(0, len(X_train), (batch_size,)) # pylint: disable=no-member + X_train_batch = X_train[batch_index] + Y_train_batch = Y_train[batch_index] + + opt.step(lambda: closure(n, var, X_train_batch, Y_train_batch)) + + # Compute predictions on train and validation set + predictions_train = [2*(variational_classifier(node, var, state_vector=f, n=n) > 0.0)-1 for f in X_train] + predictions_val = [2*(variational_classifier(node, var, state_vector=f, n=n) > 0.0)-1 for f in X_val] + + # Compute accuracy on train and validation set + acc_train = accuracy(Y_train, predictions_train) + acc_val = accuracy(Y_val, predictions_val) + + # Compute cost on complete dataset + cost_set = cost(node, n, var, X, Y) + + if (cost_set < best[1]): + best[0] = it + 1 + best[1] = cost_set + best[2] = acc_train + best[3] = acc_val + best[4] = var[-1] + best[5] = var[:-1] + + print( + "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " + "".format(it + 1, cost_set, acc_train, acc_val) + ) + time2 = time.time() + + print("Optimized rotation angles: {}".format(var[:-1])) + print("Optimized bias: {}".format(var[-1])) + print(f'Run time={((time2-time1)*1000.0):.3f}') + + return best + +def tensorflow_interface(init_node, init_var, n, lr, steps, batch_size, X, X_train, X_val, Y, Y_train, Y_val): + print('\n\nTensorFlow interface:') + + import tensorflow as tf + + best = [0, 1.0, 0.0, 0.0, 0.0, []] + + node = init_node.to_tf() + var = tf.Variable(init_var, dtype=tf.float64) + opt = tf.optimizers.Adam(learning_rate=lr) + + time1 = time.time() + for it in range(steps): + # Update the weights by one optimizer step + batch_index = np.random.randint(0, len(X_train), (batch_size,)) # pylint: disable=no-member + X_train_batch = X_train[batch_index] + Y_train_batch = Y_train[batch_index] + + with tf.GradientTape() as tape: + loss = cost(node, n, var, X_train_batch, Y_train_batch) + grads = tape.gradient(loss, [var]) + + opt.apply_gradients(zip(grads, [var])) + + # Compute predictions on train and validation set + predictions_train = [np.sign(variational_classifier(node, var, state_vector=f, n=n)) for f in X_train] # pylint: disable=no-member + predictions_val = [np.sign(variational_classifier(node, var, state_vector=f, n=n)) for f in X_val] # pylint: disable=no-member + + # Compute accuracy on train and validation set + acc_train = accuracy(Y_train, predictions_train) + acc_val = accuracy(Y_val, predictions_val) + + # Compute cost on complete dataset + cost_set = cost(node, n, var, X, Y) + + if (cost_set < best[1]): + best[0] = it + 1 + best[1] = cost_set + best[2] = acc_train + best[3] = acc_val + best[4] = var[-1] + best[5] = var[:-1] + + print( + "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " + "".format(it + 1, cost_set, acc_train, acc_val) + ) + time2 = time.time() + + print("Optimized rotation angles: {}".format(var[:-1])) + print("Optimized bias: {}".format(var[-1])) + print(f'Run time={((time2-time1)*1000.0):.3f}') + + return best diff --git a/quantum classifier/cin/pennylane/encoding/__init__.py b/quantum classifier/cin/pennylane/encoding/__init__.py new file mode 100755 index 0000000..4bf463b --- /dev/null +++ b/quantum classifier/cin/pennylane/encoding/__init__.py @@ -0,0 +1,3 @@ +__all__ = ["divide_and_conquer"] + +import cin.pennylane.encoding.divide_and_conquer diff --git a/quantum classifier/cin/pennylane/encoding/__pycache__/__init__.cpython-37.pyc b/quantum classifier/cin/pennylane/encoding/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a6fbbe597ac8338bb0b8acf246d7082ff98464c GIT binary patch literal 375 zcmZWlJ5B>J5Z&E~kC4*j1eU1MtS^8N5THarph;s5>q#<_cbwSXNa04LM|3o~#kN!& zfSw5kOkvHjloJzsRYN14Ri>evir{n%`FQAl$p8GBM}Hpxes&28cGQDKW=*6)mZ zmKJ2u09#Xeo;Mgi1)JUUJMDon;G8jSzalPY$h>sGSRz;65>Lwi+_odomn`hbh@bNH zE}fqG8a2fL==7zpni@IzsLv~~>s3vam(wQs0M_fr>)R_mAl457p1@57caIB->sJ(p z+PuxwCL4;*7VMr aHfF;#rkpL?!;{+E#^Gr$UgG9Y_ls|%9eA+- literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/encoding/__pycache__/devide_and_conquer.cpython-37.pyc b/quantum classifier/cin/pennylane/encoding/__pycache__/devide_and_conquer.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94a89f3422a46508d15c0537276d3f9ee4161dbd GIT binary patch literal 3273 zcma)8&yU=;6(%K0qtX0u;;gf~b+Q<=hLJ(r%q2jJB1rAnaWBOpNKz~^Kq1H?J*!=f zG(%}Ny9-V)n`?m{dhB7{TYKuIe?XCI4?PP#1n9{<7U-p?evg_Nuf0wX34A0)>OJzk z_kHAty=#VBQhdpzxNyb- zJx}`R`RI9)f69ifXZVxt4|(n7i|Onvq3-%|(71$K_1KYo?4k(iNcT$yH9~r* zed)^<>Xr;-8+9N<*+JcwUD-n&T66t6c%0_Zp^9hw38|-tYAO#<$}NbB8GgYHi?|`_ zNQRa2{h?dCnaXQXrst~mPvUH$%Ate4%ARN+KmLj70M&p01~ED;rfQUyI#$`}VUaAR zDzA!ibU%sZSAU+SNrA76s?f14M!$OW@kgTvX+HW)$B*Oe5c57!Cu#ZBUlsls$n+$Y zY7pmgkQDiRq4XfmCWTI`!|C8jp$GFtoL7tKpseCb4bnWV(l|@c<0>uk(fwxX6iO4A zn5jHJ%i>&(RGt(v%_k!XTT(^PAFcGiJ3Fg`C?ZW!M0+X)1mht;e|_!2ch}=Dc#?9$ zdh#_i$di)qAR}(G3yQb9KOsGgef{%i&Spw~57S?vP*#<>*6d&)U8o^;@%BjaA;pr9}FyQ_blW2XOTzq^%l z!eI`y-hQ>BdwB!F4GeQex4#cDtfG{ceK32#yXgPOxx>5seDFMm zuQr~zqyP`Wk%|rJFVU!2g}l7LOVm#XXobKXIrc~ul?P{Ygv&*!g>{^3gmoOdY#V`@ z!Z=THd9dySnUVX3p{44^b0Mw@>(qT4gLQXx{zWpbV!cP7L{iMotot-=x!#I^i;2pW z#t9iEsZJJYHS`*GBrn?R9t-&JRNtZgbNaB%K^XZNN=Zis<2T`?5Uzu(_BO71CG<9M zrhQQUTSwgiMN7UEaDsRGzTwF6_m;l#jK57^?iwFo_Li-RK;A-bQQljiBk$dxz;*M% z0h{-cdyZ*bOHOu|feDT&_r#B}V} z&iv$n_T0zr`n1Yp_B*ckumTF_0eIWS&4CTj1&rw8{x*0&K4J%AYAXi|YfKklvb$#P-C zdw11yERr28R^eu!c(*h~;s38x{_?=>gnKFXEX*+Z|7@jmamf+RnGdy|~61c0OI zRDLwLoBpyWE*5Zhv-Iq9lYOM Q8$O^rkUf=%*ZMpE2Nh1s+5i9m literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/encoding/__pycache__/divide_and_conquer.cpython-37.pyc b/quantum classifier/cin/pennylane/encoding/__pycache__/divide_and_conquer.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42498478fef1cdbf6503bd6400d9eeb36919a900 GIT binary patch literal 3280 zcma)8y^q|+6`vu8TrT%RwtVv4MfPD43r;pLv?&ZE2ngNJ%zHEM z<2UnRuNN|WpZ&cb{kzN9zo@hRTr}>Xl<$H_CV9rj9JQ0NsWWyt`x%q26kjkYE}XGI z&yzlSK6;+ypR!@=DOR%mA+NoBF`b3+c=Mo15} zFMZiU-I9T9qYh*!JE+^TD|@IztFB)MkJ3CkRPk&-A@TH4P31mHxdl=&!!NjD5jR8~ z$*@ztKXhw1Q+X}Q^jy{cNt`WIIdsrh*<A$E=A&Qg_)(l4V%{g}BrU)EtHO$bOixm& z25~M2Ns-SNN)O^}Qs}fgoDLordN5zad9|1h$||nZAkEV%jkEMTuF@hO{i0#s&*HL7 zAE!!>5@?#KJU`3gT#Zzo6f(^xqee{xHPK4V-Pu_kL=g#$B05?rKo}4C`KxO~-d*#b zGbn|IHRvm7kU=HiL15fw7vy$#e?oE?`|77p$@K8Qo95Nf(Jl09_gI}-OE#oUWBx4G zupmN^mDY3o{KjSr4ey&aAmPg`Y+!r60o{S5ryOL+HA!75*FCgfR4y|0xVizxT6J%u znmFG=F<&Wm_O0S?q0`gp+ASj2hmSepzXI56x8F5O+_1-HTfP4??V(L_~grKVA|b4B0Q=0sN}3_BEac|287 zREJSCE#xAjb~lO;=vl+j9vz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 + input_vector[k + 1] ** 2) # pylint: disable=no-member + new_x.append(norm) + if norm == 0: + beta.append(0) + else: + if input_vector[k] < 0: + beta.append(2 * np.pi - 2 * np.arcsin(input_vector[k + 1] / norm)) # pylint: disable=no-member + else: + beta.append(2 * np.arcsin(input_vector[k + 1] / norm)) # pylint: disable=no-member + Encoding._recursive_compute_beta(new_x, betas) + betas.append(beta) + + def dc_amplitude_encoding(self, input_vector, entangle): + self.num_qubits = int(len(input_vector))-1 + self.quantum_data = range(self.num_qubits) + newx = np.copy(input_vector) # pylint: disable=no-member + betas = [] + Encoding._recursive_compute_beta(newx, betas) + self._dc_generate_circuit(betas, self.quantum_data, entangle) + + def _dc_generate_circuit(self, betas, quantum_input, entangle): + ''' + doc + ''' + k = 0 + linear_angles = [] + for angles in betas: + linear_angles = linear_angles + angles + for angle in angles: + qml.RY(angle, wires=quantum_input[k]) + k += 1 + + self.heap = bin_heap(quantum_input) + my_heap = self.heap + + last = my_heap.size - 1 + actual = my_heap.parent(last) + level = my_heap.parent(last) + while actual >= 0: + left_index = my_heap.left(actual) + right_index = my_heap.right(actual) + while right_index <= last: + #if ((my_heap[left_index]==3 and my_heap[right_index]==5)==False): + qml.CSWAP(wires=[my_heap[actual], my_heap[left_index], my_heap[right_index]]) + left_index = my_heap.left(left_index) + right_index = my_heap.left(right_index) + actual -= 1 + if level != my_heap.parent(actual): + level -= 1 + + # set output qubits + next_index = 0 + while next_index < my_heap.size: + self.output_qubits.append(next_index) + next_index = my_heap.left(next_index) + diff --git a/quantum classifier/cin/pennylane/qml/__init__.py b/quantum classifier/cin/pennylane/qml/__init__.py new file mode 100755 index 0000000..eca5b7e --- /dev/null +++ b/quantum classifier/cin/pennylane/qml/__init__.py @@ -0,0 +1,4 @@ +__all__ = ["hierarchical_classifier"] + +import cin.pennylane.qml.hierarchical_classifier + diff --git a/quantum classifier/cin/pennylane/qml/__pycache__/__init__.cpython-37.pyc b/quantum classifier/cin/pennylane/qml/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..720f2d851a978315d38103a5e81abd3de99f56a2 GIT binary patch literal 368 zcmZ`#J4*yX4BiJm5U#PYopzg@KOo}yszgM+!Yv%)%-n5Y9=9{I2j>qGv=saW_b;}! zvKD)DigpH)dH-##$v#MmIj=zJ8SBHv_nbMrz~vHi0|h{S8P@YfDE>HO}I(`%29!yKTE4{$Ddex+0 z3Kys}1E-kuuIqJRU}ipGYAu`kz`7n>>Me^2l4j^IAsBpsgx>M-57p98T9p6Y#OWq3 Z#F{NcJzoyn`_`-8=!2a0kLzb{7GLr!c1HjJ literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/qml/__pycache__/hierarchical_classifier.cpython-37.pyc b/quantum classifier/cin/pennylane/qml/__pycache__/hierarchical_classifier.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1de0f769018e7bff766dbaef5a3203621d542135 GIT binary patch literal 862 zcmYjPy>1jS5FUGX?=B$;QHT-}QEWkT4O`M6L`X=5jwl30oCLwF&8>;ozO%ha4((MT zCGP+w^gIBHc!_PPQX_iCcOt^pjAuMQp7A%27Z>LN*UzWFU$0VtUqSh|P=`lI?hY~z zoG9oMPI>eZ`jp2!!879IIdofB=mEVvM1&P1wUD-v+#6&bYB(nodbaOLP0z^=yxN^a zp1zN2Qb!wT4V;rtl%T}vI`C)>czjIl3VOved*Gbjh7A}{^d$sFD~DJaR*>|%q)ASt z74C}QgIA#x8>DX1L`vu;u}lv{6OBsM(EXQ9yxn_t(2W~1YTBnl4hruYq8lQ=f?dM6 zKR=LVg(*cQon=C0J0`D6p}le0R?hh4w^HT?Z!2#s<0gBtyZ0p9mO4AI>@8CT`t6Go z=`Ozuj7YgWkzAxq^E5YlR0*3hH858CqD}56nxWv#ptH ziAi&OVkop8E2c$;{bYp{mf5_JIa5cuV$R8Tcy(_$ZsMcTjw5WvO@SsIvP9O%GO^2e zmj^>w0jz7l3RF0mAheVCtXBi4b#x0hVUi$>ga@#oPB!5p07vT>cd`x_bOX)8&6BKZIqjqI2)cY)wK3l zrDVU`vJ1g4v|?`rheWZlu>CnRbVuHJreuUE9pbDTSW#W#!blr wy-PdzGab^RHW+X$=B|HuTFI=YVEZp?7!x~9-FZ+NUMcY~Oq>h7bZDpj7rj%<#Q*>R literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/qml/hierarchical_classifier.py b/quantum classifier/cin/pennylane/qml/hierarchical_classifier.py new file mode 100644 index 0000000..2849621 --- /dev/null +++ b/quantum classifier/cin/pennylane/qml/hierarchical_classifier.py @@ -0,0 +1,24 @@ +import pennylane as qml + +def _mry(q, weights): + n = len(q) + for i in range(n): + qml.RY(weights[i], wires=q[i]) + if (i+1) % 2 == 0: + qml.CNOT(wires=[q[i], q[i-1]]) + +def circuit(n, q, weights): + layer = 0 + ops_total = 0 + while True: + ops_count = n // 2**layer + + _mry(q[ : n : n // ops_count], weights[ops_total : ops_total+ops_count]) + + ops_total += ops_count + layer += 1 + if (ops_count <= 1): + break + + return qml.expval(qml.PauliZ(0)) + diff --git a/quantum classifier/cin/pennylane/templates/__init__.py b/quantum classifier/cin/pennylane/templates/__init__.py new file mode 100755 index 0000000..586d4b0 --- /dev/null +++ b/quantum classifier/cin/pennylane/templates/__init__.py @@ -0,0 +1,7 @@ +__all__ = ["amp_hqc", "qubit_hqc", "dc_hqc", "dc_onelayer", "onelayer_dc_hqc"] + +import cin.pennylane.templates.amp_hqc +import cin.pennylane.templates.qubit_hqc +import cin.pennylane.templates.dc_hqc +import cin.pennylane.templates.dc_onelayer +import cin.pennylane.templates.onelayer_dc_hqc diff --git a/quantum classifier/cin/pennylane/templates/__pycache__/__init__.cpython-37.pyc b/quantum classifier/cin/pennylane/templates/__pycache__/__init__.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..570de5a713d944c503a9b2555bfbded29b78a01f GIT binary patch literal 590 zcmaJh}vQGP7C`nL8#Fxwc86h4D5giSc%TECjn9I530yD#LVog>EhnbpMC;d$07wd3VFyjl2a}Sfk(nv3vlCR85Ysk2w oYDfyrkj-exX0(LTGKSJox>)tjwB>~o=kQxlUVfgvRxha5AOFC@S^xk5 literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/templates/__pycache__/amp_hqc.cpython-37.pyc b/quantum classifier/cin/pennylane/templates/__pycache__/amp_hqc.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efd63f9aa71b82dc6c64fdb0994fd85eac4c6422 GIT binary patch literal 987 zcmZ`%y>1jS5cYU??^ zy0kn3Qc^;Xc!0cxTdF(&J>yMCXt3q+c*ZmH&Cl!A)fIwk{`K*Y#Dx3`kH0HI<`tgu zITAqxXfgo2sU|rcL=a?=j`L*DLOvGB85y)iSF}av3ZL=M+!m;u_;_ktJNd~X$2okw5wsA-1*xiBYFWNxSHdI_OUL;Pkp4N@stmJaw=_6_G1s9Js1xM9!|ay`v7f!|3s2aid<%@v`p&kO~I>N z8dsFrE@$HMd#-qa(#jQ6nwLGRi5Y)hTnTFxl?)*BqU43^A3)%r!GIb26W5 zG$=EcPluBk-yBpf5W}2z2OuxKA4?g0~weL*U)p+S)CY z*f32^8iPJoe&<%ZgK6yi2VUdTZU@Uy?SF8D(Xs)I@4UzhQEB-yOlpIugZ=5zPWKO? Cq5%E? literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/templates/__pycache__/dc_hqc.cpython-37.pyc b/quantum classifier/cin/pennylane/templates/__pycache__/dc_hqc.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06bdb3a0a156fa03ffee83450a08af39ab397898 GIT binary patch literal 1041 zcmZ`&y>AmS6t{hsUA!sRM#7B|PEhpD@5+k24@%dV{x=iiL z%t}YPGcxtR@XFMUg`MY1+9D);^2_u4e!us!v$nQ^;QYFHoPP-s`sp9nCjjOJ+-e61 zM;t4ZVfZBq6(kF=mjx;;I$5{nL)9yyECRm6yJslt^A#TP{u$0X9KT1&ohyigh6#2Z zT^G}1V0ug%R!a+Pw5M6gr5-cv&EP;is1J7+ZgmF4B8$HgxPc8DsAn6U;&b>;@f>q< zt8JFjb>!s@UWYoj(42UFW5EX&f9fQk!T0wM zAnBwmL@Fyog-TzQtS*GMWtF~UlwV#Hl9eE>ZD}Yk(+{uT?4`R>r~8H;P&EO&cj8c1 zm)`|=#9SUqE@G;A%t}40g^8&emqyx25syj}&uXe|UBs28R>V?EE2)wv)XGw)Zx_m4 zMXO4Vq%bLiOjDutv7%a}RuoeOepSj@KAEw>^w@PF&q$8D&`7lk1mTBx3$McWgqRI@ zU->yQzfAsgmbV>h3=a$Na)6%)pM!bO1fTFcv;+Y6V+mTovrR}xA+@wM7r9t2%6@{g z2%w^RtV9wRpC?-bq^7maXZ3-!m3y>YuzUjDP{SsYQI)fs29u8K9SJ#}fbD9FNq#68 zU~TR}G}mo&35RFxxE5p`G{*PiO)B3w!gq0(w6cT@%_c~a71zH3&IPkV8NV?m0^$;Y zb#S8{fO7Dk`r4T00XSv|^iw@9?u|5deLH{(lp(X*oDwGz+$_E!G? LAGPyZB~kwm%$XI# literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/templates/__pycache__/dc_onelayer.cpython-37.pyc b/quantum classifier/cin/pennylane/templates/__pycache__/dc_onelayer.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d80bbcd28f46072e162950678fdf254eab83a50b GIT binary patch literal 1113 zcmZ`&Piqu06i+gLc3RsCYDc^lF965GOd-_Q+xFT zcx#XL?iaA%B3DoS0D?DtnXXj?GrTu1dG94J@Au1-#l?99-js2{g>s5(W`Pr#0Ne1!UQe4ZzK?g;lIj$fkm$~o+V zHd5>&T^Hj6Fgi>cR!a+J@=UXmOFd-RhrtLz=0Mg#Dh|pbi;oFNV8aILSwn~T1inK& z#hf(wI@Gg@rlcX$z~bGg@$s>bJ)HUf4h7P}RSUbGo@cw6Hu0ihiub{F~S%^$l zh6U%ZObZq%qTxQEhH;pwYH_9yv$xb-+Y#>OPy^Sx_WerU=4)hj|8L1(rX0h08TvM;m2SaHsNkG zjVu8K$#JKNc(jH*+JI5ql4xHVQMqL(l|tFl)?DObMxt%cC}=a)LnY3C!blSr8JG%l z1xj+kq)?7*y*0jcw+Q_o*EXNjJJMDz7VpPSSN#*~E`ggCijvn#JoK-mytGk@G8^xLF~_7~rL)YJzNl6rVv^Wbs!5645j}Px6H>WQ<-{4cYk(8kg2`9G zItV9U2u73TR|s&zJm4XZz68^-3b&$ZWMe?7#`G))N1p({{Qyvld&Xbp`L`pDDBNWz zoI*F!mRzJ_#=jSyj4*wwhe`mjkpWAX1qgM)BvX!TzA?THw*-icOPfy0_tF;b#*EDA z2&P628%ai0%FYMbiQU|eki!x9F4nV8w*>=C%|)LLOBdHQ2!|&%GfveC92!3{?^V>l zD_+BEHYo6t|t^E?2dcXgd@nL?jlnTo3~jLX=X*6XHXHTTZU+OI$h5o#V7>m7A_B zGaI5K>x@`vD#o&eVm zL2$&eLSqbnqEJc30rt8;g=IAE!8zp7IU4u*fcJTPj>i$luTZ+S0$(&rv5Rz5&Q9Ub zXVS1nT88}-PzXE#-UqHZ2#zhX_!9vRY}i7^n`ntI;9KHtw7@N15Dsz&^6#QWVDVAZ zdXJvBUc$>?uU#}H7kCO07O2H7X@eF`LqHaeRs?bxk7DIT+INA}))75(Arn%$P*wQ@ z7bu|}VG|df2~*W+=mA!fX;vn0XI(u#CAyoy~y%fi?zWge{BjNH`a*; z4QHpW2RWuPkD!RU+XtNB5U=BV#B76Zi1%nxw zO`ihK%?A9t8D5DkfAyt$eI0{9I3{a&i*(wQjLZ(`(%22I+iGrs#&p}%0Z*an!|T@} plra1cye_7>?cIH&|H0w6%6Kp?epFVxQR1;*(hgA!qgf|${0lX4`+NWZ literal 0 HcmV?d00001 diff --git a/quantum classifier/cin/pennylane/templates/amp_hqc.py b/quantum classifier/cin/pennylane/templates/amp_hqc.py new file mode 100644 index 0000000..a62a209 --- /dev/null +++ b/quantum classifier/cin/pennylane/templates/amp_hqc.py @@ -0,0 +1,20 @@ +import pennylane as qml +from pennylane import numpy as np +from cin.pennylane.qml.hierarchical_classifier import circuit as circuit_hierarchical_classifier + +def config(X): + n = int(np.ceil(np.log2(len(X[0])))) # pylint: disable=no-member + n = 2**int(np.ceil(np.log2(n))) # n tem que ser potência de 2. # pylint: disable=no-member + N = n # número total de qubits no circuito. + w = 2*n - 1 # número de parâmetros do circuito (weights) + X = np.c_[X, np.zeros((len(X), 2**n-len(X[0])))] # o número de qubits necessários para codificar os dados (log_2(N)) precisa ser uma potencia de 2. # pylint: disable=no-member + + return n, N, w, X + +def circuit(weights, state_vector=None, n=4): + q=range(n) + + X = state_vector / np.linalg.norm(state_vector) # pylint: disable=no-member + qml.templates.AmplitudeEmbedding(X, wires=q) + + return circuit_hierarchical_classifier(n, q, weights) \ No newline at end of file diff --git a/quantum classifier/cin/pennylane/templates/dc_hqc.py b/quantum classifier/cin/pennylane/templates/dc_hqc.py new file mode 100644 index 0000000..b102231 --- /dev/null +++ b/quantum classifier/cin/pennylane/templates/dc_hqc.py @@ -0,0 +1,19 @@ +import pennylane as qml +from pennylane import numpy as np +from cin.pennylane.qml.hierarchical_classifier import circuit as circuit_hierarchical_classifier +from cin.pennylane.encoding.divide_and_conquer import Encoding + +def config(X): + n = int(np.ceil(np.log2(len(X[0])))) # pylint: disable=no-member + n = 2**int(np.ceil(np.log2(n))) # n tem que ser potência de 2. # pylint: disable=no-member + N = 2**n-1 # len(X[0])-1 # N precisa ser tal que n seja potência de 2 mais próxima de log_2(X[0]). O hierarchical exige que n seja dessa maneira. + w = 2*n - 1 # número de parâmetros do circuito (weights) + X = np.c_[X, np.zeros((len(X), 2**n-len(X[0])))] # o número de qubits necessários para codificar os dados (log_2(N)) precisa ser uma potencia de 2. # pylint: disable=no-member + + return n, N, w, X + +def circuit(weights, state_vector=None, n=4): + encode = Encoding(state_vector, 'dc_amplitude_encoding', entangle=True) + q = encode.output_qubits # o comprimento de q deve ser igual a n. + + return circuit_hierarchical_classifier(n , q, weights) \ No newline at end of file diff --git a/quantum classifier/cin/pennylane/templates/qubit_hqc.py b/quantum classifier/cin/pennylane/templates/qubit_hqc.py new file mode 100644 index 0000000..fdee521 --- /dev/null +++ b/quantum classifier/cin/pennylane/templates/qubit_hqc.py @@ -0,0 +1,19 @@ +import pennylane as qml +from pennylane import numpy as np +from cin.pennylane.qml.hierarchical_classifier import circuit as circuit_hierarchical_classifier + +def config(X): + n = 2**int(np.ceil(np.log2(len(X[0])))) # len(X[0]) # número de qubits necessário para armazenar o dado codificado. # pylint: disable=no-member + N = n # número total de qubits no circuito. + w = 2*n - 1 # número de parâmetros do circuito (weights) + X = np.c_[X, np.zeros((len(X), n-len(X[0])))] # pylint: disable=no-member + + return n, N, w, X + +def circuit(weights, state_vector=None, n=4): + q=range(n) + + X = state_vector * np.pi # re-scale the data vectors element-wise to lie in [0, pi]. # pylint: disable=no-member + qml.templates.AngleEmbedding(X, wires=q, rotation="Y") + + return circuit_hierarchical_classifier(n, q, weights) \ No newline at end of file diff --git a/quantum classifier/quantum_classifier.py b/quantum classifier/quantum_classifier.py new file mode 100755 index 0000000..07a1de8 --- /dev/null +++ b/quantum classifier/quantum_classifier.py @@ -0,0 +1,74 @@ +import pennylane as qml +from pennylane import numpy as np + +from cin.dataset import iris, pima, haberman, banknote_authentication, manipulate +from cin.pennylane.common import numpy_interface +from cin.pennylane.templates import qubit_hqc, amp_hqc, dc_hqc + +def main(): + # config. + reps = 10 # repetições + steps = 200 # iterações + lr = 0.1 # learning rate + batch = 0.1 # batch set size + val = 0.2 # validation set size + test = 0.2 # test set size + verbose = 1 # 0: just final results; 1: prints every iteration + + # template (select one). + tplt = qubit_hqc # qubit encoding + hierarchical quantum classifier + #tplt = amp_hqc # amplitude encoding + hierarchical quantum classifier + #tplt = dc_hqc # divide-and-conquer encoding + hierarchical quantum classifier + + # dataset (select one). + X, Y = iris.load([0, 1]) + #X, Y = pima.load() + #X, Y = banknote_authentication.load() + #X, Y = haberman.load() + + # parameterized variational circuit. + circuit = tplt.circuit + + # circuit properties. + n, N, w, X = tplt.config(X) + print("n={}, N={}, w={}, x={}".format(n, N, w, len(X))) + + # load a Pennylane plugin device and return the instance. + dev1 = qml.device("default.qubit", wires=N) + + # splits the data, "reps" times. + splitted = [manipulate.split_data(X, Y, validation_size=val, test_size=test) for i in range(reps)] + batch_size = int(batch * len(splitted[0][0])) + print("train={}, val={}, test={}, batch={}".format(len(splitted[0][0]), len(splitted[0][2]),len(splitted[0][4]), batch_size)) + + # converts "circuit" it into a QNode instance. + node = qml.QNode(circuit, dev1) + + # randomizes the init weights, "reps" times. + vars = [np.array([*np.random.uniform(low=-np.pi, high=np.pi, size=w), 0.0]) for i in range(reps)] # pylint: disable=no-member + + # learn and test, "reps" times. + best_iters = [numpy_interface(node, vars[i], n, lr, steps, batch_size, split[0], split[2], split[4], split[1], split[3], split[5], verbose) for i, split in enumerate(splitted)] + + # print best results. + print('\nBest iters:') + for best in best_iters: + print( + "Iter:{:5d} | Cost:{:0.7f} | Ac train:{:0.7f} | Ac val:{:0.7f} | Ac test:{:0.7f}" + "".format(best[0], best[1], best[2], best[3], best[4]) + ) + + print('\nBest bias:') + for best in best_iters: + print("Optimized bias: {}".format(best[5][-1])) + + print('\nBest rotation angles:') + for best in best_iters: + print("Optimized rotation angles: {}".format(best[5][:-1])) + + # print the quantum circuit (for some reason, it does not print the amplitude encoding). + print('\n') + print(node.draw(show_variable_names=True)) + +if __name__ == "__main__": + main() \ No newline at end of file From 8213b797f9b3f7686ff1471629b48667405b7b28 Mon Sep 17 00:00:00 2001 From: israelferrazaraujo Date: Wed, 27 Jan 2021 22:52:27 -0300 Subject: [PATCH 2/2] dcsp example --- Dcsp example.ipynb | 309 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 309 insertions(+) create mode 100644 Dcsp example.ipynb diff --git a/Dcsp example.ipynb b/Dcsp example.ipynb new file mode 100644 index 0000000..d7b2efa --- /dev/null +++ b/Dcsp example.ipynb @@ -0,0 +1,309 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 19, + "id": "inner-welsh", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"\n", + "Ref.: A divide-and-conquer algorithm for quantum state preparation\n", + "https://arxiv.org/abs/2008.01511\n", + "\"\"\"\n", + "import pennylane as qml\n", + "from pennylane import numpy as np\n", + "\n", + "class bin_heap:\n", + " size = None\n", + " values = None\n", + "\n", + " def __init__(self, values):\n", + " self.size = len(values)\n", + " self.values = values\n", + "\n", + " def parent(self, key):\n", + " return int((key-0.5)/2)\n", + "\n", + " def left(self, key):\n", + " return int(2 * key + 1)\n", + "\n", + " def right(self, key):\n", + " return int(2 * key + 2)\n", + "\n", + " def root(self):\n", + " return 0\n", + "\n", + " def __getitem__(self, key):\n", + " return self.values[key]\n", + "\n", + "\n", + "class Encoding:\n", + " quantum_data = None\n", + " classical_data = None\n", + " num_qubits = None\n", + " heap = None\n", + " output_qubits = []\n", + "\n", + " def __init__(self, q, input_vector, encode_type='amplitude_encoding'):\n", + " self.output_qubits = []\n", + " if encode_type == 'dc_amplitude_encoding':\n", + " self.dc_amplitude_encoding(q, input_vector)\n", + " elif encode_type == 'dc_amplitude_encoding_orthonormal_ancillary':\n", + " self.dc_amplitude_encoding_orthonormal_ancillary(q, input_vector)\n", + "\n", + " @staticmethod\n", + " def _recursive_compute_beta(input_vector, betas):\n", + " if len(input_vector) > 1:\n", + " new_x = []\n", + " beta = []\n", + " for j in range(0, len(input_vector), 2):\n", + " norm = np.sqrt(input_vector[j] ** 2 + input_vector[j + 1] ** 2)\n", + " new_x.append(norm)\n", + " if norm == 0:\n", + " beta.append(0)\n", + " else:\n", + " if input_vector[j] < 0:\n", + " beta.append(2 * np.pi - 2 * np.arcsin(input_vector[j + 1] / norm))\n", + " else:\n", + " beta.append(2 * np.arcsin(input_vector[j + 1] / norm))\n", + " Encoding._recursive_compute_beta(new_x, betas)\n", + " betas.append(beta)\n", + "\n", + " @staticmethod\n", + " def _recursive_compute_beta_z(input_vector, betas):\n", + " if len(input_vector) > 1:\n", + " new_x = []\n", + " beta = []\n", + " for j in range(0, len(input_vector), 2):\n", + " new_x.append((input_vector[j+1]+input_vector[j])/2)\n", + " beta.append(input_vector[j+1]-input_vector[j])\n", + " \n", + " Encoding._recursive_compute_beta_z(new_x, betas)\n", + " betas.append(beta)\n", + "\n", + " def dc_amplitude_encoding_orthonormal_ancillary(self, q, input_vector):\n", + " self.dc_amplitude_encoding(q, input_vector)\n", + " \n", + " q_ortho = q[self.num_qubits:]\n", + " n = len(self.output_qubits)\n", + " self.num_qubits += n\n", + " for i in range(n):\n", + " qml.CNOT(wires=[self.output_qubits[i], q_ortho[i]])\n", + "\n", + " def dc_amplitude_encoding(self, q, input_vector):\n", + " self.num_qubits = int(len(input_vector))-1\n", + " self.quantum_data = q[:self.num_qubits]\n", + " betas_y = []\n", + " betas_z = []\n", + "\n", + " newx = np.copy(input_vector)\n", + " \n", + " Encoding._recursive_compute_beta(np.abs(newx), betas_y)\n", + " Encoding._recursive_compute_beta_z(np.angle(newx), betas_z)\n", + " \n", + " self._dc_generate_circuit(betas_y, betas_z, self.quantum_data)\n", + "\n", + " def _dc_generate_circuit(self, betas_y, betas_z, quantum_input):\n", + " k = 0\n", + " for angles in betas_y:\n", + " for angle in angles:\n", + " qml.RY(angle, wires=quantum_input[k])\n", + " k += 1\n", + "\n", + " k = 0\n", + " for angles in betas_z:\n", + " for angle in angles:\n", + " qml.RZ(angle, wires=quantum_input[k])\n", + " k += 1\n", + " \n", + " self.heap = bin_heap(quantum_input)\n", + " my_heap = self.heap\n", + "\n", + " last = my_heap.size - 1\n", + " actual = my_heap.parent(last)\n", + " level = my_heap.parent(last)\n", + " while actual >= 0:\n", + " left_index = my_heap.left(actual)\n", + " right_index = my_heap.right(actual)\n", + " while right_index <= last:\n", + " qml.CSWAP(wires=[my_heap[actual], my_heap[left_index], my_heap[right_index]])\n", + " left_index = my_heap.left(left_index)\n", + " right_index = my_heap.left(right_index)\n", + " actual -= 1\n", + " if level != my_heap.parent(actual):\n", + " level -= 1\n", + " \n", + " # set output qubits\n", + " next_index = 0\n", + " while next_index < my_heap.size:\n", + " self.output_qubits.append(quantum_input[next_index])\n", + " next_index = my_heap.left(next_index)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "coordinated-michael", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"\n", + "Circuits used for testing.\n", + "\"\"\"\n", + "qml.enable_tape()\n", + "\n", + "dev_amp = qml.device(\"default.qubit\", wires=3)\n", + "dev_dc = qml.device(\"default.qubit\", wires=7)\n", + "\n", + "\"\"\"\n", + "Amplitude encoding, used for comparison.\n", + "\"\"\"\n", + "@qml.qnode(dev_amp)\n", + "def test_amp(state_vector=None):\n", + " q=range(3)\n", + " \n", + " qml.templates.AmplitudeEmbedding(state_vector, wires=q)\n", + " \n", + " return qml.probs(wires=q)\n", + "\"\"\"\n", + "Divide-and-conquer encoding.\n", + "\"\"\"\n", + "@qml.qnode(dev_dc)\n", + "def test_dcsp(state_vector=None):\n", + "\n", + " encode = Encoding(range(10), state_vector, 'dc_amplitude_encoding')\n", + " q = encode.output_qubits \n", + " \n", + " return qml.probs(wires=q)\n", + "\n", + "@qml.qnode(dev_dc)\n", + "def test_dcsp_state(state_vector=None):\n", + "\n", + " encode = Encoding(range(10), state_vector, 'dc_amplitude_encoding')\n", + " q = encode.output_qubits \n", + " \n", + " return qml.state()" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "designed-illustration", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"\n", + "State to be loaded.\n", + "\"\"\"\n", + "state_vector_1 = [np.sqrt(0.03)*np.exp(1.0j), np.sqrt(0.07)*np.exp(1.1j), np.sqrt(0.15)*np.exp(1.22j), np.sqrt(0.05)*np.exp(1.3j), np.sqrt(0.1)*np.exp(1.4j), np.sqrt(0.3)*np.exp(1.55j), np.sqrt(0.2)*np.exp(1.6j), np.sqrt(0.1)*np.exp(1.7j) ]" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "fallen-opinion", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Amplitude encoding:\n", + "probabilities:\n", + "[0.03 0.07 0.15 0.05 0.1 0.3 0.2 0.1 ]\n" + ] + } + ], + "source": [ + "\"\"\"\n", + "Amplitude enconding, to be used as a reference.\n", + "\"\"\"\n", + "print(\"Amplitude encoding:\")\n", + "print(\"probabilities:\")\n", + "print(test_amp(state_vector=state_vector_1))" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "variable-light", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dcsp encoding:\n", + "probabilities:\n", + "[0.03 0.07 0.15 0.05 0.1 0.3 0.2 0.1 ]\n" + ] + } + ], + "source": [ + "\"\"\"\n", + "Dcsp state preparation.\n", + "\"\"\"\n", + "print(\"Dcsp encoding:\")\n", + "print(\"probabilities:\")\n", + "print(test_dcsp(state_vector=state_vector_1))" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "roman-excitement", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dcsp circuit diagram:\n", + " 0: ──RY(1.98)──RZ(0.407)────────────────╭C─────╭C─────╭┤ Probs \n", + " 1: ──RY(1.91)──RZ(0.21)──────────╭C─────├SWAP──│──────├┤ Probs \n", + " 2: ──RY(1.43)──RZ(0.175)──╭C─────│──────╰SWAP──│──────│┤ \n", + " 3: ──RY(1.98)──RZ(0.1)────│──────├SWAP─────────├SWAP──╰┤ Probs \n", + " 4: ──RY(1.05)──RZ(0.08)───│──────╰SWAP─────────│───────┤ \n", + " 5: ──RY(2.09)──RZ(0.15)───├SWAP────────────────╰SWAP───┤ \n", + " 6: ──RY(1.23)──RZ(0.1)────╰SWAP────────────────────────┤ \n", + "\n" + ] + } + ], + "source": [ + "print(\"Dcsp circuit diagram:\")\n", + "print(test_dcsp.draw())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "accepting-serve", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}