Dorothydu commited on
Commit
a5a906c
·
verified ·
1 Parent(s): c6f6cfd

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. -Api_avec_python-master/Api1.py +29 -0
  2. -Api_avec_python-master/ex.py +45 -0
  3. -QuQ--master/LICENSE +201 -0
  4. -QuQ--master/baseClass/Bit.py +47 -0
  5. -QuQ--master/baseClass/Gate.py +368 -0
  6. -QuQ--master/baseClass/IBMQX.py +680 -0
  7. -QuQ--master/baseClass/baseCF.py +46 -0
  8. -QuQ--master/config/IBMToken.cfg +5 -0
  9. -QuQ--master/config/executeMode.cfg +2 -0
  10. -QuQ--master/doc/Liquid-framework.png +3 -0
  11. -QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-2.png +3 -0
  12. -QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-3.png +3 -0
  13. -QuQ--master/doc/references/High Performance Emulation of Quantum Circuits.pdf +3 -0
  14. -QuQ--master/doc/references/Simulating the Effect of Decoherence and Inaccuracies on a Quantum Computer.pdf +3 -0
  15. -QuQ--master/memory-record.txt +29 -0
  16. -QuQ--master/pic/QuanSim-FrameWork.png +3 -0
  17. -QuQ--master/tools/helperFunction.py +170 -0
  18. -QuQ--master/tools/interactCfg.py +155 -0
  19. -QuQ--master/userCode/ExpWrong.py +9 -0
  20. -QuQ--master/userCode/GroverLite.py +46 -0
  21. -QuQ--master/userCode/GroverN=8theory/chart.jpg +3 -0
  22. -QuQ--master/userCode/GroverN=8theory/qasm.txt +133 -0
  23. -QuQ--master/userCode/Test.py +70 -0
  24. -QuQ--master/userCode/header.py +15 -0
  25. .gitattributes +2 -0
  26. 0617-audio_stream-master/.pipreqs/requirements_pipreqs.txt +6 -0
  27. 0617-audio_stream-master/audio_process.py +16 -0
  28. 0617-audio_stream-master/dataset.py +53 -0
  29. 0617-audio_stream-master/model/CPD_models.py +256 -0
  30. 0617-audio_stream-master/model/HolisticAttention.py +40 -0
  31. 0617-audio_stream-master/model/vgg.py +130 -0
  32. 0617-audio_stream-master/train.py +151 -0
  33. 0621_test-master/django_app/config/settings.py +127 -0
  34. 0621_test-master/django_app/config/wsgi.py +16 -0
  35. 0621_test-master/django_app/post/admin.py +5 -0
  36. 0621_test-master/django_app/post/forms.py +5 -0
  37. 0621_test-master/django_app/post/migrations/0001_initial.py +25 -0
  38. 0621_test-master/django_app/post/tests.py +3 -0
  39. 0621_test-master/django_app/templates/post/post_list.html +23 -0
  40. 0621_test-master/django_app/templates/post/post_modify.html +17 -0
  41. 0621_test-master/requirements.txt +17 -0
  42. 10-week-algorithm-excercise-master/.gitignore +2 -0
  43. 10-week-algorithm-excercise-master/.pipreqs/requirements_pipreqs.txt +1 -0
  44. 10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.go +13 -0
  45. 10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.py +11 -0
  46. 10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.go +21 -0
  47. 10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses_test.go +23 -0
  48. 10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.go +15 -0
  49. 10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.py +12 -0
  50. 10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum.py +33 -0
