-
Notifications
You must be signed in to change notification settings - Fork 36
/
chip.py
executable file
·1227 lines (1103 loc) · 39.9 KB
/
chip.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
"""Component class and subclasses for the components making up the quantum device."""
import warnings
import numpy as np
import tensorflow as tf
from c3.c3objs import C3obj, Quantity
from c3.libraries.constants import kb, hbar
from c3.libraries.hamiltonians import hamiltonians
from c3.utils.qt_utils import hilbert_space_kron as hskron
from scipy.optimize import fmin
import tensorflow_probability as tfp
from typing import List, Dict, Union
device_lib = dict()
def dev_reg_deco(func):
"""
Decorator for making registry of functions
"""
device_lib[str(func.__name__)] = func
return func
class PhysicalComponent(C3obj):
"""
Represents the components making up a chip.
Parameters
----------
hilbert_dim : int
Dimension of the Hilbert space of this component
"""
def __init__(self, **props):
self.params = {}
self.hilbert_dim = props.pop("hilbert_dim", None)
super().__init__(**props)
self.Hs = {}
self.collapse_ops = {}
self.drive_line = None
self.index = None
def set_subspace_index(self, index):
self.index = index
def get_transformed_hamiltonians(self, transform: tf.Tensor = None):
"""
get transformed hamiltonians with given applied transformation. The Hamiltonians are assumed to be stored in `Hs`.
Parameters
----------
transform:
transform to be applied to the hamiltonians. Default: None for returning the hamiltonians without transformation applied.
Returns
-------
"""
if transform is None:
return self.Hs
transformed_Hs = dict()
for key, ham in self.Hs.items():
transformed_Hs[key] = tf.matmul(
tf.matmul(transform, self.Hs["freq"], adjoint_a=True), transform
)
def get_Hamiltonian(
self, signal: Union[dict, bool] = None, transform: tf.Tensor = None
) -> Dict[str, tf.Tensor]:
"""
Compute the Hamiltonian.
Parameters
----------
signal:
dictionary with signals to be used a time dependend Hamiltonian. By default "values" key will be used.
If `true` value control hamiltonian will be returned, used for later combination of signal and hamiltonians.
transform:
transform the hamiltonian, e.g. for expressing the hamiltonian in the expressed basis.
Use this function if transform will be necessary and signal is given, in order to apply the `transform`
only on single hamiltonians instead of all timeslices.
"""
raise NotImplementedError
def asdict(self) -> dict:
params = {}
for key, item in self.params.items():
params[key] = item.asdict()
return {
"c3type": self.__class__.__name__,
"params": params,
"hilbert_dim": self.hilbert_dim,
}
@dev_reg_deco
class Qubit(PhysicalComponent):
"""
Represents the element in a chip functioning as qubit.
Parameters
----------
freq: Quantity
frequency of the qubit
anhar: Quantity
anharmonicity of the qubit. defined as w01 - w12
t1:Quantity
t1, the time decay of the qubit due to dissipation
t2star: Quantity
t2star, the time decay of the qubit due to pure dephasing
temp: Quantity
temperature of the qubit, used to determine the Boltzmann distribution
of energy level populations
"""
def __init__(
self,
name,
hilbert_dim,
desc=None,
comment=None,
freq: Quantity = None,
anhar: Quantity = None,
t1: Quantity = None,
t2star: Quantity = None,
temp: Quantity = None,
params=None,
):
# TODO Cleanup params passing and check for conflicting information
super().__init__(
name=name,
desc=desc,
comment=comment,
hilbert_dim=hilbert_dim,
params=params,
)
if freq:
self.params["freq"] = freq
if anhar:
self.params["anhar"] = anhar
if t1:
self.params["t1"] = t1
if t2star:
self.params["t2star"] = t2star
if temp:
self.params["temp"] = temp
def init_Hs(self, ann_oper):
"""
Initialize the qubit Hamiltonians. If the dimension is higher than two, a
Duffing oscillator is used.
Parameters
----------
ann_oper : np.array
Annihilation operator in the full Hilbert space
"""
resonator = hamiltonians["resonator"]
self.Hs["freq"] = tf.constant(resonator(ann_oper), dtype=tf.complex128)
if self.hilbert_dim > 2:
duffing = hamiltonians["duffing"]
self.Hs["anhar"] = tf.constant(duffing(ann_oper), dtype=tf.complex128)
def get_Hamiltonian(
self, signal: Union[dict, bool] = None, transform: tf.Tensor = None
):
"""
Compute the Hamiltonian. Multiplies the number operator with the frequency and
anharmonicity with the Duffing part and returns their sum.
Returns
-------
tf.Tensor
Hamiltonian
"""
if signal is not None:
raise NotImplementedError(f"implement action of signal on {self.name}")
Hs = self.get_transformed_hamiltonians(transform)
h = tf.cast(self.params["freq"].get_value(), tf.complex128) * Hs["freq"]
if self.hilbert_dim > 2:
anhar = tf.cast(self.params["anhar"].get_value(), tf.complex128)
h += anhar * Hs["anhar"]
return h
def init_Ls(self, ann_oper):
"""
Initialize Lindbladian components.
Parameters
----------
ann_oper : np.array
Annihilation operator in the full Hilbert space
"""
self.collapse_ops["t1"] = ann_oper
self.collapse_ops["temp"] = ann_oper.T.conj()
self.collapse_ops["t2star"] = 2 * tf.matmul(ann_oper.T.conj(), ann_oper)
def get_Lindbladian(self, dims):
"""
Compute the Lindbladian, based on relaxation, dephasing constants and finite
temperature.
Returns
-------
tf.Tensor
Hamiltonian
"""
Ls = []
if "t1" in self.params:
t1 = self.params["t1"].get_value()
gamma = (0.5 / t1) ** 0.5
L = gamma * self.collapse_ops["t1"]
Ls.append(L)
if "temp" in self.params:
if self.hilbert_dim > 2:
freq = self.params["freq"].get_value()
anhar = self.params["anhar"].get_value()
freq_diff = np.array(
[freq + n * anhar for n in range(self.hilbert_dim)]
)
else:
freq_diff = np.array([self.params["freq"].get_value(), 0])
beta = 1 / (self.params["temp"].get_value() * kb)
det_bal = tf.exp(-hbar * tf.cast(freq_diff, tf.float64) * beta)
det_bal_mat = hskron(tf.linalg.tensor_diag(det_bal), self.index, dims)
L = gamma * tf.matmul(self.collapse_ops["temp"], det_bal_mat)
Ls.append(L)
if "t2star" in self.params:
gamma = (0.5 / self.params["t2star"].get_value()) ** 0.5
L = gamma * self.collapse_ops["t2star"]
Ls.append(L)
if not Ls:
raise Exception("No T1 or T2 provided")
return tf.cast(sum(Ls), tf.complex128)
@dev_reg_deco
class Resonator(PhysicalComponent):
"""
Represents the element in a chip functioning as resonator.
Parameters
----------
freq: np.float64
frequency of the resonator
"""
def init_Hs(self, ann_oper):
"""
Initialize the Hamiltonian as a number operator
Parameters
----------
ann_oper : np.array
Annihilation operator in the full Hilbert space.
"""
self.Hs["freq"] = tf.constant(
hamiltonians["resonator"](ann_oper), dtype=tf.complex128
)
def init_Ls(self, ann_oper):
"""NOT IMPLEMENTED"""
pass
def get_Hamiltonian(
self, signal: Union[dict, bool] = None, transform: tf.Tensor = None
):
"""Compute the Hamiltonian."""
if signal:
raise NotImplementedError(f"implement action of signal on {self.name}")
Hs = self.get_transformed_hamiltonians(transform)
freq = tf.cast(self.params["freq"].get_value(), tf.complex128)
return freq * Hs["freq"]
def get_Lindbladian(self, dims):
"""NOT IMPLEMENTED"""
pass
@dev_reg_deco
class Transmon(PhysicalComponent):
"""
Represents the element in a chip functioning as tunanble transmon qubit.
Parameters
----------
freq: np.float64
base frequency of the Transmon
phi_0: np.float64
half period of the phase dependant function
phi: np.float64
flux position
"""
def __init__(
self,
name: str,
desc: str = None,
comment: str = None,
hilbert_dim: int = None,
freq: Quantity = None,
phi: Quantity = None,
phi_0: Quantity = None,
gamma: Quantity = None,
d: Quantity = None,
t1: Quantity = None,
t2star: Quantity = None,
temp: Quantity = None,
anhar: Quantity = None,
params=None,
):
super().__init__(
name=name,
desc=desc,
comment=comment,
hilbert_dim=hilbert_dim,
params=params,
)
if freq:
self.params["freq"] = freq
if phi:
self.params["phi"] = phi
if phi_0:
self.params["phi_0"] = phi_0
if d:
self.params["d"] = d
elif gamma:
self.params["gamma"] = gamma
if anhar:
# Anharmonicity corresponding to the charging energy in the two-level case
self.params["anhar"] = anhar
if t1:
self.params["t1"] = t1
if t2star:
self.params["t2star"] = t2star
if temp:
self.params["temp"] = temp
if "d" not in self.params.keys() and "gamma" not in self.params.keys():
warnings.warn(
"C3:WANING: No junction asymmetry specified, setting symmetric SQUID"
" for tuning."
)
def get_factor(self, phi_sig=0):
pi = tf.constant(np.pi, tf.float64)
phi = self.params["phi"].get_value()
phi += phi_sig
phi_0 = self.params["phi_0"].get_value()
if "d" in self.params:
d = self.params["d"].get_value()
elif "gamma" in self.params:
gamma = self.params["gamma"].get_value()
d = (gamma - 1) / (gamma + 1)
else:
d = 0
factor = tf.sqrt(
tf.sqrt(
tf.cos(pi * phi / phi_0) ** 2 + d ** 2 * tf.sin(pi * phi / phi_0) ** 2
)
)
return factor
def get_anhar(self):
anhar = tf.cast(self.params["anhar"].get_value(), tf.complex128)
return anhar
def get_freq(self, phi_sig=0):
# TODO: Check how the time dependency affects the frequency. (Koch et al. , 2007)
freq = self.params["freq"].get_value()
anhar = self.params["anhar"].get_value()
biased_freq = (freq - anhar) * self.get_factor(phi_sig) + anhar
return tf.cast(biased_freq, tf.complex128)
def init_Hs(self, ann_oper):
resonator = hamiltonians["resonator"]
self.Hs["freq"] = tf.constant(resonator(ann_oper), dtype=tf.complex128)
if self.hilbert_dim > 2:
duffing = hamiltonians["duffing"]
self.Hs["anhar"] = tf.constant(duffing(ann_oper), dtype=tf.complex128)
def init_Ls(self, ann_oper):
"""
Initialize Lindbladian components.
Parameters
----------
ann_oper : np.array
Annihilation operator in the full Hilbert space
"""
self.collapse_ops["t1"] = ann_oper
self.collapse_ops["temp"] = ann_oper.T.conj()
self.collapse_ops["t2star"] = 2 * tf.matmul(ann_oper.T.conj(), ann_oper)
def get_Hamiltonian(
self, signal: Union[dict, bool] = None, transform: tf.Tensor = None
):
Hs = self.get_transformed_hamiltonians(transform)
H_freq = Hs["freq"]
H_anhar = Hs["anhar"]
if isinstance(signal, dict):
sig = signal["values"]
freq = tf.cast(self.get_freq(sig), tf.complex128)
freq = tf.reshape(freq, [freq.shape[0], 1, 1])
tf.expand_dims(H_freq, 0) * freq
else:
freq = self.get_freq()
h = freq * H_freq
if self.hilbert_dim > 2:
h += self.get_anhar() * H_anhar
return h
def get_Lindbladian(self, dims):
"""
Compute the Lindbladian, based on relaxation, dephasing constants and finite temperature.
Returns
-------
tf.Tensor
Hamiltonian
"""
Ls = []
if "t1" in self.params:
t1 = self.params["t1"].get_value()
gamma = (0.5 / t1) ** 0.5
L = gamma * self.collapse_ops["t1"]
Ls.append(L)
if "temp" in self.params:
if self.params["temp"].get_value().numpy():
if self.hilbert_dim > 2:
freq_diff = np.array(
[
(
self.params["freq"].get_value()
+ n * self.params["anhar"].get_value()
)
for n in range(self.hilbert_dim)
]
)
else:
freq_diff = np.array([self.params["freq"].get_value(), 0])
beta = 1 / (self.params["temp"].get_value() * kb)
det_bal = tf.exp(-hbar * tf.cast(freq_diff, tf.float64) * beta)
det_bal_mat = hskron(
tf.linalg.tensor_diag(det_bal), self.index, dims
)
L = gamma * tf.matmul(self.collapse_ops["temp"], det_bal_mat)
Ls.append(L)
if "t2star" in self.params:
gamma = (0.5 / self.params["t2star"].get_value()) ** 0.5
L = gamma * self.collapse_ops["t2star"]
Ls.append(L)
if len(Ls) == 0:
raise Exception("No T1 or T2 provided")
return tf.cast(sum(Ls), tf.complex128)
class TransmonExpanded(Transmon):
def init_Hs(self, ann_oper):
ann_oper = tf.constant(ann_oper, tf.complex128)
ann_oper_dag = tf.linalg.matrix_transpose(ann_oper, conjugate=True)
adag_plus_a = ann_oper_dag + ann_oper
sq_adag_plus_a = tf.linalg.matmul(adag_plus_a, adag_plus_a)
quartic_adag_plus_a = tf.linalg.matmul(sq_adag_plus_a, sq_adag_plus_a)
sextic_adag_plus_a = tf.linalg.matmul(quartic_adag_plus_a, sq_adag_plus_a)
self.Hs["quadratic"] = tf.linalg.matmul(ann_oper_dag, ann_oper) # + 1 / 2
self.Hs["quartic"] = quartic_adag_plus_a
self.Hs["sextic"] = sextic_adag_plus_a
if "EC" not in self.params:
self.energies_from_frequencies()
def get_prefactors(self, sig):
EC = self.params["EC"].get_value()
EJ = self.params["EJ"].get_value() * self.get_factor(sig) ** 2
prefactors = dict()
prefactors["quadratic"] = tf.math.sqrt(8 * EC * EJ)
prefactors["quartic"] = -EC / 12
prefactors["sextic"] = EJ / 720 * (2 * EC / EJ) ** (3 / 2)
return prefactors
def energies_from_frequencies(self):
freq = self.params["freq"].get_value()
anhar = self.params["anhar"].get_value()
phi = self.params["phi"].get_value()
EC_guess = -anhar
EJ_guess = (freq + EC_guess) ** 2 / (8 * EC_guess)
self.params["EC"] = Quantity(
EC_guess, min_val=0.0 * EC_guess, max_val=2 * EC_guess
)
self.params["EJ"] = Quantity(
EJ_guess, min_val=0.0 * EJ_guess, max_val=2 * EJ_guess
)
def eval_func(x):
EC, EJ = x
self.params["EC"].set_opt_value(EC)
self.params["EJ"].set_opt_value(EJ)
prefactors = self.get_prefactors(-phi)
h = tf.zeros_like(self.Hs["quadratic"])
for k in prefactors:
h += self.Hs[k] * tf.cast(prefactors[k], tf.complex128)
es = tf.linalg.eigvalsh(h)
es -= es[0]
freq_diff = tf.math.abs(tf.math.real(es[1] - es[0]) - freq)
anhar_diff = tf.math.abs(tf.math.real(es[2] - es[1]) - (freq + anhar))
return freq_diff + anhar_diff
fmin(
eval_func,
x0=[self.params["EC"].get_opt_value(), self.params["EJ"].get_opt_value()],
)
print(
(float(EC_guess), float(EJ_guess)),
(float(self.params["EC"]), float(self.params["EJ"])),
)
def get_Hamiltonian(
self, signal: Union[dict, bool] = None, transform: tf.Tensor = None
):
Hs = self.get_transformed_hamiltonians(transform)
if isinstance(signal, dict):
sig = signal["values"]
else:
sig = 0
prefactors = self.get_prefactors(sig)
h = tf.zeros_like(Hs["quadratic"])
for k in prefactors:
h += Hs[k] * tf.cast(prefactors[k], tf.complex128)
return h
@dev_reg_deco
class CShuntFluxQubitCos(Qubit):
def __init__(
self,
name: str,
desc: str = None,
comment: str = None,
hilbert_dim: int = None,
calc_dim: int = None,
EC: Quantity = None,
EJ: Quantity = None,
EL: Quantity = None,
phi: Quantity = None,
phi_0: Quantity = None,
gamma: Quantity = None,
d: Quantity = None,
t1: np.float64 = None,
t2star: np.float64 = None,
temp: np.float64 = None,
anhar: np.float64 = None,
params=None,
):
super().__init__(
name=name,
desc=desc,
comment=comment,
hilbert_dim=hilbert_dim,
freq=None,
anhar=None,
t1=t1,
t2star=t2star,
temp=temp,
params=params,
)
if EC:
self.params["EC"] = EC
if EJ:
self.params["EJ"] = EJ
if EL:
self.params["EL"] = EL
if phi:
self.params["phi"] = phi
if phi_0:
self.params["phi_0"] = phi_0
if gamma:
self.params["gamma"] = gamma
if calc_dim:
self.params["calc_dim"] = calc_dim
def get_phase_variable(self):
ann_oper = tf.linalg.diag(
tf.math.sqrt(tf.range(1, self.params["calc_dim"], dtype=tf.float64)), k=1
)
EC = self.params["EC"].get_value()
EJ = self.params["EJ"].get_value()
phi_zpf = (2.0 * EC / EJ) ** 0.25
return tf.cast(
phi_zpf * (tf.transpose(ann_oper, conjugate=True) + ann_oper), tf.complex128
)
def get_n_variable(self):
ann_oper = tf.linalg.diag(
tf.math.sqrt(tf.range(1, self.params["calc_dim"], dtype=tf.float64)), k=1
)
EC = self.params["EC"].get_value()
EJ = self.params["EJ"].get_value()
n_zpf = (EJ / EC / 32) ** 0.25
return tf.cast(
n_zpf * (-tf.transpose(ann_oper, conjugate=True) + ann_oper), tf.complex128
)
def init_exponentiated_vars(self, ann_oper):
# TODO check if a 2Pi should be included in the exponentiation
self.exp_phi_op = tf.linalg.expm(1.0j * self.get_phase_variable())
def get_freq(self):
EC = self.params["EC"].get_value()
EL = self.params["EL"].get_value()
return tf.cast(tf.math.sqrt(8.0 * EL * EC), tf.complex128)
def init_Hs(self, ann_oper):
# self.init_exponentiated_vars(ann_oper)
# resonator = hamiltonians["resonator"]
# self.Hs["freq"] = tf.constant(resonator(ann_oper), dtype=tf.complex128)
# # self.Hs["freq"] = tf.cast(tf.linalg.diag(tf.range(self.params['calc_dim'], dtype=tf.float64)), tf.complex128)
pass
def cosm(self, var, a=1, b=0):
exponent = 1j * (a * var)
exp_mat = tf.linalg.expm(exponent) * tf.exp(1j * b)
cos_mat = 0.5 * (exp_mat + tf.transpose(exp_mat, conjugate=True))
return cos_mat
def get_Hamiltonian(
self, signal: Union[dict, bool] = None, transform: tf.Tensor = None
):
if signal:
raise NotImplementedError(f"implement action of signal on {self.name}")
if transform:
raise NotImplementedError()
EJ = tf.cast(self.params["EJ"].get_value(), tf.complex128)
EC = tf.cast(self.params["EC"].get_value(), tf.complex128)
gamma = tf.cast(self.params["gamma"].get_value(), tf.complex128)
phi = tf.cast(self.params["phi"].get_value(), tf.complex128)
phi_0 = tf.cast(self.params["phi_0"].get_value(), tf.complex128)
phase = tf.cast(2 * np.pi * phi / phi_0, tf.complex128)
phi_variable = self.get_phase_variable()
n = self.get_n_variable()
h = 4 * EC * n + EJ * (
-1 * self.cosm(phi_variable, 2, phase) - 2 * gamma * self.cosm(phi_variable)
)
return tf.cast(tf.math.real(h), tf.complex128) # TODO apply kronecker product
@dev_reg_deco
class CShuntFluxQubit(Qubit):
def __init__(
self,
name: str,
desc: str = None,
comment: str = None,
hilbert_dim: int = None,
calc_dim: int = None,
EC: Quantity = None,
EJ: Quantity = None,
EL: Quantity = None,
phi: Quantity = None,
phi_0: Quantity = None,
gamma: Quantity = None,
d: Quantity = None,
t1: Quantity = None,
t2star: Quantity = None,
temp: Quantity = None,
anhar: np.float64 = None,
params=dict(),
resolution=None,
):
super().__init__(
name=name,
desc=desc,
comment=comment,
hilbert_dim=hilbert_dim,
freq=None,
anhar=None,
t1=t1,
t2star=t2star,
temp=temp,
params=params,
)
self.inputs = params.pop("inputs", 1)
self.outputs = params.pop("outputs", 0)
if resolution:
self.resolution = resolution
self.inputs = 1
self.outputs = 2
if EC:
self.params["EC"] = EC
if EJ:
self.params["EJ"] = EJ
if EL:
self.params["EL"] = EL
if phi:
self.params["phi"] = phi
if phi_0:
self.params["phi_0"] = phi_0
if gamma:
self.params["gamma"] = gamma
if calc_dim:
self.params["calc_dim"] = calc_dim
self.phi_var_min_ref = None
self.min_phi_var_change_test = 1312341234 # Random Wrong Number
def get_potential_function(self, phi_variable, deriv_order=1, phi_sig=0):
phi = (
(self.params["phi"].get_value() + phi_sig)
/ self.params["phi_0"].get_value()
* 2
* np.pi
)
gamma = self.params["gamma"].get_value()
EJ = self.params["EJ"].get_value()
phi_variable = tf.cast(phi_variable, tf.float64)
if deriv_order == 0: # Has to be defined
return EJ * (
-1 * tf.cos(phi_variable + phi) - 2 * gamma * tf.cos(phi_variable / 2)
)
elif deriv_order == 1:
return (
EJ
* (
+2 * tf.sin(phi_variable + phi)
+ 2 * gamma * tf.sin(phi_variable / 2)
)
/ 2
) # TODO: Why is this different than Krantz????
elif deriv_order == 2:
return (
EJ
* (
+4 * tf.cos(phi_variable + phi)
+ 2 * gamma * tf.cos(phi_variable / 2)
)
/ 4
)
elif deriv_order == 3:
return (
EJ
* (
-8 * tf.sin(phi_variable + phi)
- 2 * gamma * tf.sin(phi_variable / 2)
)
/ 8
)
elif deriv_order == 4:
return (
EJ
* (
-16 * tf.cos(phi_variable + phi)
- 2 * gamma * tf.cos(phi_variable / 2)
)
/ 16
)
else: # Calculate derivative by tensorflow
with tf.GradientTape() as tape:
tape.watch(phi_variable)
val = self.get_potential_function(phi_variable, deriv_order - 1)
return tape.gradient(val, phi_variable)
def get_minimum_phi_var(self, init_phi_variable: tf.float64 = 0, phi_sig=0):
# TODO maybe improve to analytical funciton here
# TODO do not reevaluate if not necessary
phi_0 = self.params["phi_0"].get_value()
initial_pot_eval = self.get_potential_function(0.0, 0)
if self.min_phi_var_change_test != initial_pot_eval and phi_sig == 0:
phi_var_min = fmin(
self.get_potential_function,
[init_phi_variable],
args=(0, 0),
disp=False,
)
self.min_phi_var_interpolation = None
self.min_phi_var_change_test = initial_pot_eval
print(phi_var_min)
return phi_var_min
if not (
self.phi_var_min_ref is not None
and self.min_phi_var_change_test == initial_pot_eval
):
print(self.params["phi"], phi_sig)
phi_var_min_ref = list()
print("a")
for phi_i in np.linspace(0, phi_0, 50): # Interpolate over 50 points
phi_var_min_ref.append(
fmin(
self.get_potential_function,
[init_phi_variable],
args=(0, phi_i),
disp=False,
)
)
print("b")
self.phi_var_min_ref = tf.reshape(
tf.constant(phi_var_min_ref, tf.float64), len(phi_var_min_ref)
)
# self.min_phi_var_interpolation = lambda x: tfp.math.interp_regular_1d_grid(tf.math.mod(x, phi_0), 0, phi_0, phi_var_min_ref)
self.min_phi_var_change_test = initial_pot_eval
phi_var_min = tfp.math.interp_regular_1d_grid(
tf.math.mod(phi_sig, phi_0), 0, phi_0, self.phi_var_min_ref
)
return phi_var_min
# gamma = self.params["gamma"].get_value()
# return tf.cast(0.5, tf.float64)
def get_frequency(self, phi_sig=0):
EC = self.params["EC"].get_value()
EJ = self.params["EJ"].get_value()
phi_var_min = self.get_minimum_phi_var(phi_sig=phi_sig)
second_order_deriv = self.get_potential_function(
phi_var_min, 2, phi_sig=phi_sig
)
fourth_order_deriv = self.get_potential_function(
phi_var_min, 4, phi_sig=phi_sig
)
# if type(phi_sig) is not int:
# print(phi_var_min.shape, phi_sig.shape, second_order_deriv.shape)
return (
tf.math.sqrt(2 * EJ * EC)
+ tf.math.sqrt(2 * EC / EJ) * second_order_deriv
+ EC / EJ * fourth_order_deriv
)
get_freq = get_frequency
def get_anharmonicity(self, phi_sig=0):
EC = self.params["EC"].get_value()
EJ = self.params["EJ"].get_value()
phi_var_min = self.get_minimum_phi_var()
fourth_order_deriv = self.get_potential_function(
phi_var_min, 4, phi_sig=phi_sig
)
return EC / EJ * fourth_order_deriv
def get_third_order_prefactor(self, phi_sig=0):
EC = self.params["EC"].get_value()
EJ = self.params["EJ"].get_value()
phi_var_min = self.get_minimum_phi_var()
third_order_deriv = self.get_potential_function(phi_var_min, 3, phi_sig=phi_sig)
return 0.5 * ((2 * EC / EJ) ** 0.75) * third_order_deriv
def init_Hs(self, ann_oper):
"""
initialize Hamiltonians for cubic hamiltinian
Parameters
----------
ann_oper : np.array
Annihilation operator in the full Hilbert space
"""
resonator = hamiltonians["resonator"]
self.Hs["freq"] = tf.constant(resonator(ann_oper), dtype=tf.complex128)
if self.hilbert_dim > 2:
duffing = hamiltonians["duffing"]
self.Hs["anhar"] = tf.constant(duffing(ann_oper), dtype=tf.complex128)
third = hamiltonians["third_order"]
self.Hs["third_order"] = tf.constant(third(ann_oper), dtype=tf.complex128)
def get_Hamiltonian(
self, signal: Union[dict, bool] = None, transform: tf.Tensor = None
) -> tf.Tensor:
"""
Calculate the hamiltonian
Returns
-------
tf.Tensor
Hamiltonian
"""
if signal:
raise NotImplementedError(f"implement action of signal on {self.name}")
Hs = self.get_transformed_hamiltonians(transform)
h = tf.cast(self.get_frequency(), tf.complex128) * Hs["freq"]
# h += tf.cast(self.get_third_order_prefactor(), tf.complex128) * Hs["third_order"]
if self.hilbert_dim > 2:
h += tf.cast(self.get_anharmonicity(), tf.complex128) * Hs["anhar"]
return h
# def process(self, instr, chan: str, signal_in):
# sig = signal_in["values"]
# anharmonicity = self.get_anharmonicity(sig)
# frequency = self.get_frequency(sig)
# # third_order = self.get_third_order_prefactor(sig)
# h = (
# tf.expand_dims(tf.expand_dims(tf.cast(frequency, tf.complex128), 1), 2)
# * self.Hs["freq"]
# )
# if self.hilbert_dim > 2:
# # h += tf.expand_dims(tf.expand_dims(tf.cast(third_order, tf.complex128), 1), 2) * self.Hs["third_order"]
# h += (
# tf.expand_dims(
# tf.expand_dims(tf.cast(anharmonicity, tf.complex128), 1), 2
# )
# * self.Hs["anhar"]
# )
# self.signal_h = h
# return {
# "ts": signal_in["ts"],
# "frequency": frequency,
# "anharmonicity": anharmonicity,
# } # , "#third order": third_order}
@dev_reg_deco
class Fluxonium(CShuntFluxQubit):
def __init__(
self,
name: str,
desc: str = None,
comment: str = None,
hilbert_dim: int = None,
calc_dim: int = None,
EC: Quantity = None,
EJ: Quantity = None,
EL: Quantity = None,
phi: Quantity = None,
phi_0: Quantity = None,
gamma: Quantity = None,
t1: np.float64 = None,
t2star: np.float64 = None,
temp: np.float64 = None,
params=None,
):
super().__init__(
name=name,
desc=desc,
comment=comment,
hilbert_dim=hilbert_dim,
EC=EC,
EJ=EJ,
phi=phi,
phi_0=phi_0,
gamma=gamma,
t1=t1,
t2star=t2star,
temp=temp,
params=params,
)
# if EC:
# self.params["EC"] = EC
# if EJ:
# self.params["EJ"] = EJ
if EL:
self.params["EL"] = EL
# if phi:
# self.params["phi"] = phi
# if phi_0:
# self.params["phi_0"] = phi_0
# if gamma:
# self.params["gamma"] = gamma
# if calc_dim:
# self.params["calc_dim"] = calc_dim
def get_potential_function(
self, phi_variable, deriv_order=1, phi_sig=0
) -> tf.float64:
if phi_sig != 0:
raise NotImplementedError()
EL = self.params["EL"].get_value()
EJ = self.params["EJ"].get_value()
phi = (
self.params["phi"].get_value()
/ self.params["phi_0"].get_value()
* 2
* np.pi
)
if deriv_order == 0: # Has to be defined
return -EJ * tf.math.cos(phi_variable + phi) + 0.5 * EL * phi_variable ** 2
elif deriv_order == 1:
return EJ * tf.math.sin(phi_variable + phi) + EL * phi_variable
elif deriv_order == 2:
return EJ * tf.math.cos(phi_variable + phi) + EL
elif deriv_order == 3:
return -EJ * tf.math.sin(phi_variable + phi)
else: # Calculate derivative by tensorflow
with tf.GradientTape() as tape:
tape.watch(phi_variable)
val = self.get_potential_function(phi_variable, deriv_order - 1)
grad = tape.gradient(val, phi_variable)
return grad
#
# def get_minimum_phi_var(self, init_phi_variable: tf.float64 = 0) -> tf.float64:
# # Redefine here as minimizing function does not work otherwise
# # TODO maybe improve to analytical funciton here