-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmisc.py
More file actions
279 lines (220 loc) · 8.58 KB
/
misc.py
File metadata and controls
279 lines (220 loc) · 8.58 KB
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
# -*- coding: utf-8 -*-
"""
@author: Steinn Ymir Agustsson
Copyright (C) 2018 Steinn Ymir Agustsson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import ast
import os
import sys
from configparser import ConfigParser
import time
import h5py
import numpy as np
import math
import xarray as xr
from PyQt5 import QtWidgets
# Qt stuff
def my_exception_hook(exctype, value, traceback):
"""error catching for qt in pycharm"""
# Print the error and traceback
print(exctype, value, traceback)
# Call the normal Exception hook after
sys._excepthook(exctype, value, traceback)
sys.exit(1)
def labeledQwidget(label, widget, align='h'):
"""Create a horizontally aligned label and widget."""
w = QtWidgets.QWidget()
if align in ['h', 'horizontal']:
l = QtWidgets.QHBoxLayout()
elif align in ['vertical', 'v']:
l = QtWidgets.QVBoxLayout()
else:
raise Exception('{} not a valid alignment, please use "h" or "v"'.format(align))
l.addWidget(QtWidgets.QLabel(label))
l.addWidget(widget)
l.addStretch()
w.setLayout(l)
return w
# Settings persing
def parse_category(category, settings_file='default'):
""" parse setting file and return desired value
Args:
category (str): title of the category
setting_file (str): path to setting file. If set to 'default' it takes
a file called SETTINGS.ini in the main folder of the repo.
Returns:
dictionary containing name and value of all entries present in this
category.
"""
settings = ConfigParser()
if settings_file == 'default':
current_path = os.path.dirname(__file__)
while not os.path.isfile(os.path.join(current_path, 'SETTINGS.ini')):
current_path = os.path.split(current_path)[0]
settings_file = os.path.join(current_path, 'SETTINGS.ini')
settings.read(settings_file)
try:
cat_dict = {}
for k, v in settings[category].items():
try:
cat_dict[k] = ast.literal_eval(v)
except ValueError:
cat_dict[k] = v
return cat_dict
except KeyError:
print('No category "{}" found in SETTINGS.ini'.format(category))
def parse_setting(category, name, settings_file='default'):
""" parse setting file and return desired value
Args:
category (str): title of the category
name (str): name of the parameter
setting_file (str): path to setting file. If set to 'default' it takes
a file called SETTINGS.ini in the main folder of the repo.
Returns:
value of the parameter, None if parameter cannot be found.
"""
settings = ConfigParser()
if settings_file == 'default':
current_path = os.path.dirname(__file__)
while not os.path.isfile(os.path.join(current_path, 'SETTINGS.ini')):
current_path = os.path.split(current_path)[0]
settings_file = os.path.join(current_path, 'SETTINGS.ini')
settings.read(settings_file)
try:
value = settings[category][name]
return ast.literal_eval(value)
except KeyError:
print('No entry "{}" in category "{}" found in SETTINGS.ini'.format(name, category))
return None
except ValueError:
return settings[category][name]
except SyntaxError:
return settings[category][name]
def write_setting(value, category, name, settings_file='default'):
""" Write enrty in the settings file
Args:
category (str): title of the category
name (str): name of the parameter
setting_file (str): path to setting file. If set to 'default' it takes
a file called SETTINGS.ini in the main folder of the repo.
Returns:
value of the parameter, None if parameter cannot be found.
"""
settings = ConfigParser()
if settings_file == 'default':
current_path = os.path.dirname(__file__)
while not os.path.isfile(os.path.join(current_path, 'SETTINGS.ini')):
current_path = os.path.split(current_path)[0]
settings_file = os.path.join(current_path, 'SETTINGS.ini')
settings.read(settings_file)
settings[category][name] = str(value)
with open(settings_file, 'w') as configfile:
settings.write(configfile)
# math
def update_average(new, avg, n):
""" Update the average with new array.
Args
new: np.array
array with the new data to be added to the average. Must have same
dimensions as avg
avg: np.array
array of average of n arrays
n:
number n of arrays used to make avg
:return:
new average
"""
prev_n = (n - 1) / n
# return (avg * (n - 1) + new) / n
return avg * prev_n + new / n
def update_running_average(new_data, all_curves, max_n_avg):
""" update the average dataset with new data
Args:
new_data: list of xarray.DataArray
list of new projected data curves to be combined in the new average
all_curves: xarray
data container with all previous datasets
max_n_avg: int
number ov averages to keep in memory
Return:
out: tuple of two xarrays
tuple containin the new all_curves xarray and the new running average xarray
"""
t0 = time.time()
for data in new_data:
data.dropna('time')
if all_curves is None:
new_all_curves = xr.concat([*new_data],'avg')
else:
new_all_curves = xr.concat([all_curves[-max_n_avg + len(new_data):], *new_data], 'avg')
running_average = new_all_curves.mean('avg').dropna('time')
dt = time.time()-t0
return (new_all_curves, running_average,dt)
def sin(x, A, f, p, o):
return A * np.sin(x / f + p) + o
def sech2_fwhm(x, A, x0, fwhm, c):
tau = fwhm * 2 / 1.76
return A / (np.cosh((x - x0) / tau)) ** 2 + c
def sech2_fwhm_wings(x, a, xc, fwhm, off, wing_sep, wing_ratio, wings_n):
""" sech squared with n wings."""
res = sech2_fwhm(x, a, xc, fwhm, off)
for n in range(1, wings_n):
res += sech2_fwhm(x, a * (wing_ratio ** n), xc - n * wing_sep, fwhm, 0)
res += sech2_fwhm(x, a * (wing_ratio ** n), xc + n * wing_sep, fwhm, 0)
return res
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def gaussian_fwhm(x, A, x0, fwhm, c):
sig = fwhm * 2 / 2.355
return A * np.exp(-np.power(x - x0, 2.) / (2 * np.power(sig, 2.))) + c
def transient_1expdec(t, A1, tau1, sigma, y0, off, t0):
""" Fitting function for transients, 1 exponent decay.
A: Amplitude
Tau: exp decay
sigma: pump pulse duration
y0: whole curve offset
off: slow dynamics offset"""
from scipy.special import erf
t = t - t0
tmp = erf((sigma ** 2. - 5.545 * tau1 * t) / (2.7726 * sigma * tau1))
tmp = .5 * (1 - tmp) * np.exp(sigma ** 2. / (11.09 * tau1 ** 2.))
return y0 + tmp * (A1 * (np.exp(-t / tau1)) + off)
def read_h5(file):
dd = {}
with h5py.File(file, 'r') as f:
if 'avg' in f:
data = f['avg']['data']
time = f['avg']['time_axis']
dd['avg'] = xr.DataArray(data, coords={'time': time}, dims=('time'))
if 'raw' in f:
dd['raw'] = f['raw']['avg'][:]
if 'all_data' in f:
data = f['all_data']['data']
time = f['all_data']['time_axis']
dd['all_data'] = xr.DataArray(data, coords={'time': time}, dims=('avg', 'time'))
return dd
def repr_byte_size(size_bytes):
""" Represent in a string the size in Bytes in a compact format.
Adapted from https://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python
Follows same notation as Windows does for files. See: https://en.wikipedia.org/wiki/Mebibyte
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
# exceptions
class NoDataException(Exception):
pass