-Api_avec_python-master/Api1.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+
4
+ url = "htpps://swap.co/api/people/"
5
+
6
+ print("bienvenue dans notre exemple")
7
+
8
+
9
+ while url is not None:
10
+
11
+ print("")
12
+
13
+ r = requests.get(url)
14
+
15
+ data = r.json()
16
+
17
+ url = data["next"]
18
+
19
+ persosTab = data["results"]
20
+
21
+ for perso in persosTab:
22
+
23
+ homeworld = requests.get(perso["homeworld"])
24
+ homeworldName = homeworld.json()["name"]
25
+
26
+
27
+ print(perso["name"] + "is a " + perso["la_couleur_des_yeux"] + "les_yeux" + perso["genre"]
28
+ + ", ils sont " + perso["la_couleur_des_cheveux "] + "cheveux_et_poids" + perso["mass"]
29
+ + ", il_vient_de_la_planete" + homeworldName + " ! 😘\n")
-Api_avec_python-master/ex.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###########
2
+ # IMPORTS #
3
+ ###########
4
+
5
+ import requests
6
+
7
+ # url va me servir à changer de page dans la boucle while
8
+ url = "https://swapi.co/api/people/"
9
+
10
+ print("Welcome to the Useless Star Wars Facts !")
11
+
12
+ # Quand il n'y a plus de "page suivante", la page "next" sera égale à None
13
+ # Donc, je boucle sur url tant qu'elle n'est pas égale à None :)
14
+ while url is not None:
15
+
16
+ ############################
17
+ # RÉCUPÉRATION DES DONNÉES #
18
+ ############################
19
+
20
+ print("")
21
+ # Je fais la requête sur la page en cours, et je récupère la data
22
+ r = requests.get(url)
23
+ data = r.json()
24
+
25
+ # C'est ici que je change l'url pour avoir la page d'après :)
26
+ url = data["next"]
27
+ # Ce tableau est la liste de tous les personnages
28
+ persosTab = data["results"]
29
+
30
+ ###########################
31
+ # UTILISATION DES DONNÉES #
32
+ ###########################
33
+
34
+ # Je fais ensuite une boucle qui parcourt tous les personnages
35
+ # et qui affiche plein d'infos sur eux :)
36
+ for perso in persosTab:
37
+ # Pour la planète natale, je récupère le lien fourni par l'API
38
+ # et je fais une requête dessus pour récupérer son nom ;)
39
+ homeworld = requests.get(perso["homeworld"])
40
+ homeworldName = homeworld.json()["name"]
41
+
42
+ # Et ici je fais un méga print qui affiche tout !
43
+ print(perso["name"] + " is a " + perso["eye_color"] + " eyed " + perso["gender"]
44
+ + ", he has " + perso["hair_color"] + " hair and weighs " + perso["mass"]
45
+ + ". He is from planet " + homeworldName + " ! 😘\n")
-QuQ--master/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
-QuQ--master/baseClass/Bit.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ #the Bit class represent the standard classical bit
3
+ #get the info about the function name and the line number
4
+ import sys
5
+
6
+ class Bit:
7
+ idList = []
8
+ def __init__(self,value = None,ids = None):
9
+ if value == None:
10
+ value = 0
11
+ self.value = value
12
+ if ids == None:
13
+ if len(Bit.idList) == 0:
14
+ ids = 0
15
+ else:
16
+ ids = max(Bit.idList) + 1
17
+ self.ids = 'c' + str(ids)
18
+ else:
19
+ #the bit is generated by the measurement of Qubit
20
+ self.ids = 'q' + str(ids)
21
+ #the index of the current bit, the range is from 0 to n
22
+ if self.ids in Bit.idList:
23
+ from Error import IDRepeatError
24
+ sys.path.append('../tools/')
25
+ from interactCfg import writeErrorMsg
26
+ try:
27
+ raise IDRepeatError("The id of this bit has been used, please choose another id!")
28
+ except IDRepeatError as ir:
29
+ info = self.get_curl_info()
30
+ funName = info[0]
31
+ line = info[1]
32
+ writeErrorMsg(ir,funName,line)
33
+ Bit.idList.append(self.ids)
34
+
35
+ #overwrite the add operator of bits
36
+ def __add__(self,other):
37
+ return (str(self.value) + str(other.value))
38
+ #please note that the first argument must Bit and the second argument must be str
39
+ def __add__(self,other:str):
40
+ return (str(self.value) + other)
41
+
42
+ def get_curl_info(self):
43
+ try:
44
+ raise Exception
45
+ except:
46
+ f = sys.exc_info()[2].tb_frame.f_back
47
+ return [f.f_code.co_name, f.f_lineno]
-QuQ--master/baseClass/Gate.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ from baseGate import *
3
+
4
+ #the dict will be used in SplitGate of Gate.py
5
+ elementGate = {
6
+ "X":"CNOT cq-0,tq-0;",
7
+ "Y":"Sd tq-0;CNOT cq-0,tq-0;S tq-0;",
8
+ "Z":"H tq-0;CNOT cq-0,tq-0;H tq-0;",
9
+ "H":"H tq-0;Sd tq-0;CNOT cq-0,tq-0;H tq-0;T tq-0;CNOT cq-0,tq-0;T tq-0;H tq-0;S tq-0;X tq-0;S cq-0;",
10
+ "S":"T tq-0;CNOT cq-0,tq-0;Td tq-0;CNOT cq-0,tq-0;",
11
+ "Sd":"Td tq-0;CNOT cq-0,tq-0;T tq-0;CNOT cq-0,tq-0;",
12
+ "T":"Rz(math.pi/8) tq-0;CNOT cq-0,tq-0;Rz(-math.pi/8) tq-0;CNOT cq-0,tq-0;",
13
+ "Td":"Rz(-math.pi/8) tq-0;CNOT cq-0,tq-0;Rz(math.pi/8) tq-0;CNOT cq-0,tq-0;",
14
+ "Rz":"Rz(alpha) tq-0;CNOT cq-0,tq-0;Rz(beta) tq-0;CNOT cq-0,tq-0;",
15
+ "Ry":"Ry(alpha) tq-0;CNOT cq-0,tq-0;Ry(beta) tq-0;CNOT cq-0,tq-0;",
16
+ #the alpha and beta is a angle, and will be replaced by parameter of CU and MCU
17
+ #alpha = -beta
18
+ }
19
+
20
+ #split a gate to the elements in the Dic "allowGate"
21
+ class SplitGate:
22
+ def __init__(self):
23
+ self.allowSet = []
24
+ for key in allowGate:
25
+ if key == 'M':
26
+ continue
27
+ self.allowSet.append(key)
28
+
29
+ #get the info about the function name and the line number
30
+ def get_curl_info(self):
31
+ try:
32
+ raise Exception
33
+ except:
34
+ f = sys.exc_info()[2].tb_frame.f_back
35
+ return [f.f_code.co_name, f.f_lineno]
36
+
37
+ #convert the c0 to c1 by addind a X gate on the control-qubit
38
+ #or restore the state of the control-qubit
39
+ def __convert0to1(self,cql:list,vl:list):
40
+ QASM = ""
41
+ for i in range(0,len(cql)):
42
+ if len(vl) == 1:
43
+ j = 0
44
+ else:
45
+ j = i
46
+ if vl[j] == 0:
47
+ QASM += "X cq-" + str(i) + ";"
48
+ #then the circuit is equal to c1-c1-c1-c1...-U
49
+ return QASM
50
+
51
+ #C-U means that this is a controlled-gate with only one control qubit
52
+ #return value is the QASM code
53
+ def CU(self,gateName:str,cq:Qubit,tq:Qubit,vl:list,angle = None,executeStatus = False):
54
+ QASM = ""
55
+ QASM += self.__convert0to1([cq],vl)
56
+ #all the control-gate can be split into CNOT and single-gate
57
+ singleGate = gateName.split("-")[1]
58
+ #the singleGate can only be an element of the set "Y,Z,H,S,Sd,T,Td,Rz,Ry"
59
+ tmpQASM = ""
60
+ #ignore the global phase
61
+ try:
62
+ tmpQASM = elementGate[singleGate]
63
+ if angle != None:
64
+ #the U is Ry or Rz
65
+ angleN = angle/2
66
+ tmpQASM = tmpQASM.replace("alpha",str(angleN),1)
67
+ tmpQASM = tmpQASM.replace("beta",str(-angleN),1)
68
+ except KeyError:
69
+ info = get_curl_info()
70
+ writeErrorMsg("Gate: "+ singleGate + " hasn't been definded in Dict:elementGate in defines.py!",info[0],info[1])
71
+ QASM += tmpQASM
72
+ QASM += self.__convert0to1([cq],vl)
73
+ if executeStatus:
74
+ return self.execute(QASM,[cq],[tq],gateName,angle)
75
+ return QASM
76
+
77
+ #MC-U means that this is a controlled-gate with more than one control qubit
78
+ #MCU will be split to Toffoli and CCU
79
+ #return value is the QASM code of this MCU
80
+ def MCU(self,gateName:str,cql:list,tq:Qubit,vl:list,angle = None,executeStatus = False):
81
+ if gateName == "c1-c1-X" or gateName == "Toffoli":
82
+ QASM = self.__Toffoli(["cq-0","cq-1"],"tq-0")
83
+ else:
84
+ #the multi-controlled qubit gate "c1-c1-c1-c1...-X" can be split to a series of Toffoli gates
85
+ #then c1-c1-c1-c1...-U is same with this case
86
+ N = len(cql) + 1
87
+ actualN = 2 * N -3
88
+ for i in range(0,actualN-1):
89
+ if i % 2 == 0 and i > 0:
90
+ #insert an auxiliary qubit
91
+ cql.insert(i,Qubit(True))
92
+ #the auxiliary qubit need NOT to use X gate to fix the state
93
+ vl.insert(i,1)
94
+ QASM = ""
95
+ QASM += self.__convert0to1(cql,vl)
96
+ for j in range(2,actualN-1,2):
97
+ QASM += self.__Toffoli(["cq-"+str(j-2),"cq-"+str(j-1)],"cq-"+str(j))
98
+ #the rest of the circuit is CCU
99
+ #the CCU is Toffoli
100
+ singleG = gateName.split("-")[-1]
101
+ if singleG == "X":
102
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
103
+ else:
104
+ #the general case: CCU
105
+ try:
106
+ if angle != None:
107
+ #the U is Rz or Ry
108
+ angleN = angle/2
109
+ if singleG == "Rz":
110
+ QASM += "Rz("+ str(angleN) +") tq-0;"
111
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
112
+ QASM += "Rz("+ str(-angleN) +") tq-0;"
113
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
114
+ elif singleG == "Ry":
115
+ QASM += "Ry("+ str(angleN) +") tq-0;"
116
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
117
+ QASM += "Ry("+ str(-angleN) +") tq-0;"
118
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
119
+ else:
120
+ raise GateNameError(singleGate)
121
+ else:
122
+ if singleG == "Y":
123
+ QASM += "Sd tq-0;"
124
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
125
+ QASM += "S tq-0;"
126
+ elif singleG == "Z":
127
+ QASM += "H tq-0;"
128
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
129
+ QASM += "H tq-0;"
130
+ elif singleG == "H":
131
+ QASM += "H tq-0;Sd tq-0;"
132
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
133
+ QASM += "H tq-0;T tq-0;"
134
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
135
+ QASM += "T tq-0;H tq-0;S tq-0;X tq-0;"
136
+ QASM += "S cq-"+str(actualN-3)+";S cq-"+str(actualN-2)+";"
137
+ elif singleG == "S":
138
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
139
+ QASM += "Td tq-0;"
140
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
141
+ QASM += "T tq-0;T cq-"+str(actualN-3)+";T cq-"+str(actualN-2)+";"
142
+ elif singleG == "Sd":
143
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
144
+ QASM += "T tq-0;"
145
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
146
+ QASM += "Td tq-0;Td cq-"+str(actualN-3)+";Td cq-"+str(actualN-2)+";"
147
+ elif singleG == "T":
148
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
149
+ QASM += "Rz(-math.pi/8) tq-0;"
150
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
151
+ QASM += "Rz(math.pi/8) tq-0;Rz(math.pi/8) cq-"+str(actualN-3)+";Rz(math.pi/8) cq-"+str(actualN-2)+";"
152
+ elif singleG == "Td":
153
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
154
+ QASM += "Rz(math.pi/8) tq-0;"
155
+ QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0")
156
+ QASM += "Rz(-math.pi/8) tq-0;Rz(-math.pi/8) cq-"+str(actualN-3)+";Rz(-math.pi/8) cq-"+str(actualN-2)+";"
157
+ else:
158
+ raise GateNameError(singleG)
159
+ except GateNameError as gne:
160
+ info = get_curl_info()
161
+ writeErrorMsg(gne,info[0],info[1])
162
+ pass
163
+ QASM += self.__convert0to1(cql,vl)
164
+ #print(QASM)
165
+
166
+ if executeStatus:
167
+ return self.execute(QASM,cql,[tq],gateName,angle)
168
+ return QASM
169
+
170
+ #special-case, this is an important element in constructing MCU
171
+ #cqIndexL stands for the list of the index of the control-qubits in the cqL
172
+ #tqIndex stands for the index of the target qubit in the tqL
173
+ def __Toffoli(self,cqIndexL:list,id_tq:str):
174
+ id_cq0 = cqIndexL[0]
175
+ id_cq1 = cqIndexL[1]
176
+ QASM = "H "+id_tq+";CNOT "+id_cq1
177
+ QASM += ","+id_tq+";Td "+id_tq+";CNOT "+id_cq0
178
+ QASM += ","+id_tq+";T "+id_tq+";CNOT "+id_cq1
179
+ QASM += ","+id_tq+";Td "+id_tq+";CNOT "+id_cq0
180
+ QASM += ","+id_tq+";Td "+id_cq1+";T "+id_tq
181
+ QASM += ";CNOT "+id_cq0+","+id_cq1+";H "+id_tq
182
+ QASM += ";Td "+id_cq1+";CNOT "+id_cq0+","+id_cq1
183
+ QASM += ";T "+id_cq0+";S "+id_cq1 +";"
184
+ #print(QASM)
185
+ return QASM
186
+
187
+ #record the entire gate in circuit.qubitExecuteList
188
+ def __recordEG(self,gateName:str,cql:list,tql:list,angle = None):
189
+ resQL = cql.copy()
190
+ for tq in tql:
191
+ resQL.append(tq)
192
+
193
+ #record the entire gate in circuit.qubitExecuteList
194
+
195
+ i = 0
196
+ while i < len(resQL):
197
+ if resQL[i].tag == "AX":
198
+ #the qubit is an auxiliary qubit
199
+ del resQL[i]
200
+ continue
201
+ i += 1
202
+
203
+ cG = [[0] * (2**len(resQL))] * (2**len(resQL))
204
+
205
+ #append the multi-controlled gate to Dict "allowGate", which is defined in baseGate.py
206
+ #allowGate[gateName] = len(resQL)
207
+
208
+ #init the Gate instance
209
+ gate = Gate(resQL,cG,gateName)
210
+ if len(resQL) == 1:
211
+ c = gate.recordSingleExecution(True,angle)
212
+ #print(c.qubitExecuteList)
213
+ else:
214
+ c = gate.recordmultiExecution(True,angle)
215
+ #print(c.qubitExecuteList)
216
+
217
+ #'er' is the QASM code generated by the other methods in this class
218
+ #note that all the Single-Gate and Double-Gate in this function shouldn't be stored in circuit.qubitExecuteList
219
+ def execute(self,er,cqL:list,tqL:list,gateName:str,angle = None):
220
+ self.__recordEG(gateName,cqL,tqL,angle)
221
+ #execute the component gate
222
+ erL = er.split(";")
223
+ for item in erL:
224
+ if item == "":
225
+ continue
226
+ tmpStr = item.split(" ")
227
+ gate = tmpStr[0]
228
+ import re
229
+ #if the gate has parameter
230
+ m = re.match("(.*)\((.*)\)(.*)", gate)
231
+ if m != None:
232
+ gate = m.group(1)
233
+ parameter = m.group(2)
234
+ exeStr = gate + "(" + parameter + ","
235
+ else:
236
+ exeStr = gate + "("
237
+ q = tmpStr[1].split(",")
238
+ for i in range(0,len(q)):
239
+ qType = q[i].split("-")[0]
240
+ index = q[i].split("-")[1]
241
+ try:
242
+ if qType == "cq":
243
+ exeStr += "cqL[" + index + "]"
244
+ elif qType == "tq":
245
+ exeStr += "tqL[" + index + "]"
246
+ else:
247
+ raise ValueError
248
+ except ValueError:
249
+ info = self.get_curl_info()
250
+ writeErrorMsg("Qubit List: "+qtype+" isn't defined in Class SplitGate!",info[0],info[1])
251
+ except IndexError:
252
+ info = self.get_curl_info()
253
+ writeErrorMsg("The index of the target element is our of range!",info[0],info[1])
254
+ if i != len(q)-1:
255
+ exeStr += ","
256
+ exeStr += ",False)"
257
+ exec(exeStr)
258
+
259
+ resQL = cqL.copy()
260
+ for tq in tqL:
261
+ resQL.append(tq)
262
+ return resQL
263
+
264
+ #record stands for whether record the gate in qubitExecuteList
265
+ #the forceQuit stands for whether record the gate in qubitExecuteList and qubitExecuteListOD
266
+ def X(q:Qubit,record = True,forceQuit = False):
267
+ X = [[0,1],[1,0]]
268
+ gate = Gate([q],X,"X")
269
+ return gate.singleOperator(record,forceQuit = forceQuit)
270
+
271
+ def Y(q:Qubit,record = True,forceQuit = False):
272
+ Y = [[0,-1j],[1j,0]]
273
+ gate = Gate([q],Y,"Y")
274
+ return gate.singleOperator(record,forceQuit = forceQuit)
275
+
276
+ def Z(q:Qubit,record = True,forceQuit = False):
277
+ Z = [[1,0],[0,-1]]
278
+ gate = Gate([q],Z,"Z")
279
+ return gate.singleOperator(record,forceQuit = forceQuit)
280
+
281
+ def I(q:Qubit,record = True,forceQuit = False):
282
+ I = [[1,0],[0,1]]
283
+ gate = Gate([q],I,"I")
284
+ return gate.singleOperator(record,forceQuit = forceQuit)
285
+
286
+
287
+ def H(q:Qubit,record = True,forceQuit = False):
288
+ H = [[1/math.sqrt(2),1/math.sqrt(2)],[1/math.sqrt(2),-1/math.sqrt(2)]]
289
+ gate = Gate([q],H,"H")
290
+ return gate.singleOperator(record,forceQuit = forceQuit)
291
+
292
+ def S(q:Qubit,record = True,forceQuit = False):
293
+ S = [[1,0],[0,1j]]
294
+ gate = Gate([q],S,"S")
295
+ return gate.singleOperator(record,forceQuit = forceQuit)
296
+
297
+ def Sd(q:Qubit,record = True,forceQuit = False):
298
+ Sd = [[1,0],[0,-1j]]
299
+ gate = Gate([q],Sd,"Sd")
300
+ return gate.singleOperator(record,forceQuit = forceQuit)
301
+
302
+
303
+ def T(q:Qubit,record = True,forceQuit = False):
304
+ T = [[1,0],[0,(1+1j)/math.sqrt(2)]]
305
+ gate = Gate([q],T,"T")
306
+ return gate.singleOperator(record,forceQuit = forceQuit)
307
+
308
+ def Td(q:Qubit,record = True,forceQuit = False):
309
+ Td = [[1,0],[0,(1-1j)/math.sqrt(2)]]
310
+ gate = Gate([q],Td,"Td")
311
+ return gate.singleOperator(record,forceQuit = forceQuit)
312
+
313
+ #all the single qubit gate can be constructed by the following two gate according to ZYZ decompose
314
+ #the argument "phi" is a rotation angle in radians
315
+ def Rz(phi,q:Qubit,record = True,forceQuit = False):
316
+ pows = 1j*phi / 2
317
+ Rz = [[cmath.exp(-pows),0],[0,cmath.exp(pows)]]
318
+ gate = Gate([q],Rz,"Rz")
319
+ return gate.singleOperator(record,phi,forceQuit = forceQuit)
320
+
321
+ def Ry(theta,q:Qubit,record = True,forceQuit = False):
322
+ Ry = [[math.cos(theta/2),-math.sin(theta/2)],[math.sin(theta/2),math.cos(theta/2)]]
323
+ gate = Gate([q],Ry,"Ry")
324
+ return gate.singleOperator(record,theta,forceQuit = forceQuit)
325
+
326
+ #this gate is implemented by Rz and Ry
327
+ def Rx(phi,q:Qubit,record = True,forceQuit = False):
328
+ PI = math.pi
329
+ I = [[1,0],[0,1]]
330
+ q = Rz(PI/2,q,False)
331
+ q = Ry(-phi,q,False)
332
+ q = Rz(-PI/2,q,False)
333
+ gate = Gate([q],I,"Rx")
334
+ gate.recordSingleExecution(True,phi,forceQuit = forceQuit)
335
+ return q
336
+
337
+
338
+ #return a Qubits, which has two entanglement qubit
339
+ #the two qubit can be independent qubits, or one of them are a part of engtanlement
340
+ #the first qubit is the control-qubit, the second qubit is the target-qubit
341
+ def CNOT(q1:Qubit,q2:Qubit,record = True,forceQuit = False):
342
+ CNOT = [[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]
343
+ gate = Gate([q1,q2],CNOT,"CNOT")
344
+ return gate.CNOTOperator(record,forceQuit = forceQuit)
345
+
346
+
347
+ def ControlledZ(q1:Qubit,q2:Qubit,record = True,forceQuit = False):
348
+ H(q2,record,forceQuit)
349
+ CNOT(q1,q2,record,forceQuit)
350
+ H(q2,record,forceQuit)
351
+ return q1.entanglement
352
+
353
+ #execute the measurement, the types of the first argument must be Qubit; the second argument is optional,
354
+ #if the parameter "result" is "False", then the result of the measurement won't be appeared in the end result
355
+ def M(q:Qubit,result = True):
356
+ I = [[1,0],[0,1]]
357
+ #print([q])
358
+ gate = Gate([q],I,"M")
359
+ #the measurement will return a Bit type
360
+ #but the qubit "q" is still a Qubit and the status of it is |0> or |1> according to the value of the Bit
361
+ return gate.MOperator(result)
362
+
363
+
364
+ #Toffoli gate, three input and three output
365
+ def Toffoli(q1:Qubit,q2:Qubit,q3:Qubit):
366
+ sg = SplitGate()
367
+ qL = sg.MCU("Toffoli",[q1,q2],q3,[1,1],None,True)
368
+ return qL
-QuQ--master/baseClass/IBMQX.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ #import the ibm code
3
+ from IBMQuantumExperience import *
4
+ from interactCfg import *
5
+ from helperFunction import *
6
+ from Error import *
7
+ import os
8
+ import sys
9
+ import re
10
+ from Gate import SplitGate
11
+ import time
12
+
13
+ #get the info about the function name and the line number
14
+ def get_curl_info():
15
+ try:
16
+ raise Exception
17
+ except:
18
+ f = sys.exc_info()[2].tb_frame.f_back
19
+ return [f.f_code.co_name, f.f_lineno]
20
+
21
+ qasmDic = {
22
+ "I":"id",
23
+ "X":"x",
24
+ "Y":"y",
25
+ "Z":"z",
26
+ "H":"h",
27
+ "S":"s",
28
+ "T":"t",
29
+ "CNOT":"cx",
30
+ "Td":"tdg",
31
+ "Sd":"sdg",
32
+ "M":"measure",
33
+ "Rz":"u1",
34
+ "Ry":"u3"
35
+ }
36
+
37
+ #the max execute times is made by IBM stuff
38
+ MAXTIMES = 8192
39
+ #the min executive times is made by IBM stuff
40
+ MINTIMES = 1
41
+
42
+ class IBMQX:
43
+ def __init__(self):
44
+ print("Connecting to the Server...")
45
+ #change the config message in config/IBMToken.cfg
46
+ tokenDic = readCfgPM()
47
+ self.__config = {
48
+ "url": tokenDic['url']
49
+ }
50
+ #init the api
51
+ self.api = IBMQuantumExperience(tokenDic['token'], self.__config)
52
+ print("Getting the available backend information...")
53
+ deviceList = self.__getAvailalbeBak()
54
+ self.device = tokenDic['device']
55
+ self.shot = int(tokenDic['shot'])
56
+ if self.device not in deviceList:
57
+ try:
58
+ raise IBMError("The seleted device isn't available")
59
+ except IBMError as ie:
60
+ info = get_curl_info()
61
+ funName = info[0]
62
+ line = info[1]
63
+ writeErrorMsg(ie.value,funName,line)
64
+ if self.shot < MINTIMES or self.shot > MAXTIMES:
65
+ try:
66
+ raise IBMError("The execute times must be from " + str(MINTIMES) + " to " + str(MAXTIMES) + ", but the input is " + str(self.shot))
67
+ except IBMError as ie:
68
+ info = get_curl_info()
69
+ funName = info[0]
70
+ line = info[1]
71
+ writeErrorMsg(ie.value,funName,line)
72
+ #get the connectivity map of the device according to the name of the device
73
+ try:
74
+ dic = tokenDic['connectivity'][self.device]
75
+ #change the key and item from str to int
76
+ self.connectivity = {}
77
+ for key in dic:
78
+ for item in dic[key]:
79
+ if int(key) in self.connectivity:
80
+ self.connectivity[int(key)].append(int(item))
81
+ else:
82
+ self.connectivity[int(key)] = [int(item)]
83
+ except KeyError as ke:
84
+ info = get_curl_info()
85
+ funName = info[0]
86
+ line = info[1]
87
+ writeErrorMsg("the IBMToken.cfg doesn't have the connectivity of the current device: " + self.device,funName,line)
88
+ #create a new folder to save the data of IBMQX
89
+ circuit = checkEnvironment()
90
+ if os.path.exists(circuit.urls + "/IBMQX") == False:
91
+ try:
92
+ os.makedirs(circuit.urls + "/IBMQX")
93
+ except OSError:
94
+ info = get_curl_info()
95
+ funName = info[0]
96
+ line = info[1]
97
+ interactCfg.writeErrorMsg("Can't create the new folder 'IBMQX'!",funName,line)
98
+
99
+ #get the availalbe backend, return the backend list
100
+ def __getAvailalbeBak(self):
101
+ result = []
102
+ lists = self.api.available_backends()
103
+ for item in lists:
104
+ try:
105
+ backend = item['name']
106
+ result.append(backend)
107
+ except KeyError:
108
+ info = get_curl_info()
109
+ funName = info[0]
110
+ line = info[1]
111
+ writeErrorMsg("Can't get the key:'name' in the backend information!".funName,line)
112
+ return result
113
+
114
+ #translate the QASM to Open-QASM
115
+ #the parameter 'c' is the current Circuit instance
116
+
117
+ #return True: translate successfully!
118
+ #return False: there is if statement in the QASM code
119
+ def __translateQASM(self,c):
120
+ global QASM
121
+ #the code has been store in circuit.url/QASM.txt
122
+ codeLocation = c.urls + "/Physical-Level/QASM.txt"
123
+ #this function must be called after circuit.execute()
124
+ if os.path.exists(codeLocation) == False:
125
+ info = get_curl_info()
126
+ funName = info[0]
127
+ line = info[1]
128
+ writeErrorMsg("The QASM code hasn't been generated, please check your code!",funName,line)
129
+ file = open(codeLocation)
130
+ codes = file.readlines()
131
+ file.close()
132
+
133
+ for item in codes:
134
+ #whether the statement is "if"
135
+ if re.search(r'if(.+)',item) != None:
136
+ return False
137
+ tmpCode = ""
138
+ tmp = item.split(" ")
139
+ gate = tmp[0]
140
+ #if the gate is M: M q[0] -> c[0], we have to get the tmp[1:len]
141
+ qubitL = tmp[1:len(tmp)]
142
+ try:
143
+ para = None
144
+ if re.search(r'^R\w{1}\(.+\)$',gate) != None:
145
+ #the gate is Rn and has the parameter
146
+ para = gate.split("(")[1].split(")")[0]
147
+ gate = gate.split("(")[0]
148
+
149
+ gate = qasmDic[gate]
150
+ if gate == "u1":
151
+ gate += "(" + para + ")"
152
+ if gate == "u3":
153
+ gate += "(" + para + ",0,0)"
154
+ #the gate with parameter
155
+ tmpCode += gate + " "
156
+ for q in qubitL:
157
+ tmpCode += q
158
+ except KeyError:
159
+ info = get_curl_info()
160
+ funName = info[0]
161
+ line = info[1]
162
+ #print(tmpCode)
163
+ QASM.append(tmpCode)
164
+ return True
165
+
166
+
167
+ #adjust the QASM code, which is producted by circuit.QASM(), so that the qubits can satisfy the constraint
168
+ #of the CNOT connectivity
169
+ def __canExecute(self):
170
+ circuit = checkEnvironment()
171
+ if circuit == None:
172
+ return None
173
+ global QASM,qubitList,CNOTList
174
+ QASM = []
175
+ #record the reason for why can't execute the code
176
+ reasonList = []
177
+ print("Translating the QASM to Open-QASM...")
178
+ if self.__translateQASM(circuit):
179
+ #translate successfully!
180
+ print("Optimizing the Open-QASM code, please wait for a while...")
181
+
182
+ #record the ids of qubits in the current circuit
183
+ qubitList = []
184
+ #record the cnot map in the current circuit
185
+ CNOTList = []
186
+
187
+ #find the num in the str
188
+ mode = re.compile(r'\d+')
189
+ #analyse the QASM code
190
+ for l in range(0,len(QASM)):
191
+ if l == 0:
192
+ continue
193
+ else:
194
+ qs = mode.findall(QASM[l])
195
+ if "measure" in QASM[l]:
196
+ qs = [qs[0]]
197
+ for q in qs:
198
+ if int(q) in qubitList:
199
+ continue
200
+ else:
201
+ qubitList.append(int(q))
202
+ if "cx" in QASM[l]:
203
+ #get the id of control-qubit and target-qubit
204
+ tQ = int(qs[1])
205
+ cQ = int(qs[0])
206
+ #the reverse cnot won't be appended to the list
207
+ if [cQ,tQ] in CNOTList or [tQ,cQ] in CNOTList:
208
+ continue
209
+ CNOTList.append([cQ,tQ])
210
+
211
+ totalConnectivity = self.__getTotalConnectivity()
212
+
213
+ cnotBool = True
214
+ idBool = True
215
+ idBool = self.__determindID(totalConnectivity,reasonList)
216
+ if idBool:
217
+ cnotBool = self.__checkAllConstraint(CNOTList,totalConnectivity)
218
+ if cnotBool == False:
219
+ #when __adjustCNOT was called, the CNOTList doesn't satisfy the constraint of IBM directly
220
+ cnotBool = self.__adjustCNOT(totalConnectivity,reasonList)
221
+
222
+ #the circuit can be executed
223
+ if idBool & cnotBool:
224
+ numQ = str(len(totalConnectivity))
225
+ code = 'OPENQASM 2.0;include "qelib1.inc";qreg q[' + numQ + '];creg c[' + numQ + '];\n'
226
+ self.__reverseCNOT()
227
+ for line in QASM:
228
+ code += line
229
+ try:
230
+ file = open(circuit.urls + "/IBMQX/Open-QASM.txt","w")
231
+ file.write(code)
232
+ file.close()
233
+ except IOError:
234
+ info = get_curl_info()
235
+ funName = info[0]
236
+ line = info[1]
237
+ writeErrorMsg("Can't write QASM code to Open-QASM.txt!",funName,line)
238
+ return code
239
+ else:
240
+ #if statement
241
+ reasonList.append("The Mif and Qif aren't supported by IBMQX for now!")
242
+
243
+ #if statement or there is something wrong with the number of qubits or connectivity of qubits
244
+ self.__writeErrorMsg(circuit.urls,reasonList)
245
+
246
+
247
+ #write the reason why the code can't be executed on IBMQX
248
+ def __writeErrorMsg(self,urls,reasonList:list):
249
+ #can't execute the circuit
250
+ file = open(urls + "/IBMQX/codeWarning.txt",'a')
251
+ file.write("WARNING:\n")
252
+ #write the reason in codeWarning.txt
253
+ for i in range(0,len(reasonList)):
254
+ strs = str(i+1) + "." + reasonList[i] + "\n"
255
+ file.write(strs)
256
+ return None
257
+
258
+ #add self.connectivity and reverse self.connectivity, the type of the returned parameter is dict
259
+ def __getTotalConnectivity(self):
260
+ totalConnectivity = {}
261
+ for cQ in self.connectivity:
262
+ for tQ in self.connectivity[cQ]:
263
+ if cQ in totalConnectivity:
264
+ totalConnectivity[cQ].append(tQ)
265
+ else:
266
+ totalConnectivity[cQ] = [tQ]
267
+ if tQ in totalConnectivity:
268
+ totalConnectivity[tQ].append(cQ)
269
+ else:
270
+ totalConnectivity[tQ] = [cQ]
271
+ return totalConnectivity
272
+
273
+ #determind whether the number of qubit in this circuit is more than the actual number
274
+ #if bigger, return False; else return True;
275
+ #if necessary, adjust the id of the qubit so that they are in line with the actual device
276
+ def __determindID(self,totalConnectivity,reasonList):
277
+ #we assume that there is no qubit isolated in ibm chip!
278
+ useQubit = len(qubitList)
279
+ actualQubit = len(totalConnectivity)
280
+ if useQubit > actualQubit:
281
+ reasonList.append("There are "+ str(useQubit) + " have been used! But the device you choose only have " + str(actualQubit) + " qubits!")
282
+ return False
283
+ if max(qubitList) < actualQubit:
284
+ return True
285
+ qubitList.sort()
286
+ availalbleQ = [i for i in range(0,actualQubit)]
287
+ qMap = {}
288
+ for q in qubitList:
289
+ qMap[q] = q
290
+ if q < actualQubit:
291
+ try:
292
+ availalbleQ.remove(q)
293
+ except ValueError:
294
+ info = get_curl_info()
295
+ funName = info[0]
296
+ line = info[1]
297
+ writeErrorMsg("Q "+ str(q) + " isn't available!",funName,line)
298
+ continue
299
+ #q >= actualQubit
300
+ #because actualQubit is more than useQubit, the actualQubit[0] is always existing
301
+ qMap[q] = availalbleQ[0]
302
+ availalbleQ.remove(availalbleQ[0])
303
+ self.__changeQASMandCNOT(qMap)
304
+ return True
305
+
306
+ #check the CNOT list whether satisfies the constraint of the connectivity
307
+ #if satisfies or we can adjust the cnot to satisfy the constraint, return True;
308
+ #else return False and store the 'bad' cnot in reasonList
309
+ def __adjustCNOT(self,totalConnectivity,reasonList):
310
+ cnotNum = len(CNOTList)
311
+ ibmNum = 0
312
+ for k in self.connectivity:
313
+ ibmNum += len(self.connectivity[k])
314
+ if cnotNum > ibmNum:
315
+ reason = "There are " + str(cnotNum) + " different connectivities in this circuit, but only " + str(ibmNum) + " are allowd in IBM chip!"
316
+ reasonList.append(reason)
317
+ return False
318
+ totalCNOT = {}
319
+ cnotQList = []
320
+ for cnot in CNOTList:
321
+ if cnot[0] not in cnotQList:
322
+ cnotQList.append(cnot[0])
323
+ if cnot[1] not in cnotQList:
324
+ cnotQList.append(cnot[1])
325
+ if cnot[0] in totalCNOT:
326
+ totalCNOT[cnot[0]].append(cnot[1])
327
+ else:
328
+ totalCNOT[cnot[0]] = [cnot[1]]
329
+ if cnot[1] in totalCNOT:
330
+ totalCNOT[cnot[1]].append(cnot[0])
331
+ else:
332
+ totalCNOT[cnot[1]] = [cnot[0]]
333
+ choiceList = []
334
+ for cq in totalCNOT:
335
+ tmp = []
336
+ for tcq in totalConnectivity:
337
+ if len(totalConnectivity[tcq]) >= len(totalCNOT[cq]):
338
+ tmp.append(tcq)
339
+ choiceList.append(tmp)
340
+ #the solution space is choiceList[]
341
+ solution = [-1] * len(cnotQList)
342
+ newMaps = self.__backTrace(0,len(cnotQList),solution,totalConnectivity,choiceList,cnotQList)
343
+ if newMaps != None:
344
+ self.__changeQASMandCNOT(newMaps)
345
+ return True
346
+ else:
347
+ reason = "Can't adjust the connectivity in your circuit to satisfy the requirement of the IBM chip!"
348
+ reasonList.append(reason)
349
+ return False
350
+ def __backTrace(self,depth,N,solution,tc,choiceList,cnotQList):
351
+ if depth >= N:
352
+ dic = self.__getQubitMap(cnotQList,solution,tc)
353
+ if self.__checkMapConstraint(dic,tc):
354
+ return dic
355
+ else:
356
+ return None
357
+ else:
358
+ for i in range(0,len(choiceList[depth])):
359
+ if choiceList[depth][i] in solution[0:depth+1]:
360
+ continue
361
+ else:
362
+ solution[depth] = choiceList[depth][i]
363
+ res = self.__backTrace(depth+1,N,solution,tc,choiceList,cnotQList)
364
+ if res != None:
365
+ return res
366
+
367
+ #use two list to construct a map: the key is from the first list and the value is from the second list
368
+ #note: the dimension of l1 and l2 must be same with each other
369
+ #and if there is qubits in qubitList but not in CNOTList, we should append the item in the dict
370
+ def __getQubitMap(self,l1,l2,tc):
371
+ if len(l1) != len(l2):
372
+ try:
373
+ raise IBMError("The dimension of the Qubit list should be same with the dimension of the solution!")
374
+ except IBMError as ie:
375
+ info = get_curl_info()
376
+ funName = info[0]
377
+ line = info[1]
378
+ writeErrorMsg(ie.value,funName,line)
379
+ dic = {}
380
+ availalbleQ = [i for i in range(0,len(tc))]
381
+
382
+ for index in range(0,len(l1)):
383
+ dic[l1[index]] = l2[index]
384
+ availalbleQ.remove(l2[index])
385
+
386
+ for q in qubitList:
387
+ if q in dic:
388
+ continue
389
+ else:
390
+ dic[q] = availalbleQ[0]
391
+ del availalbleQ[0]
392
+ return dic
393
+
394
+ #adjust the copy of CNOTList according to the map, and call the __checkAllConstraint
395
+ def __checkMapConstraint(self,maps,tc):
396
+ if len(maps) != len(qubitList):
397
+ return False
398
+ cCNOTList = CNOTList.copy()
399
+ for i in range(0,len(cCNOTList)):
400
+ cCNOTList[i] = [maps[cCNOTList[i][0]],maps[cCNOTList[i][1]]]
401
+ return self.__checkAllConstraint(cCNOTList,tc)
402
+
403
+ #change the global parameter qubitList, QASM, CNOTList according to the qmap
404
+ def __changeQASMandCNOT(self,qMap):
405
+ global QASM
406
+ #change the id in CNOTList to satisfy the requirement
407
+ for i in range(0,len(CNOTList)):
408
+ for j in range(0,len(CNOTList[i])):
409
+ CNOTList[i][j] = qMap[CNOTList[i][j]]
410
+
411
+ #change the QASM code
412
+ mode = re.compile(r'\d+')
413
+ for l in range(0,len(QASM)):
414
+ if l == 0:
415
+ continue
416
+ else:
417
+ qs = mode.findall(QASM[l])
418
+ if len(qs) == 1:
419
+ #single-qubit gate
420
+ QASM[l] = QASM[l].replace("[" + str(qs[0]) + "]","[" + str(qMap[int(qs[0])]) + "]")
421
+ elif len(qs) == 2 and qs[0] == qs[1]:
422
+ #measurement
423
+ QASM[l] = QASM[l].replace("[" + str(qs[0]) + "]","[" + str(qMap[int(qs[0])]) + "]")
424
+ else:
425
+ #multi-qubits gate
426
+ newQASM = QASM[l].split(" ")[0] + " "
427
+ qubit = QASM[l].split(" ")[1].split(",")
428
+ for qi in range(0,len(qs)):
429
+ newQASM += qubit[qi].replace("[" + str(qs[qi]) + "]","[" + str(qMap[int(qs[qi])]) + "]")
430
+ if qi != len(qs)-1:
431
+ newQASM += ","
432
+ QASM[l] = newQASM
433
+
434
+ #change the qubitList according to the qMap
435
+ for qi in range(0,len(qubitList)):
436
+ if qubitList[qi] in qMap:
437
+ qubitList[qi] = qMap[qubitList[qi]]
438
+
439
+ #the the max neighbor in totalconnectivity
440
+ def __getMaxNeighbor(self,tc):
441
+ if type(tc) != dict:
442
+ try:
443
+ raise TypeError
444
+ except TypeError:
445
+ info = get_curl_info()
446
+ funName = info[0]
447
+ line = info[1]
448
+ writeErrorMsg("The type of the argument must be Dict!",funName,line)
449
+ maxs = 0
450
+ for c in tc:
451
+ maxs = max(maxs,len(tc[c]))
452
+ return maxs
453
+
454
+ #check cnot whether satisfies the constraint
455
+ #the format of cnot should be [1,3]
456
+ def __checkSingleConstraint(self,cnot:list,tc):
457
+ if len(cnot) != 2:
458
+ try:
459
+ raise ValueError
460
+ except ValueError:
461
+ info = get_curl_info()
462
+ funName = info[0]
463
+ line = info[1]
464
+ writeErrorMsg("The cnot should be two-dimension!",funName,line)
465
+ cQ = cnot[0]
466
+ tQ = cnot[1]
467
+ if cQ in tc and tQ in tc[cQ]:
468
+ #directly satisfy the constraint
469
+ return True
470
+ else:
471
+ return False
472
+ def __checkAllConstraint(self,cnotList,tc):
473
+ for c in cnotList:
474
+ if self.__checkSingleConstraint(c,tc):
475
+ continue
476
+ else:
477
+ return False
478
+ return True
479
+
480
+ #get the legal cnot gate in current device
481
+ def __getLegalCNOT(self):
482
+ legalCList = []
483
+ for cQ in self.connectivity:
484
+ for tQ in self.connectivity[cQ]:
485
+ if [cQ,tQ] not in legalCList:
486
+ legalCList.append([cQ,tQ])
487
+ if [tQ,cQ] not in legalCList:
488
+ legalCList.append([tQ,cQ])
489
+ return legalCList
490
+
491
+ #modify the qasm code by adding H to reverse the current CNOT
492
+ def __reverseCNOT(self):
493
+ lineN = 0
494
+ while lineN < len(QASM):
495
+ if 'cx' in QASM[lineN]:
496
+ q = QASM[lineN].split(" ")[1]
497
+ strs = q.split(',')
498
+ #get the id of control-qubit and target-qubit
499
+ tQ = int(strs[1][2])
500
+ cQ = int(strs[0][2])
501
+ if tQ in self.connectivity and cQ in self.connectivity[tQ]:
502
+ #add H gate to satisfy the constraint
503
+ hExternal = "h q[" + str(cQ) + "];\r\nh q[" + str(tQ) + "];\r\n"
504
+ gateStr = "cx q[" + str(cQ) + "],q[" + str(tQ) + "];"
505
+ if gateStr in QASM[lineN]:
506
+ QASM.insert(lineN,hExternal)
507
+ QASM[lineN+1] = "cx q[" + str(tQ) + "],q[" + str(cQ) + "];\r\n"
508
+ QASM.insert(lineN+2,hExternal)
509
+ lineN += 1
510
+
511
+ #execute the code
512
+ def executeQASM(self,experimentName = None):
513
+ code = self.__canExecute()
514
+ circuit = checkEnvironment()
515
+ if code == None:
516
+ info = get_curl_info()
517
+ funName = info[0]
518
+ line = info[1]
519
+ writeErrorMsg("The QASM code generated by QuanSim doesn't satisfy the requirement of IBMQX!",funName,line)
520
+ return False
521
+ try:
522
+ data = self.api.run_experiment(code,self.device,self.shot,experimentName,timeout = 300)
523
+ except ConnectionError as ce:
524
+ info = get_curl_info()
525
+ funName = info[0]
526
+ line = info[1]
527
+ writeErrorMsg("Can't connect to the server, Please try again later!",funName,line)
528
+ res = self.__analyseData(data)
529
+
530
+ #get the result analysed
531
+ if res['status'] == 0:
532
+ #waiting
533
+ blank = {}
534
+ resOfExe = self.__query(res['msg'])
535
+ if resOfExe == blank:
536
+ print("The experiment is still waiting in the executive queue, We'll query every 5 seconds! You can also find the result on the Web of IBM Quantum Experience!")
537
+ while resOfExe == blank:
538
+ #still no result
539
+ print("Waiting in the queue...")
540
+ #sleep for 5 seconds
541
+ time.sleep(5)
542
+ resOfExe = self.__query(res['msg'])
543
+ #get the result
544
+ self.__writeRaWData(resOFExe)
545
+ measure = resOFExe['measure']
546
+ qubits = measure['qubits']
547
+ labels = measure['labels']
548
+ values = measure['values']
549
+ rList = []
550
+ for i in range(0,len(labels)):
551
+ states = ""
552
+ for q in qubits:
553
+ state = labels[i][len(labels[i])-q-1]
554
+ states += state
555
+ rList.append([states,values[i]])
556
+ dataMsg = "-" * 30
557
+ dataMsg += " the data of IBMQX "
558
+ dataMsg += "-" * 31
559
+ dataMsg += "\r\n"
560
+ dataMsg += "Result:\r\n"
561
+ for r in rList:
562
+ prob = float(r[1]) * 100
563
+ dataMsg += " "*8+"|" + r[0] + ">----%.2f%%"%(prob)
564
+ dataMsg += "\r\n"
565
+ dataMsg += "-" * 80
566
+ print(dataMsg)
567
+ self.__writeAnalyData(dataMsg)
568
+
569
+ elif res['status'] == 2:
570
+ #wrong
571
+ self.__writeRaWData(data)
572
+ else:
573
+ #successful
574
+ self.__writeRaWData(data)
575
+ self.__writeAnalyData(res['msg'])
576
+
577
+
578
+
579
+ #analyse the date
580
+ ##############################################
581
+ #the return value is a Dict{'status':0,"msg":None}
582
+ #if successful, then status is 1 and msg is the data analysed
583
+ #if waiting, then status is 0 and msg is the id of the experiment
584
+ #if error, then status is 2 and msg is None
585
+ ###############################################
586
+ def __analyseData(self,data):
587
+ res = {'status':0,"msg":None}
588
+ try:
589
+ #judge the status of the experiment
590
+ status = data['status']
591
+ if status == "WORKING_IN_PROGRESS":
592
+ #still in queue
593
+ #then get the id of the experiment
594
+ ids = data['idExecution']
595
+ res['status'] = 0
596
+ res['msg'] = ids
597
+ return res
598
+
599
+ elif status == "":
600
+ #successful
601
+ status = data['status']
602
+ result = data['result']
603
+ measure = result['measure']
604
+ qubits = measure['qubits']
605
+ labels = measure['labels']
606
+ values = measure['values']
607
+ rList = []
608
+ for i in range(0,len(labels)):
609
+ states = ""
610
+ for q in qubits:
611
+ state = labels[i][len(labels[i])-q-1]
612
+ states += state
613
+ rList.append([states,values[i]])
614
+ dataMsg = "-" * 30
615
+ dataMsg += " the data of IBMQX "
616
+ dataMsg += "-" * 31
617
+ dataMsg += "\r\n"
618
+ dataMsg += "Result:\r\n"
619
+ for r in rList:
620
+ prob = float(r[1]) * 100
621
+ dataMsg += " "*8+"|" + r[0] + ">----%.2f%%"%(prob)
622
+ dataMsg += "\r\n"
623
+ dataMsg += "-" * 80
624
+ print(dataMsg)
625
+ res['status'] = 1
626
+ res['msg'] = dataMsg
627
+ return res
628
+
629
+ else:
630
+ #there is something wrong
631
+ res['status'] = 2
632
+ res['msg'] = None
633
+ return 1
634
+
635
+ except KeyError:
636
+ info = get_curl_info()
637
+ funName = info[0]
638
+ line = info[1]
639
+ writeErrorMsg("There are some keys aren't in the result returned by IBMQX!",funName,line)
640
+
641
+ #write the raw data of IBMQX to file
642
+ def __writeRaWData(self,rawData):
643
+ if rawData == "":
644
+ return False
645
+ #write the date to file
646
+ try:
647
+ rawDataFile = open(circuit.urls + "/IBMQX/rawData_IBMQX.txt","w",encoding='utf-8')
648
+ rawDataFile.write(rawData)
649
+ rawDataFile.close()
650
+ except IOError:
651
+ info = get_curl_info()
652
+ funName = info[0]
653
+ line = info[1]
654
+ writeErrorMsg("Can't write the raw data of IBMQX to rawData_IBMQX.txt!",funName,line)
655
+
656
+ #write the data analysed of IBMQX to file
657
+ def __writeAnalyData(self,data):
658
+ if data == "":
659
+ return False
660
+ #write the data to Data_IBMQX.txt
661
+ try:
662
+ dataFile = open(circuit.urls + "/IBMQX/Data_IBMQX.txt","w",encoding='utf-8')
663
+ dataFile.write(Data)
664
+ dataFile.close()
665
+ except IOError:
666
+ info = get_curl_info()
667
+ funName = info[0]
668
+ line = info[1]
669
+ writeErrorMsg("Can't write the data of IBMQX to Data_IBMQX.txt!",funName,line)
670
+
671
+ #get information (including the Code information) about a specific Execution of a Code,
672
+ #the parameter "id_execution" is the id of the experiment
673
+ def __query(self,id_execution):
674
+ res = self.api.get_result_from_execution(id_execution)
675
+ # print(res)
676
+ return res
677
+
678
+ def test(self):
679
+ res = self.api.get_result_from_execution("ff5b9f00a8333ee1f5586699c45a5bc8")
680
+ print(res)
-QuQ--master/baseClass/baseCF.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from Qubit import *
2
+ sys.path.append('../tools/')
3
+ from interactCfg import writeErrorMsg
4
+ from helperFunction import get_curl_info
5
+
6
+ class ControlFlow:
7
+ def __init__(self,q,v):
8
+ self.ql = []
9
+ self.vl = []
10
+ typeQ = type(q)
11
+ typeV = type(v)
12
+ if typeQ == Qubit and typeV == int:
13
+ self.ql.append(q)
14
+ self.vl.append(v)
15
+ elif typeQ == list and typeV == list:
16
+ if len(q) != len(v):
17
+ try:
18
+ raise ValueError()
19
+ except ValueError as t:
20
+ info = get_curl_info()
21
+ funName = info[0]
22
+ line = info[1]
23
+ writeErrorMsg("The length of the qubit list should be same with the length of the value list!",funName,line)
24
+ if repeatElement(q):
25
+ info = get_curl_info()
26
+ writeErrorMsg("There are repeating elements in the control-qubits list!",info[0],info[1])
27
+ self.ql = q
28
+ self.vl = v
29
+ elif typeQ == list and typeV == int:
30
+ self.ql = q
31
+ self.vl.append(v)
32
+ else:
33
+ try:
34
+ raise TypeError()
35
+ except TypeError as t:
36
+ info = get_curl_info()
37
+ funName = info[0]
38
+ line = info[1]
39
+ writeErrorMsg("The types of the two arguments aren't allowed,\
40
+ they should be (Qubit,int),(list,list) or (list,int)!",funName,line)
41
+
42
+ def __enter__(self):
43
+ return True
44
+ def __exit__(self,a,b,c):
45
+ pass
46
+
-QuQ--master/config/IBMToken.cfg ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"url":"https://quantumexperience.ng.bluemix.net/api"}
2
+ {"token":"35aea318934a99580a91a7b9d86c87a7b233f04df077a51f1f3a9f14089683e2493fb71d9e91eed4c883f645aa128ae429fd2b7ac7fa26497365a0ac5876a012"}
3
+ {"device":"ibmqx2"}
4
+ {"shot":"1024"}
5
+ {"connectivity":{"ibmqx2":{"0":["1","2"],"1":["2"],"3":["2","4"],"4":["2"]},"ibmqx4":{"1":["0"],"2":["0","1","4"],"3":["2","4"]},"ibmqx5":{"1":["2"],"2":["3"],"3":["4","14"],"5":["4"],"6":["7","11"],"7":["10"],"8":["7"],"9":["8","10"],"11":["10"],"12":["5","11","13"],"13":["4","14"],"15":["0","2","14"]}}}
-QuQ--master/config/executeMode.cfg ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"executeMode":"simulator"}
2
+ {"precision":"4"}
-QuQ--master/doc/Liquid-framework.png ADDED

