forked from qutip/qutip
/
states.py
1077 lines (849 loc) · 27.4 KB
/
states.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 file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
__all__ = ['basis', 'qutrit_basis', 'coherent', 'coherent_dm', 'fock_dm',
'fock', 'thermal_dm', 'maximally_mixed_dm', 'ket2dm', 'projection',
'qstate', 'ket', 'bra', 'state_number_enumerate',
'state_number_index', 'state_index_number', 'state_number_qobj',
'phase_basis', 'zero_ket', 'spin_state', 'spin_coherent',
'bell_state', 'singlet_state', 'triplet_states', 'w_state',
'ghz_state']
import numpy as np
from scipy import arange, conj, prod
import scipy.sparse as sp
from qutip.qobj import Qobj
from qutip.operators import destroy, jmat
from qutip.tensor import tensor
def basis(N, n=0, offset=0):
"""Generates the vector representation of a Fock state.
Parameters
----------
N : int
Number of Fock states in Hilbert space.
n : int
Integer corresponding to desired number state, defaults
to 0 if omitted.
offset : int (default 0)
The lowest number state that is included in the finite number state
representation of the state.
Returns
-------
state : qobj
Qobj representing the requested number state ``|n>``.
Examples
--------
>>> basis(5,2)
Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
Qobj data =
[[ 0.+0.j]
[ 0.+0.j]
[ 1.+0.j]
[ 0.+0.j]
[ 0.+0.j]]
Notes
-----
A subtle incompatibility with the quantum optics toolbox: In QuTiP::
basis(N, 0) = ground state
but in the qotoolbox::
basis(N, 1) = ground state
"""
if (not isinstance(N, (int, np.integer))) or N < 0:
raise ValueError("N must be integer N >= 0")
if (not isinstance(n, (int, np.integer))) or n < offset:
raise ValueError("n must be integer n >= 0")
if n - offset > (N - 1): # check if n is within bounds
raise ValueError("basis vector index need to be in n <= N-1")
bas = sp.lil_matrix((N, 1)) # column vector of zeros
bas[n - offset, 0] = 1 # 1 located at position n
bas = bas.tocsr()
return Qobj(bas)
def qutrit_basis():
"""Basis states for a three level system (qutrit)
Returns
-------
qstates : array
Array of qutrit basis vectors
"""
return np.array([basis(3, 0), basis(3, 1), basis(3, 2)], dtype=object)
def _sqrt_factorial(n_vec):
# take the square root before multiplying
return np.array([np.prod(np.sqrt(np.arange(1, n + 1))) for n in n_vec])
def coherent(N, alpha, offset=0, method='operator'):
"""Generates a coherent state with eigenvalue alpha.
Constructed using displacement operator on vacuum state.
Parameters
----------
N : int
Number of Fock states in Hilbert space.
alpha : float/complex
Eigenvalue of coherent state.
offset : int (default 0)
The lowest number state that is included in the finite number state
representation of the state. Using a non-zero offset will make the
default method 'analytic'.
method : string {'operator', 'analytic'}
Method for generating coherent state.
Returns
-------
state : qobj
Qobj quantum object for coherent state
Examples
--------
>>> coherent(5,0.25j)
Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
Qobj data =
[[ 9.69233235e-01+0.j ]
[ 0.00000000e+00+0.24230831j]
[ -4.28344935e-02+0.j ]
[ 0.00000000e+00-0.00618204j]
[ 7.80904967e-04+0.j ]]
Notes
-----
Select method 'operator' (default) or 'analytic'. With the
'operator' method, the coherent state is generated by displacing
the vacuum state using the displacement operator defined in the
truncated Hilbert space of size 'N'. This method guarantees that the
resulting state is normalized. With 'analytic' method the coherent state
is generated using the analytical formula for the coherent state
coefficients in the Fock basis. This method does not guarantee that the
state is normalized if truncated to a small number of Fock states,
but would in that case give more accurate coefficients.
"""
if method == "operator" and offset == 0:
x = basis(N, 0)
a = destroy(N)
D = (alpha * a.dag() - conj(alpha) * a).expm()
return D * x
elif method == "analytic" or offset > 0:
data = np.zeros([N, 1], dtype=complex)
n = arange(N) + offset
data[:, 0] = np.exp(-(abs(alpha) ** 2) / 2.0) * (alpha ** (n)) / \
_sqrt_factorial(n)
return Qobj(data)
else:
raise TypeError(
"The method option can only take values 'operator' or 'analytic'")
def coherent_dm(N, alpha, offset=0, method='operator'):
"""Density matrix representation of a coherent state.
Constructed via outer product of :func:`qutip.states.coherent`
Parameters
----------
N : int
Number of Fock states in Hilbert space.
alpha : float/complex
Eigenvalue for coherent state.
offset : int (default 0)
The lowest number state that is included in the finite number state
representation of the state.
method : string {'operator', 'analytic'}
Method for generating coherent density matrix.
Returns
-------
dm : qobj
Density matrix representation of coherent state.
Examples
--------
>>> coherent_dm(3,0.25j)
Quantum object: dims = [[3], [3]], \
shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.93941695+0.j 0.00000000-0.23480733j -0.04216943+0.j ]
[ 0.00000000+0.23480733j 0.05869011+0.j 0.00000000-0.01054025j]
[-0.04216943+0.j 0.00000000+0.01054025j 0.00189294+0.j\
]]
Notes
-----
Select method 'operator' (default) or 'analytic'. With the
'operator' method, the coherent density matrix is generated by displacing
the vacuum state using the displacement operator defined in the
truncated Hilbert space of size 'N'. This method guarantees that the
resulting density matrix is normalized. With 'analytic' method the coherent
density matrix is generated using the analytical formula for the coherent
state coefficients in the Fock basis. This method does not guarantee that
the state is normalized if truncated to a small number of Fock states,
but would in that case give more accurate coefficients.
"""
if method == "operator":
psi = coherent(N, alpha, offset=offset)
return psi * psi.dag()
elif method == "analytic":
psi = coherent(N, alpha, offset=offset, method='analytic')
return psi * psi.dag()
else:
raise TypeError(
"The method option can only take values 'operator' or 'analytic'")
def fock_dm(N, n=0, offset=0):
"""Density matrix representation of a Fock state
Constructed via outer product of :func:`qutip.states.fock`.
Parameters
----------
N : int
Number of Fock states in Hilbert space.
n : int
``int`` for desired number state, defaults to 0 if omitted.
Returns
-------
dm : qobj
Density matrix representation of Fock state.
Examples
--------
>>> fock_dm(3,1)
Quantum object: dims = [[3], [3]], \
shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 1.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j]]
"""
psi = basis(N, n, offset=offset)
return psi * psi.dag()
def fock(N, n=0, offset=0):
"""Bosonic Fock (number) state.
Same as :func:`qutip.states.basis`.
Parameters
----------
N : int
Number of states in the Hilbert space.
n : int
``int`` for desired number state, defaults to 0 if omitted.
Returns
-------
Requested number state :math:`\\left|n\\right>`.
Examples
--------
>>> fock(4,3)
Quantum object: dims = [[4], [1]], shape = [4, 1], type = ket
Qobj data =
[[ 0.+0.j]
[ 0.+0.j]
[ 0.+0.j]
[ 1.+0.j]]
"""
return basis(N, n, offset=offset)
def thermal_dm(N, n, method='operator'):
"""Density matrix for a thermal state of n particles
Parameters
----------
N : int
Number of basis states in Hilbert space.
n : float
Expectation value for number of particles in thermal state.
method : string {'operator', 'analytic'}
``string`` that sets the method used to generate the
thermal state probabilities
Returns
-------
dm : qobj
Thermal state density matrix.
Examples
--------
>>> thermal_dm(5, 1)
Quantum object: dims = [[5], [5]], \
shape = [5, 5], type = oper, isHerm = True
Qobj data =
[[ 0.51612903 0. 0. 0. 0. ]
[ 0. 0.25806452 0. 0. 0. ]
[ 0. 0. 0.12903226 0. 0. ]
[ 0. 0. 0. 0.06451613 0. ]
[ 0. 0. 0. 0. 0.03225806]]
>>> thermal_dm(5, 1, 'analytic')
Quantum object: dims = [[5], [5]], \
shape = [5, 5], type = oper, isHerm = True
Qobj data =
[[ 0.5 0. 0. 0. 0. ]
[ 0. 0.25 0. 0. 0. ]
[ 0. 0. 0.125 0. 0. ]
[ 0. 0. 0. 0.0625 0. ]
[ 0. 0. 0. 0. 0.03125]]
Notes
-----
The 'operator' method (default) generates
the thermal state using the truncated number operator ``num(N)``. This
is the method that should be used in computations. The
'analytic' method uses the analytic coefficients derived in
an infinite Hilbert space. The analytic form is not necessarily normalized,
if truncated too aggressively.
"""
if n == 0:
return fock_dm(N, 0)
else:
i = arange(N)
if method == 'operator':
beta = np.log(1.0 / n + 1.0)
diags = np.exp(-beta * i)
diags = diags / np.sum(diags)
# populates diagonal terms using truncated operator expression
rm = sp.spdiags(diags, 0, N, N, format='csr')
elif method == 'analytic':
# populates diagonal terms using analytic values
rm = sp.spdiags((1.0 + n) ** (-1.0) * (n / (1.0 + n)) ** (i),
0, N, N, format='csr')
else:
raise ValueError(
"'method' keyword argument must be 'operator' or 'analytic'")
return Qobj(rm)
def maximally_mixed_dm(N):
"""
Returns the maximally mixed density matrix for a Hilbert space of
dimension N.
Parameters
----------
N : int
Number of basis states in Hilbert space.
Returns
-------
dm : qobj
Thermal state density matrix.
"""
if (not isinstance(N, (int, np.int64))) or N <= 0:
raise ValueError("N must be integer N > 0")
dm = sp.spdiags(np.ones(N, dtype=complex)/float(N), 0, N, N, format='csr')
return Qobj(dm, isherm=True)
def ket2dm(Q):
"""Takes input ket or bra vector and returns density matrix
formed by outer product.
Parameters
----------
Q : qobj
Ket or bra type quantum object.
Returns
-------
dm : qobj
Density matrix formed by outer product of `Q`.
Examples
--------
>>> x=basis(3,2)
>>> ket2dm(x)
Quantum object: dims = [[3], [3]], \
shape = [3, 3], type = oper, isHerm = True
Qobj data =
[[ 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 1.+0.j]]
"""
if Q.type == 'ket':
out = Q * Q.dag()
elif Q.type == 'bra':
out = Q.dag() * Q
else:
raise TypeError("Input is not a ket or bra vector.")
return Qobj(out)
#
# projection operator
#
def projection(N, n, m, offset=0):
"""The projection operator that projects state |m> on state |n>: |n><m|.
Parameters
----------
N : int
Number of basis states in Hilbert space.
n, m : float
The number states in the projection.
offset : int (default 0)
The lowest number state that is included in the finite number state
representation of the projector.
Returns
-------
oper : qobj
Requested projection operator.
"""
ket1 = basis(N, n, offset=offset)
ket2 = basis(N, m, offset=offset)
return ket1 * ket2.dag()
#
# composite qubit states
#
def qstate(string):
"""Creates a tensor product for a set of qubits in either
the 'up' :math:`|0>` or 'down' :math:`|1>` state.
Parameters
----------
string : str
String containing 'u' or 'd' for each qubit (ex. 'ududd')
Returns
-------
qstate : qobj
Qobj for tensor product corresponding to input string.
Notes
-----
Look at ket and bra for more general functions
creating multiparticle states.
Examples
--------
>>> qstate('udu')
Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket
Qobj data =
[[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 1.]
[ 0.]
[ 0.]]
"""
n = len(string)
if n != (string.count('u') + string.count('d')):
raise TypeError('String input to QSTATE must consist ' +
'of "u" and "d" elements only')
else:
up = basis(2, 1)
dn = basis(2, 0)
lst = []
for k in range(n):
if string[k] == 'u':
lst.append(up)
else:
lst.append(dn)
return tensor(lst)
#
# different qubit notation dictionary
#
_qubit_dict = {'g': 0, # ground state
'e': 1, # excited state
'u': 0, # spin up
'd': 1, # spin down
'H': 0, # horizontal polarization
'V': 1} # vertical polarization
def _character_to_qudit(x):
"""
Converts a character representing a one-particle state into int.
"""
if x in _qubit_dict:
return _qubit_dict[x]
else:
return int(x)
def ket(seq, dim=2):
"""
Produces a multiparticle ket state for a list or string,
where each element stands for state of the respective particle.
Parameters
----------
seq : str / list of ints or characters
Each element defines state of the respective particle.
(e.g. [1,1,0,1] or a string "1101").
For qubits it is also possible to use the following conventions:
- 'g'/'e' (ground and excited state)
- 'u'/'d' (spin up and down)
- 'H'/'V' (horizontal and vertical polarization)
Note: for dimension > 9 you need to use a list.
dim : int (default: 2) / list of ints
Space dimension for each particle:
int if there are the same, list if they are different.
Returns
-------
ket : qobj
Examples
--------
>>> ket("10")
Quantum object: dims = [[2, 2], [1, 1]], shape = [4, 1], type = ket
Qobj data =
[[ 0.]
[ 0.]
[ 1.]
[ 0.]]
>>> ket("Hue")
Quantum object: dims = [[2, 2, 2], [1, 1, 1]], shape = [8, 1], type = ket
Qobj data =
[[ 0.]
[ 1.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]]
>>> ket("12", 3)
Quantum object: dims = [[3, 3], [1, 1]], shape = [9, 1], type = ket
Qobj data =
[[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 1.]
[ 0.]
[ 0.]
[ 0.]]
>>> ket("31", [5, 2])
Quantum object: dims = [[5, 2], [1, 1]], shape = [10, 1], type = ket
Qobj data =
[[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 1.]
[ 0.]
[ 0.]]
"""
if isinstance(dim, int):
dim = [dim] * len(seq)
return tensor([basis(dim[i], _character_to_qudit(x))
for i, x in enumerate(seq)])
def bra(seq, dim=2):
"""
Produces a multiparticle bra state for a list or string,
where each element stands for state of the respective particle.
Parameters
----------
seq : str / list of ints or characters
Each element defines state of the respective particle.
(e.g. [1,1,0,1] or a string "1101").
For qubits it is also possible to use the following conventions:
- 'g'/'e' (ground and excited state)
- 'u'/'d' (spin up and down)
- 'H'/'V' (horizontal and vertical polarization)
Note: for dimension > 9 you need to use a list.
dim : int (default: 2) / list of ints
Space dimension for each particle:
int if there are the same, list if they are different.
Returns
-------
bra : qobj
Examples
--------
>>> bra("10")
Quantum object: dims = [[1, 1], [2, 2]], shape = [1, 4], type = bra
Qobj data =
[[ 0. 0. 1. 0.]]
>>> bra("Hue")
Quantum object: dims = [[1, 1, 1], [2, 2, 2]], shape = [1, 8], type = bra
Qobj data =
[[ 0. 1. 0. 0. 0. 0. 0. 0.]]
>>> bra("12", 3)
Quantum object: dims = [[1, 1], [3, 3]], shape = [1, 9], type = bra
Qobj data =
[[ 0. 0. 0. 0. 0. 1. 0. 0. 0.]]
>>> bra("31", [5, 2])
Quantum object: dims = [[1, 1], [5, 2]], shape = [1, 10], type = bra
Qobj data =
[[ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]]
"""
return ket(seq, dim=dim).dag()
#
# quantum state number helper functions
#
def state_number_enumerate(dims, state=None, idx=0):
"""
An iterator that enumerate all the state number arrays (quantum numbers on
the form [n1, n2, n3, ...]) for a system with dimensions given by dims.
Example:
>>> for state in state_number_enumerate([2,2]):
>>> print state
[ 0. 0.]
[ 0. 1.]
[ 1. 0.]
[ 1. 1.]
Parameters
----------
dims : list or array
The quantum state dimensions array, as it would appear in a Qobj.
state : list
Current state in the iteration. Used internally.
idx : integer
Current index in the iteration. Used internally.
Returns
-------
state_number : list
Successive state number arrays that can be used in loops and other
iterations, using standard state enumeration *by definition*.
"""
if state is None:
state = np.zeros(len(dims))
if idx == len(dims):
yield np.array(state)
else:
for n in range(dims[idx]):
state[idx] = n
for s in state_number_enumerate(dims, state, idx + 1):
yield s
def state_number_index(dims, state):
"""
Return the index of a quantum state corresponding to state,
given a system with dimensions given by dims.
Example:
>>> state_number_index([2, 2, 2], [1, 1, 0])
6.0
Parameters
----------
dims : list or array
The quantum state dimensions array, as it would appear in a Qobj.
state : list
State number array.
Returns
-------
idx : list
The index of the state given by `state` in standard enumeration
ordering.
"""
return sum([state[i] * prod(dims[i + 1:]) for i, d in enumerate(dims)])
def state_index_number(dims, index):
"""
Return a quantum number representation given a state index, for a system
of composite structure defined by dims.
Example:
>>> state_index_number([2, 2, 2], 6)
[1, 1, 0]
Parameters
----------
dims : list or array
The quantum state dimensions array, as it would appear in a Qobj.
index : integer
The index of the state in standard enumeration ordering.
Returns
-------
state : list
The state number array corresponding to index `index` in standard
enumeration ordering.
"""
state = np.empty_like(dims)
D = np.concatenate([np.flipud(np.cumprod(np.flipud(dims[1:]))), [1]])
for n in range(len(dims)):
state[n] = index / D[n]
index -= state[n] * D[n]
return list(state)
def state_number_qobj(dims, state):
"""
Return a Qobj representation of a quantum state specified by the state
array `state`.
Example:
>>> state_number_qobj([2, 2, 2], [1, 0, 1])
Quantum object: dims = [[2, 2, 2], [1, 1, 1]], \
shape = [8, 1], type = ket
Qobj data =
[[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]
[ 1.]
[ 0.]
[ 0.]]
Parameters
----------
dims : list or array
The quantum state dimensions array, as it would appear in a Qobj.
state : list
State number array.
Returns
-------
state : :class:`qutip.Qobj.qobj`
The state as a :class:`qutip.Qobj.qobj` instance.
"""
return tensor([fock(dims[i], s) for i, s in enumerate(state)])
def phase_basis(N, m, phi0=0):
"""
Basis vector for the mth phase of the Pegg-Barnett phase operator.
Parameters
----------
N : int
Number of basis vectors in Hilbert space.
m : int
Integer corresponding to the mth discrete phase phi_m=phi0+2*pi*m/N
phi0 : float (default=0)
Reference phase angle.
Returns
-------
state : qobj
Ket vector for mth Pegg-Barnett phase operator basis state.
Notes
-----
The Pegg-Barnett basis states form a complete set over the truncated
Hilbert space.
"""
phim = phi0 + (2.0 * np.pi * m) / N
n = np.arange(N).reshape((N, 1))
data = 1.0 / np.sqrt(N) * np.exp(1.0j * n * phim)
return Qobj(data)
def zero_ket(N, dims=None):
"""
Creates the zero ket vector with shape Nx1 and
dimensions `dims`.
Parameters
----------
N : int
Hilbert space dimensionality
dims : list
Optional dimensions if ket corresponds to
a composite Hilbert space.
Returns
-------
zero_ket : qobj
Zero ket on given Hilbert space.
"""
return Qobj(sp.csr_matrix((N, 1), dtype=complex), dims=dims)
def spin_state(j, m, type='ket'):
"""Generates the spin state |j, m>, i.e. the eigenstate
of the spin-j Sz operator with eigenvalue m.
Parameters
----------
j : float
The spin of the state ().
m : int
Eigenvalue of the spin-j Sz operator.
type : string {'ket', 'bra', 'dm'}
Type of state to generate.
Returns
-------
state : qobj
Qobj quantum object for spin state
"""
J = 2 * j + 1
if type == 'ket':
return basis(int(J), int(j - m))
elif type == 'bra':
return basis(int(J), int(j - m)).dag()
elif type == 'dm':
return fock_dm(int(J), int(j - m))
else:
raise ValueError("invalid value keyword argument 'type'")
def spin_coherent(j, theta, phi, type='ket'):
"""Generates the spin state |j, m>, i.e. the eigenstate
of the spin-j Sz operator with eigenvalue m.
Parameters
----------
j : float
The spin of the state.
theta : float
Angle from z axis.
phi : float
Angle from x axis.
type : string {'ket', 'bra', 'dm'}
Type of state to generate.
Returns
-------
state : qobj
Qobj quantum object for spin coherent state
"""
Sp = jmat(j, '+')
Sm = jmat(j, '-')
psi = (0.5 * theta * np.exp(1j * phi) * Sm -
0.5 * theta * np.exp(-1j * phi) * Sp).expm() * spin_state(j, j)
if type == 'ket':
return psi
elif type == 'bra':
return psi.dag()
elif type == 'dm':
return ket2dm(psi)
else:
raise ValueError("invalid value keyword argument 'type'")
def bell_state(state='00'):
"""
Returns the Bell state:
|B00> = 1 / sqrt(2)*[|0>|0>+|1>|1>]
|B01> = 1 / sqrt(2)*[|0>|0>-|1>|1>]
|B10> = 1 / sqrt(2)*[|0>|1>+|1>|0>]
|B11> = 1 / sqrt(2)*[|0>|1>-|1>|0>]
Returns
-------
Bell_state : qobj
Bell state
"""
if state == '00':
Bell_state = tensor(
basis(2), basis(2))+tensor(basis(2, 1), basis(2, 1))
elif state == '01':
Bell_state = tensor(
basis(2), basis(2))-tensor(basis(2, 1), basis(2, 1))
elif state == '10':
Bell_state = tensor(
basis(2), basis(2, 1))+tensor(basis(2, 1), basis(2))
elif state == '11':
Bell_state = tensor(
basis(2), basis(2, 1))-tensor(basis(2, 1), basis(2))
return Bell_state.unit()
def singlet_state():
"""
Returns the two particle singlet-state:
|S>=1/sqrt(2)*[|0>|1>-|1>|0>]