Commit 05967046 authored by Michael Rudolf's avatar Michael Rudolf
Browse files

Reformatting with `black`

parent bd94c6e0
......@@ -32,10 +32,10 @@ from rstevaluation import mainGUI
def run():
app = mainGUI.RST_pick_GUI(None)
app.title('RSTpick GUI')
mpl.use('qt5agg')
app.title("RSTpick GUI")
mpl.use("qt5agg")
app.mainloop()
if __name__ == '__main__':
if __name__ == "__main__":
run()
......@@ -16,5 +16,5 @@
""" Runs rst-evaluation with a GUI """
from rstevaluation import RST_pick_GUI
if __name__ == '__main__':
if __name__ == "__main__":
RST_pick_GUI.run()
......@@ -35,23 +35,24 @@ def rst_analmut(x, y):
(cohesion, C) by mutual two point linear regressions:
"""
# n = len(x)
ys = [y[k] for k in range(len(x)) for j in range(len(x)-k)]
xs = [x[k] for k in range(len(x)) for j in range(len(x)-k)]
ys = [y[k] for k in range(len(x)) for j in range(len(x) - k)]
xs = [x[k] for k in range(len(x)) for j in range(len(x) - k)]
M = np.array(
[
(y[k+j]-y[k])/(x[k+j]-x[k])
for k in range(len(x)) for j in range(len(x)-k)
if not (x[k+j]-x[k]) == 0
(y[k + j] - y[k]) / (x[k + j] - x[k])
for k in range(len(x))
for j in range(len(x) - k)
if not (x[k + j] - x[k]) == 0
]
)
C = np.array([(y-m*x) for y, m, x in zip(ys, M, xs)])
C = np.array([(y - m * x) for y, m, x in zip(ys, M, xs)])
# M = M[np.nonzero(np.isfinite(M))]
# C = C[np.nonzero(np.isfinite(C))]
statsM = spstats.norm.fit([d.n for d in M])
statsC = spstats.norm.fit([d.n for d in C])
uncM = unc.ufloat(statsM[0], 2*statsM[1])
uncC = unc.ufloat(statsC[0], 2*statsC[1])
uncM = unc.ufloat(statsM[0], 2 * statsM[1])
uncC = unc.ufloat(statsC[0], 2 * statsC[1])
fric_mut = (uncM, uncC)
data_mut = (M, C)
return fric_mut, data_mut
......@@ -59,18 +60,20 @@ def rst_analmut(x, y):
# %%=======================STANDARD LINEAR REGRESSION==========================
def rst_analstd_old(x, y):
""" Correlation of normal and shear stress: y = slope * x+intercept """
"""Correlation of normal and shear stress: y = slope * x+intercept"""
x = np.array(x)
y = np.array(y)
n = len(x)
P1 = n*np.sum(x*y)-np.sum(x)*np.sum(y)
P2 = n*np.sum(x**2)-np.sum(x)**2
slope = P1/P2 # coefficient of friction
intercept = (np.sum(x**2)*np.sum(y)-np.sum(x)*np.sum(x*y))/P2 # cohesion
diff = y-intercept-slope*x
s = np.sum(diff**2)/(n-2)
std_slope = np.sqrt(n*s/P2) # standard error Coef. friction
std_intercept = np.sqrt(np.sum(x**2)*s/P2) # standard error cohesion
P1 = n * np.sum(x * y) - np.sum(x) * np.sum(y)
P2 = n * np.sum(x**2) - np.sum(x) ** 2
slope = P1 / P2 # coefficient of friction
intercept = (
np.sum(x**2) * np.sum(y) - np.sum(x) * np.sum(x * y)
) / P2 # cohesion
diff = y - intercept - slope * x
s = np.sum(diff**2) / (n - 2)
std_slope = np.sqrt(n * s / P2) # standard error Coef. friction
std_intercept = np.sqrt(np.sum(x**2) * s / P2) # standard error cohesion
y_fit = np.polyval([slope, intercept], x)
out_var = (slope, std_slope, intercept, std_intercept, y_fit)
......@@ -89,11 +92,7 @@ def rst_analstd(x, y):
# pfit, perr = fit_bootstrap(x, ynv, fitfric, yerr_systematic=10,
# yerr=yerr)
pfit, pcov = spopt.curve_fit(
fitfric,
x, ynv,
sigma=yerr
)
pfit, pcov = spopt.curve_fit(fitfric, x, ynv, sigma=yerr)
lcb, ucb = confband(xq, x, ynv, pfit, pcov, fitfric)
......@@ -103,7 +102,7 @@ def rst_analstd(x, y):
def fitfric(x, a, b):
return a*x+b
return a * x + b
def confband(x, xd, yd, popt, pcov, func, conf=0.95):
......@@ -139,8 +138,8 @@ def confband(x, xd, yd, popt, pcov, func, conf=0.95):
y = func(x, *corr_val)
nom = unp.nominal_values(y)
std = unp.std_devs(y)
lcb = nom - 2*std
ucb = nom + 2*std
lcb = nom - 2 * std
ucb = nom + 2 * std
return lcb, ucb
......@@ -150,8 +149,8 @@ def vst_analysis(data, config):
"""
Simply fits the apparent friction with the current loading velocity.
"""
mu_app = data['shearstress']/data['normalstress'] # Apparent friction
logvel = np.log10(data['velocity'])
mu_app = data["shearstress"] / data["normalstress"] # Apparent friction
logvel = np.log10(data["velocity"])
# Remove nonfinite values for fitting
onlyfinite = np.isfinite(mu_app)
......@@ -163,17 +162,13 @@ def vst_analysis(data, config):
# Remove values where logvel < -4
mu_app = mu_app[logvel >= -4]
logvel = logvel[logvel >= -4]
pfit, pcov, x, y = vst_fit(
fitfric, logvel, mu_app, config
)
perr = 2*np.sqrt(np.diag(pcov))
pfit, pcov, x, y = vst_fit(fitfric, logvel, mu_app, config)
perr = 2 * np.sqrt(np.diag(pcov))
name_fit = (
r'y = ({:.4f}$\pm${:.5f})log10(x) +' +
'\n\t\t' +
r'({:.4f}$\pm${:.5f})').format(pfit[0],
perr[0],
pfit[1],
perr[1])
r"y = ({:.4f}$\pm${:.5f})log10(x) +"
+ "\n\t\t"
+ r"({:.4f}$\pm${:.5f})"
).format(pfit[0], perr[0], pfit[1], perr[1])
return pfit, perr, name_fit, logvel, mu_app, x, y
......@@ -185,16 +180,14 @@ def vst_analysis_alternative(data, config):
First the stick-slip events are detected with peak detection. Then the
peaks are fit with a log-linear equation.
"""
mu_app = data['shearstress']/data['normalstress'] # Apparent friction
logvel = np.log10(data['velocity'])
mu_app = data["shearstress"] / data["normalstress"] # Apparent friction
logvel = np.log10(data["velocity"])
peaks = spsig.find_peaks(
mu_app,
prominence=config.getfloat('parameters', 'peak_prominence')
mu_app, prominence=config.getfloat("parameters", "peak_prominence")
)[0].tolist()
troughs = spsig.find_peaks(
-mu_app,
prominence=config.getfloat('parameters', 'peak_prominence')
-mu_app, prominence=config.getfloat("parameters", "peak_prominence")
)[0].tolist()
# If the first trough is before a peak delete it
......@@ -206,13 +199,12 @@ def vst_analysis_alternative(data, config):
if len(peaks) != len(troughs):
troughs = [
troughs[int(np.argwhere(p < np.array(troughs))[0])]
for p in peaks
troughs[int(np.argwhere(p < np.array(troughs))[0])] for p in peaks
]
# Calculate means for fitting
mu_app_fit = np.array(
[(mu_app[p] + mu_app[t])/2 for p, t in zip(peaks, troughs)]
[(mu_app[p] + mu_app[t]) / 2 for p, t in zip(peaks, troughs)]
)
logvel_fit = logvel[peaks]
......@@ -227,17 +219,13 @@ def vst_analysis_alternative(data, config):
mu_app_fit = mu_app_fit[logvel_fit >= -4]
logvel_fit = logvel_fit[logvel_fit >= -4]
# Do fitting
pfit, pcov, x, y = vst_fit(
fitfric, logvel_fit, mu_app_fit, config
)
perr = 2*np.sqrt(np.diag(pcov))
pfit, pcov, x, y = vst_fit(fitfric, logvel_fit, mu_app_fit, config)
perr = 2 * np.sqrt(np.diag(pcov))
name_fit = (
r'y = ({:.4f}$\pm${:.5f})log10(x) +' +
'\n\t\t' +
r'({:.4f}$\pm${:.5f})').format(pfit[0],
perr[0],
pfit[1],
perr[1])
r"y = ({:.4f}$\pm${:.5f})log10(x) +"
+ "\n\t\t"
+ r"({:.4f}$\pm${:.5f})"
).format(pfit[0], perr[0], pfit[1], perr[1])
return pfit, perr, name_fit, logvel_fit, mu_app_fit, x, y, peaks, troughs
......@@ -245,19 +233,19 @@ def vst_fit(fitfunc, logvel, mu_app, config):
"""
Takes a special subsample per velocity step.
"""
vel_round = np.around(logvel, config.getint('parameters', 'vel_accuracy'))
vel_round = np.around(logvel, config.getint("parameters", "vel_accuracy"))
vel_un = np.unique(vel_round)
# sample_counts = [len(np.argwhere(vel_round == v)) for v in vel_un]
# min_samples = np.min(sample_counts)
x = []
y = []
prct = np.linspace(1, 99, config.getint('parameters', 'fit_percentiles'))
prct = np.linspace(1, 99, config.getint("parameters", "fit_percentiles"))
for vu in vel_un:
# selection = np.argwhere(vel_round == vu)[:min_samples]
# x.extend(vel_round[selection])
# y.extend(mu_app[selection])
selection = mu_app[np.argwhere(vel_round == vu)]
if len(selection) > config.getint('parameters', 'min_peaks'):
if len(selection) > config.getint("parameters", "min_peaks"):
for p in prct:
x.append(vu)
y.append(np.percentile(selection, p))
......@@ -269,7 +257,7 @@ def vst_fit(fitfunc, logvel, mu_app, config):
def vst_manual_pick(data: dict, cfg: configparser.ConfigParser):
ppm = cfg.getfloat('parameters', 'peak_prominence')
ppm = cfg.getfloat("parameters", "peak_prominence")
def _switch(ppm):
nonlocal fig
......@@ -277,77 +265,86 @@ def vst_manual_pick(data: dict, cfg: configparser.ConfigParser):
@animation.wait()
def eval_ppm(ppm):
print('Evaluating')
print("Evaluating")
nonlocal data
nonlocal cfg
nonlocal axes
displ = data['displacement']
shrst = data['shearstress']
cfg.set('parameters', 'peak_prominence', str(ppm))
displ = data["displacement"]
shrst = data["shearstress"]
cfg.set("parameters", "peak_prominence", str(ppm))
pfit, pe, nfit, x, y, xq, yq, p, t = vst_analysis_alternative(
data, cfg)
data, cfg
)
axes[0].cla()
axes[0].plot(displ, shrst)
axes[0].plot(displ[p], shrst[p], 'rs')
axes[0].plot(displ[t], shrst[t], 'gs')
axes[0].plot(displ[p], shrst[p], "rs")
axes[0].plot(displ[t], shrst[t], "gs")
# shear velocity vs. fricton:
axes[1].cla()
axes[1].plot(10**x, y, 'k.', ms=2, rasterized=True,
label='original data')
axes[1].plot(10**xq, yq, 'r.', ms=2, rasterized=True, label='fit data')
axes[1].plot(
10**x, fitfric(x, *pfit),
'g-',
label='curve fit: ' + nfit
10**x, y, "k.", ms=2, rasterized=True, label="original data"
)
axes[1].plot(
10**xq, yq, "r.", ms=2, rasterized=True, label="fit data"
)
axes[1].plot(
10**x, fitfric(x, *pfit), "g-", label="curve fit: " + nfit
)
axes[1].set_xscale('log')
axes[1].set_xscale("log")
axes[1].set_xlim(
np.nanmin(10**x)-(np.nanmin(10**x)/5),
np.nanmax(10**x)+np.nanmax(10**x)/5
np.nanmin(10**x) - (np.nanmin(10**x) / 5),
np.nanmax(10**x) + np.nanmax(10**x) / 5,
)
axes[1].legend(
fontsize=8,
facecolor='w',
edgecolor='k',
facecolor="w",
edgecolor="k",
# loc='upper right',
framealpha=0.5
framealpha=0.5,
)
fig = plt.figure()
fig.suptitle('Adjust Peak Prominence:', fontsize='large')
fig.suptitle("Adjust Peak Prominence:", fontsize="large")
gs = gridspec.GridSpec(1, 3, wspace=0.4, hspace=0.3)
ax1 = fig.add_subplot(gs[0, :2])
ax3 = fig.add_subplot(gs[0, 2])
axes = [ax1, ax3]
dpi = fig.get_dpi()
fig.set_size_inches((1920/1.5)/float(dpi), (1080/2)/float(dpi))
plt.subplots_adjust(bottom=0.2, top=0.9, right=.95, left=.05)
axslid = plt.axes([.2, .05, .5, .075])
fig.set_size_inches((1920 / 1.5) / float(dpi), (1080 / 2) / float(dpi))
plt.subplots_adjust(bottom=0.2, top=0.9, right=0.95, left=0.05)
axslid = plt.axes([0.2, 0.05, 0.5, 0.075])
peak_prom_slider = mpl.widgets.Slider(
axslid,
label='Peak Prominence',
valmin=ppm/4,
valmax=ppm*2,
valinit=ppm
label="Peak Prominence",
valmin=ppm / 4,
valmax=ppm * 2,
valinit=ppm,
)
peak_prom_slider.on_changed(eval_ppm)
axok = plt.axes([0.81, 0.05, 0.1, 0.075])
bok = mpl.widgets.Button(axok, 'All ok!')
bok = mpl.widgets.Button(axok, "All ok!")
bok.on_clicked(_switch)
eval_ppm(ppm)
plt.show()
return (fig, axes)
# %%======================BOOTSTRAP LINEAR REGRESSION==========================
def fit_bootstrap(datax, datay, function=None,
yerr_systematic=0.0, nsigma=2, nsets=100,
yerr=None):
def fit_bootstrap(
datax,
datay,
function=None,
yerr_systematic=0.0,
nsigma=2,
nsets=100,
yerr=None,
):
"""
Does a bootstrap fit of datax and datay by fitting a number of nsets. Each
set contains normal distributed noise derived from the standard deviation
......@@ -368,17 +365,18 @@ def fit_bootstrap(datax, datay, function=None,
# Get the stdev of the residuals
residuals = errfunc(pfit, datax, datay)
sigma_res = nsigma*np.std(residuals)
sigma_res = nsigma * np.std(residuals)
sigma_err_total = np.sqrt(sigma_res**2 + yerr_systematic**2)
# 100 random data sets are generated and fitted
ps = []
for _ in range(nsets):
randomDelta = np.random.normal(0., sigma_err_total, len(datay))
randomDelta = np.random.normal(0.0, sigma_err_total, len(datay))
randomdataY = datay + randomDelta
randomfit, _ = spopt.curve_fit(
function, datax, randomdataY, sigma=yerr)
function, datax, randomdataY, sigma=yerr
)
ps.append(randomfit)
ps = np.array(ps)
mean_pfit = np.mean(ps, axis=0)
......
......@@ -50,9 +50,12 @@ class ToolTip(object):
tw.wm_geometry("+%d+%d" % (x, y))
label = ttk.Label(
tw,
text=self.text, justify=tk.LEFT,
background="#ffffe0", relief=tk.SOLID, borderwidth=1,
font=("tahoma", "8", "normal")
text=self.text,
justify=tk.LEFT,
background="#ffffe0",
relief=tk.SOLID,
borderwidth=1,
font=("tahoma", "8", "normal"),
)
label.pack(ipadx=1)
......@@ -73,8 +76,9 @@ def create_tooltip(widget, text):
def leave(event):
toolTip.hidetip()
widget.bind('<Enter>', enter)
widget.bind('<Leave>', leave)
widget.bind("<Enter>", enter)
widget.bind("<Leave>", leave)
def format_text(text, num=80):
......@@ -82,15 +86,15 @@ def format_text(text, num=80):
Inserts new lines into text after 'num' characters when there is a space
character.
"""
split_text = text.split(' ')
new_text = ''
current_line = ''
split_text = text.split(" ")
new_text = ""
current_line = ""
for s in split_text:
if len(current_line) + len(s) < num:
current_line += s + ' '
current_line += s + " "
else:
new_text += current_line + '\n'
current_line = s + ' '
new_text += current_line + "\n"
current_line = s + " "
if current_line:
new_text += current_line
return new_text
......@@ -99,7 +103,7 @@ def format_text(text, num=80):
class ResultEncoder(NumpyEncoder):
def default(self, obj):
if isinstance(obj, uncertainties.core.Variable):
return (repr(obj))
return repr(obj)
elif isinstance(obj, uncertainties.core.AffineScalarFunc):
return (repr(obj))
return repr(obj)
return NumpyEncoder.default(self, obj)
......@@ -25,8 +25,8 @@ def downsample_data(data, R):
Pads the data with NaN at the edges if not divisible by R so that the last
value uses less data points for the mean.
"""
pad_size = int(np.ceil(float(data.size)/R)*R - data.size)
data_padded = np.append(data, np.ones(pad_size)*np.NaN)
pad_size = int(np.ceil(float(data.size) / R) * R - data.size)
data_padded = np.append(data, np.ones(pad_size) * np.NaN)
new_data = np.nanmean(data_padded.reshape(-1, R), axis=1)
return new_data
......@@ -38,12 +38,11 @@ def downsample_file(file_path, freq=5):
Keywords:
- freq: Frequency to downsample to (default=5Hz)
"""
new_file_path = file_path.replace(
'.tdms', '_downsampled.tdms'
)
new_file_path = file_path.replace(".tdms", "_downsampled.tdms")
with nptdms.TdmsFile(file_path) as tdms_file, \
nptdms.TdmsWriter(new_file_path) as new_file:
with nptdms.TdmsFile(file_path) as tdms_file, nptdms.TdmsWriter(
new_file_path
) as new_file:
root_object = nptdms.RootObject(tdms_file.properties)
original_groups = tdms_file.groups()
channels = [
......@@ -56,16 +55,16 @@ def downsample_file(file_path, freq=5):
def downsample_channel(channel, freq):
""" Downsamples a channel to given frequency """
old_freq = 1/channel.time_track()[1]
"""Downsamples a channel to given frequency"""
old_freq = 1 / channel.time_track()[1]
R = int(old_freq / freq)
props = channel.properties
props['wf_increment'] *= R
props["wf_increment"] *= R
downsampled = nptdms.ChannelObject(
group=channel.group_name,
channel=channel.name,
data=downsample_data(channel.data, R),
properties=props
properties=props,
)
return downsampled
This diff is collapsed.
......@@ -20,65 +20,56 @@ from importlib import resources
def icon_rst():
""" Returns main application icon """
"""Returns main application icon"""
try:
with resources.path(
'rstevaluation.icons', 'rst-evaluation.png'
"rstevaluation.icons", "rst-evaluation.png"
) as fpath:
phim = tk.PhotoImage(
file=fpath
)
phim = tk.PhotoImage(file=fpath)
except TypeError as _:
phim = tk.PhotoImage(file='rstevaluation\\icons\\rst-evaluation.png')
phim = tk.PhotoImage(file="rstevaluation\\icons\\rst-evaluation.png")
return phim
def icon_load():
""" Returns an icon for loading from a folder """
"""Returns an icon for loading from a folder"""
try:
with resources.path('rstevaluation.icons', 'home.png') as fpath:
phim = tk.PhotoImage(
file=fpath
)
with resources.path("rstevaluation.icons", "home.png") as fpath:
phim = tk.PhotoImage(file=fpath)
except TypeError as _:
phim = tk.PhotoImage(file='rstevaluation\\icons\\home.png')
phim = tk.PhotoImage(file="rstevaluation\\icons\\home.png")
return phim
def icon_save():
""" Returns an icon for saving to a folder """
"""Returns an icon for saving to a folder"""
try:
with resources.path('rstevaluation.icons', 'filesave.png') as fpath:
phim = tk.PhotoImage(
file=fpath
)
with resources.path("rstevaluation.icons", "filesave.png") as fpath:
phim = tk.PhotoImage(file=fpath)
except TypeError as _:
phim = tk.PhotoImage(file='rstevaluation\\icons\\filesave.png')
phim = tk.PhotoImage(file="rstevaluation\\icons\\filesave.png")
return phim
def icon_options():
""" Returns an icon for options """
"""Returns an icon for options"""
try:
with resources.path('rstevaluation.icons', 'subplots.png') as fpath:
phim = tk.PhotoImage(
file=fpath
)
with resources.path("rstevaluation.icons", "subplots.png") as fpath:
phim = tk.PhotoImage(file=fpath)
except TypeError as _:
phim = tk.PhotoImage(file='rstevaluation\\icons\\subplots.png')
phim = tk.PhotoImage(file="rstevaluation\\icons\\subplots.png")
return phim
def icon_start():
""" Returns an icon for processing """
"""Returns an icon for processing"""
try:
with resources.path(
'rstevaluation.icons', 'qt4_editor_options.png'
"rstevaluation.icons", "qt4_editor_options.png"
) as fpath:
phim = tk.PhotoImage(
file=fpath
)
phim = tk.PhotoImage(file=fpath)
except TypeError as _:
phim = tk.PhotoImage(
file='rstevaluation\\icons\\qt4_editor_options.png')
file="rstevaluation\\icons\\qt4_editor_options.png"
)
return phim
This diff is collapsed.