Git LFS Details

  • SHA256: 6c2d6d1ecef6741a83b7e073ce54e9e5aad25aeeb1c25da4ccdd48a8e7029ccf
  • Pointer size: 130 Bytes
  • Size of remote file: 99.4 kB
-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-2.png ADDED

Git LFS Details

  • SHA256: 7ccbbf7c6a663eeaacf5048c6cc423a5ebc3b9a7692394382bf3d5955ca7d665
  • Pointer size: 130 Bytes
  • Size of remote file: 25.2 kB
-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-3.png ADDED

Git LFS Details

  • SHA256: df95bb7601d2873a7208b14cf836ed34c7a950d0521be50df04aecfae52c9e77
  • Pointer size: 130 Bytes
  • Size of remote file: 12.2 kB
-QuQ--master/doc/references/High Performance Emulation of Quantum Circuits.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8bca63e44a599d89bb6da7049386b99ad417d65722a7ba11c0e95bb6df0fc73
3
+ size 593924
-QuQ--master/doc/references/Simulating the Effect of Decoherence and Inaccuracies on a Quantum Computer.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50e9ed1a25754c3113ad65ac41743a8ef4acbb14c741ed432b2cd6e88ac1baa4
3
+ size 231018
-QuQ--master/memory-record.txt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ͳ���ڴ�ʹ�ã�
2
+ ����20��qubit��
3
+ ��0��1,1��2...13��14���о������ó��ڴ棺
4
+ ִ��ǰ��53866496
5
+ ִ�к�59154432
6
+ ����5287936bit = 5.0429M
7
+
8
+ ��0��1...14��15���о������ó��ڴ棺
9
+ ִ��ǰ��53915648
10
+ ִ�к�63778816
11
+ ����9863168bit = 9.40625M
12
+
13
+ ��0��1...15��16���о������ó��ڴ棺
14
+ ִ��ǰ��53878784
15
+ ִ�к�70717440
16
+ ����16838656bit = 16.0586M
17
+
18
+ ��0��1...16��17���о������ó��ڴ棺
19
+ ִ��ǰ��53878784
20
+ ִ�к�85184512
21
+ ����3130528bit = 29.85546875M
22
+
23
+
24
+
25
+ ��simulatorģʽ��ִ���£���Ϊ���ս����̬���ܶ�Ӧ�ĸ��ʷ���ƽ���Ͳ�Ϊ1�����Բ���helperFunction����ĺ���normalize���������һ��������
26
+ ������ʽ�Ƿ���ȷ
27
+
28
+ ����ʱ����monte-carlo simulation����
29
+
-QuQ--master/pic/QuanSim-FrameWork.png ADDED

