clelandlab-utils 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Cleland Lab
4
+ Copyright (c) 2026 Cleland Lab
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: clelandlab-utils
3
+ Version: 0.1.0
4
+ Summary: Utility Functions
5
+ Author: Cleland Lab
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://clelandlab-utils.readthedocs.io/en/latest/
8
+ Project-URL: Source, https://github.com/clelandlab/utils
9
+ Project-URL: Tracker, https://github.com/clelandlab/utils/issues
10
+ Requires-Python: <4,>=3.13
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: scipy
15
+ Requires-Dist: matplotlib
16
+ Requires-Dist: PyYAML
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: func_timeout
19
+ Dynamic: license-file
20
+
21
+ # Cleland Lab utils
22
+
23
+ [![Documentation](https://img.shields.io/readthedocs/clelandlab-utils?style=for-the-badge&logo=readthedocs&logoColor=white)](https://clelandlab-utils.readthedocs.io/en/latest/)
24
+ [![PyPI](https://img.shields.io/pypi/v/clelandlab-utils?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/clelandlab-utils/)
25
+ [![GitHub stars](https://img.shields.io/github/stars/clelandlab/utils?style=for-the-badge&logo=github)](https://github.com/clelandlab/utils)
26
+
27
+ ## Get Started
28
+
29
+ ```shell
30
+ pip install clelandlab-utils
31
+ ```
32
+
33
+ ```python
34
+ from utils import fitT1
35
+ ```
36
+
37
+ See the [documentation](https://clelandlab-utils.readthedocs.io/en/latest/) for all functions and examples.
@@ -0,0 +1,17 @@
1
+ # Cleland Lab utils
2
+
3
+ [![Documentation](https://img.shields.io/readthedocs/clelandlab-utils?style=for-the-badge&logo=readthedocs&logoColor=white)](https://clelandlab-utils.readthedocs.io/en/latest/)
4
+ [![PyPI](https://img.shields.io/pypi/v/clelandlab-utils?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/clelandlab-utils/)
5
+ [![GitHub stars](https://img.shields.io/github/stars/clelandlab/utils?style=for-the-badge&logo=github)](https://github.com/clelandlab/utils)
6
+
7
+ ## Get Started
8
+
9
+ ```shell
10
+ pip install clelandlab-utils
11
+ ```
12
+
13
+ ```python
14
+ from utils import fitT1
15
+ ```
16
+
17
+ See the [documentation](https://clelandlab-utils.readthedocs.io/en/latest/) for all functions and examples.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "clelandlab-utils"
7
+ version = "0.1.0"
8
+ description = "Utility Functions"
9
+ readme = "README.md"
10
+ requires-python = ">=3.13,<4"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Cleland Lab"}]
14
+ dependencies = [
15
+ "numpy",
16
+ "scipy",
17
+ "matplotlib",
18
+ "PyYAML",
19
+ "tqdm",
20
+ "func_timeout",
21
+ ]
22
+
23
+ [project.urls]
24
+ Documentation = "https://clelandlab-utils.readthedocs.io/en/latest/"
25
+ Source = "https://github.com/clelandlab/utils"
26
+ Tracker = "https://github.com/clelandlab/utils/issues"
27
+
28
+ [tool.setuptools.packages.find]
29
+ where = ["src"]
30
+ include = ["utils*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: clelandlab-utils
3
+ Version: 0.1.0
4
+ Summary: Utility Functions
5
+ Author: Cleland Lab
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://clelandlab-utils.readthedocs.io/en/latest/
8
+ Project-URL: Source, https://github.com/clelandlab/utils
9
+ Project-URL: Tracker, https://github.com/clelandlab/utils/issues
10
+ Requires-Python: <4,>=3.13
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: scipy
15
+ Requires-Dist: matplotlib
16
+ Requires-Dist: PyYAML
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: func_timeout
19
+ Dynamic: license-file
20
+
21
+ # Cleland Lab utils
22
+
23
+ [![Documentation](https://img.shields.io/readthedocs/clelandlab-utils?style=for-the-badge&logo=readthedocs&logoColor=white)](https://clelandlab-utils.readthedocs.io/en/latest/)
24
+ [![PyPI](https://img.shields.io/pypi/v/clelandlab-utils?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/clelandlab-utils/)
25
+ [![GitHub stars](https://img.shields.io/github/stars/clelandlab/utils?style=for-the-badge&logo=github)](https://github.com/clelandlab/utils)
26
+
27
+ ## Get Started
28
+
29
+ ```shell
30
+ pip install clelandlab-utils
31
+ ```
32
+
33
+ ```python
34
+ from utils import fitT1
35
+ ```
36
+
37
+ See the [documentation](https://clelandlab-utils.readthedocs.io/en/latest/) for all functions and examples.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/clelandlab_utils.egg-info/PKG-INFO
5
+ src/clelandlab_utils.egg-info/SOURCES.txt
6
+ src/clelandlab_utils.egg-info/dependency_links.txt
7
+ src/clelandlab_utils.egg-info/requires.txt
8
+ src/clelandlab_utils.egg-info/top_level.txt
9
+ src/utils/__init__.py
10
+ src/utils/_utils.py
@@ -0,0 +1,6 @@
1
+ numpy
2
+ scipy
3
+ matplotlib
4
+ PyYAML
5
+ tqdm
6
+ func_timeout
@@ -0,0 +1,4 @@
1
+ """Data saving, parameter sweeps, and analysis helpers for experiments."""
2
+
3
+ from ._utils import *
4
+ from ._utils import __all__
@@ -0,0 +1,499 @@
1
+ """Utility functions for data saving, parameter sweeps, and experimental analysis.
2
+
3
+ Copyright (c) 2024 Cleland Lab. Licensed under the MIT License; see LICENSE.
4
+ """
5
+
6
+ import copy
7
+ import os
8
+ import re
9
+ from datetime import datetime
10
+
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ import yaml
14
+ from func_timeout import func_timeout
15
+ from numpy import pi as π
16
+ from scipy import stats
17
+ from scipy.optimize import curve_fit, leastsq, minimize
18
+ from tqdm.auto import tqdm
19
+
20
+ __all__ = [
21
+ "Saver",
22
+ "Sweep",
23
+ "dB2gain",
24
+ "estimateOmega",
25
+ "evalStr",
26
+ "feistel_network",
27
+ "fitResonator",
28
+ "fitT1",
29
+ "fitT2",
30
+ "gain2dB",
31
+ "iq_scatter",
32
+ "load_data",
33
+ "load_yaml",
34
+ "nested_get",
35
+ "print_yaml",
36
+ "safe_wrap",
37
+ "save_yaml",
38
+ "symmetryCenter",
39
+ "π",
40
+ ]
41
+
42
+
43
+ yaml.add_representer(np.ndarray, lambda dumper, array: dumper.represent_sequence('tag:yaml.org,2002:seq', array.tolist(), flow_style=True))
44
+ yaml.add_multi_representer(np.generic, lambda dumper, data: dumper.represent_data(data.item()))
45
+
46
+ def print_yaml(data): # Print in yaml format
47
+ print(yaml.dump(data))
48
+
49
+ def load_yaml(path):
50
+ file = open(path, "r")
51
+ content = yaml.safe_load(file)
52
+ file.close()
53
+ return content
54
+
55
+ def save_yaml(path, data):
56
+ file = open(path, "w")
57
+ content = yaml.dump(data)
58
+ file.write(content)
59
+ return content
60
+
61
+ def load_data(*paths):
62
+ data_list = []
63
+ for p in paths:
64
+ d = np.genfromtxt(p, delimiter=",")
65
+ data_list.append(d)
66
+ return np.concatenate(data_list)
67
+
68
+
69
+ class Saver:
70
+ def __init__(self, title, path, indep_params=[], dep_params=[], params={}):
71
+ self.indep_params = []
72
+ self.dep_params = []
73
+ self.params = params
74
+ self.title = title
75
+ self.path = path
76
+ self.file_name = ''
77
+ self.has_data = False
78
+ os.path.exists(path)
79
+ try: # check variables
80
+ for value in indep_params:
81
+ self.indep_params.append([value[0], value[1]])
82
+ for value in dep_params:
83
+ self.dep_params.append([value[0], value[1]])
84
+ except KeyError:
85
+ print("Variables incorrectly formatted. Variable: ('label', 'unit')")
86
+ # Detect max existing file number
87
+ existing_files = [f for f in os.listdir(self.path) if re.search(r"^\d\d\d\d\d \- .*\.csv$", f)]
88
+ if existing_files:
89
+ existing_numbers = [int(f.split(' - ')[0]) for f in existing_files]
90
+ next_number = max(existing_numbers) + 1
91
+ else:
92
+ next_number = 0
93
+ # Creating file name + path
94
+ self.file_name = self.path + f"/{next_number:05d} - {self.title}"
95
+ self.created_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
96
+ self.write_yml()
97
+ np.savetxt(self.file_name + '.csv', [], delimiter=',')
98
+ def write_yml(self):
99
+ meta = {
100
+ "created": self.created_time,
101
+ "completed": datetime.now().strftime("%Y-%m-%d %H:%M:%S") if self.has_data else "N/A",
102
+ "title": self.title,
103
+ "independent": self.indep_params,
104
+ "dependent": self.dep_params,
105
+ "parameters": self.params
106
+ }
107
+ save_yaml(self.file_name + ".yml", meta)
108
+ def write_data(self, data):
109
+ self.has_data = True
110
+ with open(self.file_name + '.csv', 'a+') as f:
111
+ np.savetxt(f, data, fmt="%.9e", delimiter=',')
112
+ # self.write_yml() # do not call it every time for efficiency
113
+
114
+
115
+ def feistel_network(i, N, seed): # generate pseudo-random permutation
116
+ half_bits = (N - 1).bit_length() // 2 + (N - 1).bit_length() % 2
117
+ limit = 1 << half_bits
118
+ mask = limit - 1
119
+ def round_function(val, round_idx): # a variation of a 32-bit MurmurHash-style mixer.
120
+ x = (val ^ seed ^ round_idx) * 0x45d9f3b
121
+ x = ((x >> 16) ^ x) * 0x45d9f3b
122
+ x = (x >> 16) ^ x
123
+ return x & mask
124
+ def permute(val):
125
+ left = val >> half_bits
126
+ right = val & mask
127
+ for r in range(5):
128
+ left, right = right, left ^ round_function(right, r)
129
+ return (left << half_bits) | right
130
+ curr = permute(i % N)
131
+ while curr >= N:
132
+ curr = permute(curr)
133
+ return curr
134
+
135
+ def nested_get(d, key): # key is a list
136
+ for k in key:
137
+ d = d[k]
138
+ return d
139
+
140
+ class Sweep:
141
+ def __init__(self, config, sweepConfig, random=False, progressBar=True):
142
+ self.config = copy.deepcopy(config) # Copy config, avoid changing the original
143
+ self.sweep = [] # [{ "key", "list", "len" }]
144
+ self.progressBar = progressBar
145
+ self.random = random
146
+ self.total = 1
147
+ self.index = 0 # iteration index, increase in order
148
+ self.seed = np.random.randint(2147483647)
149
+ def parse_sweep(key, d): # key is a list
150
+ for k, v in d.items():
151
+ if isinstance(v, dict):
152
+ parse_sweep(key + [k], v)
153
+ continue
154
+ if np.iterable(v) and not isinstance(v, str):
155
+ self.sweep.append({ "key": key + [k], "list": list(v), "len": len(v) })
156
+ self.total *= len(v)
157
+ continue
158
+ nested_get(self.config, key)[k] = v
159
+ try:
160
+ parse_sweep([], sweepConfig)
161
+ self.sweep.reverse()
162
+ if self.total == 0:
163
+ raise("Empty Sweep")
164
+ except:
165
+ raise("Invalid Sweep Config")
166
+ def __iter__(self): # initialze all iterator
167
+ if self.progressBar:
168
+ self.progress = tqdm(total=self.total, mininterval=0, miniters=1, desc='utils.Sweep')
169
+ self.index = 0
170
+ return self
171
+ def __next__(self):
172
+ if self.index > 0 and self.progressBar:
173
+ self.progress.update()
174
+ if self.index == self.total:
175
+ if self.progressBar:
176
+ self.progress.close()
177
+ raise StopIteration
178
+ i = feistel_network(self.index, self.total, self.seed) if self.random else self.index
179
+ for s in self.sweep:
180
+ nested_get(self.config, s["key"][:-1])[s["key"][-1]] = s["list"][i % s["len"]]
181
+ i = i // s["len"]
182
+ self.index += 1
183
+ return self.config
184
+
185
+
186
+ def dB2gain(dB, ref_gain=1, ref_dB=None):
187
+ return ref_gain * 10 ** (dB / 20) if ref_dB is None else 10 ** ((dB + ref_dB) / 20)
188
+
189
+ def gain2dB(gain, ref_gain=1, ref_dB=None):
190
+ return 20 * np.log10(gain / ref_gain) if ref_dB is None else 20 * np.log10(gain) - ref_dB
191
+
192
+
193
+ def evalStr(s, var, _var=None):
194
+ return eval(f"f'''{s}'''", _var, var) # How amazing this is!
195
+
196
+ def safe_wrap(retry=2, timeout=300):
197
+ def decorator(func):
198
+ def wrapper(*args, **kwargs):
199
+ for i in range(retry + 1):
200
+ try: # func_timeout is dark magic. It calls ctypes.pythonapi to kill a thread
201
+ return func_timeout(timeout, func, args, kwargs)
202
+ except Exception:
203
+ if i == retry:
204
+ raise
205
+ return wrapper
206
+ return decorator
207
+
208
+
209
+ # T1 fit and plot
210
+ def fitT1(T, S, plot=True):
211
+ def m(x, *p):
212
+ return p[0] * np.exp(-x / p[1]) + p[2]
213
+ def jac(x, *p):
214
+ d0 = np.exp(-x / p[1])
215
+ d1 = p[0] * x / p[1] ** 2 * np.exp(-x / p[1])
216
+ d2 = np.ones(len(x))
217
+ return np.transpose([d0, d1, d2])
218
+ p0 = [1.0, 1.0, 1.0]
219
+ p, pcov = curve_fit(m, T, S, p0=p0, jac=jac)
220
+ perr = np.sqrt(np.diag(pcov)) # Standard deviation of parameters
221
+ residuals = S - m(T, *p)
222
+ r2 = 1 - np.sum(residuals**2) / np.sum((S - np.mean(S))**2)
223
+ if not plot:
224
+ return p, perr, r2, None
225
+ dof = len(T) - len(p)
226
+ fig, ax = plt.subplots()
227
+ ax.scatter(T, S, color='black', s=10, label='Original Data')
228
+ ax.plot(T, m(T, *p), color='red', label='Fit')
229
+ annotation_text = (
230
+ r"$S = S_0e^{-\tau/T_1} + C$" + "\n" +
231
+ "Fitting Result:\n" +
232
+ r"$S_0 = ({:.2f} \pm {:.2f})$".format(p[0], perr[0]) + "\n" +
233
+ r"$T_1 = ({:.2f} \pm {:.2f})$ us".format(p[1], perr[1]) + "\n" +
234
+ r"$C = ({:.2f} \pm {:.2f})$".format(p[2], perr[2]) + "\n" +
235
+ r"$n = {}$ (DOF)".format(dof) + "\n" +
236
+ r"$R^2 = {:.3f}$%".format(r2*100)
237
+ )
238
+ ax.set_xlabel(r"Pulse Delay $\tau$ (us)")
239
+ ax.set_ylabel("Population")
240
+ ax.set_title("T1 Measurement")
241
+ ax.grid()
242
+ ax.legend()
243
+ mid_index = len(T) // 2
244
+ ax.annotate(annotation_text, (T[mid_index], S[mid_index]), fontsize=8, xycoords='data', textcoords='offset points', xytext=(20, 20))
245
+ return p, perr, r2, fig
246
+
247
+ # T2 fit and plot
248
+ def fitT2(T, S, omega=2*π, T2=20.0, plot=True):
249
+ def m(x, *p):
250
+ return p[0] * np.exp(-x / p[1]) * np.cos(p[2] * x) + p[3]
251
+ def jac(x, *p):
252
+ d0 = np.exp(-x / p[1]) * np.cos(p[2] * x)
253
+ d1 = p[0] * x / p[1] ** 2 * np.exp(-x / p[1]) * np.cos(p[2] * x)
254
+ d2 = - x * p[0] * np.exp(-x / p[1]) * np.sin(p[2] * x)
255
+ d3 = np.ones(len(x))
256
+ return np.transpose([d0, d1, d2, d3])
257
+ def me(x, *p):
258
+ return p[0] * np.exp(-x / p[1]) + p[3]
259
+ p0 = [0.4, T2, omega, 0.5]
260
+ p, pcov = curve_fit(m, T, S, p0=p0, jac=jac)
261
+ perr = np.sqrt(np.diag(pcov)) # Standard deviation of parameters
262
+ residuals = S - m(T, *p)
263
+ r2 = 1 - np.sum(residuals**2) / np.sum((S - np.mean(S))**2)
264
+ if not plot:
265
+ return p, perr, r2, None
266
+ dof = len(T) - len(p)
267
+ fig, ax = plt.subplots()
268
+ ax.scatter(T, S, color='black', s=10, label='Original Data')
269
+ ax.plot(T, m(T, *p), color='red', label='Fit')
270
+ ax.plot(T, me(T, *p), color='blue', label='Fit Exponential')
271
+ annotation_text = (
272
+ r"$S = S_0e^{-\tau/T_2}\cos(\omega\tau) + C$" + "\n" +
273
+ "Fitting Result:\n" +
274
+ r"$S_0 = ({:.2f} \pm {:.2f})$, $C = ({:.2f} \pm {:.2f})$".format(p[0], perr[0], p[3], perr[3]) + "\n" +
275
+ r"$T_2 = ({:.2f} \pm {:.2f})$ us".format(p[1], perr[1]) + "\n" +
276
+ r"$\omega = ({:.2f} \pm {:.2f})$ rad/us".format(p[2], perr[2]) + "\n" +
277
+ r"$n = {}$ (DOF), $R^2 = {:.3f}$%".format(dof, r2 * 100)
278
+ )
279
+ ax.set_xlabel(r"Pulse Delay $\tau$ (us)")
280
+ ax.set_ylabel("Population")
281
+ ax.set_title("T2 Measurement")
282
+ ax.grid()
283
+ ax.legend(loc="lower right")
284
+ mid_index = len(T) // 2
285
+ ax.annotate(annotation_text, (T[mid_index], me(T[mid_index], *p)), fontsize=8, xycoords='data', textcoords='offset points', xytext=(10, 10))
286
+ return p, perr, r2, fig
287
+
288
+ def fitResonator(F, S, fit="circle", p0=[None, None, None, None], plot=True, normalize_background=True, normalize_phase=True):
289
+ def dB(a):
290
+ return 20. * np.log10(np.abs(a))
291
+ def S21_th(f, *p):
292
+ Qi, Qc, fr, phi = p
293
+ return 1 / (1 + Qi / Qc * np.exp(1j * phi) / (1 + 2j * Qi * (f - fr) / fr))
294
+ def normalize(F, S):
295
+ n = 4
296
+ s = F.argsort()
297
+ F, S = F[s], S[s]
298
+ logmag = dB(S)
299
+ if normalize_background:
300
+ magoffset = np.mean(np.concatenate((logmag[:n], logmag[-n:])))
301
+ logmag = logmag - magoffset
302
+ fit_logmag_background = np.polyfit(np.concatenate((F[:n], F[-n:])), np.concatenate((logmag[:n], logmag[-n:])), 1)
303
+ logmag_background_line = np.poly1d(fit_logmag_background)
304
+ logmag = logmag - logmag_background_line(F)
305
+ phase = np.unwrap(np.angle(S))
306
+ if normalize_phase:
307
+ fitphase = np.polyfit(np.concatenate((F[:n], F[-n:])), np.concatenate((phase[:n], phase[-n:])), 1)
308
+ phaseline = np.poly1d(fitphase)
309
+ phase = phase - phaseline(F)
310
+ S = 10**(logmag/20.)*np.exp(1j*phase)
311
+ return F, S
312
+ F, S = normalize(F, S)
313
+ S_inv, S_dB = 1 / S, dB(S)
314
+ _p0 = [100000, 10000, F[np.argmin(S_dB)], 0.0]
315
+ p0 = list(p0)
316
+ for i in range(len(p0)):
317
+ if p0[i] is None:
318
+ p0[i] = _p0[i]
319
+ bounds = ([-np.inf, -np.inf, 0, -2*π], [np.inf, np.inf, np.inf, 2*π])
320
+ def p_b2i(p):
321
+ _p = []
322
+ for i in range(len(p)):
323
+ if bounds[0][i] == -np.inf:
324
+ _p.append(p[i])
325
+ continue
326
+ if bounds[1][i] == np.inf:
327
+ _p.append(np.sqrt((p[i] - bounds[0][i] + 1) ** 2 - 1))
328
+ continue
329
+ _p.append(np.arcsin(2 * (p[i] - bounds[0][i]) / (bounds[1][i] - bounds[0][i]) - 1))
330
+ return _p
331
+ def p_i2b(_p):
332
+ p = []
333
+ for i in range(len(_p)):
334
+ if bounds[0][i] == -np.inf:
335
+ p.append(_p[i])
336
+ continue
337
+ if bounds[1][i] == np.inf:
338
+ p.append(bounds[0][i] - 1 + np.sqrt(_p[i] ** 2 + 1))
339
+ continue
340
+ p.append(bounds[0][i] + (np.sin(_p[i]) + 1) * (bounds[1][i] - bounds[0][i]) / 2)
341
+ return p
342
+ def err_i2b(_p, _perr):
343
+ perr = []
344
+ for i in range(len(_p)):
345
+ if bounds[1][i] == np.inf:
346
+ perr.append(np.abs(_p[i] / np.sqrt(_p[i]**2 + 1)) * _perr[i])
347
+ else:
348
+ perr.append(np.abs(np.cos(_p[i]) * (bounds[1][i] - bounds[0][i]) / 2) * _perr[i])
349
+ return perr
350
+ def S21_circle_fit_err(_p):
351
+ y = 1 / S21_th(F, *p_i2b(_p))
352
+ return np.concatenate((np.real(S_inv - y), np.imag(S_inv - y)))
353
+ def S21_amp_fit_err(_p):
354
+ return dB(S21_th(F, *p_i2b(_p))) - S_dB
355
+ def S21_arg_fit_err(_p):
356
+ return np.angle(S / S21_th(F, *p_i2b(_p)))
357
+ fun = { "circle": S21_circle_fit_err, "amp": S21_amp_fit_err, "arg": S21_arg_fit_err }
358
+ result, cov, _, _, _ = leastsq(fun[fit], p_b2i(p0), maxfev=50000, xtol=1.e-7, ftol=1.e-7, col_deriv=False, gtol=1.e-7, full_output=True)
359
+ p = p_i2b(result)
360
+ perr = err_i2b(result, np.sqrt(np.diag(cov*np.var(fun[fit](p)))))
361
+ S21_fit = S21_th(F, *p)
362
+ residuals = 1/S - 1/S21_fit
363
+ residuals = np.concatenate((np.real(residuals), np.imag(residuals)))
364
+ flat_S_inv = np.concatenate((np.real(S_inv), np.imag(S_inv)))
365
+ r2 = 1 - np.sum(residuals**2) / np.sum((flat_S_inv - np.mean(flat_S_inv))**2)
366
+ p[0], p[1] = abs(p[0]), abs(p[1])
367
+ if not plot:
368
+ return p, perr, r2, None
369
+ dof = len(residuals) - len(p)
370
+ fig = plt.figure(figsize=(12, 6), tight_layout=True)
371
+ axes = [fig.add_subplot(121), fig.add_subplot(222), fig.add_subplot(224)]
372
+ axes[0].scatter((1 / S).real, (1 / S).imag, label="raw", alpha=0.5, linewidths=0.0)
373
+ axes[0].plot((1 / S21_fit).real, (1 / S21_fit).imag, "r-", label="fit")
374
+ axes[0].set_xlabel(r"Re $\widetilde{S}_{21}^{-1}$")
375
+ axes[0].set_ylabel(r"Im $\widetilde{S}_{21}^{-1}$")
376
+ axes[0].grid()
377
+ axes[1].scatter(F, S_dB, alpha=0.5, linewidths=0.0)
378
+ axes[1].plot(F, dB(S21_fit), "r-")
379
+ axes[1].set_ylabel(r"$|S_{21}|$(dB)")
380
+ axes[1].text(0.025, 0.21, r"$Q_i = %.3e$" % p[0] + "\n" + r" $\pm %.1e$" % perr[0], ha="left", va="bottom", transform=axes[1].transAxes)
381
+ axes[1].text(0.025, 0.05, r"$Q_c = %.3e$" % p[1] + "\n" + r" $\pm %.1e$" % perr[1], ha="left", va="bottom", transform=axes[1].transAxes)
382
+ axes[1].text(0.7, 0.05, r"$f = %.7e$" % p[2], ha="left", va="bottom", transform=axes[1].transAxes)
383
+ axes[1].grid()
384
+ mean_phase_data, mean_phase_fit = np.mean(np.unwrap(np.angle(S))), np.mean(np.unwrap(np.angle(S21_fit)))
385
+ match = int((mean_phase_fit - mean_phase_data) / (2 * π) + 0.5)
386
+ axes[2].sharex(axes[1])
387
+ axes[2].scatter(F, np.unwrap(np.angle(S)), alpha=0.5, linewidths=0.0)
388
+ axes[2].plot(F, np.unwrap(np.angle(S21_fit)) - match * 2 * π, 'r-')
389
+ axes[2].text(0.025, 0.95, r"n = {} (DOF)".format(dof), ha="left", va="top", transform=axes[2].transAxes)
390
+ axes[2].text(0.025, 0.87, r"$R^2 = {:.3f}$%".format(r2 * 100), ha="left", va="top", transform=axes[2].transAxes)
391
+ axes[2].set_xlim(F[0], F[-1])
392
+ axes[2].set_xlabel(r"Frequency (MHz)")
393
+ axes[2].set_ylabel(r"$arg~S_{21}$")
394
+ axes[2].grid()
395
+ return p, perr, r2, fig
396
+
397
+
398
+ def iq_scatter(S0s, S1s, c0=None, c1=None, plot=True):
399
+ if c0 is None:
400
+ c0 = np.median(S0s.real) + 1j * np.median(S0s.imag)
401
+ if c1 is None:
402
+ c1 = np.median(S1s.real) + 1j * np.median(S1s.imag)
403
+ def negative_visibility(_p):
404
+ p = _p[0] + 1j * _p[1]
405
+ angle = np.angle(c0 - p)
406
+ S0 = (S0s - (p + c0) / 2.0) * np.exp(-1j * angle)
407
+ S1 = (S1s - (p + c0) / 2.0) * np.exp(-1j * angle)
408
+ prob0 = float(S0.real[S0.real < 0].size) / S0.size
409
+ prob1 = float(S1.real[S1.real < 0].size) / S1.size
410
+ return prob0 - prob1
411
+ res = minimize(negative_visibility, [c1.real, c1.imag], method='Nelder-Mead') # optimize c1
412
+ visibility = -1 * negative_visibility(res.x)
413
+ c1 = res.x[0] + 1j * res.x[1]
414
+ o = (c0 + c1) / 2.0 # origin
415
+ g = o - c0 # project on opposite of g
416
+ S0p = np.real((S0s - o) * np.conj(g)) / np.abs(g)
417
+ S1p = np.real((S1s - o) * np.conj(g)) / np.abs(g)
418
+ S0p_right, S1p_right = S0p[S0p < 0], S1p[S1p > 0]
419
+ S0s_right, S0s_wrong = S0s[S0p < 0], S0s[S0p >= 0]
420
+ S1s_right, S1s_wrong = S1s[S1p > 0], S1s[S1p <= 0]
421
+ Fg, Fe = len(S0p_right) / len(S0p), len(S1p_right) / len(S1p)
422
+ phase, threshold = float(-np.angle(c1 - c0, deg=True)), float(np.real((c1 + c0) / 2 * np.exp(-1j * np.angle(c1 - c0))))
423
+ if not plot:
424
+ return phase, threshold, visibility, Fg, Fe, c0, c1, None
425
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5.44)) # plot the histogram
426
+ xp = np.linspace(np.min(S0p), np.max(S1p), 2001) # axis of projection
427
+ g_hist, _ = np.histogram(S0p, bins=100, density=True, range=[xp[0], xp[-1]])
428
+ e_hist, _ = np.histogram(S1p, bins=100, density=True, range=[xp[0], xp[-1]])
429
+ g_cdf = np.cumsum(g_hist) * (xp[-1] - xp[0]) / 100
430
+ e_cdf = np.cumsum(e_hist) * (xp[-1] - xp[0]) / 100
431
+ axes[1].hist(S0p, color='blue', alpha=0.5, bins=100, density=True, range=[xp[0], xp[-1]], label=r'$|g\rangle$')
432
+ axes[1].hist(S1p, color='red', alpha=0.5, bins=100, density=True, range=[xp[0], xp[-1]], label=r'$|e\rangle$')
433
+ g_mu, g_std = stats.norm.fit(S0p_right)
434
+ axes[1].plot(xp, stats.norm.pdf(xp, g_mu, g_std), color='blue', linestyle='dotted')
435
+ e_mu, e_std = stats.norm.fit(S1p_right)
436
+ axes[1].plot(xp, stats.norm.pdf(xp, e_mu, e_std), color='red', linestyle='dotted')
437
+ axr = axes[1].twinx()
438
+ axr.set_ylim([0, 1])
439
+ axr.set_ylabel("Cumulative Probability")
440
+ axr.plot(np.linspace(xp[0], xp[-1], 100), g_cdf, color='blue', linewidth=2)
441
+ axr.plot(np.linspace(xp[0], xp[-1], 100), e_cdf, color='red', linewidth=2)
442
+ axr.plot(np.linspace(xp[0], xp[-1], 100), g_cdf - e_cdf, color='green', linewidth=2)
443
+ axes[1].set_xlabel('Projected IQ Amplitude (a.u.)')
444
+ axes[1].set_ylabel('Probability Density')
445
+ axes[1].legend(shadow=False, loc=1, frameon=True)
446
+ axes[1].grid()
447
+ axes[1].text(0.05, 0.95, 'Visibility=%.3f' % visibility, ha='left', transform=axes[1].transAxes)
448
+ axes[1].text(0.05, 0.9, '$F_g$=%.3f' % Fg, ha='left', transform=axes[1].transAxes)
449
+ axes[1].text(0.05, 0.85, '$F_e$=%.3f' % Fe, ha='left', transform=axes[1].transAxes)
450
+ # scatter plot
451
+ axes[0].scatter(S0s_right.real, S0s_right.imag, s=10, marker='o', zorder=0, alpha=0.5, c='blue', linewidths=0.0)
452
+ axes[0].scatter(S1s_right.real, S1s_right.imag, s=10, marker='o', zorder=0, alpha=0.5, c='red', linewidths=0.0)
453
+ axes[0].scatter(S0s_wrong.real, S0s_wrong.imag, s=10, marker='o', zorder=0, alpha=0.5, c='blue', linewidths=0.0)
454
+ axes[0].scatter(S1s_wrong.real, S1s_wrong.imag, s=10, marker='o', zorder=0, alpha=0.5, c='red', linewidths=0.0)
455
+ axes[0].grid()
456
+ axes[0].set_xlabel('I (a.u.)')
457
+ axes[0].set_ylabel('Q (a.u.)')
458
+ _r = max(max(np.max(np.real(S0s - o)), np.max(np.real(S1s - o))), max(np.max(np.imag(S0s - o)), np.max(np.imag(S1s - o))))
459
+ axes[0].set_xlim(-1.1 * _r + o.real, 1.1 * _r + o.real)
460
+ axes[0].set_ylim(-1.1 * _r + o.imag, 1.1 * _r + o.imag)
461
+ # plot the cut
462
+ _x = np.linspace(-1.1 * _r + o.real, 1.1 * _r + o.real, 101)
463
+ axes[0].plot(_x, -(c0.real - c1.real) / (c0.imag - c1.imag) * (_x - (c0.real + c1.real) / 2) + (c0.imag + c1.imag) / 2, 'k--')
464
+ # add the circle to the IQ scatter plot
465
+ theta = np.linspace(-π, π, 1001)
466
+ I_g_fit_list = np.median(S0s_right.real) + np.cos(theta) * 3 * g_std
467
+ Q_g_fit_list = np.median(S0s_right.imag) + np.sin(theta) * 3 * g_std
468
+ I_e_fit_list = np.median(S1s_right.real) + np.cos(theta) * 3 * e_std
469
+ Q_e_fit_list = np.median(S1s_right.imag) + np.sin(theta) * 3 * e_std
470
+ axes[0].plot(I_g_fit_list, Q_g_fit_list, color='darkblue', linestyle='--', label=r'$|g\rangle$, $3\sigma$')
471
+ axes[0].plot(I_e_fit_list, Q_e_fit_list, color='darkred', linestyle='--', label=r'$|e\rangle$, $3\sigma$')
472
+ axes[0].legend(shadow=False, loc=1, frameon=True)
473
+ return phase, threshold, visibility, Fg, Fe, c0, c1, fig
474
+
475
+
476
+ def symmetryCenter(x, y, it=3):
477
+ L = len(y)
478
+ R = int(L / 2)
479
+ Δ = int(R / 2)
480
+ freq = np.fft.rfftfreq(L*2)
481
+ y = (y - np.mean(y)) / np.std(y)
482
+ fft = np.fft.rfft(np.append(y, np.zeros(L)))
483
+ res, d = 0, 0
484
+ for _ in range(it): # dark magic: phase shift in Fourier space to align cross-correlation peak to the center iteratively
485
+ fft *= np.exp(2j*π*d*freq)
486
+ co = np.fft.irfft(fft**2)[R-1:L+R-1]
487
+ i = np.argmax(co[R-Δ:R+Δ]) + R-Δ
488
+ p = np.polynomial.polynomial.polyfit(np.arange(i-2, i+3), co[i-2:i+3], 2)
489
+ d = -p[1]/4/p[2] - R/2
490
+ res += d
491
+ i = res + R - 0.5
492
+ _i = int(i)
493
+ return x[_i] + (x[_i+1] - x[_i]) * (i - _i)
494
+
495
+ def estimateOmega(x, y):
496
+ y = (y - np.mean(y)) / np.std(y)
497
+ rfft = np.fft.rfft(y)
498
+ freq = np.fft.rfftfreq(len(y))
499
+ return len(y) * freq[np.argmax(np.abs(rfft))] * 2 * π / (x[len(x) - 1] - x[0])