-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
811 lines (723 loc) · 33.2 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Quantum Computing Circuit Designer for Q#</title>
<link rel="stylesheet" href="https://unpkg.com/spectre.css/dist/spectre.min.css">
<link rel="stylesheet" href="https://unpkg.com/spectre.css/dist/spectre-icons.min.css">
<style>
/* https://codepen.io/jasonadelia/pen/DnrAe */
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
height: 100%;
background-color: #434343;
background-image: linear-gradient(#434343, #282828);
}
pre {-moz-tab-size: 4;} /* Firefox */
pre {tab-size: 4;}
.navbar {
border-bottom:1px solid darkgray;
background:#444;
height:55px;
-webkit-box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.75);
box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.75);
}
.modal-wide {
max-width: 90%;
}
.clickable {
cursor:pointer;
}
.gate-toolbar{
z-index: 300;/* note: modal's backdrop is 400 */
}
#main {
background-color: transparent;
background-image: linear-gradient(0deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent), linear-gradient(90deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent);
height: 100%;
background-size: 100px 100px;
}
.qubit-line {
border: 3px solid #222;
position: absolute;
width:90%;
}
.gate {
background-color: #333;
width: 46px; /* border 1px each side */
height: 46px;
border: 1px solid #666;
font-family:Arial, Helvetica, sans-serif;
z-index:100;
-webkit-box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.75);
box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.75);
}
.gate-placeholder {
border: 2px dashed white!important;
position:absolute;
width: 39px!important;
height: 39px!important;
}
.qubit-placeholder {
display:none;
}
.gate:before {
line-height: 46px;
display: flex;
justify-content: center;
align-items: center;
color:#bbb;
font-weight: 100;
}
.X:before {
content:"X";
font-size:2.5em;
}
.Y:before {
content:"Y";
font-size:2.5em;
}
.Z:before {
content:"Z";
font-size:2.5em;
}
.T:before {
content:"T";
font-size:2.5em;
}
.P:before {
content:"P";
font-size:2.5em;
}
.H:before {
content: "H";
font-size:2.5em;
}
.M:before {
content: "M";
font-size:2.5em;
}
/* maybe svg is better */
/* https://editor.method.ac/ */
.CNOT {
/*
height:110px;
background: linear-gradient(#676767 0% 100%);
background-repeat: no-repeat;
background-size: 5px 110px;
background-position: 21px 20px;
*/
/* cancel default gate expression */
border:none;
background-color:transparent;
-webkit-box-shadow: 0px 0px 0px 0px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 0px 0px 0px rgba(0,0,0,0.75);
box-shadow: 0px 0px 0px 0px rgba(0,0,0,0.75);
/* vertical bar */
/*
height:110px;
background: linear-gradient(#676767 0% 100%);
background-repeat: no-repeat;
background-size: 5px 110px;
background-position: 24px 20px;
*/
}
.CNOT:before {
/*content:"ᐧ";*/
content:url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPGNpcmNsZSByPSI5IiBjeD0iMTAiIGN5PSIxMCIgc3Ryb2tlLXdpZHRoPSIxIiBzdHJva2U9IiM5OTkiIGZpbGw9IiNmN2Y5ZjkiLz4KPC9zdmc+');
padding-top:7px;
padding-left:15px;
position: fixed;
/*margin-bottom:55px;*/ /* y pos of XOR */
top:-164px;
/* vertical bar */
height:180px;
background: linear-gradient(#676767 0% 100%);
background-repeat: no-repeat;
background-size: 5px 110px;
background-position: 23px 100px;
}
.CNOT:after {
/* content:"⊕"; */
content:url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPGNpcmNsZSByPSIxOCIgY3g9IjIwIiBjeT0iMjAiIHN0cm9rZS13aWR0aD0iNCIgc3Ryb2tlPSIjZjdmOWY5IiBmaWxsLW9wYWNpdHk9IjAiLz4KICA8bGluZSB4MT0iMjAiIHkxPSIyIiB4Mj0iMjAiIHkyPSIzOCIgc3Ryb2tlLXdpZHRoPSI0IiBzdHJva2U9IiNmN2Y5ZjkiIC8+CiAgPGxpbmUgeDE9IjIiIHkxPSIyMCIgeDI9IjM4IiB5Mj0iMjAiIHN0cm9rZS13aWR0aD0iNCIgc3Ryb2tlPSIjZjdmOWY5IiAvPgo8L3N2Zz4K');
position:fixed;
padding-top:6px;
padding-left:5px;
}
.Q:before {
content:"❘0⟩";
font-size:1.8em;
}
.Q {
background-color:#262626;
}
</style>
</head>
<body>
<header class="navbar" id="toolbar">
<section class="navbar-section">
<h1 class="navbar-brand mr-2 text-light ml-2">Quantum Computing Circuit Designer</h1>
<!-- <a class="btn ml-2" onClick="test()">Test to Add Some Gates</a> -->
</section>
<section class="navbar-section">
<div class="input-group input-inline">
<button class="btn" onClick="showExport()">Code <i class="icon icon-resize-horiz"></i></button>
<button class="btn" onClick="showExamples()">Examples <i class="icon icon-apps"></i></button>
<button id="export-button" class="btn" onClick="addQubit()">Qubit <i class="icon icon-plus"></i></button>
</div>
</section>
</header>
<div id="main">
</div>
<!-- EXPORT MODAL DIALOG -->
<div class="modal " id="modal-export">
<a href="#close" class="modal-overlay" onClick="hideDialog('modal-export')"></a>
<div class="modal-container modal-wide">
<div class="modal-header pt-3 pl-0 pr-0">
<a href="#close" class="btn btn-clear float-right" onClick="hideDialog('modal-export')"></a>
<div class="modal-title h5 columns">
<div class="column col-1">
Export
</div>
<div class="column col-3">
<select id="export" class="form-select select-sm" onChange="bindCode()">
<option value="qasm">QASM</option>
<option value="qsharp">Q#</option>
<option value="json">Raw JSON Data</option>
</select>
</div>
</div>
</div>
<div class="modal-body pt-0 pl-0 pr-0">
<div class="content">
<pre class="code mt-0 " data-lang="Q#"><code id="code"></code></pre>
</div>
</div>
<div class="modal-footer">
<button class="btn" onClick="copyToClipboard()">Copy to Clipboard <i class="icon icon-link"></i></button>
</div>
</div>
</div>
<!-- EXAMPLES MODAL DIALOG -->
<div class="modal " id="modal-examples">
<a href="#close" class="modal-overlay" onClick="hideDialog('modal-examples')"></a>
<div class="modal-container">
<div class="modal-header pt-3 pl-0 pr-0">
<a href="#close" class="btn btn-clear float-right" onClick="hideDialog('modal-examples')"></a>
<div class="modal-title h5">Circuit Examples</div>
</div>
<div class="modal-body pt-0 pl-0 pr-0">
<div class="content">
<ul class="menu" id="modal-examples-menu">
</ul>
</div>
</div>
</div>
</div>
<script>
// draggable https://github.com/bcherny/draggable/
!function (t, e) { "object" == typeof exports ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : t.Draggable = e() }(this, function () { "use strict"; var t = { grid: 0, filterTarget: null, limit: { x: null, y: null }, threshold: 0, setCursor: !1, setPosition: !0, smoothDrag: !0, useGPU: !0, onDrag: u, onDragStart: u, onDragEnd: u }, e = { transform: function () { for (var t = " -o- -ms- -moz- -webkit-".split(" "), e = document.body.style, n = t.length; n--;) { var o = t[n] + "transform"; if (o in e) return o } }() }, n = { assign: function () { for (var t = arguments[0], e = arguments.length, n = 1; n < e; n++) { var o = arguments[n]; for (var i in o) t[i] = o[i] } return t }, bind: function (t, e) { return function () { t.apply(e, arguments) } }, on: function (t, e, o) { if (e && o) n.addEvent(t, e, o); else if (e) for (var i in e) n.addEvent(t, i, e[i]) }, off: function (t, e, o) { if (e && o) n.removeEvent(t, e, o); else if (e) for (var i in e) n.removeEvent(t, i, e[i]) }, limit: function (t, e) { return e instanceof Array ? t < (e = [+e[0], +e[1]])[0] ? t = e[0] : t > e[1] && (t = e[1]) : t = +e, t }, addEvent: "attachEvent" in Element.prototype ? function (t, e, n) { t.attachEvent("on" + e, n) } : function (t, e, n) { t.addEventListener(e, n, !1) }, removeEvent: "attachEvent" in Element.prototype ? function (t, e, n) { t.detachEvent("on" + e, n) } : function (t, e, n) { t.removeEventListener(e, n) } }; function o(e, o) { var i = this, r = n.bind(i.start, i), s = n.bind(i.drag, i), u = n.bind(i.stop, i); if (!a(e)) throw new TypeError("Draggable expects argument 0 to be an Element"); o = n.assign({}, t, o), n.assign(i, { element: e, handle: o.handle && a(o.handle) ? o.handle : e, handlers: { start: { mousedown: r, touchstart: r }, move: { mousemove: s, mouseup: u, touchmove: s, touchend: u } }, options: o }), i.initialize() } function i(t) { return parseInt(t, 10) } function r(t) { return "currentStyle" in t ? t.currentStyle : getComputedStyle(t) } function s(t) { return null != t } function a(t) { return t instanceof Element || "undefined" != typeof HTMLDocument && t instanceof HTMLDocument } function u() { } return n.assign(o.prototype, { setOption: function (t, e) { var n = this; return n.options[t] = e, n.initialize(), n }, get: function () { var t = this.dragEvent; return { x: t.x, y: t.y } }, set: function (t, e) { var n = this.dragEvent; return n.original = { x: n.x, y: n.y }, this.move(t, e), this }, dragEvent: { started: !1, x: 0, y: 0 }, initialize: function () { var t, o = this, i = o.element, s = (o.handle, i.style), a = r(i), u = o.options, f = e.transform, l = o._dimensions = { height: i.offsetHeight, left: i.offsetLeft, top: i.offsetTop, width: i.offsetWidth }; u.useGPU && f && ("none" === (t = a[f]) && (t = ""), s[f] = t + " translate3d(0,0,0)"), u.setPosition && (s.display = "block", s.left = l.left + "px", s.top = l.top + "px", s.width = l.width + "px", s.height = l.height + "px", s.bottom = s.right = "auto", s.margin = 0, s.position = "absolute"), u.setCursor && (s.cursor = "move"), o.setLimit(u.limit), n.assign(o.dragEvent, { x: l.left, y: l.top }), n.on(o.handle, o.handlers.start) }, start: function (t) { var e = this, o = e.getCursor(t), i = e.element; e.useTarget(t.target || t.srcElement) && (t.preventDefault && !t.target.getAttribute("contenteditable") ? t.preventDefault() : t.target.getAttribute("contenteditable") || (t.returnValue = !1), e.dragEvent.oldZindex = i.style.zIndex, i.style.zIndex = 1e4, e.setCursor(o), e.setPosition(), e.setZoom(), n.on(document, e.handlers.move)) }, drag: function (t) { var e = this, n = e.dragEvent, o = e.element, i = e._cursor, r = e._dimensions, s = e.options, a = r.zoom, u = e.getCursor(t), f = s.threshold, l = (u.x - i.x) / a + r.left, d = (u.y - i.y) / a + r.top; !n.started && f && Math.abs(i.x - u.x) < f && Math.abs(i.y - u.y) < f || (n.original || (n.original = { x: l, y: d }), n.started || (s.onDragStart(o, l, d, t), n.started = !0), e.move(l, d) && s.onDrag(o, n.x, n.y, t)) }, move: function (t, e) { var n = this, o = n.dragEvent, i = n.options, r = i.grid, s = n.element.style, a = n.limit(t, e, o.original.x, o.original.y); return !i.smoothDrag && r && (a = n.round(a, r)), (a.x !== o.x || a.y !== o.y) && (o.x = a.x, o.y = a.y, s.left = a.x + "px", s.top = a.y + "px", !0) }, stop: function (t) { var e, o = this, i = o.dragEvent, r = o.element, s = o.options, a = s.grid; n.off(document, o.handlers.move), r.style.zIndex = i.oldZindex, s.smoothDrag && a && (e = o.round({ x: i.x, y: i.y }, a), o.move(e.x, e.y), n.assign(o.dragEvent, e)), o.dragEvent.started && s.onDragEnd(r, i.x, i.y, t), o.reset() }, reset: function () { this.dragEvent.started = !1 }, round: function (t) { var e = this.options.grid; return { x: e * Math.round(t.x / e), y: e * Math.round(t.y / e) } }, getCursor: function (t) { return { x: (t.targetTouches ? t.targetTouches[0] : t).clientX, y: (t.targetTouches ? t.targetTouches[0] : t).clientY } }, setCursor: function (t) { this._cursor = t }, setLimit: function (t) { var e = this, o = function (t, e) { return { x: t, y: e } }; if (t instanceof Function) e.limit = t; else if (a(t)) { var i = e._dimensions, r = t.scrollHeight - i.height, u = t.scrollWidth - i.width; e.limit = function (t, e) { return { x: n.limit(t, [0, u]), y: n.limit(e, [0, r]) } } } else if (t) { var f = s(t.x), l = s(t.y); e.limit = f || l ? function (e, o) { return { x: f ? n.limit(e, t.x) : e, y: l ? n.limit(o, t.y) : o } } : o } else e.limit = o }, setPosition: function () { var t = this.element, e = t.style; n.assign(this._dimensions, { left: i(e.left) || t.offsetLeft, top: i(e.top) || t.offsetTop }) }, setZoom: function () { for (var t = this.element, e = 1; t = t.offsetParent;) { var n = r(t).zoom; if (n && "normal" !== n) { e = n; break } } this._dimensions.zoom = e }, useTarget: function (t) { var e = this.options.filterTarget; return !(e instanceof Function) || e(t) }, destroy: function () { n.off(this.handle, this.handlers.start), n.off(document, this.handlers.move) } }), o });
</script>
<script>
// Toolbar Blueprint
let toolbarGates = [
{type:"H", class:" gate-toolbar", x:500, y:5},
{type:"X", class:" gate-toolbar", x:550, y:5},
{type:"Y", class:" gate-toolbar", x:600, y:5},
{type:"Z", class:" gate-toolbar", x:650, y:5},
{type:"P", class:" gate-toolbar", x:700, y:5},
{type:"T", class:" gate-toolbar", x:750, y:5},
{type:"M", class:" gate-toolbar", x:800, y:5},
];
// Exportable Variables
let state = {
labels: [],
qubits: 0,
gates:[]
};
const samples = [
{
name:"Bell State",
category: "Basic",
state:{
labels:[
{
text: 'Phase Query',
t:[1,2]
},
{
text: 'Oracle',
t:[3]
},
{
text: 'Measurement',
t:[4]
}
],
qubits:2,
gates:[
{type:"Q",q:0, t:0},
{type:"Q",q:1, t:0},
// Create 1/sqrt(2)(|00> + |11>)
{type:"H", q:0, t:1},
{type:"CNOT",q:1, t:2, controls:[0]},
// Measure
{type:"M",q:0, t:3},
{type:"M",q:1, t:3}
]
}
},
{
name:"Quantum Teleportation",
category: "Quantum Internet",
state:{
labels:[
{
text: 'Bob\'s Entanglement with the bridge',
t:[1,2]
},
{
text: 'Alice is relating her bit with CNOT on bridge',
t:[3,4]
},
{
text: 'Measurement',
t:[5,6]
}
],
qubits:3,
gates:[
// Alice's qubit. She wants to clone this state in Bob's qubit
// We just initialize this with |0> for now, but this could be rotated
// and turn it to arbitral state |ψ>
{type:"Q",q:0, t:0},
{type:"Q",q:1, t:0},
{type:"Q",q:2, t:0},
// Bob - Entangle his bit with bridge
{type:"H",q:1, t:2},
{type:"CNOT",q:2, t:3, controls:[1]},
// Alice - Relate her qubit with CNOT
{type:"CNOT",q:1, t:4, controls:[0]},
// Then apply H on her qubit
{type:"H",q:0, t:5},
// Measure - 3rd bit no need to measure, discard
{type:"M",q:0, t:7},
{type:"M",q:1, t:7}
]
}
},
{
name:"Deutch's Algorithm",
category: "Algorithm",
state:{
labels:[
{
text: 'Phase Query',
t:[1,2]
},
{
text: 'Oracle',
t:[3]
},
{
text: 'Measurement',
t:[4]
}
],
qubits:2,
gates:[
{type:"Q",q:0, t:0},
{type:"Q",q:1, t:0},
// Deutch's Algorithm
// Setup
{type:"H",q:0, t:2},
{type:"X",q:1, t:1},
{type:"H",q:1, t:2},
// Oracle e.g. Identity, balanced function
{type:"CNOT",q:1, t:3, controls:[0]},
// Measure
{type:"M",q:0, t:4},
{type:"M",q:1, t:4}
]
}
}
];
state = samples[1].state; // example
// Reference to HTML Elements
let gateRefs = {};
// Globals
let gridSize = 100;
let offsetLeft = gridSize * 1;
let offsetTop = gridSize * 1;
// Main
renderMain();
function renderMain(){
clearMainArea();
renderQubitLines(state.qubits);
renderGates(state.gates);
renderToolbar();
}
function renderToolbar(){
let toolbarElem = document.getElementById('main');
toolbarGates.forEach((tgate)=>{
let toolbarGate = createGate(tgate);
toolbarElem.appendChild(toolbarGate);
let options = {
grid: gridSize,
setCursor: true,
smoothDrag:false,
smoothDrag:true,
onDragStart: startDragToolbarGate,
onDrag: updateToolbarGate,
onDragEnd: endDragToolbarGate
};
let drag = new Draggable(toolbarGate, options);
drag.set(tgate.x, tgate.y);
gateRefs['gate-toolbar-'+tgate.type] = drag;
let toolbarPlaceholder = createPlaceholder(tgate.x, tgate.y);
toolbarElem.append(toolbarPlaceholder);
});
}
function startDragToolbarGate(element, x, y, ev) {
showQubitPlaceholders();
}
function updateToolbarGate(element, x, y, ev) {
}
function endDragToolbarGate(element, x, y, ev){
let tgateElem = gateRefs['gate-toolbar-' + element.dataset.type];
// add new gate
let t = getT(x);
let q = getQ(y);
//console.log(tgateElem.element.dataset.type,t,q);
if (canAddGate(t, q)){
let tmp = {type:tgateElem.element.dataset.type,q:q, t:t};
addGate(tmp);
state.gates.push(tmp);
//console.log(state);
}
// put toolbar one back to original pos
setTimeout(()=>{
tgateElem.set(tgateElem._dimensions.left, tgateElem._dimensions.top);
},300);
hideQubitPlaceholders();
}
function canAddGate(t, q){
if (gateRefs['gate-' + t + '-' + q]){
return false;
}
if (q < 0 || q >= state.qubits){
return false;
}
return true;
}
function addGate(gate){
let gateElem = createGate(gate);
document.getElementById('main').appendChild(gateElem);
let x = getX(gate.t);
let y = getY(gate.q);
let limX = null;
let limY = null;
let cursor = true;
// can't move
if (gate.type === 'Q'){
limX = x;
limY = y;
cursor = false;
}
let options = {
grid: gridSize,
setCursor: cursor,
smoothDrag:true,
limit: {x:limX,y:limY},
onDragStart: startDragGate,
onDrag: updateGate,
onDragEnd: endDragGate
};
let drag = new Draggable(gateElem, options);
drag.set(x,y);
gateRefs['gate-' + gate.t+'-'+gate.q] = drag;
}
function createGate(gate){
let idx = (document.getElementsByClassName('gate').length);
let gateElem = document.createElement("div");
gateElem.className = "gate " + gate.type + (gate.class ? gate.class : "");
gateElem.setAttribute('data-type',gate.type);
gateElem.setAttribute('data-index',idx);
gateElem.id = 'gate_' + idx;
return gateElem;
}
function createPlaceholder(x, y, className, t = -1, q = -1){
let gateElem = document.createElement("div");
gateElem.className = "gate-placeholder " + (className ? className : "");
gateElem.style.left = x + "px";
gateElem.style.top = y + "px";
gateElem.setAttribute('data-t',t);
gateElem.setAttribute('data-q',q);
return gateElem;
}
function clearMainArea(){
document.getElementById('main').innerHTML = '';
}
function renderQubitLines(qubits){
for (let i=0; i<qubits; i++){
addQubitLine(i);
}
}
function addQubitLine(idx){
let qubitLine = createQubitLine(idx); // idx is q
let main = document.getElementById('main');
main.appendChild(qubitLine);
//let y = getY(idx);
for (let t=0; t<10; t++){
let x = getX(t);
let qPlaceholder = createPlaceholder(x-gridSize-25,0-25, "qubit-placeholder", t, idx);
qubitLine.append(qPlaceholder);
}
}
function createQubitLine(idx){
let qubitLine = document.createElement('hr');
qubitLine.className = 'qubit-line';
qubitLine.style.left = (25 + offsetLeft) + 'px';
qubitLine.style.top = (offsetTop + (idx * gridSize) + 15) + 'px';
return qubitLine;
}
function renderGates(gates){
gates.forEach((gate) => {
addGate(gate);
});
}
function startDragGate(element, x, y, ev){
showQubitPlaceholders();
}
function updateGate(element, x, y, ev) {
//console.log(x, y, getT(x), getQ(y), element.getAttribute('data-type'),element.getAttribute('data-index'),element);
//let idx = parseInt(element.getAttribute('data-index'));
let idx = parseInt(element.dataset.index);
state.gates[idx].t = getT(x);
state.gates[idx].q = getQ(y);
}
function endDragGate(element, x, y, ev){
hideQubitPlaceholders();
}
function showQubitPlaceholders(){
document.querySelectorAll(".qubit-placeholder").forEach((elem)=>{
// Probably faster if I mark all placeholder underneath, especially for CNOT Gate
// let found = gateRefs['gate-' + elem.dataset.t + '-' + elem.dataset.q];
// if (!found){
elem.style.display = 'block';
// }
});
}
function hideQubitPlaceholders(){
document.querySelectorAll(".qubit-placeholder").forEach((elem)=>{
elem.style.display = 'none';
})
}
// translate evolution timeline t to screen coord x
function getX(t){
return offsetLeft + t * gridSize;
}
// translate qubits position q to screen coord y
function getY(q) {
return offsetTop + q * gridSize;
}
// translate screen coord x to evolution timeline t
function getT(x){
return (x - offsetLeft) / gridSize;
}
// translate screen coord y to qubits position q
function getQ(y){
return (y - offsetTop) / gridSize;
}
// https://quantum-circuit.com/qconvert
function exportQASM(data){
let glines = [];
for (let i=0; i<data?.gates?.length; i++){
let gtype = data?.gates[i]?.type;
let tpos = data?.gates[i]?.t;
let qpos = data?.gates[i]?.q;
if (!glines[tpos]) {
glines[tpos] = [];
// this will be inserted first
glines[tpos][0] = `// t=${tpos}`;
}
let func = '';
if (gtype === 'Q'){
// do nothing
}
else if (gtype === 'CNOT'){
let controls = data?.gates[i]?.controls;
func = `cx q[${controls[0]}], q[${qpos}];`;
}
else if (gtype === 'M'){
func = `measure q[${qpos}] -> c[${qpos}];`;
}
else {
func = `${gtype.toLowerCase()} q[${qpos}];`;
}
if (func){
glines[tpos][1+qpos] = func; // +1 reserved 1st one for comment
}
}
let gatesCode = glines.filter((line)=>line.length > 1).map((line)=>{
//console.log(line);
return line.filter((seg)=>seg).map((seg)=>{
return seg;
}).join('\n');
}).join('\n\n');
let codeStr = `
OPENQASM 2.0;
include "qelib1.inc";
qreg q[${data?.qubits}];
creg c[${data?.qubits}];
${gatesCode}
`;
return codeStr;
}
function exportQSharp(data){
// sort labels by t = pos
// sort gates by t
let glines = [];
for (let i=0; i<data?.gates?.length; i++){
let gtype = data?.gates[i]?.type;
let tpos = data?.gates[i]?.t;
let qpos = data?.gates[i]?.q;
if (!glines[tpos]) {
glines[tpos] = [];
// this will be inserted first
glines[tpos][0] = `// t=${tpos}`;
}
let func = '';
if (gtype === 'Q'){
// do nothing
}
else if (gtype === 'CNOT'){
let controls = data?.gates[i]?.controls;
func = `CNOT(qubits[${controls[0]}],qubits[${qpos}]);`;
}
//else if (gtype === 'TOFFOLI'){
// let controls = data?.gates[i]?.controls;
// func = `TOFFOLI(qubits[${controls[0]}],qubits[${controls[1]}],qubits[${qpos}]);`;
//}
else {
func = `${gtype}(qubits[${qpos}]);`;
}
if (func){
glines[tpos][1+qpos] = func; // +1 reserved 1st one for comment
}
}
let gatesCode = glines.filter((line)=>line.length > 1).map((line)=>{
//console.log(line);
return line.filter((seg)=>seg).map((seg)=>{
return seg;
}).join('\n\t\t\t');
}).join('\n\n\t\t\t');
let usingCode = `
\t\tusing(qubits = Qubit[${data?.qubits}]){
\t\t\t${gatesCode}
\t\t\t//Reset All
\t\t\tfor(qb in qubits){
\t\t\t\tReset(qb);
\t\t\t}
\t\t}
`;
let codeStr = `namespace MyCircuit {
\topen Microsoft.Quantum.Canon;
\topen Microsoft.Quantum.Intrinsic;
\topen Microsoft.Quantum.Convert;
\topen Microsoft.Quantum.Math;
\t@EntryPoint()
\toperation Main(): Unit{
${usingCode}
\t}
}
`;
return codeStr;
}
function showExport(){
document.getElementById("modal-export").classList.add('active');
bindCode();
}
function bindCode(){
let type = document.querySelector('#export').value;
generateCode(type, state);
}
function generateCode(type, data){
let code = '';
if (type === 'qasm'){
code = exportQASM(data);
}
else if (type === 'qsharp'){
code = exportQSharp(data);
}
else if (type === 'json') {
code = JSON.stringify(data,4,4);
}
document.getElementById('code').innerHTML = code;
}
function hideDialog(id) {
document.getElementById(id).classList.remove('active');
}
function copyToClipboard() {
var input = document.createElement('textarea');
input.innerHTML = document.getElementById('code').innerHTML;
document.body.appendChild(input);
input.select();
var result = document.execCommand('copy');
document.body.removeChild(input);
return result;
}
function showExamples(){
document.getElementById('modal-examples-menu').innerHTML = createExampleMenuItems(samples);
document.getElementById("modal-examples").classList.add('active');
}
function createExampleMenuItems(sampleData){
const categories = ["Basic","Quantum Internet", "Algorithm"];
return categories.map((cat)=>{
let retHtml = `<li class="divider" data-content="${cat}"></li>`
+ sampleData
.map((item,index)=>{
item['index'] = index;
return item;
})
.filter((item)=>item.category === cat)
.map((item)=>{
return `
<li class="menu-item">
<a class="clickable" onclick="loadExample(${item.index})">
${item.name} <i class="icon icon-download"></i>
</a>
</li>
`;
}).join("\n");
return retHtml;
}).join("\n");
}
function loadExample(index){
state = samples[index].state;
renderMain();
hideDialog('modal-examples');
}
function addQubit(){
state.qubits++;
addQubitLine(state.qubits-1);
let newGate = {type:"Q",q:state.qubits-1, t:0};
state.gates.push(newGate);
addGate(newGate);
}
function test(){
let tmp = {type:"X",q:-1, t:5};
addGate(tmp);
state.gates.push(tmp);
console.log(state);
}
</script>
</body>
</html>