Git LFS Details

  • SHA256: 89a7ef677eabf26dfe43ad35e2ea2b9581af47b47bcdf365b84f7347f4cddb2f
  • Pointer size: 130 Bytes
  • Size of remote file: 52.9 kB
-QuQ--master/tools/helperFunction.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ #public function is written in this file
3
+ import sys
4
+ import os
5
+ sys.path.append('../baseClass/')
6
+
7
+ from Bit import Bit
8
+
9
+ #from Circuit import *
10
+ from interactCfg import *
11
+
12
+ #return a str according to the number of qubits and the postion of 1
13
+ #For example: getCorrespondStr(3,0) = 00000001; (3,1) = 00000010
14
+ def getCorrespondStr(number,position):
15
+ strs = bin(int(position)).split('b')[1]
16
+ while len(strs) < number:
17
+ strs = '0' + strs
18
+ return strs
19
+
20
+ #suggest use this function to print message
21
+ #it can decide the style of output according to the type of the input
22
+ def QSprint(data):
23
+ from Qubit import Qubit,Qubits
24
+ precision = readCfgP()
25
+ preStr = '{:.' + str(precision) + 'f}'
26
+ types = type(data)
27
+ if types == Bit:
28
+ print("{\"Type:" + "Bit;")
29
+ print(" Value:" + str(data.value) + ";")
30
+ if 'c' in data.ids:
31
+ print(" Original qubit:" + "None" + ";")
32
+ else:
33
+ print(" Original qubit:" + str(data.ids) + ";")
34
+ print(" ID:" + str(data.ids) +" \"}" )
35
+
36
+ if types == Qubit:
37
+ print("{\"Type:" + "Qubit;")
38
+ #the amplitude is complex will disturb the format
39
+ amplitude = data.getAmp()
40
+ coefficient0 = amplitude[0]
41
+ coefficient1 = amplitude[1]
42
+ if coefficient0.imag == 0:
43
+ coefficient0 = coefficient0.real
44
+ if coefficient1.imag == 0:
45
+ coefficient1 = coefficient1.real
46
+ value = preStr.format(coefficient0) + "|0> + " + preStr.format(coefficient1) + "|1>"
47
+ print(" Value:" + value + ";")
48
+ print(" ID:" + str(data.ids) +" \"}" )
49
+
50
+ if types == Qubits:
51
+ print("{\"Type:" + "Qubits;")
52
+ print(" The Number of Qubits:" + str(data.number))
53
+ qubitStr = ""
54
+ for i in range(0,data.number):
55
+ qubitStr += "Q" + str(data[i].ids) + ";"
56
+ print(" They are:" + qubitStr )
57
+ value = ""
58
+ length = 2**data.number
59
+ amplitude = data.getAmp()
60
+ for j in range(0,length):
61
+ real = amplitude[j].real
62
+ imag = amplitude[j].imag
63
+ if real == 0 and imag == 0:
64
+ continue
65
+ elif imag == 0 and real != 0:
66
+ value += preStr.format(real) + "|" + getCorrespondStr(data.number,j) + ">"
67
+ elif imag != 0 and real == 0:
68
+ value += preStr.format(imag) + "|" + getCorrespondStr(data.number,j) + ">"
69
+ else:
70
+ value += "(" + preStr.format(real) + "+" + preStr.format(imag) + "j)" + "|" + getCorrespondStr(data.number,j) + ">"
71
+ if j != (length-1):
72
+ value += "+"
73
+ print(" Value:" + value +" \"}")
74
+
75
+
76
+ #get the info about the function name and the line number
77
+ def get_curl_info():
78
+ try:
79
+ raise Exception
80
+ except:
81
+ f = sys.exc_info()[2].tb_frame.f_back
82
+ return [f.f_code.co_name, f.f_lineno]
83
+
84
+ #sort the qubitList according to the qubit.ids
85
+ def quickSortQubit(ql,low,high):
86
+ i = low
87
+ j = high
88
+ if i >= j:
89
+ return ql
90
+ key = ql[low]
91
+ while i < j:
92
+ while i < j and ql[j].ids <= key.ids:
93
+ j = j-1
94
+ ql[i] = ql[j]
95
+ while i < j and ql[i].ids >= key.ids:
96
+ i = i+1
97
+ ql[j] = ql[i]
98
+ ql[i] = key
99
+ quickSortQubit(ql,low,i-1)
100
+ quickSortQubit(ql,j+1,high)
101
+ return ql
102
+ return True
103
+
104
+ #judge whether d2 in d1
105
+ def dictInDict(d1,d2):
106
+ bools = False
107
+ for k in d2:
108
+ if k in d1 and d2[k] == d1[k]:
109
+ bools = True
110
+ else:
111
+ bools = False
112
+ return bools
113
+
114
+ #construct the partitioned matrix
115
+ def constructPM(m1,m2):
116
+ #use the m1 and m2 as the diagonal element
117
+ m1_rows = len(m1)
118
+ m1_cols = len(m1[0])
119
+ m2_rows = len(m2)
120
+ m2_cols = len(m2[0])
121
+ mNew = []
122
+ mNew_cols = m1_cols * m2_cols
123
+ mNew_rows = m1_rows * m2_rows
124
+ for i in range(0,m1_rows):
125
+ for l in range(0,m2_rows):
126
+ tmp = []
127
+ for j in range(0,m1_cols):
128
+ for k in range(0,m2_cols):
129
+ tmp.append(m1[i][j] * m2[l][k])
130
+ mNew.append(tmp)
131
+ return mNew
132
+
133
+ #sort the list1 according to the list2
134
+ def adjustOrder(list1:list,list2:list):
135
+ for i in range(1,len(list2)):
136
+ tmp = i-1
137
+ while tmp >=0:
138
+ if list2[tmp] > list2[i]:
139
+ list2[i],list2[tmp] = list2[tmp],list2[i]
140
+ list1[i],list1[tmp] = list1[tmp],list1[i]
141
+ i = tmp
142
+ tmp -= 1
143
+ return True
144
+
145
+ #judge whether there is repeating element in the list.
146
+ #If two elements have the same address, then we say that the two elements are repeating elements.
147
+ #if there is repeating elements, then return True; else return False
148
+ def repeatElement(lt:list):
149
+ for i in range(0,len(lt)):
150
+ for j in range(i+1,len(lt)):
151
+ if id(lt[i]) == id(lt[j]):
152
+ return True
153
+ return False
154
+
155
+ #create a folder and the parameter "" stands for the name of the folder
156
+ def createFolder(name):
157
+ tmp = 1
158
+ #create a new folder according to the parameter "name"
159
+ while os.path.exists(name) == True:
160
+ name += str(tmp)
161
+ tmp += 1
162
+
163
+ #the whole result of the experiment is stored in this folder
164
+ try:
165
+ os.makedirs(name)
166
+ except OSError:
167
+ info = helperFunction.get_curl_info()
168
+ funName = info[0]
169
+ line = info[1]
170
+ writeErrorMsg("Can't create the new folder '" + self.name + "'!",funName,line)
-QuQ--master/tools/interactCfg.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ #interact with the cfg file
3
+ import datetime
4
+ import json
5
+ import sys
6
+ import os
7
+ sys.path.append('../baseClass/')
8
+ cfgLocation = "../config/"
9
+
10
+ #write the error message to LOG when error occurs
11
+ def writeErrorMsg(msg,funName,line):
12
+ print("Unfortunately, the following errors were happened in QuanSim when running the code:")
13
+ funName = "Function Name: "+ str(funName) + "()"
14
+ line = "Line: "+ str(line)
15
+ print(funName)
16
+ print(line)
17
+ print(msg)
18
+
19
+ #import the Circuit class
20
+ from Circuit import Circuit
21
+ circuit = Circuit.instance
22
+ if circuit == None:
23
+ print("there is no circuit instance in the code, please add at least one instance!")
24
+ else:
25
+ file = open(circuit.urls + "/errorMsg.txt","a")
26
+ time = datetime.datetime.now()
27
+ errorStr = "Time:" + str(time) + "\r\n"
28
+ errorStr += "Error Message: "
29
+ errorStr += str(msg)
30
+ errorStr += "\r\n"
31
+ errorStr += funName
32
+ errorStr += "\r\n"
33
+ errorStr += line
34
+ file.write(errorStr)
35
+ file.close
36
+ sys.exit(1)
37
+
38
+ #read the config file about the executeMode (EM for short)
39
+ def readCfgEM():
40
+ try:
41
+ EMcfg = cfgLocation + "executeMode.cfg"
42
+ confFile = open(EMcfg,"r")
43
+ content = confFile.readline()
44
+ mode = json.loads(content)['executeMode']
45
+ except IOError as io:
46
+ writeErrorMsg(io)
47
+ except KeyError as ke:
48
+ writeErrorMsg("Key: "+ str(ke) + "doesn't exist in executeMode.cfg, please check the cfg file!")
49
+ confFile.close()
50
+ return mode
51
+
52
+ #read the config file about the output precision (P for short)
53
+ #the type of return-value is int
54
+ def readCfgP():
55
+ try:
56
+ EMcfg = cfgLocation + "executeMode.cfg"
57
+ confFile = open(EMcfg,"r")
58
+ content = confFile.readline()
59
+ content = confFile.readline()
60
+ pre = json.loads(content)['precision']
61
+ pre = int(pre)
62
+ except IOError as io:
63
+ writeErrorMsg(io)
64
+ except KeyError as ke:
65
+ writeErrorMsg("Key: "+ str(ke) + "doesn't exist in executeMode.cfg, please check the cfg file!")
66
+ except TypeError as te:
67
+ writeErrorMsg(te)
68
+ confFile.close()
69
+ return pre
70
+
71
+ #read the config file about the assignment error (ER for short)
72
+ def readCfgER(ids):
73
+ #the error of readout error is the fidelity, and shouldn't be read directly
74
+ #it's the cumulative results in average
75
+ return 0.0
76
+
77
+ # try:
78
+ # ERcfg = cfgLocation + "errorRate.cfg"
79
+ # confFile = open(ERcfg,"r")
80
+ # content = confFile.readline()
81
+ # errorList = json.loads(content)['assignmentError']
82
+ # #our data is equal with IBMqx5, there are only 15qubits; so we only have 15 items
83
+ # #if current id is bigger then 15, compute ids%15
84
+ # errorRate = float(errorList[str(ids%15)])
85
+ # except IOError as io:
86
+ # writeErrorMsg(io)
87
+ # except KeyError as ke:
88
+ # writeErrorMsg("Key: "+ str(ke) + "doesn't exist in errorRate.cfg, please check the cfg file!")
89
+ # confFile.close()
90
+ # return errorRate
91
+
92
+ #read the config file about the gate error (GE for short)
93
+ #if the para gateType == single, then get the single-qubit gate error according to the qid
94
+ #if the para gateType == multi, then get the multi-qubit gate error;
95
+ #in the second case, all the qubit have the same error rate
96
+ def readCfgGE(gateType:str,qid = None):
97
+ if gateType == 'single' and qid == None:
98
+ writeErrorMsg("You want to get the single-qubit gate error, but don't give the id of the qubit!")
99
+ try:
100
+ ERcfg = cfgLocation + "errorRate.cfg"
101
+ confFile = open(ERcfg,"r")
102
+ content = confFile.readlines()
103
+ for line in content:
104
+ js = json.loads(line)
105
+ if gateType in js.keys():
106
+ if gateType == "single":
107
+ errorRate = float(js[gateType][str(qid%15)])
108
+ elif gateType == "multi":
109
+ errorRate = float(js[gateType])
110
+ else:
111
+ writeErrorMsg("There are only two kinds of gate errors: 'single' or 'multi'; but you gave another one!")
112
+ except IOError as io:
113
+ writeErrorMsg(io)
114
+ except KeyError as ke:
115
+ writeErrorMsg("Key: "+ str(ke) + "doesn't exist in errorRate.cfg, please check the cfg file!")
116
+ confFile.close()
117
+ return errorRate
118
+
119
+ #read the config file about the personal message on IBMQX(PM for short)
120
+ def readCfgPM():
121
+ result = {}
122
+ try:
123
+ message = cfgLocation + "IBMToken.cfg"
124
+ confFile = open(message,"r")
125
+ lines = confFile.readlines()
126
+ for line in lines:
127
+ pm = json.loads(line)
128
+ result = dict(result,**pm)
129
+ except IOError as io:
130
+ writeErrorMsg(io)
131
+ except KeyError as ke:
132
+ writeErrorMsg("Key: "+ str(ke) + "doesn't exist in IBMToken.cfg, please check the cfg file!")
133
+ except TypeError as te:
134
+ writeErrorMsg(te)
135
+ confFile.close()
136
+ return result
137
+
138
+ #read the config file about the existing algorithm(EA for short)
139
+ def readCfgEA():
140
+ try:
141
+ EAcfg = cfgLocation + "function.cfg"
142
+ confFile = open(EAcfg,"r")
143
+ content = confFile.readlines()
144
+ result = []
145
+ for line in content:
146
+ fileName = json.loads(line)['fileName']
147
+ function = json.loads(line)['entryFunction']
148
+ result.append([fileName,function])
149
+ except IOError as io:
150
+ writeErrorMsg(io)
151
+ except KeyError as ke:
152
+ writeErrorMsg("Key: "+ str(ke) + "doesn't exist in function.cfg, please check the cfg file!")
153
+ confFile.close()
154
+ return result
155
+
-QuQ--master/userCode/ExpWrong.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+
3
+ def wrong():
4
+ c = Circuit(True)
5
+ q = Qubit()
6
+ #the qubit has the same id of q
7
+ q_wrong = Qubit(False,0)
8
+ M(q)
9
+ c.execute(1024)
-QuQ--master/userCode/GroverLite.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+
3
+ def groverLite():
4
+ totalElement = 4
5
+ targetElement = "11"
6
+ #the number of the qubits in theory
7
+ N = 3
8
+ c = Circuit()
9
+ qList = []
10
+ for i in range(0,N):
11
+ q = Qubit()
12
+ qList.append(q)
13
+
14
+ X(qList[N-1])
15
+ for i in range(0,N):
16
+ H(qList[i])
17
+
18
+ #apply the G operator on the qubits
19
+ G(qList,targetElement)
20
+
21
+ #measure the qubits
22
+ for i in range(0,N-1):
23
+ qList[i] = M(qList[i])
24
+
25
+ #execute the circuit for 1024 times
26
+ c.execute(1024)
27
+
28
+ def G(qList:list,target):
29
+ vl = []
30
+ for i in range(0,len(target)):
31
+ vl.append(int(target[i]))
32
+
33
+ with DMif([qList[0],qList[1]],vl) as dmo:
34
+ dmo.X(qList[2])
35
+
36
+ for i in range(0,2):
37
+ H(qList[i])
38
+ X(qList[i])
39
+ H(qList[1])
40
+ CNOT(qList[0],qList[1])
41
+ H(qList[1])
42
+ for i in range(0,2):
43
+ X(qList[i])
44
+ H(qList[i])
45
+
46
+
-QuQ--master/userCode/GroverN=8theory/chart.jpg ADDED

