-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
state_visualization.py
1580 lines (1330 loc) · 53.5 KB
/
state_visualization.py
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
# pylint: disable=missing-param-doc,missing-type-doc,unused-argument
"""
Visualization functions for quantum states.
"""
from typing import Optional, List, Union
from functools import reduce
import colorsys
import numpy as np
from qiskit import user_config
from qiskit.quantum_info.states.statevector import Statevector
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import PauliList, SparsePauliOp
from qiskit.quantum_info.states.densitymatrix import DensityMatrix
from qiskit.utils.deprecation import deprecate_arg, deprecate_func
from qiskit.utils import optionals as _optionals
from qiskit.circuit.tools.pi_check import pi_check
from .array import _num_to_latex, array_to_latex
from .utils import matplotlib_close_if_inline
from .exceptions import VisualizationError
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_hinton(
state, title="", figsize=None, ax_real=None, ax_imag=None, *, rho=None, filename=None
):
"""Plot a hinton diagram for the density matrix of a quantum state.
The hinton diagram represents the values of a matrix using
squares, whose size indicate the magnitude of their corresponding value
and their color, its sign. A white square means the value is positive and
a black one means negative.
Args:
state (Statevector or DensityMatrix or ndarray): An N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
filename (str): file path to save image to.
ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if
neither ax_real or ax_imag is set.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
"""
from matplotlib import pyplot as plt
# Figure data
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
max_weight = 2 ** np.ceil(np.log(np.abs(rho.data).max()) / np.log(2))
datareal = np.real(rho.data)
dataimag = np.imag(rho.data)
if figsize is None:
figsize = (8, 5)
if not ax_real and not ax_imag:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
else:
if ax_real:
fig = ax_real.get_figure()
else:
fig = ax_imag.get_figure()
ax1 = ax_real
ax2 = ax_imag
# Reversal is to account for Qiskit's endianness.
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)][::-1]
ly, lx = datareal.shape
# Real
if ax1:
ax1.patch.set_facecolor("gray")
ax1.set_aspect("equal", "box")
ax1.xaxis.set_major_locator(plt.NullLocator())
ax1.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(datareal):
# Convert from matrix co-ordinates to plot co-ordinates.
plot_x, plot_y = y, lx - x - 1
color = "white" if w > 0 else "black"
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle(
[0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2],
size,
size,
facecolor=color,
edgecolor=color,
)
ax1.add_patch(rect)
ax1.set_xticks(0.5 + np.arange(lx))
ax1.set_yticks(0.5 + np.arange(ly))
ax1.set_xlim([0, lx])
ax1.set_ylim([0, ly])
ax1.set_yticklabels(row_names, fontsize=14)
ax1.set_xticklabels(column_names, fontsize=14, rotation=90)
ax1.set_title("Re[$\\rho$]", fontsize=14)
# Imaginary
if ax2:
ax2.patch.set_facecolor("gray")
ax2.set_aspect("equal", "box")
ax2.xaxis.set_major_locator(plt.NullLocator())
ax2.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(dataimag):
# Convert from matrix co-ordinates to plot co-ordinates.
plot_x, plot_y = y, lx - x - 1
color = "white" if w > 0 else "black"
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle(
[0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2],
size,
size,
facecolor=color,
edgecolor=color,
)
ax2.add_patch(rect)
ax2.set_xticks(0.5 + np.arange(lx))
ax2.set_yticks(0.5 + np.arange(ly))
ax2.set_xlim([0, lx])
ax2.set_ylim([0, ly])
ax2.set_yticklabels(row_names, fontsize=14)
ax2.set_xticklabels(column_names, fontsize=14, rotation=90)
ax2.set_title("Im[$\\rho$]", fontsize=14)
fig.tight_layout()
if title:
fig.suptitle(title, fontsize=16)
if ax_real is None and ax_imag is None:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_bloch_vector(
bloch, title="", ax=None, figsize=None, coord_type="cartesian", font_size=None
):
"""Plot the Bloch sphere.
Plot a Bloch sphere with the specified coordinates, that can be given in both
cartesian and spherical systems.
Args:
bloch (list[double]): array of three elements where [<x>, <y>, <z>] (Cartesian)
or [<r>, <theta>, <phi>] (spherical in radians)
<theta> is inclination angle from +z direction
<phi> is azimuth from +x direction
title (str): a string that represents the plot title
ax (matplotlib.axes.Axes): An Axes to use for rendering the bloch
sphere
figsize (tuple): Figure size in inches. Has no effect is passing ``ax``.
coord_type (str): a string that specifies coordinate type for bloch
(Cartesian or spherical), default is Cartesian
font_size (float): Font size.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` : A matplotlib figure instance if ``ax = None``.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
Examples:
.. plot::
:include-source:
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0], title="New Bloch Sphere")
.. plot::
:include-source:
import numpy as np
from qiskit.visualization import plot_bloch_vector
# You can use spherical coordinates instead of cartesian.
plot_bloch_vector([1, np.pi/2, np.pi/3], coord_type='spherical')
"""
from .bloch import Bloch
if figsize is None:
figsize = (5, 5)
B = Bloch(axes=ax, font_size=font_size)
if coord_type == "spherical":
r, theta, phi = bloch[0], bloch[1], bloch[2]
bloch[0] = r * np.sin(theta) * np.cos(phi)
bloch[1] = r * np.sin(theta) * np.sin(phi)
bloch[2] = r * np.cos(theta)
B.add_vectors(bloch)
B.render(title=title)
if ax is None:
fig = B.fig
fig.set_size_inches(figsize[0], figsize[1])
matplotlib_close_if_inline(fig)
return fig
return None
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_bloch_multivector(
state,
title="",
figsize=None,
*,
rho=None,
reverse_bits=False,
filename=None,
font_size=None,
title_font_size=None,
title_pad=1,
):
r"""Plot a Bloch sphere for each qubit.
Each component :math:`(x,y,z)` of the Bloch sphere labeled as 'qubit i' represents the expected
value of the corresponding Pauli operator acting only on that qubit, that is, the expected value
of :math:`I_{N-1} \otimes\dotsb\otimes I_{i+1}\otimes P_i \otimes I_{i-1}\otimes\dotsb\otimes
I_0`, where :math:`N` is the number of qubits, :math:`P\in \{X,Y,Z\}` and :math:`I` is the
identity operator.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): size of each individual Bloch sphere figure, in inches.
reverse_bits (bool): If True, plots qubits following Qiskit's convention [Default:False].
font_size (float): Font size for the Bloch ball figures.
title_font_size (float): Font size for the title.
title_pad (float): Padding for the title (suptitle `y` position is `y=1+title_pad/100`).
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
A matplotlib figure instance.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
"""
from matplotlib import pyplot as plt
# Data
bloch_data = (
_bloch_multivector_data(state)[::-1] if reverse_bits else _bloch_multivector_data(state)
)
num = len(bloch_data)
if figsize is not None:
width, height = figsize
width *= num
else:
width, height = plt.figaspect(1 / num)
default_title_font_size = font_size if font_size is not None else 16
title_font_size = title_font_size if title_font_size is not None else default_title_font_size
fig = plt.figure(figsize=(width, height))
for i in range(num):
pos = num - 1 - i if reverse_bits else i
ax = fig.add_subplot(1, num, i + 1, projection="3d")
plot_bloch_vector(
bloch_data[i], "qubit " + str(pos), ax=ax, figsize=figsize, font_size=font_size
)
fig.suptitle(title, fontsize=title_font_size, y=1.0 + title_pad / 100)
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_city(
state,
title="",
figsize=None,
color=None,
alpha=1,
ax_real=None,
ax_imag=None,
*,
rho=None,
filename=None,
):
"""Plot the cityscape of quantum state.
Plot two 3d bar graphs (two dimensional) of the real and imaginary
part of the density matrix rho.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list): A list of len=2 giving colors for real and
imaginary components of matrix elements.
alpha (float): Transparency value for bars
ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_real only the imaginary component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if the
``ax_real`` and ``ax_imag`` kwargs are not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
ValueError: When 'color' is not a list of len=2.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
# You can choose different colors for the real and imaginary parts of the density matrix.
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
.. plot::
:include-source:
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
"""
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
# get the real and imag parts of rho
datareal = np.real(rho.data)
dataimag = np.imag(rho.data)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx * ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
if color is None:
color = ["#648fff", "#648fff"]
else:
if len(color) != 2:
raise ValueError("'color' must be a list of len=2.")
if color[0] is None:
color[0] = "#648fff"
if color[1] is None:
color[1] = "#648fff"
if ax_real is None and ax_imag is None:
# set default figure size
if figsize is None:
figsize = (15, 5)
fig = plt.figure(figsize=figsize)
ax1 = fig.add_subplot(1, 2, 1, projection="3d")
ax2 = fig.add_subplot(1, 2, 2, projection="3d")
elif ax_real is not None:
fig = ax_real.get_figure()
ax1 = ax_real
ax2 = ax_imag
else:
fig = ax_imag.get_figure()
ax1 = None
ax2 = ax_imag
max_dzr = max(dzr)
min_dzr = min(dzr)
min_dzi = np.min(dzi)
max_dzi = np.max(dzi)
# There seems to be a rounding error in which some zero bars are negative
dzr = np.clip(dzr, 0, None)
if ax1 is not None:
fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])
for idx, cur_zpos in enumerate(zpos):
if dzr[idx] > 0:
zorder = 2
else:
zorder = 0
b1 = ax1.bar3d(
xpos[idx],
ypos[idx],
cur_zpos,
dx[idx],
dy[idx],
dzr[idx],
alpha=alpha,
zorder=zorder,
)
b1.set_facecolors(fc1[6 * idx : 6 * idx + 6])
xlim, ylim = ax1.get_xlim(), ax1.get_ylim()
x = [xlim[0], xlim[1], xlim[1], xlim[0]]
y = [ylim[0], ylim[0], ylim[1], ylim[1]]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
pc1 = Poly3DCollection(verts, alpha=0.15, facecolor="k", linewidths=1, zorder=1)
if min(dzr) < 0 < max(dzr):
ax1.add_collection3d(pc1)
ax1.set_xticks(np.arange(0.5, lx + 0.5, 1))
ax1.set_yticks(np.arange(0.5, ly + 0.5, 1))
if max_dzr != min_dzr:
ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, max_dzi))
else:
if min_dzr == 0:
ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, np.max(dzi)))
else:
ax1.axes.set_zlim3d(auto=True)
ax1.get_autoscalez_on()
ax1.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top")
ax1.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center")
ax1.set_zlabel("Re[$\\rho$]", fontsize=14)
for tick in ax1.zaxis.get_major_ticks():
tick.label1.set_fontsize(14)
if ax2 is not None:
fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])
for idx, cur_zpos in enumerate(zpos):
if dzi[idx] > 0:
zorder = 2
else:
zorder = 0
b2 = ax2.bar3d(
xpos[idx],
ypos[idx],
cur_zpos,
dx[idx],
dy[idx],
dzi[idx],
alpha=alpha,
zorder=zorder,
)
b2.set_facecolors(fc2[6 * idx : 6 * idx + 6])
xlim, ylim = ax2.get_xlim(), ax2.get_ylim()
x = [xlim[0], xlim[1], xlim[1], xlim[0]]
y = [ylim[0], ylim[0], ylim[1], ylim[1]]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
pc2 = Poly3DCollection(verts, alpha=0.2, facecolor="k", linewidths=1, zorder=1)
if min(dzi) < 0 < max(dzi):
ax2.add_collection3d(pc2)
ax2.set_xticks(np.arange(0.5, lx + 0.5, 1))
ax2.set_yticks(np.arange(0.5, ly + 0.5, 1))
if min_dzi != max_dzi:
eps = 0
ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps))
else:
if min_dzi == 0:
ax2.set_zticks([0])
eps = 1e-9
ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps))
else:
ax2.axes.set_zlim3d(auto=True)
ax2.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top")
ax2.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center")
ax2.set_zlabel("Im[$\\rho$]", fontsize=14)
for tick in ax2.zaxis.get_major_ticks():
tick.label1.set_fontsize(14)
ax2.get_autoscalez_on()
fig.suptitle(title, fontsize=16)
if ax_real is None and ax_imag is None:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_paulivec(
state, title="", figsize=None, color=None, ax=None, *, rho=None, filename=None
):
r"""Plot the Pauli-vector representation of a quantum state as bar graph.
The Pauli-vector of a density matrix :math:`\rho` is defined by the expectation of each
possible tensor product of single-qubit Pauli operators (including the identity), that is
.. math ::
\rho = \frac{1}{2^n} \sum_{\sigma \in \{I, X, Y, Z\}^{\otimes n}}
\mathrm{Tr}(\sigma \rho) \sigma.
This function plots the coefficients :math:`\mathrm{Tr}(\sigma\rho)` as bar graph.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the coefficient value bars.
ax (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. Additionally, if specified there
will be no returned Figure since it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if the
``ax`` kwarg is not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
.. plot::
:include-source:
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
"""
from matplotlib import pyplot as plt
labels, values = _paulivec_data(state)
numelem = len(values)
if figsize is None:
figsize = (7, 5)
if color is None:
color = "#648fff"
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
if ax is None:
return_fig = True
fig, ax = plt.subplots(figsize=figsize)
else:
return_fig = False
fig = ax.get_figure()
ax.grid(zorder=0, linewidth=1, linestyle="--")
ax.bar(ind, values, width, color=color, zorder=2)
ax.axhline(linewidth=1, color="k")
# add some text for labels, title, and axes ticks
ax.set_ylabel("Coefficients", fontsize=14)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=14, rotation=70)
ax.set_xlabel("Pauli", fontsize=14)
ax.set_ylim([-1, 1])
ax.set_facecolor("#eeeeee")
for tick in ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks():
tick.label1.set_fontsize(14)
ax.set_title(title, fontsize=16)
if return_fig:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1], zip(range(n - k + 1, n + 1), range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = [n - 1 - x for x in lst]
dualm = sum(n_choose_k(comb[k - 1 - i], i + 1) for i in range(k))
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
if s.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_rgb(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to the HSL color wheel
"""
angles = (np.angle(complex_number) + (np.pi * 5 / 4)) % (np.pi * 2)
rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5)
return rgb
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
@_optionals.HAS_SEABORN.require_in_call
def plot_state_qsphere(
state,
figsize=None,
ax=None,
show_state_labels=True,
show_state_phases=False,
use_degrees=False,
*,
rho=None,
filename=None,
):
"""Plot the qsphere representation of a quantum state.
Here, the size of the points is proportional to the probability
of the corresponding term in the state and the color represents
the phase.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
figsize (tuple): Figure size in inches.
ax (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. Additionally, if specified there
will be no returned Figure since it is redundant.
show_state_labels (bool): An optional boolean indicating whether to
show labels for each basis state.
show_state_phases (bool): An optional boolean indicating whether to
show the phase for each basis state.
use_degrees (bool): An optional boolean indicating whether to use
radians or degrees for the phase values in the plot.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
A matplotlib figure instance if the ``ax`` kwarg is not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
QiskitError: Input statevector does not have valid dimensions.
Examples:
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
.. plot::
:include-source:
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
"""
from matplotlib import gridspec
from matplotlib import pyplot as plt
from matplotlib.patches import Circle
import seaborn as sns
from scipy import linalg
from .bloch import Arrow3D
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
# get the eigenvectors and eigenvalues
eigvals, eigvecs = linalg.eigh(rho.data)
if figsize is None:
figsize = (7, 7)
if ax is None:
return_fig = True
fig = plt.figure(figsize=figsize)
else:
return_fig = False
fig = ax.get_figure()
gs = gridspec.GridSpec(nrows=3, ncols=3)
ax = fig.add_subplot(gs[0:3, 0:3], projection="3d")
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.axes.grid(False)
ax.view_init(elev=5, azim=275)
# Force aspect ratio
# MPL 3.2 or previous do not have set_box_aspect
if hasattr(ax.axes, "set_box_aspect"):
ax.axes.set_box_aspect((1, 1, 1))
# start the plotting
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(
x, y, z, rstride=1, cstride=1, color=plt.rcParams["grid.color"], alpha=0.2, linewidth=0
)
# Get rid of the panes
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
# traversing the eigvals/vecs backward as sorted low->high
for idx in range(eigvals.shape[0] - 1, -1, -1):
if eigvals[idx] > 0.001:
# get the max eigenvalue
state = eigvecs[:, idx]
loc = np.absolute(state).argmax()
# remove the global phase from max element
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j * angles)
state = angleset * state
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
angle = (float(weight) / d) * (np.pi * 2) + (
weight_order * 2 * (np.pi / number_of_divisions)
)
if (weight > d / 2) or (
(weight == d / 2) and (weight_order >= number_of_divisions / 2)
):
angle = np.pi - angle - (2 * np.pi / number_of_divisions)
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
prob = min(prob, 1) # See https://github.com/Qiskit/qiskit-terra/issues/4666
colorstate = phase_to_rgb(state[i])
alfa = 1
if yvalue >= 0.1:
alfa = 1.0 - yvalue
if not np.isclose(prob, 0) and show_state_labels:
rprime = 1.3
angle_theta = np.arctan2(np.sqrt(1 - zvalue**2), zvalue)
xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle)
yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle)
zvalue_text = rprime * np.cos(angle_theta)
element_text = "$\\vert" + element + "\\rangle$"
if show_state_phases:
element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2)
if use_degrees:
element_text += "\n$%.1f^\\circ$" % (element_angle * 180 / np.pi)
else:
element_angle = pi_check(element_angle, ndigits=3).replace("pi", "\\pi")
element_text += "\n$%s$" % (element_angle)
ax.text(
xvalue_text,
yvalue_text,
zvalue_text,