-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexperiment.py
415 lines (338 loc) · 15.2 KB
/
experiment.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
# -*- coding: utf-8 -*-
__all__ = ['Experiment']
import xml.etree.ElementTree as ET
from pathlib import Path
import joblib
import pandas as pd
import numpy as np
class Experiment(object):
"""A generic class capable of handling data.
Parameters
----------
path : str
path to the experiment data file
scan_init_file : str, optional
file name of scan initial settings, by default 'InitValues.csv'
scan_setup_file : str, optional
file name of scan setup, by default 'ScanLists.csv'
scan_value_file : str, optional
file name of scan values, by default 'ScanValues.csv'
exp_setting_file : str, optional
file name of experiment settings, by default 'SettingsV3.xml'
"""
def __init__(
self, path,
scan_init_file='InitValues.csv',
scan_setup_file='ScanLists.csv',
scan_value_file='ScanValues.csv',
exp_setting_file='SettingsV3.xml'):
self.__path = Path(path)
# Create a folder to hold supporting files.
if not self.__path.joinpath('assets').exists():
self.__path.joinpath('assets').mkdir(parents=True, exist_ok=False)
# Assemble the experiment setting file.
self._setting_assembly(scan_init_file, scan_setup_file,
scan_value_file, exp_setting_file)
# Read in experiment data.
self.__r = self._get_data()
@property
def path(self):
"""Returns the path to the data file.
Returns
-------
pathlib.Path
a pathlib Path object that points to the data files
"""
return self.__path
@property
def scan_init(self):
"""Returns the scan initial settings of the experiment.
Returns
-------
pandas.Dataframe
a Pandas Dataframe object that mimics the 'Object Init' part
in LabVIEW program
"""
return self.__scan_init
@property
def scan_setup(self):
"""Returns the scan settings of the experiment.
Returns
-------
pandas.Dataframe
a Pandas Dataframe object that mimics the 'Object Scan' part
in LabVIEW program
"""
return self.__scan_setup
@property
def scan_value(self):
"""Returns the multidimensional scan values of the experiment.
Returns
-------
list
a list of numpy.ndarray objects, each array corresponds to a scan
axis calculated scan step values and initial values
"""
return self.__scan_value
@property
def scan_size(self):
"""Returns the scan size of the experiment.
Returns
-------
numpy.ndarray
a 1-d array of scan sizes
"""
return self.__scan_size
@property
def number_of_readout(self):
"""Returns the number of readout resonators.
Returns
-------
int
number of readout resonators, calculated from the number of
heterodyne frequency found
"""
return self.__number_of_readout
@property
def average_axis(self):
"""Returns the axes along which averaging shall be carried out.
Returns
-------
tuple
average axis indices, obtained from scan setup where scan
target is set to 'Repeat'
"""
return self.__average_axis
@property
def data(self):
"""Returns the experiment raw data.
Returns
-------
list of list of numpy.ndarray
experiment raw data, has a three layer structure,
should be accessed with form
data[resonator index][IQ quadrature index][shape of scan setup]
Examples
--------
To access I quadrature data of the first readout resonator,
>>> exp.data[0][0][...]
"""
return self.__r
def average(self, average_axis=None):
"""Averages the experiment data.
Parameters
----------
average_axis : tuple, optional
the axis along which to carry out averaging,
if not specified all 'Repeat' axes will be averaged,
by default None
Returns
-------
list of list of numpy.ndarray
averaged data, has a three layer structure,
should be accessed with form
data[resonator #][quadrature #][scan setup excluding 'Repeat'],
if 'average_axis' is not specified,
all 'Repeat' axes will be averaged,
by default None
"""
if average_axis is None:
average_axis = self.__average_axis
averaged_data = np.mean(self.data, axis=average_axis)
return averaged_data
def mean_mag(self, decibel=True):
"""Returns mean magnitude of the resonator signal.
Parameters
----------
decibel : bool, optional
decides the unit of the return, by default True
Returns
-------
list of numpy.ndarray
magnitude calculated from averaged data, sqrt(I**2+Q**2),
result should be accessed with form
mean_mag[resonator index][scan setup excluding 'Repeat']
"""
if decibel:
mag = 20*np.log10(np.linalg.norm(self.average(), axis=1))
else:
mag = np.linalg.norm(self.average(), axis=1)
return mag
def mean_phase(self, deg=False):
"""Returns mean phase of the resonator signal.
Parameters
----------
deg : bool, optional
decides the unit of the return, by default True
Returns
-------
list of numpy.ndarray
phase calculated from averaged data, arctan(Q/I),
result should be accessed with form
phase[resonator #][scan setup excluding 'Repeat']
"""
complex_data = [[None] for _ in range(self.__number_of_readout)]
for res in range(self.__number_of_readout):
complex_data[res] = self.average()[res][0] +1j*self.average()[res][1]
if deg:
phz = np.angle(complex_data, deg=True)
else:
phz = np.angle(complex_data)
return phz
def _setting_assembly(self, scan_init_file, scan_setup_file,
scan_value_file, exp_setting_file):
"""Method to put together the experiment setting file.
Parameters
----------
scan_init_file : str, optional
file name of scan initial settings, by default 'InitValues.csv'
scan_setup_file : str, optional
file name of scan setup, by default 'ScanLists.csv'
scan_value_file : str, optional
file name of scan values, by default 'ScanValues.csv'
exp_setting_file : str, optional
file name of experiment settings, by default 'SettingsV3.xml'
"""
# check if the data has already been processed
if self.__path.joinpath('assets/settings.joblib').exists():
with open(self.__path.joinpath('assets/settings.joblib'), 'rb') as handle:
setting_ensemble = joblib.load(handle)
# load from existing file
self.__scan_init = setting_ensemble['scan_init']
self.__scan_setup = setting_ensemble['scan_setup']
self.__scan_value = setting_ensemble['scan_value']
self.__scan_size = setting_ensemble['scan_size']
self.__number_of_readout = setting_ensemble['number_of_readout']
self.__average_axis = setting_ensemble['average_axis']
else:
# read in scan initial settings
self.__scan_init = pd.read_csv(
self.__path.joinpath(scan_init_file),
index_col=0,
header=None,
float_precision='round_trip'
)
self.__scan_init.index.name = None
self.__scan_init.columns = self.__scan_init.columns - 1
# hardcoded -1 is to fix name mismatch
# read in scan settings
self.__scan_setup = pd.read_csv(
self.__path.joinpath(scan_setup_file),
index_col=None,
header=None,
float_precision='round_trip'
)
self.__scan_setup.index = ['Enabled',
'Target',
'Parameter',
'Scan #',
'Object #',
'Start',
'Stop',
'# of Step']
self.__disabled_object = np.nonzero(
self.__scan_setup.loc['Enabled', :].str.contains('FALSE').to_numpy())[0] # check for scan terms which are disabled in LabVIEW setting
self.__scan_setup = self.__scan_setup.drop(self.__disabled_object, axis=1) # drop the disabled terms
self.__scan_setup.columns = range(len(self.__scan_setup.columns)) # index columns
# assume scan sizes based on the '# of step' row of scan setup Dataframe
self.__scan_size = self.__scan_setup.iloc[[-1]].to_numpy().astype(int)[0]
# assume average axis by searching for 'Repeat' in the 'Target' row of scan setup Dataframe
self.__average_axis = tuple(
np.nonzero(self.__scan_setup.loc['Target', :].str.contains('Repeat').to_numpy())[0]+2 # hardcorded +2 is to take care of the resonator index and quadrature index
)
# read in the raw scan values without initial value added
self.__scan_value_raw = pd.read_csv(
self.__path.joinpath(scan_value_file),
index_col=None,
header=None,
skiprows=self.__disabled_object,
float_precision='round_trip').to_numpy()
# load 'SettingsV3.xml'
tree = ET.parse(self.__path.joinpath(exp_setting_file))
root = tree.getroot()
# Determine number of readout resonator based on number of heterodyne frequency
for array in root.iter('{http://www.ni.com/LVData}Array'):
if array.find('{http://www.ni.com/LVData}Name').text == 'HeteroFreq':
self.__number_of_readout = int(
array.findall('{http://www.ni.com/LVData}Dimsize')[1].text)
# correct scan size for 'Sequencer' target in single-shot experiments
for ew_element in root.iter('{http://www.ni.com/LVData}EW'):
if ew_element.find('{http://www.ni.com/LVData}Val').text == '5':
for u32 in root.iter('{http://www.ni.com/LVData}U32'):
if u32.find('{http://www.ni.com/LVData}Name').text == '#rec':
self.__scan_size[0] = int(u32.find('{http://www.ni.com/LVData}Val').text)
self.__scan_value_raw[0, :self.__scan_size[0]] = np.arange(self.__scan_size[0])
# calculate the actual scan values by adding initial value and differential scan value
self.__scan_value = [np.zeros(dim) for dim in self.__scan_size]
for dim in range(len(self.__scan_size)):
target = self.__scan_setup.loc[['Target', 'Parameter'], dim].str.cat(sep=' ')
if target.lower() in self.__scan_init.index.str.lower():
init_val_row = self.__scan_init.index.str.lower().get_loc(target.lower())
init_val_col = int(self.__scan_setup.loc['Object #', dim])
init_val = self.__scan_init.iloc[init_val_row, init_val_col]
else:
init_val = 0
self.__scan_value[dim] = self.__scan_value_raw[dim, :self.__scan_size[dim]] + init_val
self.__scan_value[dim].round(decimals=6)
# put settings together
setting_ensemble = dict(scan_init=self.__scan_init,
scan_setup=self.__scan_setup,
scan_value=self.__scan_value,
scan_size=self.__scan_size,
number_of_readout=self.__number_of_readout,
average_axis=self.__average_axis)
with open(self.__path.joinpath('assets/settings.joblib'), 'wb') as handle:
joblib.dump(setting_ensemble, handle)
def _get_data(self):
"""Method to read in raw data.
Raises
------
FileNotFoundError
if the last data file is missing,
indicating a noncompleted experiment
FileNotFoundError
if the data size in the last data file is not correct,
indicating a noncompleted experiment
"""
# check if the data file already exists
if self.__path.joinpath('assets/data.joblib').exists():
self.__r = joblib.load(self.__path.joinpath('assets/data.joblib'))
else:
# initiate data array
# shape: (# of readout)*(quadrature count)*(scan array)
self.__r = [[np.zeros(self.__scan_size) for _ in range(2)] for _ in range(self.__number_of_readout)]
if len(self.__scan_size) < 3:
try:
pd.read_csv(self.__path.joinpath(f'R{self.__number_of_readout-1}I.csv'))
except FileNotFoundError:
raise FileNotFoundError('Experiment not completed.')
for res in range(self.__number_of_readout):
self.__r[res][0] = pd.read_csv(
self.__path.joinpath(f'R{res}I.csv'),
index_col=None,
float_precision='round_trip',
header=None).T.to_numpy()
self.__r[res][1] = pd.read_csv(
self.__path.joinpath(f'R{res}Q.csv'),
index_col=None,
float_precision='round_trip',
header=None).T.to_numpy()
elif len(self.__scan_size) == 3:
try:
pd.read_csv(self.__path.joinpath(f'R{self.__number_of_readout-1}I_{self.__scan_size[-1]-1}.csv'))
except FileNotFoundError:
raise FileNotFoundError(f'Experiment not completed. {self.__scan_size[-1]} experiments expected.')
for res in range(self.__number_of_readout):
for scan in range(self.__scan_size[-1]):
self.__r[res][0][:, :, scan] = pd.read_csv(
self.__path.joinpath(f'R{res}I_{scan}.csv'),
index_col=None,
float_precision='round_trip',
header=None).T.to_numpy()
self.__r[res][1][:, :, scan] = pd.read_csv(
self.__path.joinpath(f'R{res}Q_{scan}.csv'),
index_col=None,
float_precision='round_trip',
header=None).T.to_numpy()
joblib.dump(self.__r, self.__path.joinpath('assets/data.joblib'))
return self.__r