Git LFS Details

  • SHA256: d4fa36589132bc75f7ac37c236084357402c1ff94eed2ac127fc09980d7828fe
  • Pointer size: 130 Bytes
  • Size of remote file: 88.9 kB
-QuQ--master/userCode/GroverN=8theory/qasm.txt ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ OPENQASM 2.0;include "qelib1.inc";qreg q[5];creg c[2];
2
+ h q[0];
3
+ h q[1];
4
+ h q[2];
5
+ h q[3];
6
+ x q[4];
7
+ cx q[1],q[2];
8
+ h q[4];
9
+ tdg q[2];
10
+ h q[4];
11
+ cx q[0],q[2];
12
+ cx q[3],q[4];
13
+ t q[2];
14
+ tdg q[4];
15
+ cx q[1],q[2];
16
+ tdg q[1];
17
+ tdg q[2];
18
+ cx q[0],q[2];
19
+ cx q[0],q[1];
20
+ t q[2];
21
+ tdg q[1];
22
+ h q[2];
23
+ cx q[0],q[1];
24
+ cx q[2],q[4];
25
+ t q[0];
26
+ s q[1];
27
+ t q[4];
28
+ h q[0];
29
+ h q[1];
30
+ cx q[3],q[4];
31
+ x q[0];
32
+ x q[1];
33
+ tdg q[3];
34
+ tdg q[4];
35
+ cx q[2],q[4];
36
+ cx q[2],q[3];
37
+ t q[4];
38
+ tdg q[3];
39
+ h q[4];
40
+ cx q[2],q[3];
41
+ h q[4];
42
+ t q[2];
43
+ s q[3];
44
+ h q[2];
45
+ h q[3];
46
+ cx q[1],q[2];
47
+ x q[3];
48
+ tdg q[2];
49
+ h q[3];
50
+ cx q[0],q[2];
51
+ h q[3];
52
+ t q[2];
53
+ x q[3];
54
+ cx q[1],q[2];
55
+ h q[3];
56
+ tdg q[1];
57
+ tdg q[2];
58
+ cx q[3],q[4];
59
+ cx q[0],q[2];
60
+ tdg q[4];
61
+ cx q[0],q[1];
62
+ t q[2];
63
+ tdg q[1];
64
+ h q[2];
65
+ cx q[0],q[1];
66
+ h q[2];
67
+ t q[0];
68
+ s q[1];
69
+ x q[0];
70
+ x q[1];
71
+ h q[0];
72
+ h q[1];
73
+ cx q[1],q[2];
74
+ tdg q[2];
75
+ cx q[0],q[2];
76
+ t q[2];
77
+ cx q[1],q[2];
78
+ tdg q[1];
79
+ tdg q[2];
80
+ cx q[0],q[2];
81
+ cx q[0],q[1];
82
+ t q[2];
83
+ tdg q[1];
84
+ h q[2];
85
+ cx q[0],q[1];
86
+ cx q[2],q[4];
87
+ t q[0];
88
+ s q[1];
89
+ t q[4];
90
+ h q[0];
91
+ h q[1];
92
+ cx q[3],q[4];
93
+ x q[0];
94
+ x q[1];
95
+ tdg q[3];
96
+ tdg q[4];
97
+ cx q[2],q[4];
98
+ cx q[2],q[3];
99
+ t q[4];
100
+ tdg q[3];
101
+ h q[4];
102
+ cx q[2],q[3];
103
+ t q[2];
104
+ s q[3];
105
+ h q[2];
106
+ h q[3];
107
+ cx q[1],q[2];
108
+ x q[3];
109
+ tdg q[2];
110
+ h q[3];
111
+ cx q[0],q[2];
112
+ h q[3];
113
+ t q[2];
114
+ x q[3];
115
+ cx q[1],q[2];
116
+ h q[3];
117
+ tdg q[1];
118
+ tdg q[2];
119
+ measure q[3] -> c[3];
120
+ cx q[0],q[2];
121
+ cx q[0],q[1];
122
+ t q[2];
123
+ tdg q[1];
124
+ h q[2];
125
+ cx q[0],q[1];
126
+ t q[0];
127
+ s q[1];
128
+ x q[0];
129
+ x q[1];
130
+ h q[0];
131
+ h q[1];
132
+ measure q[0] -> c[0];
133
+ measure q[1] -> c[1];
-QuQ--master/userCode/Test.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+
3
+ def u():
4
+ c = Circuit(True)
5
+ q0 = Qubit()
6
+ q1 = Qubit()
7
+ q2 = Qubit()
8
+ q3 = Qubit()
9
+ Rx(PI/4,q3)
10
+ Rx(PI/4,q3)
11
+ Rx(PI/4,q3)
12
+ Rx(PI/4,q3)
13
+ # with DMif([q0,q1],[1,0]) as dmo:
14
+ # dmo.H(q2)
15
+ # dmo.CNOT(q2,q3)
16
+ # with Qif([q0,q1],[1,0]) as isTrue:
17
+ # if isTrue:
18
+ # H(q2)
19
+ # CNOT(q2,q3)
20
+ #M(q2)
21
+ M(q3)
22
+ c.execute(1024)
23
+ # bt = c.beginTime
24
+ # bm = c.beginMemory
25
+ # sums = 1
26
+ # for i in range(1,2001):
27
+ # sums *= i
28
+ # time.sleep(0.001)
29
+ # c.execute(1)
30
+ # et = c.endTime
31
+ # em = c.endMemory
32
+ # print("消耗时间:%d S"%(et-bt).total_seconds())
33
+ # print("占用内存:%d bit"%(em-bm))
34
+ #c.execute(1)
35
+ # q = Qubit()
36
+ # qList = []
37
+ # for i in range(0,2):
38
+ # qList.append(Qubit())
39
+ # #Rx(PI,qList[0])
40
+ # #Rx(PI,qList[0])
41
+ # #X(q)
42
+ # #QSprint(qList[0])
43
+ # #X(q)
44
+ # #Toffoli(q,qList[0],qList[1])
45
+ # #CNOT(qList[0],qList[1])
46
+ # with Mif([qList[0],qList[1]],[0,0]) as mo:
47
+ # mo.X(q)
48
+ # #mo.H(qList[1])
49
+ # #mo.CNOT(q,qList[1])
50
+ # # mo.CNOT(qList[2],qList[1])
51
+ # q1 = Qubit()
52
+ # q2 = Qubit()
53
+ # Rx(PI,q2)
54
+ # #print(c.qubitExecuteListOD)
55
+ # #Rx(PI/2,q)
56
+ # with DMif([q1,q2],[0,1]) as dmo:
57
+ # dmo.H(q)
58
+ # #dmo.H(qList[1])
59
+ # #q = dmo.Ry(PI,q)[-1]
60
+ # #q = dmo.Rz(-PI/2,q)[-1]
61
+ # # with DMif([qList[0],qList[1]],[1,0]) as dmo:
62
+ # # dmo.H(q)
63
+ # #M(qList[1])
64
+ # #QSprint(q)
65
+ # #QSprint(q.entanglement)
66
+ # #M(q)
67
+ # #QSprint(q)
68
+ # M(q)
69
+ # #M(qList[0])
70
+ #c.execute(1024)
-QuQ--master/userCode/header.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ################################################################
2
+ #Any code file in the floder "userCode" should import this file
3
+ ################################################################
4
+
5
+ import sys
6
+ sys.path.append('../baseClass/')
7
+ sys.path.append('../tools/')
8
+ from Bit import Bit
9
+ from Qubit import *
10
+ from helperFunction import *
11
+ from Circuit import Circuit
12
+ from Gate import *
13
+ from ControlFlow import *
14
+ #from IBMQX import *
15
+ PI = math.pi
.gitattributes CHANGED
@@ -57,3 +57,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ -QuQ--master/doc/references/Simulating[[:space:]]the[[:space:]]Effect[[:space:]]of[[:space:]]Decoherence[[:space:]]and[[:space:]]Inaccuracies[[:space:]]on[[:space:]]a[[:space:]]Quantum[[:space:]]Computer.pdf filter=lfs diff=lfs merge=lfs -text
61
+ -QuQ--master/doc/references/High[[:space:]]Performance[[:space:]]Emulation[[:space:]]of[[:space:]]Quantum[[:space:]]Circuits.pdf filter=lfs diff=lfs merge=lfs -text
0617-audio_stream-master/.pipreqs/requirements_pipreqs.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ matplotlib==3.10.1
2
+ numpy==2.2.4
3
+ Pillow==11.1.0
4
+ scipy==1.15.2
5
+ torch==2.1.0
6
+ torchvision==0.16.0+cu121
0617-audio_stream-master/audio_process.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from hyper import *
4
+ from PIL import Image
5
+ import torchvision.transforms.functional as F
6
+
7
+
8
+ def load_single_sp_gt(sp_name, gt_name):
9
+ audio = Image.open(sp_name).convert('RGB')
10
+ audio_data = F.to_tensor(audio)
11
+ audio_data = F.normalize(audio_data, MEAN, STD)
12
+
13
+ gt = Image.open(gt_name).convert('L')
14
+ gt_data = F.to_tensor(gt)
15
+
16
+ return audio_data, gt_data
0617-audio_stream-master/dataset.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.utils.data as data
2
+ from audio_process import *
3
+ from mean_std import *
4
+
5
+
6
+ class LoadDataset(data.Dataset):
7
+ def __init__(self, root_folder):
8
+ self.root_folder = root_folder
9
+ self.specs = []
10
+ self.gt = []
11
+
12
+ specs_path = self.root_folder.split('frames')[0] + 'specs' + self.root_folder.split('frames')[1]
13
+ print("Specs Root : ", specs_path, "\n")
14
+
15
+ self.specs = [os.path.join(specs_path, f) for f in os.listdir(specs_path) if f.endswith('.jpg')]
16
+ self.gt = [os.path.join(self.root_folder, f) for f in os.listdir(self.root_folder) if f.endswith('.jpg')]
17
+
18
+ self.specs.sort()
19
+ self.gt.sort()
20
+
21
+ def __len__(self):
22
+ return len(self.specs)
23
+
24
+ def __getitem__(self, item):
25
+ sp_name = self.specs[item]
26
+ gt_name = self.gt[item]
27
+
28
+ audio_data, gt_data = load_single_sp_gt(sp_name, gt_name)
29
+
30
+ return audio_data, gt_data
31
+
32
+
33
+ class LoadTestData:
34
+ def __init__(self, test_root):
35
+ # print(test_root, specs_root)
36
+ self.frames = [test_root + f for f in os.listdir(test_root) if f.endswith('.jpg')]
37
+ self.frames = sorted(self.frames)
38
+ self.size = len(self.frames)
39
+ self.index = 0
40
+
41
+ def load_data(self):
42
+ frame = self.data_loader_frames(self.frames[self.index])
43
+ name = self.frames[self.index].split('/')[-1]
44
+ self.index += 1
45
+
46
+ return frame, name, self.index
47
+
48
+ def data_loader_frames(self, name):
49
+ audio = Image.open(name).convert('RGB')
50
+ # convert a PIL image to tensor (HWC) in range [0,255] to a torch.Tensor(CHW) in the range [0.0,1.0]
51
+ audio_data = F.to_tensor(audio)
52
+
53
+ return audio_data
0617-audio_stream-master/model/CPD_models.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torchvision
4
+ from hyper import *
5
+ from model.HolisticAttention import HA
6
+ from model.ResNe3D import resnet18
7
+ from model.ResNet_18 import ResNet2_18
8
+ from model.vgg import B2_VGG
9
+ from model.v_a_con import *
10
+
11
+
12
+ class RFB(nn.Module):
13
+ def __init__(self, in_channel, out_channel):
14
+ super(RFB, self).__init__()
15
+ self.relu = nn.ReLU(True)
16
+ self.branch0 = nn.Sequential(
17
+ nn.Conv2d(in_channel, out_channel, 1),
18
+ )
19
+ self.branch1 = nn.Sequential(
20
+ nn.Conv2d(in_channel, out_channel, 1),
21
+ nn.Conv2d(out_channel, out_channel, kernel_size=(1, 3), padding=(0, 1)),
22
+ nn.Conv2d(out_channel, out_channel, kernel_size=(3, 1), padding=(1, 0)),
23
+ nn.Conv2d(out_channel, out_channel, 3, padding=3, dilation=3)
24
+ )
25
+ self.branch2 = nn.Sequential(
26
+ nn.Conv2d(in_channel, out_channel, 1),
27
+ nn.Conv2d(out_channel, out_channel, kernel_size=(1, 5), padding=(0, 2)),
28
+ nn.Conv2d(out_channel, out_channel, kernel_size=(5, 1), padding=(2, 0)),
29
+ nn.Conv2d(out_channel, out_channel, 3, padding=5, dilation=5)
30
+ )
31
+ self.branch3 = nn.Sequential(
32
+ nn.Conv2d(in_channel, out_channel, 1),
33
+ nn.Conv2d(out_channel, out_channel, kernel_size=(1, 7), padding=(0, 3)),
34
+ nn.Conv2d(out_channel, out_channel, kernel_size=(7, 1), padding=(3, 0)),
35
+ nn.Conv2d(out_channel, out_channel, 3, padding=7, dilation=7)
36
+ )
37
+ self.conv_cat = nn.Conv2d(4 * out_channel, out_channel, 3, padding=1)
38
+ self.conv_res = nn.Conv2d(in_channel, out_channel, 1)
39
+
40
+ for m in self.modules():
41
+ if isinstance(m, nn.Conv2d):
42
+ m.weight.data.normal_(std=0.01)
43
+ m.bias.data.fill_(0)
44
+
45
+ def forward(self, x):
46
+ x0 = self.branch0(x)
47
+ x1 = self.branch1(x)
48
+ x2 = self.branch2(x)
49
+ x3 = self.branch3(x)
50
+
51
+ x_cat = torch.cat((x0, x1, x2, x3), 1)
52
+ x_cat = self.conv_cat(x_cat)
53
+
54
+ x = self.relu(x_cat + self.conv_res(x))
55
+ return x
56
+
57
+
58
+ class aggregation(nn.Module):
59
+ def __init__(self, channel):
60
+ super(aggregation, self).__init__()
61
+ self.relu = nn.ReLU(True)
62
+
63
+ self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
64
+ self.conv_upsample1 = nn.Conv2d(channel, channel, 3, padding=1)
65
+ self.conv_upsample2 = nn.Conv2d(channel, channel, 3, padding=1)
66
+ self.conv_upsample3 = nn.Conv2d(channel, channel, 3, padding=1)
67
+ self.conv_upsample4 = nn.Conv2d(channel, channel, 3, padding=1)
68
+ self.conv_upsample5 = nn.Conv2d(2 * channel, 2 * channel, 3, padding=1)
69
+
70
+ self.conv_concat2 = nn.Conv2d(2 * channel, 2 * channel, 3, padding=1)
71
+ self.conv_concat3 = nn.Conv2d(3 * channel, 3 * channel, 3, padding=1)
72
+ self.conv4 = nn.Conv2d(3 * channel, 3 * channel, 3, padding=1)
73
+ self.conv5 = nn.Conv2d(3 * channel, 1, 1)
74
+
75
+ for m in self.modules():
76
+ if isinstance(m, nn.Conv2d):
77
+ m.weight.data.normal_(std=0.01)
78
+ m.bias.data.fill_(0)
79
+
80
+ def forward(self, x1, x2, x3):
81
+ # x1: 1/16 x2: 1/8 x3: 1/4
82
+ x1_1 = x1
83
+
84
+ x2_1 = self.conv_upsample1(self.upsample(x1)) * x2
85
+
86
+ x3_1 = self.conv_upsample2(self.upsample(self.upsample(x1))) \
87
+ * self.conv_upsample3(self.upsample(x2)) * x3
88
+
89
+ x2_2 = torch.cat((x2_1, self.conv_upsample4(self.upsample(x1_1))), 1)
90
+
91
+ x2_2 = self.conv_concat2(x2_2)
92
+
93
+ x3_2 = torch.cat((x3_1, self.conv_upsample5(self.upsample(x2_2))), 1)
94
+
95
+ x3_2 = self.conv_concat3(x3_2)
96
+
97
+ x = self.conv4(x3_2)
98
+ x = self.conv5(x)
99
+
100
+ return x
101
+
102
+
103
+ class CPD_VGG(nn.Module):
104
+ def __init__(self, channel=32):
105
+ super(CPD_VGG, self).__init__()
106
+ self.vgg = B2_VGG()
107
+ self.rfb3_1 = RFB(256, channel)
108
+ self.rfb4_1 = RFB(512, channel)
109
+ self.rfb5_1 = RFB(512, channel)
110
+ self.agg1 = aggregation(channel)
111
+
112
+ self.rfb3_2 = RFB(256, channel)
113
+ self.rfb4_2 = RFB(512, channel)
114
+ self.rfb5_2 = RFB(512, channel)
115
+ self.agg2 = aggregation(channel)
116
+
117
+ self.HA = HA()
118
+ self.upsample = nn.Upsample(scale_factor=4, mode='bilinear', align_corners=False)
119
+
120
+ def forward(self, x, y):
121
+ x1 = self.vgg.conv1(x)
122
+ x2 = self.vgg.conv2(x1)
123
+ x3 = self.vgg.conv3(x2)
124
+ x3_1 = x3
125
+
126
+ x4_1 = self.vgg.conv4_1(x3_1)
127
+ x5_1 = self.vgg.conv5_1(x4_1)
128
+
129
+ '''
130
+ Audio Stream
131
+ '''
132
+ y1 = self.spec_vgg.conv1(y)
133
+ y2 = self.spec_vgg.conv2(y1)
134
+ y3 = self.spec_vgg.conv3(y2)
135
+ y3_1 = y3
136
+
137
+ y4_1 = self.spec_vgg.conv4_1(y3_1)
138
+ y5_1 = self.spec_vgg.conv5_1(y4_1)
139
+ '''
140
+ video stream and audio stream concentration
141
+ '''
142
+ print("CPD video : ", x3_1.shape, x4_1.shape, x5_1.shape)
143
+ print("CPD audio : ", y3_1.shape, y4_1.shape, y5_1.shape)
144
+ exit(0)
145
+ mix3 = self.v_a_con(x3_1, y3_1)
146
+ mix4 = self.v_a_con(x4_1, y4_1)
147
+ mix5 = self.v_a_con(x5_1, y5_1)
148
+ x3_1 = self.v_a_con.conv_3(mix3)
149
+ x4_1 = self.v_a_con.conv_4(mix4)
150
+ x5_1 = self.v_a_con.conv_5(mix5)
151
+ '''
152
+ print('Conca : ', mix3.shape, mix4.shape, mix5.shape)
153
+ print('Conca : ', x3_1.shape, x4_1.shape, x5_1.shape)
154
+ exit(0)
155
+ '''
156
+ x3_1 = self.rfb3_1(x3_1)
157
+ x4_1 = self.rfb4_1(x4_1)
158
+ x5_1 = self.rfb5_1(x5_1)
159
+
160
+ attention = self.agg1(x5_1, x4_1, x3_1)
161
+
162
+ x3_2 = self.HA(attention.sigmoid(), x3)
163
+ x4_2 = self.vgg.conv4_2(x3_2)
164
+ x5_2 = self.vgg.conv5_2(x4_2)
165
+ x3_2 = self.rfb3_2(x3_2)
166
+ x4_2 = self.rfb4_2(x4_2)
167
+ x5_2 = self.rfb5_2(x5_2)
168
+ detection = self.agg2(x5_2, x4_2, x3_2)
169
+
170
+ return self.upsample(attention), self.upsample(detection)
171
+
172
+
173
+ class CPD_3DResNet(nn.Module):
174
+ def __init__(self, channel=32):
175
+ super(CPD_3DResNet, self).__init__()
176
+ # self.video_branch = resnet18(shortcut_type='A', sample_size=112, sample_duration=16, last_fc=False,
177
+ # last_pool=False)
178
+ # self.audio_branch = resnet18(shortcut_type='A', sample_size=64, sample_duration=16, num_classes=12,
179
+ # last_fc=False, last_pool=True)
180
+ # self.audio_branch = ResNet2_18()
181
+ self.audio_branch = torchvision.models.resnet18(pretrained=False)
182
+
183
+ self.v_a_con = Video_Audio_Con()
184
+
185
+ self.vgg = B2_VGG()
186
+ self.rfb3_1 = RFB(256, channel)
187
+ self.rfb4_1 = RFB(512, channel)
188
+ self.rfb5_1 = RFB(512, channel)
189
+ self.agg1 = aggregation(channel)
190
+
191
+ self.rfb3_2 = RFB(256, channel)
192
+ self.rfb4_2 = RFB(512, channel)
193
+ self.rfb5_2 = RFB(512, channel)
194
+ self.agg2 = aggregation(channel)
195
+
196
+ self.HA = HA()
197
+
198
+ self.upsample_a1 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
199
+ self.upsample_a2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
200
+ self.upsample_a3 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
201
+ '''
202
+ '''
203
+ self.upsample = nn.Upsample(scale_factor=4, mode='bilinear', align_corners=False)
204
+
205
+ def forward(self, a):
206
+ # f_num = 3, [bs, 128, 32, 40] [bs, 256, 16, 20] [bs, 512, 8, 10]
207
+ # v1, v2, v3 = self.video_branch(v)
208
+ a1, a2, a3 = self.audio_branch(a)
209
+
210
+ '''
211
+ a1 = self.v_a_con_audio.upsample_a1(a1)
212
+ detection = self.v_a_con_audio.conv_last(a1)
213
+ '''
214
+ '''
215
+ print(a1.shape, a2.shape, a3.shape)
216
+ exit(0)
217
+ '''
218
+
219
+ '''
220
+ a1 = torch.squeeze(a1, dim=2)
221
+ a1 = self.v_a_con_10.upsample_a1(a1)
222
+ detection = self.v_a_con_10.conv_last(a1)
223
+ '''
224
+
225
+ a1 = self.upsample_a1(a1)
226
+ a2 = self.upsample_a2(a2)
227
+ a3 = self.upsample_a3(a3)
228
+
229
+ x3_1 = self.v_a_con.conv_3(a1)
230
+ x4_1 = self.v_a_con.conv_4(a2)
231
+ x5_1 = self.v_a_con.conv_5(a3)
232
+
233
+ xx = x3_1
234
+ # print(x3_1.shape, x4_1.shape, x5_1.shape)
235
+
236
+ x3_1 = self.rfb3_1(x3_1)
237
+ x4_1 = self.rfb4_1(x4_1)
238
+ x5_1 = self.rfb5_1(x5_1)
239
+ # print(x3_1.shape, x4_1.shape, x5_1.shape)
240
+
241
+ attention = self.agg1(x5_1, x4_1, x3_1)
242
+
243
+ x3_2 = self.HA(attention.sigmoid(), xx)
244
+ x4_2 = self.vgg.conv4_2(x3_2)
245
+ x5_2 = self.vgg.conv5_2(x4_2)
246
+ # print(x3_2.shape, x4_2.shape, x5_2.shape)
247
+ # exit(0)
248
+
249
+ x3_2 = self.rfb3_2(x3_2)
250
+ x4_2 = self.rfb4_2(x4_2)
251
+ x5_2 = self.rfb5_2(x5_2)
252
+ detection = self.agg2(x5_2, x4_2, x3_2)
253
+
254
+ '''
255
+ '''
256
+ return self.upsample(detection)
0617-audio_stream-master/model/HolisticAttention.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import torch.nn as nn
4
+ from torch.nn.parameter import Parameter
5
+
6
+ import numpy as np
7
+ import scipy.stats as st
8
+
9
+
10
+ def gkern(kernlen=16, nsig=3):
11
+ interval = (2*nsig+1.)/kernlen
12
+ x = np.linspace(-nsig-interval/2., nsig+interval/2., kernlen+1)
13
+ kern1d = np.diff(st.norm.cdf(x))
14
+ kernel_raw = np.sqrt(np.outer(kern1d, kern1d))
15
+ kernel = kernel_raw/kernel_raw.sum()
16
+ return kernel
17
+
18
+
19
+ def min_max_norm(in_):
20
+ max_ = in_.max(3)[0].max(2)[0].unsqueeze(2).unsqueeze(3).expand_as(in_)
21
+ min_ = in_.min(3)[0].min(2)[0].unsqueeze(2).unsqueeze(3).expand_as(in_)
22
+ in_ = in_ - min_
23
+ return in_.div(max_-min_+1e-8)
24
+
25
+
26
+ class HA(nn.Module):
27
+ # holistic attention module
28
+ def __init__(self):
29
+ super(HA, self).__init__()
30
+ gaussian_kernel = np.float32(gkern(31, 4))
31
+ gaussian_kernel = gaussian_kernel[np.newaxis, np.newaxis, ...]
32
+ self.gaussian_kernel = Parameter(torch.from_numpy(gaussian_kernel))
33
+
34
+ def forward(self, attention, x):
35
+
36
+ soft_attention = F.conv2d(attention, self.gaussian_kernel, padding=15)
37
+ soft_attention = min_max_norm(soft_attention)
38
+ x = torch.mul(x, soft_attention.max(attention))
39
+
40
+ return x
0617-audio_stream-master/model/vgg.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ class B2_VGG(nn.Module):
5
+ # VGG16 with two branches
6
+ # pooling layer at the front of block
7
+ def __init__(self):
8
+ super(B2_VGG, self).__init__()
9
+ conv1 = nn.Sequential()
10
+ conv1.add_module('conv1_1', nn.Conv2d(3, 64, 3, 1, 1))
11
+ conv1.add_module('relu1_1', nn.ReLU(inplace=True))
12
+ conv1.add_module('conv1_2', nn.Conv2d(64, 64, 3, 1, 1))
13
+ conv1.add_module('relu1_2', nn.ReLU(inplace=True))
14
+
15
+ self.conv1 = conv1
16
+ conv2 = nn.Sequential()
17
+ conv2.add_module('pool1', nn.AvgPool2d(2, stride=2))
18
+ conv2.add_module('conv2_1', nn.Conv2d(64, 128, 3, 1, 1))
19
+ conv2.add_module('relu2_1', nn.ReLU())
20
+ conv2.add_module('conv2_2', nn.Conv2d(128, 128, 3, 1, 1))
21
+ conv2.add_module('relu2_2', nn.ReLU())
22
+ self.conv2 = conv2
23
+
24
+ conv3 = nn.Sequential()
25
+ conv3.add_module('pool2', nn.AvgPool2d(2, stride=2))
26
+ conv3.add_module('conv3_1', nn.Conv2d(128, 256, 3, 1, 1))
27
+ conv3.add_module('relu3_1', nn.ReLU())
28
+ conv3.add_module('conv3_2', nn.Conv2d(256, 256, 3, 1, 1))
29
+ conv3.add_module('relu3_2', nn.ReLU())
30
+ conv3.add_module('conv3_3', nn.Conv2d(256, 256, 3, 1, 1))
31
+ conv3.add_module('relu3_3', nn.ReLU())
32
+ self.conv3 = conv3
33
+
34
+ conv4_1 = nn.Sequential()
35
+ conv4_1.add_module('pool3_1', nn.AvgPool2d(2, stride=2))
36
+ conv4_1.add_module('conv4_1_1', nn.Conv2d(256, 512, 3, 1, 1))
37
+ conv4_1.add_module('relu4_1_1', nn.ReLU())
38
+ conv4_1.add_module('conv4_2_1', nn.Conv2d(512, 512, 3, 1, 1))
39
+ conv4_1.add_module('relu4_2_1', nn.ReLU())
40
+ conv4_1.add_module('conv4_3_1', nn.Conv2d(512, 512, 3, 1, 1))
41
+ conv4_1.add_module('relu4_3_1', nn.ReLU())
42
+ self.conv4_1 = conv4_1
43
+
44
+ conv5_1 = nn.Sequential()
45
+ conv5_1.add_module('pool4_1', nn.AvgPool2d(2, stride=2))
46
+ conv5_1.add_module('conv5_1_1', nn.Conv2d(512, 512, 3, 1, 1))
47
+ conv5_1.add_module('relu5_1_1', nn.ReLU())
48
+ conv5_1.add_module('conv5_2_1', nn.Conv2d(512, 512, 3, 1, 1))
49
+ conv5_1.add_module('relu5_2_1', nn.ReLU())
50
+ conv5_1.add_module('conv5_3_1', nn.Conv2d(512, 512, 3, 1, 1))
51
+ conv5_1.add_module('relu5_3_1', nn.ReLU())
52
+ self.conv5_1 = conv5_1
53
+
54
+ conv4_2 = nn.Sequential()
55
+ conv4_2.add_module('pool3_2', nn.AvgPool2d(2, stride=2))
56
+ conv4_2.add_module('conv4_1_2', nn.Conv2d(256, 512, 3, 1, 1))
57
+ conv4_2.add_module('relu4_1_2', nn.ReLU())
58
+ conv4_2.add_module('conv4_2_2', nn.Conv2d(512, 512, 3, 1, 1))
59
+ conv4_2.add_module('relu4_2_2', nn.ReLU())
60
+ conv4_2.add_module('conv4_3_2', nn.Conv2d(512, 512, 3, 1, 1))
61
+ conv4_2.add_module('relu4_3_2', nn.ReLU())
62
+ self.conv4_2 = conv4_2
63
+
64
+ conv5_2 = nn.Sequential()
65
+ conv5_2.add_module('pool4_2', nn.AvgPool2d(2, stride=2))
66
+ conv5_2.add_module('conv5_1_2', nn.Conv2d(512, 512, 3, 1, 1))
67
+ conv5_2.add_module('relu5_1_2', nn.ReLU())
68
+ conv5_2.add_module('conv5_2_2', nn.Conv2d(512, 512, 3, 1, 1))
69
+ conv5_2.add_module('relu5_2_2', nn.ReLU())
70
+ conv5_2.add_module('conv5_3_2', nn.Conv2d(512, 512, 3, 1, 1))
71
+ conv5_2.add_module('relu5_3_2', nn.ReLU())
72
+ self.conv5_2 = conv5_2
73
+
74
+ # pre_train = torch.load('~/.torch/models/vgg16-397923af.pth')
75
+ # pre_train = torch.load('pre-trained/vgg16-397923af.pth')
76
+ # self._initialize_weights(pre_train)
77
+ print("\n===== This is VGG !=====\n")
78
+
79
+ def forward(self, x):
80
+ x = self.conv1(x)
81
+ x = self.conv2(x)
82
+ x = self.conv3(x)
83
+ x1 = self.conv4_1(x)
84
+ x1 = self.conv5_1(x1)
85
+ x2 = self.conv4_2(x)
86
+ x2 = self.conv5_2(x2)
87
+ return x1, x2
88
+
89
+ def _initialize_weights(self, pre_train):
90
+ keys = pre_train.keys()
91
+ keys=list(pre_train.keys())
92
+ self.conv1.conv1_1.weight.data.copy_(pre_train[keys[0]])
93
+ self.conv1.conv1_2.weight.data.copy_(pre_train[keys[2]])
94
+ self.conv2.conv2_1.weight.data.copy_(pre_train[keys[4]])
95
+ self.conv2.conv2_2.weight.data.copy_(pre_train[keys[6]])
96
+ self.conv3.conv3_1.weight.data.copy_(pre_train[keys[8]])
97
+ self.conv3.conv3_2.weight.data.copy_(pre_train[keys[10]])
98
+ self.conv3.conv3_3.weight.data.copy_(pre_train[keys[12]])
99
+ self.conv4_1.conv4_1_1.weight.data.copy_(pre_train[keys[14]])
100
+ self.conv4_1.conv4_2_1.weight.data.copy_(pre_train[keys[16]])
101
+ self.conv4_1.conv4_3_1.weight.data.copy_(pre_train[keys[18]])
102
+ self.conv5_1.conv5_1_1.weight.data.copy_(pre_train[keys[20]])
103
+ self.conv5_1.conv5_2_1.weight.data.copy_(pre_train[keys[22]])
104
+ self.conv5_1.conv5_3_1.weight.data.copy_(pre_train[keys[24]])
105
+ self.conv4_2.conv4_1_2.weight.data.copy_(pre_train[keys[14]])
106
+ self.conv4_2.conv4_2_2.weight.data.copy_(pre_train[keys[16]])
107
+ self.conv4_2.conv4_3_2.weight.data.copy_(pre_train[keys[18]])
108
+ self.conv5_2.conv5_1_2.weight.data.copy_(pre_train[keys[20]])
109
+ self.conv5_2.conv5_2_2.weight.data.copy_(pre_train[keys[22]])
110
+ self.conv5_2.conv5_3_2.weight.data.copy_(pre_train[keys[24]])
111
+
112
+ self.conv1.conv1_1.bias.data.copy_(pre_train[keys[1]])
113
+ self.conv1.conv1_2.bias.data.copy_(pre_train[keys[3]])
114
+ self.conv2.conv2_1.bias.data.copy_(pre_train[keys[5]])
115
+ self.conv2.conv2_2.bias.data.copy_(pre_train[keys[7]])
116
+ self.conv3.conv3_1.bias.data.copy_(pre_train[keys[9]])
117
+ self.conv3.conv3_2.bias.data.copy_(pre_train[keys[11]])
118
+ self.conv3.conv3_3.bias.data.copy_(pre_train[keys[13]])
119
+ self.conv4_1.conv4_1_1.bias.data.copy_(pre_train[keys[15]])
120
+ self.conv4_1.conv4_2_1.bias.data.copy_(pre_train[keys[17]])
121
+ self.conv4_1.conv4_3_1.bias.data.copy_(pre_train[keys[19]])
122
+ self.conv5_1.conv5_1_1.bias.data.copy_(pre_train[keys[21]])
123
+ self.conv5_1.conv5_2_1.bias.data.copy_(pre_train[keys[23]])
124
+ self.conv5_1.conv5_3_1.bias.data.copy_(pre_train[keys[25]])
125
+ self.conv4_2.conv4_1_2.bias.data.copy_(pre_train[keys[15]])
126
+ self.conv4_2.conv4_2_2.bias.data.copy_(pre_train[keys[17]])
127
+ self.conv4_2.conv4_3_2.bias.data.copy_(pre_train[keys[19]])
128
+ self.conv5_2.conv5_1_2.bias.data.copy_(pre_train[keys[21]])
129
+ self.conv5_2.conv5_2_2.bias.data.copy_(pre_train[keys[23]])
130
+ self.conv5_2.conv5_3_2.bias.data.copy_(pre_train[keys[25]])
0617-audio_stream-master/train.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import matplotlib.pyplot as plt
3
+ import torch
4
+ import numpy as np
5
+ from torch.autograd import Variable
6
+ from torch.utils.data import DataLoader
7
+ from dataset import LoadDataset
8
+ from hyper import *
9
+ from model.CPD_models import CPD_3DResNet
10
+
11
+ torch.cuda.set_device(0)
12
+
13
+
14
+ class Train(object):
15
+ def __init__(self):
16
+ super(Train, self).__init__()
17
+ self.train_list = [os.path.join(train_data_path, p) for p in os.listdir(train_data_path)]
18
+ self.model = CPD_3DResNet()
19
+ self.optimizer = torch.optim.Adam(self.model.parameters(), lr=lr)
20
+ self.optimizer_name = str(self.optimizer).split(' ')[0]
21
+ self.func_name = str(obj_func).split('()')[0]
22
+ self.model = self.model.cuda()
23
+ self.loss_dict = []
24
+ self.lr = lr
25
+ # self.model.load_state_dict(torch.load(checkpoint_load))
26
+
27
+ save_model = torch.load(checkpoint_load)
28
+ # save_model = torch.load(checkpoint_load)['state_dict']
29
+ now_model = self.model.state_dict()
30
+ state_dict = {k: v for k, v in save_model.items() if k in now_model.keys()}
31
+ now_model.update(state_dict)
32
+ self.model.load_state_dict(now_model)
33
+ '''
34
+ dict_name = list(state_dict)
35
+ for i1, p1 in enumerate(dict_name):
36
+ print(i1, p1)
37
+
38
+ exit(0)
39
+
40
+ f = 0
41
+ # 329
42
+ for name, para in self.model.named_parameters():
43
+ f += 1
44
+ self.flag = [1 for x in range(0, f)]
45
+
46
+ ff = 0
47
+ for name, para in self.model.named_parameters():
48
+ for i1, p1 in enumerate(dict_name):
49
+ if name == p1:
50
+ ff = i1
51
+ self.flag[ff] = 0
52
+ # print(i1, name)
53
+ # exit(0)
54
+ '''
55
+
56
+ print("\n================\nPre-Model setup OK !\n================")
57
+ # self.checkpoint_save = 'No_Pretrained'
58
+ torch.cuda.empty_cache()
59
+ self.checkpoint_save = checkpoint_save + 'cpd_' + now[5:7] + now[8:10]
60
+
61
+ def train(self):
62
+ # 新建保存 checkpoint 的文件夹
63
+ if not os.path.exists(self.checkpoint_save):
64
+ os.makedirs(self.checkpoint_save)
65
+
66
+ for epoch in range(epochs):
67
+ print("=====This is Epoch =====", epoch)
68
+ '''
69
+ if epoch < 2:
70
+ for idx, p in enumerate(self.model.parameters()):
71
+ if self.flag[idx] == 0:
72
+ p.requires_grad = False
73
+ else:
74
+ for idx, p in enumerate(self.model.parameters()):
75
+ p.requires_grad = True
76
+
77
+ fixed = 1
78
+ '''
79
+
80
+ if epoch % decay == 0:
81
+ for param_group in self.optimizer.param_groups:
82
+ param_group['lr'] = self.lr * 0.1
83
+ self.lr = param_group['lr']
84
+ print("learning rate : {}".format(self.optimizer.state_dict()['param_groups'][0]['lr']))
85
+ learning_rate = str(self.optimizer.state_dict()['param_groups'][0]['lr'])
86
+
87
+ dir_num = 0
88
+
89
+ for dir in self.train_list:
90
+ i = 0
91
+ train_set = LoadDataset(dir)
92
+ train_loader = DataLoader(train_set, batch_size=batch_size,
93
+ num_workers=0, shuffle=True)
94
+
95
+ for idx, train_data in enumerate(train_loader):
96
+ audio, gt = train_data
97
+ # print('Train : ', audio.shape, gt.shape)
98
+ # exit(0)
99
+ # torch.Size([bs, 3, f_num, 256, 320])
100
+ # torch.Size([bs, 3, f_num, 256, 320])
101
+ # torch.Size([bs, 1, 256, 320])
102
+
103
+ # image = Variable(image).cuda()
104
+ audio = Variable(audio).cuda()
105
+ gt = Variable(gt).cuda()
106
+
107
+ det = self.model(audio)
108
+ # print('Result : ', det.shape, gt.shape)
109
+ # exit(0)
110
+
111
+ # loss1 = obj_func(att, gt)
112
+ loss2 = obj_func(det, gt)
113
+ loss = loss2
114
+
115
+ self.optimizer.zero_grad()
116
+ loss.backward()
117
+ self.optimizer.step()
118
+ self.loss_dict.append(loss.item())
119
+
120
+ i += 1
121
+
122
+ print('Epoch: [{}], Root_folder: {}, Frames: {}, Enumerate: {}\n=====Loss: {:.6f}=====\n'.format(
123
+ epoch, dir, len(train_set), i, loss.item()))
124
+ '''
125
+ dir_num += 1
126
+ if dir_num == 500:
127
+ break
128
+ '''
129
+ if epoch % save_hop == 0:
130
+ torch.save(self.model.state_dict(),
131
+ os.path.join(self.checkpoint_save, 'model_%s_%s_%s_%d_%s_%d.pth' % (checkpoint_name,
132
+ self.optimizer_name,
133
+ learning_rate,
134
+ batch_size,
135
+ self.func_name,
136
+ epoch)))
137
+
138
+ end_time = str(datetime.now())[11:13] + str(datetime.now())[14:16]
139
+ save_name = './charts/' + self.optimizer_name + '_' + str(lr) + '_' + self.func_name + '_' + end_time + '.png'
140
+ plt.title(self.optimizer_name + '_' + str(lr) + '_' + str(epochs) + '_' + str(decay) + '_' + str(fixed) + end_time)
141
+ plt.xlabel('batch')
142
+ plt.ylabel('loss')
143
+
144
+ plt.plot(self.loss_dict)
145
+ plt.savefig(save_name)
146
+ plt.show()
147
+
148
+
149
+ if __name__ == '__main__':
150
+ t = Train()
151
+ t.train()
0621_test-master/django_app/config/settings.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Django settings for test_project project.
3
+
4
+ Generated by 'django-admin startproject' using Django 1.11.2.
5
+
6
+ For more information on this file, see
7
+ https://docs.djangoproject.com/en/1.11/topics/settings/
8
+
9
+ For the full list of settings and their values, see
10
+ https://docs.djangoproject.com/en/1.11/ref/settings/
11
+ """
12
+
13
+ import os
14
+
15
+ # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
18
+
19
+
20
+ # Quick-start development settings - unsuitable for production
21
+ # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
22
+
23
+ # SECURITY WARNING: keep the secret key used in production secret!
24
+ SECRET_KEY = 'v^72um0=i317_-3&g^1q&!9e)wcit&*mlt_ejz#p03_vu=9p1s'
25
+
26
+ # SECURITY WARNING: don't run with debug turned on in production!
27
+ DEBUG = True
28
+
29
+ ALLOWED_HOSTS = []
30
+
31
+
32
+ # Application definition
33
+
34
+ INSTALLED_APPS = [
35
+ 'django.contrib.admin',
36
+ 'django.contrib.auth',
37
+ 'django.contrib.contenttypes',
38
+ 'django.contrib.sessions',
39
+ 'django.contrib.messages',
40
+ 'django.contrib.staticfiles',
41
+
42
+ 'django_extensions',
43
+
44
+ 'post'
45
+ ]
46
+
47
+ MIDDLEWARE = [
48
+ 'django.middleware.security.SecurityMiddleware',
49
+ 'django.contrib.sessions.middleware.SessionMiddleware',
50
+ 'django.middleware.common.CommonMiddleware',
51
+ 'django.middleware.csrf.CsrfViewMiddleware',
52
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
53
+ 'django.contrib.messages.middleware.MessageMiddleware',
54
+ 'django.middleware.clickjacking.XFrameOptionsMiddleware',
55
+ ]
56
+
57
+ ROOT_URLCONF = 'config.urls'
58
+
59
+ TEMPLATES = [
60
+ {
61
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
62
+ 'DIRS': [
63
+ TEMPLATES_DIR
64
+ ],
65
+ 'APP_DIRS': True,
66
+ 'OPTIONS': {
67
+ 'context_processors': [
68
+ 'django.template.context_processors.debug',
69
+ 'django.template.context_processors.request',
70
+ 'django.contrib.auth.context_processors.auth',
71
+ 'django.contrib.messages.context_processors.messages',
72
+ ],
73
+ },
74
+ },
75
+ ]
76
+
77
+ WSGI_APPLICATION = 'config.wsgi.application'
78
+
79
+
80
+ # Database
81
+ # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
82
+
83
+ DATABASES = {
84
+ 'default': {
85
+ 'ENGINE': 'django.db.backends.sqlite3',
86
+ 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
87
+ }
88
+ }
89
+
90
+
91
+ # Password validation
92
+ # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
93
+
94
+ AUTH_PASSWORD_VALIDATORS = [
95
+ {
96
+ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
97
+ },
98
+ {
99
+ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
100
+ },
101
+ {
102
+ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
103
+ },
104
+ {
105
+ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
106
+ },
107
+ ]
108
+
109
+
110
+ # Internationalization
111
+ # https://docs.djangoproject.com/en/1.11/topics/i18n/
112
+
113
+ LANGUAGE_CODE = 'en-us'
114
+
115
+ TIME_ZONE = 'UTC'
116
+
117
+ USE_I18N = True
118
+
119
+ USE_L10N = True
120
+
121
+ USE_TZ = True
122
+
123
+
124
+ # Static files (CSS, JavaScript, Images)
125
+ # https://docs.djangoproject.com/en/1.11/howto/static-files/
126
+
127
+ STATIC_URL = '/static/'
0621_test-master/django_app/config/wsgi.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ WSGI config for test_project project.
3
+
4
+ It exposes the WSGI callable as a module-level variable named ``application``.
5
+
6
+ For more information on this file, see
7
+ https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
8
+ """
9
+
10
+ import os
11
+
12
+ from django.core.wsgi import get_wsgi_application
13
+
14
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
15
+
16
+ application = get_wsgi_application()
0621_test-master/django_app/post/admin.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from django.contrib import admin
2
+
3
+ from .models import Post
4
+
5
+ admin.site.register(Post)
0621_test-master/django_app/post/forms.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from django import forms
2
+
3
+
4
+ class CommentForm(forms.Form):
5
+ comment = forms.CharField(max_length=200)
0621_test-master/django_app/post/migrations/0001_initial.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by Django 1.11.2 on 2017-06-21 06:46
3
+ from __future__ import unicode_literals
4
+
5
+ from django.db import migrations, models
6
+
7
+
8
+ class Migration(migrations.Migration):
9
+
10
+ initial = True
11
+
12
+ dependencies = [
13
+ ]
14
+
15
+ operations = [
16
+ migrations.CreateModel(
17
+ name='Post',
18
+ fields=[
19
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
20
+ ('comment', models.CharField(max_length=200)),
21
+ ('created_date', models.DateTimeField(auto_now_add=True)),
22
+ ('modify_date', models.DateTimeField(auto_now=True)),
23
+ ],
24
+ ),
25
+ ]
0621_test-master/django_app/post/tests.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from django.test import TestCase
2
+
3
+ # Create your tests here.
0621_test-master/django_app/templates/post/post_list.html ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="ko">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport"
6
+ content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
7
+ <meta http-equiv="X-UA-Compatible" content="ie=edge">
8
+ <title>Document</title>
9
+ </head>
10
+ <body>
11
+
12
+ {% for post in posts %}
13
+ {{ post.comment }}
14
+ <a href="{{request.path}}{{post.id}}/modify">수정</a>
15
+ <form action="{{request.path}}{{post.id}}/delete" method="post">
16
+ {% csrf_token %}
17
+ <button type="submit">삭제</button>
18
+ </form>
19
+ <br>
20
+ {% endfor %}
21
+
22
+ </body>
23
+ </html>
0621_test-master/django_app/templates/post/post_modify.html ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="ko">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport"
6
+ content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
7
+ <meta http-equiv="X-UA-Compatible" content="ie=edge">
8
+ <title>Document</title>
9
+ </head>
10
+ <body>
11
+ <form action="" method="post">
12
+ {% csrf_token %}
13
+ {{form}}
14
+ <button type="submit">수정</button>
15
+ </form>
16
+ </body>
17
+ </html>
0621_test-master/requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ appnope==0.1.0
2
+ decorator==4.0.11
3
+ Django==1.11.2
4
+ django-extensions==1.7.9
5
+ ipython==6.1.0
6
+ ipython-genutils==0.2.0
7
+ jedi==0.10.2
8
+ pexpect==4.2.1
9
+ pickleshare==0.7.4
10
+ prompt-toolkit==1.0.14
11
+ ptyprocess==0.5.1
12
+ Pygments==2.2.0
13
+ pytz==2017.2
14
+ simplegeneric==0.8.1
15
+ six==1.10.0
16
+ traitlets==4.3.2
17
+ wcwidth==0.1.7
10-week-algorithm-excercise-master/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .idea/*
2
+ .idea
10-week-algorithm-excercise-master/.pipreqs/requirements_pipreqs.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.go ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func twoSum(nums []int, target int) []int {
4
+ cache := make(map[int]int, 0)
5
+ for i, n := range nums {
6
+ m := target - n
7
+ if j, ok := cache[m]; ok {
8
+ return []int{j, i}
9
+ }
10
+ cache[n] = i
11
+ }
12
+ return nil
13
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ class Solution:
4
+ def twoSum(self, nums: List[int], target: int) -> List[int]:
5
+ cache = {}
6
+ for i, n in enumerate(nums):
7
+ m = target - n
8
+ if m in cache:
9
+ return [cache[m], i]
10
+ cache[n] = i
11
+ return []
10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "strings"
4
+
5
+ func removeOuterParentheses(S string) string {
6
+ var strs []string
7
+ start := 0
8
+ counter := 0
9
+ for i, c := range S {
10
+ if c == '(' {
11
+ counter++
12
+ } else {
13
+ counter--
14
+ }
15
+ if counter == 0 {
16
+ strs = append(strs, S[start+1:i])
17
+ start = i + 1
18
+ }
19
+ }
20
+ return strings.Join(strs, "")
21
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses_test.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ tests := []struct {
7
+ S string
8
+ target string
9
+ }{
10
+ {"", ""},
11
+ {"()", ""},
12
+ {"(())", "()"},
13
+ {"()()", ""},
14
+ {"(()())", "()()"},
15
+ {"(()())((()))", "()()(())"},
16
+ }
17
+
18
+ for _, tt := range tests {
19
+ if ans := removeOuterParentheses(tt.S); ans != tt.target {
20
+ t.Fatalf("S: %s, target: %s, ans: %s\n", tt.S, tt.target, ans)
21
+ }
22
+ }
23
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.go ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func maxDepth2(root *TreeNode) int {
4
+ if root == nil {
5
+ return 0
6
+ }
7
+ return max(maxDepth2(root.Left), maxDepth2(root.Right)) + 1
8
+ }
9
+
10
+ func max(x, y int) int {
11
+ if x > y {
12
+ return x
13
+ }
14
+ return y
15
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class TreeNode:
2
+ def __init__(self, x):
3
+ self.val = x
4
+ self.left = None
5
+ self.right = None
6
+
7
+
8
+ class Solution:
9
+ def maxDepth(self, root: TreeNode) -> int:
10
+ if root is None:
11
+ return 0
12
+ return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def threeSum(self, nums: List[int]) -> List[List[int]]:
6
+ nums.sort()
7
+ res = []
8
+ for i in range(len(nums) - 2):
9
+ if nums[i] > 0:
10
+ break
11
+ if i > 0 and nums[i] == nums[i - 1]:
12
+ continue
13
+
14
+ j, k = i + 1, len(nums) - 1
15
+ while j < k:
16
+ s = nums[i] + nums[j] + nums[k]
17
+ if s == 0:
18
+ res.append([nums[i], nums[j], nums[k]])
19
+ j += 1
20
+ k -= 1
21
+ while j < k and nums[j] == nums[j - 1]:
22
+ j += 1
23
+ while j < k and nums[k] == nums[k + 1]:
24
+ k -= 1
25
+ elif s > 0:
26
+ k -= 1
27
+ while j < k and nums[k] == nums[k + 1]:
28
+ k -= 1
29
+ else:
30
+ j += 1
31
+ while j < k and nums[j] == nums[j - 1]:
32
+ j += 1
33
+ return res