СРОЧНО: пожалуйста, помогите... Я потратил 2 недели на написание кода с нуля и улучшение его различными способами, пока не возникла последняя проблема.
Мой код предназначен для вычисления двух различия на пик (на набор данных приходится 2 пика, одновременно анализируется 6 наборов данных), [абс. значение среднего (положение x) - максимум (положение x)] и [абс. значение среднего значения (положение x) – медиана (положение x)].
Как только он это сделает, он должен ИНДИВИДУАЛЬНО вычислить стандартное отклонение для каждого, а затем распечатать два стандартных отклонения для каждого пика. (Пик 1 и Пик 2) для каждого набора данных.
Мое текущее состояние:
Мой код не вычисляет это для обоих пиков. Он правильно вычисляет обе разницы для пика 1 и пика 2 для каждого набора данных. Однако он может преобразовать разницу только одного пика в стандартные отклонения.
Более того, я не очень верю в сам протокол стандартных отклонений — у меня есть подозрение, что сами пики вычисляются вместе, чтобы создать некоторое среднее стандартное отклонение, которое не связано с различиями, упомянутыми выше.
Буду очень признателен за быструю помощь. Потерял на этом много времени.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.signal import find_peaks
from sklearn.metrics import r2_score
# 1. User datasets:
x_data = np.array([25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105,
110, 115, 120, 125, 130])
y_data50 = np.array([0, 0.50031, 4.00248, 9.50589, 13.50837, 15.0093, 16.00992, 17.01054,
18.01116, 19.01178, 20.51271, 21.51333, 23.01426, 25.0155, 27.51705, 30.51891, 32.52015,
33.270615, 33.770925, 33.770925, 34.02108, 34.271235])
y_data100 = np.array([0, 4.95405, 12.88053, 20.80701, 28.73349, 36.65997, 39.6324,
42.109425, 44.58645, 47.55888, 50.035905, 52.51293, 55.48536, 59.4486, 63.41184, 68.36589,
72.32913, 73.31994, 74.31075, 75.30156, 75.30156, 75.30156])
y_data150 = np.array([0, 2.96262, 8.88786, 35.55144, 51.84585, 57.77109, 62.21502, 65.17764,
68.14026, 72.58419, 75.54681, 79.250085, 83.694015, 88.8786, 94.063185, 99.24777,
107.394975, 115.54218, 119.98611, 122.94873, 124.43004, 124.43004])
y_data200 = np.array([0, 5.91543, 29.57715, 70.98516, 88.73145, 92.67507, 98.5905,
102.53412, 108.44955, 112.39317, 118.3086, 126.19584, 132.11127, 139.99851, 151.82937,
161.68842, 173.51928, 175.49109, 177.4629, 179.43471, 179.43471, 179.43471])
y_data250 = np.array([0, 12.31155, 39.39696, 83.71854, 105.87933, 115.72857, 120.65319,
128.04012, 135.42705, 142.81398, 152.66322, 162.51246, 169.89939, 182.21094, 194.52249,
206.83404, 219.14559, 221.6079, 224.07021, 226.53252, 226.53252, 226.53252])
y_data300 = np.array([0, 11.81124, 38.38653, 76.77306, 121.06521, 132.87645, 138.78207,
147.6405, 153.54612, 159.45174, 168.31017, 180.12141, 188.97984, 203.74389, 218.50794,
236.2248, 248.03604, 253.94166, 259.84728, 261.323685, 262.80009, 265.7529])
#-----------------------------------------------
# Library of empirical data for user selection:
#-----------------------------------------------
# (A-1.) 'Stretched Fibrils'' Work Density Data:
# m(w) = 50m(f): y_data50 = np.array([0, 0.50031, 4.00248, 9.50589, 13.50837, 15.0093,
16.00992, 17.01054, 18.01116, 19.01178, 20.51271, 21.51333, 23.01426, 25.0155, 27.51705,
30.51891, 32.52015, 33.270615, 33.770925, 33.770925, 34.02108, 34.271235])
# m(w) = 100m(f): y_data100 = np.array([0, 4.95405, 12.88053, 20.80701, 28.73349, 36.65997,
39.6324, 42.109425, 44.58645, 47.55888, 50.035905, 52.51293, 55.48536, 59.4486, 63.41184,
68.36589, 72.32913, 73.31994, 74.31075, 75.30156, 75.30156, 75.30156])
# m(w) = 150m(f): y_data150 = np.array([0, 2.96262, 8.88786, 35.55144, 51.84585, 57.77109,
62.21502, 65.17764, 68.14026, 72.58419, 75.54681, 79.250085, 83.694015, 88.8786, 94.063185,
99.24777, 107.394975, 115.54218, 119.98611, 122.94873, 124.43004, 124.43004])
# m(w) = 200m(f): y_data200 = np.array([0, 5.91543, 29.57715, 70.98516, 88.73145, 92.67507,
98.5905, 102.53412, 108.44955, 112.39317, 118.3086, 126.19584, 132.11127, 139.99851,
151.82937, 161.68842, 173.51928, 175.49109, 177.4629, 179.43471, 179.43471, 179.43471])
# m(w) = 250m(f): y_data250 = np.array([0, 12.31155, 39.39696, 83.71854, 105.87933,
115.72857, 120.65319, 128.04012, 135.42705, 142.81398, 152.66322, 162.51246, 169.89939,
182.21094, 194.52249, 206.83404, 219.14559, 221.6079, 224.07021, 226.53252, 226.53252,
226.53252])
# m(w) = 300m(f): y_data300 = np.array([0, 11.81124, 38.38653, 76.77306, 121.06521,
132.87645, 138.78207, 147.6405, 153.54612, 159.45174, 168.31017, 180.12141, 188.97984,
203.74389, 218.50794, 236.2248, 248.03604, 253.94166, 259.84728, 261.323685, 262.80009,
265.7529])
#-----------------------------------------
# (A-2.) 'Stretched Fibrils'' Strain Data:
# m(w) = 50m(f): y_data50 = ([0, 0.008928571, 0.071428571, 0.169642857, 0.241071429,
0.267857143, 0.285714286, 0.303571429, 0.321428571, 0.339285714, 0.366071429, 0.383928571,
0.410714286, 0.446428571, 0.491071429, 0.544642857, 0.580357143, 0.59375, 0.602678571,
0.602678571, 0.607142857, 0.611607143])
# m(w) = 100m(f): y_data100 = ([0, 0.041666667, 0.108333333, 0.175, 0.241666667,
0.308333333, 0.333333333, 0.354166667, 0.375, 0.4, 0.420833333, 0.441666667, 0.466666667,
0.5, 0.533333333, 0.575, 0.608333333, 0.616666667, 0.625, 0.633333333, 0.633333333,
0.633333333])
# m(w) = 150m(f): y_data150 = ([0, 0.015151515, 0.045454545, 0.181818182, 0.265151515,
0.295454545, 0.318181818, 0.333333333, 0.348484848, 0.371212121, 0.386363636, 0.40530303,
0.428030303, 0.454545455, 0.481060606, 0.507575758, 0.549242424, 0.590909091, 0.613636364,
0.628787879, 0.636363636, 0.636363636])
# m(w) = 200m(f): y_data200 = ([0, 0.021582734, 0.107913669, 0.258992806, 0.323741007,
0.338129496, 0.35971223, 0.374100719, 0.395683453, 0.410071942, 0.431654676, 0.460431655,
0.482014388, 0.510791367, 0.553956835, 0.589928058, 0.633093525, 0.64028777, 0.647482014,
0.654676259, 0.654676259, 0.654676259])
# m(w) = 250m(f): y_data250 = ([0, 0.04, 0.128, 0.272, 0.344, 0.376, 0.392, 0.416, 0.44,
0.464, 0.496, 0.528, 0.552, 0.592, 0.632, 0.672, 0.712, 0.72, 0.728, 0.736, 0.736, 0.736])
# m(w) = 300m(f): y_data300 = ([0, 0.032, 0.104, 0.208, 0.328, 0.36, 0.376, 0.4, 0.416,
0.432, 0.456, 0.488, 0.512, 0.552, 0.592, 0.64, 0.672, 0.688, 0.704, 0.708, 0.712, 0.72])
#--------------------------------------------------------
# (B-1.) 'Stretched-Annealed Fibrils'' Work Density Data:
# m(w) = 50m(f): y_data50 = ([0, 1.998142105, 4.495819737, 8.492103947, 12.98792368,
14.48653026, 15.48560132, 16.48467237, 17.48374342, 18.48281447, 19.73165329, 20.98049211,
22.72886645, 24.72700855, 27.97398947, 30.97120263, 33.2191125, 33.46888026, 33.96841579,
34.46795132, 34.96748684, 35.46702237])
# m(w) = 100m(f): y_data100 = ([0, 1.980071053, 6.930248684, 14.85053289, 25.7409236,
29.70106579, 31.68113684, 33.66120789, 35.64127895, 38.61138553, 40.59145658, 44.55159868,
49.50177632, 52.96690066, 57.91707829, 64.35230921, 68.80746908, 69.30248684, 70.29252237,
70.78754013, 70.78754013, 70.78754013])
# m(w) = 150m(f): y_data150 = ([0, 2.961071053, 11.84428421, 26.64963947, 32.57178158,
34.79258487, 38.49392368, 42.93553026, 45.89660132, 50.33820789, 54.77981447, 59.22142105,
65.14356316, 71.80597303, 80.68918618, 93.27373816, 99.19588026, 101.4166836, 103.6374868,
105.1180224, 108.0790934, 109.5596289])
# m(w) = 200m(f): y_data200 = ([0, 0, 15.77448, 37.46439, 61.12611, 69.01335, 74.92878,
80.84421, 85.773735, 90.70326, 97.604595, 104.50593, 110.42136, 120.28041, 130.13946,
141.97032, 151.82937, 158.730705, 163.66023, 166.617945, 167.60385, 169.57566])
# m(w) = 250m(f): y_data250 = ([0, 0, 4.92462, 43.090425, 50.477355, 56.63313, 62.788905,
68.94468, 76.33161, 83.71854, 91.10547, 100.95471, 113.26626, 125.57781, 135.42705,
147.7386, 160.05015, 172.3617, 179.74863, 185.904405, 188.366715, 189.59787])
# m(w) = 300m(f): y_data300 = ([0, 1.476405, 2.95281, 8.85843, 29.5281, 41.33934, 50.19777,
57.579795, 64.96182, 73.82025, 82.67868, 95.966325, 109.25397, 121.06521, 135.82926,
153.54612, 168.31017, 181.597815, 190.456245, 197.83827, 200.79108, 202.267485])
#--------------------------------------------------
# (B-2.) 'Stretched-Annealed Fibrils'' Strain Data:
# m(w) = 50m(f): y_data50 = ([0, 0.035087719, 0.078947368, 0.149122807, 0.228070175,
0.254385965, 0.271929825, 0.289473684, 0.307017544, 0.324561404, 0.346491228, 0.368421053,
0.399122807, 0.434210526, 0.49122807, 0.543859649, 0.583333333, 0.587719298, 0.596491228,
0.605263158, 0.614035088, 0.622807018])
# m(w) = 100m(f): y_data100 = ([0, 0.017391304, 0.060869565, 0.130434783, 0.226086957,
0.260869565, 0.27826087, 0.295652174, 0.313043478, 0.339130435, 0.356521739, 0.391304348,
0.434782609, 0.465217391, 0.508695652, 0.565217391, 0.604347826, 0.608695652, 0.617391304,
0.62173913, 0.62173913, 0.62173913])
# m(w) = 150m(f): y_data150 = ([0, 0.017391304, 0.069565217, 0.156521739, 0.191304348,
0.204347826, 0.226086957, 0.252173913, 0.269565217, 0.295652174, 0.32173913, 0.347826087,
0.382608696, 0.42173913, 0.473913043, 0.547826087, 0.582608696, 0.595652174, 0.608695652,
0.617391304, 0.634782609, 0.643478261])
# m(w) = 200m(f): y_data200 = ([0, 0, 0.066666667, 0.158333333, 0.258333333, 0.291666667,
0.316666667, 0.341666667, 0.3625, 0.383333333, 0.4125, 0.441666667, 0.466666667,
0.508333333, 0.55, 0.6, 0.641666667, 0.670833333, 0.691666667, 0.704166667, 0.708333333,
0.716666667])
# m(w) = 250m(f): y_data250 = ([0, 0, 0.016260163, 0.142276423, 0.166666667, 0.18699187,
0.207317073, 0.227642276, 0.25203252, 0.276422764, 0.300813008, 0.333333333, 0.37398374,
0.414634146, 0.447154472, 0.487804878, 0.528455285, 0.569105691, 0.593495935, 0.613821138,
0.62195122, 0.62601626])
# m(w) = 300m(f): y_data300 = ([0, 0.004065041, 0.008130081, 0.024390244, 0.081300813,
0.113821138, 0.138211382, 0.158536585, 0.178861789, 0.203252033, 0.227642276, 0.264227642,
0.300813008, 0.333333333, 0.37398374, 0.422764228, 0.463414634, 0.5, 0.524390244,
0.544715447, 0.552845528, 0.556910569])
#----------------------------------------------------------------------------------
# 2a. Sigmoid function definition:
def compound_sigmoid(x, U1, x01, k1, U2, x02, k2):
return U1 / (1 + np.exp(-k1 * (x - x01))) + U2 / (1 + np.exp(-k2 * (x - x02)))
# 2b. Derivative of sigmoid function:
def compound_sigmoid_derivative(x, U1, x01, k1, U2, x02, k2):
sig1 = (U1 * k1 * np.exp(-k1 * (x - x01))) / ((1 + np.exp(-k1 * (x - x01))) ** 2)
sig2 = (U2 * k2 * np.exp(-k2 * (x - x02))) / ((1 + np.exp(-k2 * (x - x02))) ** 2)
return sig1 + sig2
# 3. Sigmoid x-fit defined:
x_fit = np.linspace(25, 130, 100)
# 4. Initial guesses for calculating fitting parameters: >USER SELECTION REQUIRED<
#---------------------------------------------------------------
# (A-1.) [PERSONAL/EACH] >WORK DENSITY< Initial Guesses for [STRETCHED]: USER SELECTION
REQUIRED
p0_50 = [max(y_data50)/2, 38, 0.1, max(y_data50), 65, 0.1]
p0_100 = [max(y_data100)/2, 38, 0.1, max(y_data100), 65, 0.1]
p0_150 = [max(y_data150)/2, 38, 0.1, max(y_data150), 65, 0.1]
p0_200 = [max(y_data200)/2, 38, 0.1, max(y_data200), 65, 0.1]
p0_250 = [max(y_data250)/2, 38, 0.1, max(y_data250), 65, 0.1]
p0_300 = [max(y_data300)/2, 38, 0.1, max(y_data300), 65, 0.1]
# (A-2.) [PERSONAL/EACH] >STRAIN< Initial Guesses for [STRETCHED]: >USER SELECTION REQUIRED<
#p0_50 = [max(y_data50)/2, 38, -0.1, max(y_data50), 60, -0.1]
#p0_100 = [max(y_data100)/2, 38, -0.1, max(y_data100), 60, -0.1]
#p0_150 = [max(y_data150)/2, 38, -0.1, max(y_data150), 60, -0.1]
#p0_200 = [max(y_data200)/2, 38, -0.1, max(y_data200), 60, -0.1]
#p0_250 = [max(y_data250)/2, 38, -0.1, max(y_data250), 60, -0.1]
#p0_300 = [max(y_data300)/2, 38, -0.1, max(y_data300), 60, -0.1]
# (B-1.) [PERSONAL/EACH] >WORK DENSITY< Initial Guesses for [STRETCHED-ANNEALED]: >USER
SELECTION REQUIRED<
#p0_50 = [max(y_data50)/2, 36, -0.1, max(y_data50), 60, -0.1]
#p0_100 = [max(y_data100)/2, 36, -0.1, max(y_data100), 60, -0.1]
#p0_150 = [max(y_data150)/2, 36, -0.1, max(y_data150), 60, -0.1]
#p0_200 = [max(y_data200)/2, 36, -0.1, max(y_data200), 60, -0.1]
#p0_250 = [max(y_data250)/2, 36, -0.1, max(y_data250), 55, -0.1]
#p0_300 = [max(y_data300)/2, 40, -0.1, max(y_data300), 60, -0.1]
# (B-2.) [PERSONAL/EACH] >STRAIN< Initial Guesses for [STRETCHED-ANNEALED]: >USER SELECTION
REQUIRED<
#p0_50 = [max(y_data50)/2, 38, -0.1, max(y_data50), 65, -0.1]
#p0_100 = [max(y_data100)/2, 38, -0.1, max(y_data100), 65, -0.1]
#p0_150 = [max(y_data150)/2, 38, -0.1, max(y_data150), 65, -0.1]
#p0_200 = [max(y_data200)/2, 38, -0.1, max(y_data200), 65, -0.1]
#p0_250 = [max(y_data250)/2, 34, -0.1, max(y_data250), 65, -0.1]
#p0_300 = [max(y_data300)/2, 34, -0.1, max(y_data300), 65, -0.1]
#---------------------------------------------------------------
# 5. Optimization parameters for ROI-specific calculation of the parameters:
bounds = (0, [np.inf, np.inf, np.inf, np.inf, np.inf, np.inf])
# 6. Fitting the data according to the initial guesses and the compound sigmoid function:
popt_50, _ = curve_fit(compound_sigmoid, x_data, y_data50, p0_50, bounds=bounds, maxfev =
5000)
popt_100, _ = curve_fit(compound_sigmoid, x_data, y_data100, p0_100, bounds=bounds, maxfev =
5000)
popt_150, _ = curve_fit(compound_sigmoid, x_data, y_data150, p0_150, bounds=bounds, maxfev =
5000)
popt_200, _ = curve_fit(compound_sigmoid, x_data, y_data200, p0_200, bounds=bounds, maxfev =
5000)
popt_250, _ = curve_fit(compound_sigmoid, x_data, y_data250, p0_250, bounds=bounds, maxfev =
5000)
popt_300, _ = curve_fit(compound_sigmoid, x_data, y_data300, p0_300, bounds=bounds, maxfev =
5000)
# 7a. Calculation of the y-value compound sigmoid fit data per data set:
y_fit50 = compound_sigmoid(x_fit, *popt_50)
y_fit100 = compound_sigmoid(x_fit, *popt_100)
y_fit150 = compound_sigmoid(x_fit, *popt_150)
y_fit200 = compound_sigmoid(x_fit, *popt_200)
y_fit250 = compound_sigmoid(x_fit, *popt_250)
y_fit300 = compound_sigmoid(x_fit, *popt_300)
# 7b. Calculation of the derivative series' y-values from the theoretical compound sigmoid:
dy_dx_fit50 = compound_sigmoid_derivative(x_fit, *popt_50)
dy_dx_fit100 = compound_sigmoid_derivative(x_fit, *popt_100)
dy_dx_fit150 = compound_sigmoid_derivative(x_fit, *popt_150)
dy_dx_fit200 = compound_sigmoid_derivative(x_fit, *popt_200)
dy_dx_fit250 = compound_sigmoid_derivative(x_fit, *popt_250)
dy_dx_fit300 = compound_sigmoid_derivative(x_fit, *popt_300)
# 8. Locating the peaks within the theoretical derivative plots (x-axis values):
peaks50, _ = find_peaks(dy_dx_fit50)
peaks100, _ = find_peaks(dy_dx_fit100)
peaks150, _ = find_peaks(dy_dx_fit150)
peaks200, _ = find_peaks(dy_dx_fit200)
peaks250, _ = find_peaks(dy_dx_fit250)
peaks300, _ = find_peaks(dy_dx_fit300)
# 9. Statistical parameter calculation functions according to peak distinction indices:
def calculate_statistics(x, y):
std = np.std(y)
mean = np.mean(y)
mean_location = np.sum(x * y) / np.sum(y) #-here, indices are based on distribution
values. Only second half of sorted indices given.
median_location = np.median(x[np.argsort(y)[len(y) // 2:]]) #-the median of the second
half sorted is calculated. This is better for skewed distributions.
return std, mean, mean_location, median_location
# 9a. Define a the maxima, distinguishing local and absolute.
def find_maxima(x, y):
peaks, _ = find_peaks(y)
maxima = [(x[p], y[p]) for p in peaks]
absolute_maximum = (x[np.argmax(y)], np.max(y))
return maxima, absolute_maximum
# 9b. Calculation and printing of the statistical parameters' values according to bounds:
def calculate_local_statistics(x, y, peak_indices, window_size = 5):
statistics = []
for peak in peak_indices:
start = max(0, peak - window_size)
end = min(len(x), peak + window_size + 1)
x_local = x[start:end]
y_local = y[start:end]
std, mean, mean_location, median_location = calculate_statistics(x_local, y_local)
# 9d. Position of the maximum is found within localized metrics:
max_location = x_local[np.argmax(y_local)]
# 9e. The distances [max. position - mean position] and [mean position - median position]
are taken:
distance_max_to_mean = max_location - mean_location
distance_mean_to_median = mean_location - median_location
statistics.append((std, mean, mean_location, median_location, distance_max_to_mean,
distance_mean_to_median))
return statistics
#9f. Datasets referenced for individual parameters:
datasets = [
('50m(f)', dy_dx_fit50),
('100m(f)', dy_dx_fit100),
('150m(f)', dy_dx_fit150),
('200m(f)', dy_dx_fit200),
('250m(f)', dy_dx_fit250),
('300m(f)', dy_dx_fit300)
]
# 10a. Local calculation of all statistics done for the listed datasets:
for label, dy_dx_fit in datasets:
maxima, absolute_maximum = find_maxima(x_fit, dy_dx_fit)
peak_indices = [np.where(x_fit == m[0])[0][0] for m in maxima]
local_stats = calculate_local_statistics(x_fit, dy_dx_fit, peak_indices)
# 10b. Standard deviations are computed for the distances found for the peak crest
parameters:
distances_max_to_mean = [stat[4] for stat in local_stats]
distances_mean_to_median = [stat[5] for stat in local_stats]
std_max_to_mean = np.std(distances_max_to_mean)
std_mean_to_median = np.std(distances_mean_to_median)
# 10c. Statistical parameters are printed
print(f"\nStatistics for {label}:")
for i, ((x_peak, y_peak), (std, mean, mean_location, median_location,
distance_max_to_mean, distance_mean_to_median)) in enumerate(zip(maxima, local_stats)):
print(f" Peak {i+1}:")
print(f" Maximum Location: ({x_peak}, {y_peak})")
print(f" Std: {std:.4f}")
print(f" Mean: {mean:.4f}")
print(f" Mean Location: {mean_location:.4f}")
print(f" Median Location: {median_location:.4f}")
print(f" Distance from Max to Mean: {distance_max_to_mean:.4f}")
print(f" Distance from Mean to Median: {distance_mean_to_median:.4f}")
print(f" Std from Max to Mean: {std_max_to_mean:.4f}")
print(f" Std from Mean to Median: {std_mean_to_median:.4f}")
# 11. Plot data, logistic sigmoid function fit & the derivative:
# 11a. Figures dimensions adjustment:
plt.figure(figsize = (9, 10))
plt.subplots_adjust(hspace=0.275)
# 11b. Datas' & Sigmoid Fits' series to be plotted in the 1st subplot:
plt.subplot(2, 1, 1)
plt.plot(x_data, y_data300, 'o', color = 'black', label = f'$m_{"w"}$ = $300m_{"f"}$' + '
Empirical')
plt.plot(x_fit, y_fit300, '-', color = 'black', label=f'$m_{"w"}$ = $300m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit250, '-', color = 'purple', label=f'$m_{"w"}$ = $250m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit200, '-', color = 'red', label=f'$m_{"w"}$ = $200m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit150, '-', color = 'darkorange', label=f'$m_{"w"}$ = $150m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit100, '-', color = 'gold', label=f'$m_{"w"}$ = $100m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit50, '-', color = 'green', label=f'$m_{"w"}$ = $50m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_data, y_data50, 'o', color = 'green', label = f'$m_{"w"}$ = $50m_{"f"}$' + '
Empirical')
# 11c. Work Density Title [Stretched]: >USER SELECTION REQUIRED<
plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
plt.xlim((25, 130))
plt.ylim((0, 275)) #- Suitable for presenting Stretched.
plt.xticks(np.arange(25, 130, 15.0))
plt.ylabel('Work Density ' + '$\it{WD}$ ' + '(Nm/kg)', size = 11, x = 1.02)
plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+ 'Logistic Sigmoidal Fit
to Work Density Data', size = 13, y = 1.02)
plt.legend(prop = {"size": 8})
plt.grid(True)
# 11c. Strain Title [Stretched]: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 0.8)) #- Suitable for presenting Stretched.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Strain ' + '$\it{ε}$ ' + '(Nm/kg)', size = 11, x = 1.02)
#plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+ 'Logistic Sigmoidal Fit
to Strain Data', size = 13, y = 1.02)
#plt.legend(prop = {"size": 8})
#plt.grid(True)
# 11c. Work Density Title [Stretched-Annealed]: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 220)) #- Suitable for presenting Stretched-Annealed.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Work Density ' + '$\it{WD}$ ' + '(Nm/kg)', size = 11, x = 1.02)
#plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+
'$\mathregular{[T_{ann}}$ = $\mathregular{(5.2)T_{0}]}$ ' + ' Logistic Sigmoidal Fit to Work
Density Data', size = 13, y = 1.02)
#plt.legend(prop = {"size": 8})
#plt.grid(True)
# 11c. Strain Title [Stretched-Annealed]: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 0.75)) #- Suitable for presenting Stretched-Annealed.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Strain ' + '$\it{ε}$ ' + '(Nm/kg)', size = 11, x = 1.02)
#plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+
'$\mathregular{[T_{ann}}$ = $\mathregular{(5.2)T_{0}]}$ ' + ' Logistic Sigmoidal Fit to
Strain Data', size = 13, y = 1.02)
#plt.legend(prop = {"size": 8})
#plt.grid(True)
# 12a. Derivatives of the sigmoids' series to be plotted in the 2nd subplot:
plt.subplot(2, 1, 2)
plt.plot(x_fit, dy_dx_fit300, '--', color = 'black', label = f'$m_{"w"}$ = $300m_{"f"}$')
plt.plot(x_fit, dy_dx_fit250, '--', color = 'purple', label = f'$m_{"w"}$ = $250m_{"f"}$')
plt.plot(x_fit, dy_dx_fit200, '--', color = 'red', label = f'$m_{"w"}$ = $200m_{"f"}$')
plt.plot(x_fit, dy_dx_fit150, '--', color = 'darkorange', label = f'$m_{"w"}$ =
$150m_{"f"}$')
plt.plot(x_fit, dy_dx_fit100, '--', color = 'gold', label = f'$m_{"w"}$ = $100m_{"f"}$')
plt.plot(x_fit, dy_dx_fit50, '--', color = 'green', label = f'$m_{"w"}$ = $50m_{"f"}$')
# 12b. Derivative Subplot Work Density Title: >USER SELECTION REQUIRED<
plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
plt.xlim((25, 130))
plt.ylim((0, 10)) #- Suitable for presenting Stretched: USER SELECTION REQUIRED.
#plt.ylim((0, 15)) #- Suitable for presenting Stretched-Annealed: USER SELECTION REQUIRED.
plt.xticks(np.arange(25, 130, 15.0))
plt.ylabel('Rate of Change ' + '$\it{ΔWD/ΔT}$ ' + '(Nm/kg°C)', size = 11, x = 1.02)
plt.legend(prop = {"size": 10})
plt.title('Work Density Rates (Derivatives of Characteristic Sigmoids)', size = 13, y =
1.02)
plt.grid(True)
# 12b. Derivative Subplot Strain Title: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 0.035)) #- Suitable for presenting Stretched: USER SELECTION REQUIRED.
#plt.ylim((0, 0.05)) #- Suitable for presenting Stretched-Annealed: USER SELECTION REQUIRED.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Rate of Change ' + '$\it{Δε/T}$ ' + '(Δε/°C)', size = 11, x = 1.02)
#plt.legend(prop = {"size": 8})
#plt.title('Strain Rates (Derivatives of Characteristic Sigmoids)', size = 13, y = 1.02)
#plt.grid(True)
plt.show()
Подробнее здесь: https://stackoverflow.com/questions/786 ... ean-median
Код устранения неполадок: рассчитайте разницу между средним-максимальным и средним-медианой на пик в одном и том же набо ⇐ Python
Программы на Python
1719616934
Anonymous
СРОЧНО: пожалуйста, помогите... Я потратил 2 недели на написание кода с нуля и улучшение его различными способами, пока не возникла последняя проблема.
Мой код предназначен для вычисления двух различия на пик (на набор данных приходится 2 пика, одновременно анализируется 6 наборов данных), [абс. значение среднего (положение x) - максимум (положение x)] и [абс. значение среднего значения (положение x) – медиана (положение x)].
Как только он это сделает, он должен ИНДИВИДУАЛЬНО вычислить стандартное отклонение для каждого, а затем распечатать два стандартных отклонения для каждого пика. (Пик 1 и Пик 2) для каждого набора данных.
Мое текущее состояние:
Мой код не вычисляет это для обоих пиков. Он правильно вычисляет обе разницы для пика 1 и пика 2 для каждого набора данных. Однако он может преобразовать разницу только одного пика в стандартные отклонения.
Более того, я не очень верю в сам протокол стандартных отклонений — у меня есть подозрение, что сами пики вычисляются вместе, чтобы создать некоторое среднее стандартное отклонение, которое не связано с различиями, упомянутыми выше.
Буду очень признателен за быструю помощь. Потерял на этом много времени.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.signal import find_peaks
from sklearn.metrics import r2_score
# 1. User datasets:
x_data = np.array([25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105,
110, 115, 120, 125, 130])
y_data50 = np.array([0, 0.50031, 4.00248, 9.50589, 13.50837, 15.0093, 16.00992, 17.01054,
18.01116, 19.01178, 20.51271, 21.51333, 23.01426, 25.0155, 27.51705, 30.51891, 32.52015,
33.270615, 33.770925, 33.770925, 34.02108, 34.271235])
y_data100 = np.array([0, 4.95405, 12.88053, 20.80701, 28.73349, 36.65997, 39.6324,
42.109425, 44.58645, 47.55888, 50.035905, 52.51293, 55.48536, 59.4486, 63.41184, 68.36589,
72.32913, 73.31994, 74.31075, 75.30156, 75.30156, 75.30156])
y_data150 = np.array([0, 2.96262, 8.88786, 35.55144, 51.84585, 57.77109, 62.21502, 65.17764,
68.14026, 72.58419, 75.54681, 79.250085, 83.694015, 88.8786, 94.063185, 99.24777,
107.394975, 115.54218, 119.98611, 122.94873, 124.43004, 124.43004])
y_data200 = np.array([0, 5.91543, 29.57715, 70.98516, 88.73145, 92.67507, 98.5905,
102.53412, 108.44955, 112.39317, 118.3086, 126.19584, 132.11127, 139.99851, 151.82937,
161.68842, 173.51928, 175.49109, 177.4629, 179.43471, 179.43471, 179.43471])
y_data250 = np.array([0, 12.31155, 39.39696, 83.71854, 105.87933, 115.72857, 120.65319,
128.04012, 135.42705, 142.81398, 152.66322, 162.51246, 169.89939, 182.21094, 194.52249,
206.83404, 219.14559, 221.6079, 224.07021, 226.53252, 226.53252, 226.53252])
y_data300 = np.array([0, 11.81124, 38.38653, 76.77306, 121.06521, 132.87645, 138.78207,
147.6405, 153.54612, 159.45174, 168.31017, 180.12141, 188.97984, 203.74389, 218.50794,
236.2248, 248.03604, 253.94166, 259.84728, 261.323685, 262.80009, 265.7529])
#-----------------------------------------------
# Library of empirical data for user selection:
#-----------------------------------------------
# (A-1.) 'Stretched Fibrils'' Work Density Data:
# m(w) = 50m(f): y_data50 = np.array([0, 0.50031, 4.00248, 9.50589, 13.50837, 15.0093,
16.00992, 17.01054, 18.01116, 19.01178, 20.51271, 21.51333, 23.01426, 25.0155, 27.51705,
30.51891, 32.52015, 33.270615, 33.770925, 33.770925, 34.02108, 34.271235])
# m(w) = 100m(f): y_data100 = np.array([0, 4.95405, 12.88053, 20.80701, 28.73349, 36.65997,
39.6324, 42.109425, 44.58645, 47.55888, 50.035905, 52.51293, 55.48536, 59.4486, 63.41184,
68.36589, 72.32913, 73.31994, 74.31075, 75.30156, 75.30156, 75.30156])
# m(w) = 150m(f): y_data150 = np.array([0, 2.96262, 8.88786, 35.55144, 51.84585, 57.77109,
62.21502, 65.17764, 68.14026, 72.58419, 75.54681, 79.250085, 83.694015, 88.8786, 94.063185,
99.24777, 107.394975, 115.54218, 119.98611, 122.94873, 124.43004, 124.43004])
# m(w) = 200m(f): y_data200 = np.array([0, 5.91543, 29.57715, 70.98516, 88.73145, 92.67507,
98.5905, 102.53412, 108.44955, 112.39317, 118.3086, 126.19584, 132.11127, 139.99851,
151.82937, 161.68842, 173.51928, 175.49109, 177.4629, 179.43471, 179.43471, 179.43471])
# m(w) = 250m(f): y_data250 = np.array([0, 12.31155, 39.39696, 83.71854, 105.87933,
115.72857, 120.65319, 128.04012, 135.42705, 142.81398, 152.66322, 162.51246, 169.89939,
182.21094, 194.52249, 206.83404, 219.14559, 221.6079, 224.07021, 226.53252, 226.53252,
226.53252])
# m(w) = 300m(f): y_data300 = np.array([0, 11.81124, 38.38653, 76.77306, 121.06521,
132.87645, 138.78207, 147.6405, 153.54612, 159.45174, 168.31017, 180.12141, 188.97984,
203.74389, 218.50794, 236.2248, 248.03604, 253.94166, 259.84728, 261.323685, 262.80009,
265.7529])
#-----------------------------------------
# (A-2.) 'Stretched Fibrils'' Strain Data:
# m(w) = 50m(f): y_data50 = ([0, 0.008928571, 0.071428571, 0.169642857, 0.241071429,
0.267857143, 0.285714286, 0.303571429, 0.321428571, 0.339285714, 0.366071429, 0.383928571,
0.410714286, 0.446428571, 0.491071429, 0.544642857, 0.580357143, 0.59375, 0.602678571,
0.602678571, 0.607142857, 0.611607143])
# m(w) = 100m(f): y_data100 = ([0, 0.041666667, 0.108333333, 0.175, 0.241666667,
0.308333333, 0.333333333, 0.354166667, 0.375, 0.4, 0.420833333, 0.441666667, 0.466666667,
0.5, 0.533333333, 0.575, 0.608333333, 0.616666667, 0.625, 0.633333333, 0.633333333,
0.633333333])
# m(w) = 150m(f): y_data150 = ([0, 0.015151515, 0.045454545, 0.181818182, 0.265151515,
0.295454545, 0.318181818, 0.333333333, 0.348484848, 0.371212121, 0.386363636, 0.40530303,
0.428030303, 0.454545455, 0.481060606, 0.507575758, 0.549242424, 0.590909091, 0.613636364,
0.628787879, 0.636363636, 0.636363636])
# m(w) = 200m(f): y_data200 = ([0, 0.021582734, 0.107913669, 0.258992806, 0.323741007,
0.338129496, 0.35971223, 0.374100719, 0.395683453, 0.410071942, 0.431654676, 0.460431655,
0.482014388, 0.510791367, 0.553956835, 0.589928058, 0.633093525, 0.64028777, 0.647482014,
0.654676259, 0.654676259, 0.654676259])
# m(w) = 250m(f): y_data250 = ([0, 0.04, 0.128, 0.272, 0.344, 0.376, 0.392, 0.416, 0.44,
0.464, 0.496, 0.528, 0.552, 0.592, 0.632, 0.672, 0.712, 0.72, 0.728, 0.736, 0.736, 0.736])
# m(w) = 300m(f): y_data300 = ([0, 0.032, 0.104, 0.208, 0.328, 0.36, 0.376, 0.4, 0.416,
0.432, 0.456, 0.488, 0.512, 0.552, 0.592, 0.64, 0.672, 0.688, 0.704, 0.708, 0.712, 0.72])
#--------------------------------------------------------
# (B-1.) 'Stretched-Annealed Fibrils'' Work Density Data:
# m(w) = 50m(f): y_data50 = ([0, 1.998142105, 4.495819737, 8.492103947, 12.98792368,
14.48653026, 15.48560132, 16.48467237, 17.48374342, 18.48281447, 19.73165329, 20.98049211,
22.72886645, 24.72700855, 27.97398947, 30.97120263, 33.2191125, 33.46888026, 33.96841579,
34.46795132, 34.96748684, 35.46702237])
# m(w) = 100m(f): y_data100 = ([0, 1.980071053, 6.930248684, 14.85053289, 25.7409236,
29.70106579, 31.68113684, 33.66120789, 35.64127895, 38.61138553, 40.59145658, 44.55159868,
49.50177632, 52.96690066, 57.91707829, 64.35230921, 68.80746908, 69.30248684, 70.29252237,
70.78754013, 70.78754013, 70.78754013])
# m(w) = 150m(f): y_data150 = ([0, 2.961071053, 11.84428421, 26.64963947, 32.57178158,
34.79258487, 38.49392368, 42.93553026, 45.89660132, 50.33820789, 54.77981447, 59.22142105,
65.14356316, 71.80597303, 80.68918618, 93.27373816, 99.19588026, 101.4166836, 103.6374868,
105.1180224, 108.0790934, 109.5596289])
# m(w) = 200m(f): y_data200 = ([0, 0, 15.77448, 37.46439, 61.12611, 69.01335, 74.92878,
80.84421, 85.773735, 90.70326, 97.604595, 104.50593, 110.42136, 120.28041, 130.13946,
141.97032, 151.82937, 158.730705, 163.66023, 166.617945, 167.60385, 169.57566])
# m(w) = 250m(f): y_data250 = ([0, 0, 4.92462, 43.090425, 50.477355, 56.63313, 62.788905,
68.94468, 76.33161, 83.71854, 91.10547, 100.95471, 113.26626, 125.57781, 135.42705,
147.7386, 160.05015, 172.3617, 179.74863, 185.904405, 188.366715, 189.59787])
# m(w) = 300m(f): y_data300 = ([0, 1.476405, 2.95281, 8.85843, 29.5281, 41.33934, 50.19777,
57.579795, 64.96182, 73.82025, 82.67868, 95.966325, 109.25397, 121.06521, 135.82926,
153.54612, 168.31017, 181.597815, 190.456245, 197.83827, 200.79108, 202.267485])
#--------------------------------------------------
# (B-2.) 'Stretched-Annealed Fibrils'' Strain Data:
# m(w) = 50m(f): y_data50 = ([0, 0.035087719, 0.078947368, 0.149122807, 0.228070175,
0.254385965, 0.271929825, 0.289473684, 0.307017544, 0.324561404, 0.346491228, 0.368421053,
0.399122807, 0.434210526, 0.49122807, 0.543859649, 0.583333333, 0.587719298, 0.596491228,
0.605263158, 0.614035088, 0.622807018])
# m(w) = 100m(f): y_data100 = ([0, 0.017391304, 0.060869565, 0.130434783, 0.226086957,
0.260869565, 0.27826087, 0.295652174, 0.313043478, 0.339130435, 0.356521739, 0.391304348,
0.434782609, 0.465217391, 0.508695652, 0.565217391, 0.604347826, 0.608695652, 0.617391304,
0.62173913, 0.62173913, 0.62173913])
# m(w) = 150m(f): y_data150 = ([0, 0.017391304, 0.069565217, 0.156521739, 0.191304348,
0.204347826, 0.226086957, 0.252173913, 0.269565217, 0.295652174, 0.32173913, 0.347826087,
0.382608696, 0.42173913, 0.473913043, 0.547826087, 0.582608696, 0.595652174, 0.608695652,
0.617391304, 0.634782609, 0.643478261])
# m(w) = 200m(f): y_data200 = ([0, 0, 0.066666667, 0.158333333, 0.258333333, 0.291666667,
0.316666667, 0.341666667, 0.3625, 0.383333333, 0.4125, 0.441666667, 0.466666667,
0.508333333, 0.55, 0.6, 0.641666667, 0.670833333, 0.691666667, 0.704166667, 0.708333333,
0.716666667])
# m(w) = 250m(f): y_data250 = ([0, 0, 0.016260163, 0.142276423, 0.166666667, 0.18699187,
0.207317073, 0.227642276, 0.25203252, 0.276422764, 0.300813008, 0.333333333, 0.37398374,
0.414634146, 0.447154472, 0.487804878, 0.528455285, 0.569105691, 0.593495935, 0.613821138,
0.62195122, 0.62601626])
# m(w) = 300m(f): y_data300 = ([0, 0.004065041, 0.008130081, 0.024390244, 0.081300813,
0.113821138, 0.138211382, 0.158536585, 0.178861789, 0.203252033, 0.227642276, 0.264227642,
0.300813008, 0.333333333, 0.37398374, 0.422764228, 0.463414634, 0.5, 0.524390244,
0.544715447, 0.552845528, 0.556910569])
#----------------------------------------------------------------------------------
# 2a. Sigmoid function definition:
def compound_sigmoid(x, U1, x01, k1, U2, x02, k2):
return U1 / (1 + np.exp(-k1 * (x - x01))) + U2 / (1 + np.exp(-k2 * (x - x02)))
# 2b. Derivative of sigmoid function:
def compound_sigmoid_derivative(x, U1, x01, k1, U2, x02, k2):
sig1 = (U1 * k1 * np.exp(-k1 * (x - x01))) / ((1 + np.exp(-k1 * (x - x01))) ** 2)
sig2 = (U2 * k2 * np.exp(-k2 * (x - x02))) / ((1 + np.exp(-k2 * (x - x02))) ** 2)
return sig1 + sig2
# 3. Sigmoid x-fit defined:
x_fit = np.linspace(25, 130, 100)
# 4. Initial guesses for calculating fitting parameters: >USER SELECTION REQUIRED<
#---------------------------------------------------------------
# (A-1.) [PERSONAL/EACH] >WORK DENSITY< Initial Guesses for [STRETCHED]: USER SELECTION
REQUIRED
p0_50 = [max(y_data50)/2, 38, 0.1, max(y_data50), 65, 0.1]
p0_100 = [max(y_data100)/2, 38, 0.1, max(y_data100), 65, 0.1]
p0_150 = [max(y_data150)/2, 38, 0.1, max(y_data150), 65, 0.1]
p0_200 = [max(y_data200)/2, 38, 0.1, max(y_data200), 65, 0.1]
p0_250 = [max(y_data250)/2, 38, 0.1, max(y_data250), 65, 0.1]
p0_300 = [max(y_data300)/2, 38, 0.1, max(y_data300), 65, 0.1]
# (A-2.) [PERSONAL/EACH] >STRAIN< Initial Guesses for [STRETCHED]: >USER SELECTION REQUIRED<
#p0_50 = [max(y_data50)/2, 38, -0.1, max(y_data50), 60, -0.1]
#p0_100 = [max(y_data100)/2, 38, -0.1, max(y_data100), 60, -0.1]
#p0_150 = [max(y_data150)/2, 38, -0.1, max(y_data150), 60, -0.1]
#p0_200 = [max(y_data200)/2, 38, -0.1, max(y_data200), 60, -0.1]
#p0_250 = [max(y_data250)/2, 38, -0.1, max(y_data250), 60, -0.1]
#p0_300 = [max(y_data300)/2, 38, -0.1, max(y_data300), 60, -0.1]
# (B-1.) [PERSONAL/EACH] >WORK DENSITY< Initial Guesses for [STRETCHED-ANNEALED]: >USER
SELECTION REQUIRED<
#p0_50 = [max(y_data50)/2, 36, -0.1, max(y_data50), 60, -0.1]
#p0_100 = [max(y_data100)/2, 36, -0.1, max(y_data100), 60, -0.1]
#p0_150 = [max(y_data150)/2, 36, -0.1, max(y_data150), 60, -0.1]
#p0_200 = [max(y_data200)/2, 36, -0.1, max(y_data200), 60, -0.1]
#p0_250 = [max(y_data250)/2, 36, -0.1, max(y_data250), 55, -0.1]
#p0_300 = [max(y_data300)/2, 40, -0.1, max(y_data300), 60, -0.1]
# (B-2.) [PERSONAL/EACH] >STRAIN< Initial Guesses for [STRETCHED-ANNEALED]: >USER SELECTION
REQUIRED<
#p0_50 = [max(y_data50)/2, 38, -0.1, max(y_data50), 65, -0.1]
#p0_100 = [max(y_data100)/2, 38, -0.1, max(y_data100), 65, -0.1]
#p0_150 = [max(y_data150)/2, 38, -0.1, max(y_data150), 65, -0.1]
#p0_200 = [max(y_data200)/2, 38, -0.1, max(y_data200), 65, -0.1]
#p0_250 = [max(y_data250)/2, 34, -0.1, max(y_data250), 65, -0.1]
#p0_300 = [max(y_data300)/2, 34, -0.1, max(y_data300), 65, -0.1]
#---------------------------------------------------------------
# 5. Optimization parameters for ROI-specific calculation of the parameters:
bounds = (0, [np.inf, np.inf, np.inf, np.inf, np.inf, np.inf])
# 6. Fitting the data according to the initial guesses and the compound sigmoid function:
popt_50, _ = curve_fit(compound_sigmoid, x_data, y_data50, p0_50, bounds=bounds, maxfev =
5000)
popt_100, _ = curve_fit(compound_sigmoid, x_data, y_data100, p0_100, bounds=bounds, maxfev =
5000)
popt_150, _ = curve_fit(compound_sigmoid, x_data, y_data150, p0_150, bounds=bounds, maxfev =
5000)
popt_200, _ = curve_fit(compound_sigmoid, x_data, y_data200, p0_200, bounds=bounds, maxfev =
5000)
popt_250, _ = curve_fit(compound_sigmoid, x_data, y_data250, p0_250, bounds=bounds, maxfev =
5000)
popt_300, _ = curve_fit(compound_sigmoid, x_data, y_data300, p0_300, bounds=bounds, maxfev =
5000)
# 7a. Calculation of the y-value compound sigmoid fit data per data set:
y_fit50 = compound_sigmoid(x_fit, *popt_50)
y_fit100 = compound_sigmoid(x_fit, *popt_100)
y_fit150 = compound_sigmoid(x_fit, *popt_150)
y_fit200 = compound_sigmoid(x_fit, *popt_200)
y_fit250 = compound_sigmoid(x_fit, *popt_250)
y_fit300 = compound_sigmoid(x_fit, *popt_300)
# 7b. Calculation of the derivative series' y-values from the theoretical compound sigmoid:
dy_dx_fit50 = compound_sigmoid_derivative(x_fit, *popt_50)
dy_dx_fit100 = compound_sigmoid_derivative(x_fit, *popt_100)
dy_dx_fit150 = compound_sigmoid_derivative(x_fit, *popt_150)
dy_dx_fit200 = compound_sigmoid_derivative(x_fit, *popt_200)
dy_dx_fit250 = compound_sigmoid_derivative(x_fit, *popt_250)
dy_dx_fit300 = compound_sigmoid_derivative(x_fit, *popt_300)
# 8. Locating the peaks within the theoretical derivative plots (x-axis values):
peaks50, _ = find_peaks(dy_dx_fit50)
peaks100, _ = find_peaks(dy_dx_fit100)
peaks150, _ = find_peaks(dy_dx_fit150)
peaks200, _ = find_peaks(dy_dx_fit200)
peaks250, _ = find_peaks(dy_dx_fit250)
peaks300, _ = find_peaks(dy_dx_fit300)
# 9. Statistical parameter calculation functions according to peak distinction indices:
def calculate_statistics(x, y):
std = np.std(y)
mean = np.mean(y)
mean_location = np.sum(x * y) / np.sum(y) #-here, indices are based on distribution
values. Only second half of sorted indices given.
median_location = np.median(x[np.argsort(y)[len(y) // 2:]]) #-the median of the second
half sorted is calculated. This is better for skewed distributions.
return std, mean, mean_location, median_location
# 9a. Define a the maxima, distinguishing local and absolute.
def find_maxima(x, y):
peaks, _ = find_peaks(y)
maxima = [(x[p], y[p]) for p in peaks]
absolute_maximum = (x[np.argmax(y)], np.max(y))
return maxima, absolute_maximum
# 9b. Calculation and printing of the statistical parameters' values according to bounds:
def calculate_local_statistics(x, y, peak_indices, window_size = 5):
statistics = []
for peak in peak_indices:
start = max(0, peak - window_size)
end = min(len(x), peak + window_size + 1)
x_local = x[start:end]
y_local = y[start:end]
std, mean, mean_location, median_location = calculate_statistics(x_local, y_local)
# 9d. Position of the maximum is found within localized metrics:
max_location = x_local[np.argmax(y_local)]
# 9e. The distances [max. position - mean position] and [mean position - median position]
are taken:
distance_max_to_mean = max_location - mean_location
distance_mean_to_median = mean_location - median_location
statistics.append((std, mean, mean_location, median_location, distance_max_to_mean,
distance_mean_to_median))
return statistics
#9f. Datasets referenced for individual parameters:
datasets = [
('50m(f)', dy_dx_fit50),
('100m(f)', dy_dx_fit100),
('150m(f)', dy_dx_fit150),
('200m(f)', dy_dx_fit200),
('250m(f)', dy_dx_fit250),
('300m(f)', dy_dx_fit300)
]
# 10a. Local calculation of all statistics done for the listed datasets:
for label, dy_dx_fit in datasets:
maxima, absolute_maximum = find_maxima(x_fit, dy_dx_fit)
peak_indices = [np.where(x_fit == m[0])[0][0] for m in maxima]
local_stats = calculate_local_statistics(x_fit, dy_dx_fit, peak_indices)
# 10b. Standard deviations are computed for the distances found for the peak crest
parameters:
distances_max_to_mean = [stat[4] for stat in local_stats]
distances_mean_to_median = [stat[5] for stat in local_stats]
std_max_to_mean = np.std(distances_max_to_mean)
std_mean_to_median = np.std(distances_mean_to_median)
# 10c. Statistical parameters are printed
print(f"\nStatistics for {label}:")
for i, ((x_peak, y_peak), (std, mean, mean_location, median_location,
distance_max_to_mean, distance_mean_to_median)) in enumerate(zip(maxima, local_stats)):
print(f" Peak {i+1}:")
print(f" Maximum Location: ({x_peak}, {y_peak})")
print(f" Std: {std:.4f}")
print(f" Mean: {mean:.4f}")
print(f" Mean Location: {mean_location:.4f}")
print(f" Median Location: {median_location:.4f}")
print(f" Distance from Max to Mean: {distance_max_to_mean:.4f}")
print(f" Distance from Mean to Median: {distance_mean_to_median:.4f}")
print(f" Std from Max to Mean: {std_max_to_mean:.4f}")
print(f" Std from Mean to Median: {std_mean_to_median:.4f}")
# 11. Plot data, logistic sigmoid function fit & the derivative:
# 11a. Figures dimensions adjustment:
plt.figure(figsize = (9, 10))
plt.subplots_adjust(hspace=0.275)
# 11b. Datas' & Sigmoid Fits' series to be plotted in the 1st subplot:
plt.subplot(2, 1, 1)
plt.plot(x_data, y_data300, 'o', color = 'black', label = f'$m_{"w"}$ = $300m_{"f"}$' + '
Empirical')
plt.plot(x_fit, y_fit300, '-', color = 'black', label=f'$m_{"w"}$ = $300m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit250, '-', color = 'purple', label=f'$m_{"w"}$ = $250m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit200, '-', color = 'red', label=f'$m_{"w"}$ = $200m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit150, '-', color = 'darkorange', label=f'$m_{"w"}$ = $150m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit100, '-', color = 'gold', label=f'$m_{"w"}$ = $100m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_fit, y_fit50, '-', color = 'green', label=f'$m_{"w"}$ = $50m_{"f"}$') # |
$R^{"2"}$ Value = {r_squared300:.3f}')
plt.plot(x_data, y_data50, 'o', color = 'green', label = f'$m_{"w"}$ = $50m_{"f"}$' + '
Empirical')
# 11c. Work Density Title [Stretched]: >USER SELECTION REQUIRED<
plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
plt.xlim((25, 130))
plt.ylim((0, 275)) #- Suitable for presenting Stretched.
plt.xticks(np.arange(25, 130, 15.0))
plt.ylabel('Work Density ' + '$\it{WD}$ ' + '(Nm/kg)', size = 11, x = 1.02)
plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+ 'Logistic Sigmoidal Fit
to Work Density Data', size = 13, y = 1.02)
plt.legend(prop = {"size": 8})
plt.grid(True)
# 11c. Strain Title [Stretched]: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 0.8)) #- Suitable for presenting Stretched.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Strain ' + '$\it{ε}$ ' + '(Nm/kg)', size = 11, x = 1.02)
#plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+ 'Logistic Sigmoidal Fit
to Strain Data', size = 13, y = 1.02)
#plt.legend(prop = {"size": 8})
#plt.grid(True)
# 11c. Work Density Title [Stretched-Annealed]: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 220)) #- Suitable for presenting Stretched-Annealed.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Work Density ' + '$\it{WD}$ ' + '(Nm/kg)', size = 11, x = 1.02)
#plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+
'$\mathregular{[T_{ann}}$ = $\mathregular{(5.2)T_{0}]}$ ' + ' Logistic Sigmoidal Fit to Work
Density Data', size = 13, y = 1.02)
#plt.legend(prop = {"size": 8})
#plt.grid(True)
# 11c. Strain Title [Stretched-Annealed]: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 0.75)) #- Suitable for presenting Stretched-Annealed.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Strain ' + '$\it{ε}$ ' + '(Nm/kg)', size = 11, x = 1.02)
#plt.title('$\mathregular{[l_{i}}$ = $\mathregular{(1.5)L_{0}]}$ '+
'$\mathregular{[T_{ann}}$ = $\mathregular{(5.2)T_{0}]}$ ' + ' Logistic Sigmoidal Fit to
Strain Data', size = 13, y = 1.02)
#plt.legend(prop = {"size": 8})
#plt.grid(True)
# 12a. Derivatives of the sigmoids' series to be plotted in the 2nd subplot:
plt.subplot(2, 1, 2)
plt.plot(x_fit, dy_dx_fit300, '--', color = 'black', label = f'$m_{"w"}$ = $300m_{"f"}$')
plt.plot(x_fit, dy_dx_fit250, '--', color = 'purple', label = f'$m_{"w"}$ = $250m_{"f"}$')
plt.plot(x_fit, dy_dx_fit200, '--', color = 'red', label = f'$m_{"w"}$ = $200m_{"f"}$')
plt.plot(x_fit, dy_dx_fit150, '--', color = 'darkorange', label = f'$m_{"w"}$ =
$150m_{"f"}$')
plt.plot(x_fit, dy_dx_fit100, '--', color = 'gold', label = f'$m_{"w"}$ = $100m_{"f"}$')
plt.plot(x_fit, dy_dx_fit50, '--', color = 'green', label = f'$m_{"w"}$ = $50m_{"f"}$')
# 12b. Derivative Subplot Work Density Title: >USER SELECTION REQUIRED<
plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
plt.xlim((25, 130))
plt.ylim((0, 10)) #- Suitable for presenting Stretched: USER SELECTION REQUIRED.
#plt.ylim((0, 15)) #- Suitable for presenting Stretched-Annealed: USER SELECTION REQUIRED.
plt.xticks(np.arange(25, 130, 15.0))
plt.ylabel('Rate of Change ' + '$\it{ΔWD/ΔT}$ ' + '(Nm/kg°C)', size = 11, x = 1.02)
plt.legend(prop = {"size": 10})
plt.title('Work Density Rates (Derivatives of Characteristic Sigmoids)', size = 13, y =
1.02)
plt.grid(True)
# 12b. Derivative Subplot Strain Title: >USER SELECTION REQUIRED<
#plt.xlabel('Temperature (°C)', size = 11, y = 0.97)
#plt.xlim((25, 130))
#plt.ylim((0, 0.035)) #- Suitable for presenting Stretched: USER SELECTION REQUIRED.
#plt.ylim((0, 0.05)) #- Suitable for presenting Stretched-Annealed: USER SELECTION REQUIRED.
#plt.xticks(np.arange(25, 130, 15.0))
#plt.ylabel('Rate of Change ' + '$\it{Δε/T}$ ' + '(Δε/°C)', size = 11, x = 1.02)
#plt.legend(prop = {"size": 8})
#plt.title('Strain Rates (Derivatives of Characteristic Sigmoids)', size = 13, y = 1.02)
#plt.grid(True)
plt.show()
Подробнее здесь: [url]https://stackoverflow.com/questions/78684720/troubleshooting-code-calculate-the-differences-between-mean-max-and-mean-median[/url]
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Код устранения неполадок: рассчитайте разницу между средним-максимальным и средним-медианой на пик в одном и том же набо
Anonymous » » в форуме PythonСРОЧНО: пожалуйста, помогите... Я потратил 2 недели на написание кода с нуля и улучшение его различными способами, пока не возникла последняя проблема.
Мой код предназначен для вычисления двух различия на пик (на набор данных приходится 2 пика,... - 0 Ответы
- 30 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Код устранения неполадок: рассчитайте разницу между средним-максимальным и средним-медианой на пик в одном и том же набо
Anonymous » » в форуме PythonЯ потратил 2 недели на написание кода с нуля и улучшал его различными способами, пока не возникла последняя проблема.
Мой код предназначен для вычисления двух разностей для каждого пика (есть 2 пиков на набор данных, одновременно анализируются 6... - 0 Ответы
- 38 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Ошибка сокета [WinError 10054] после нескольких попыток устранения неполадок
Anonymous » » в форуме PythonЯ столкнулся с проблемой при запуске скрипта Python. Скрипт предназначен для установки соединения через API Telegram, но он постоянно завершается с ошибкой:
Невозможно подключиться из-за проблем с сетью: Ошибка сокета. : Существующее соединение... - 0 Ответы
- 54 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Ошибка сокета [WinError 10054] после нескольких попыток устранения неполадок
Anonymous » » в форуме PythonЯ столкнулся с проблемой при запуске скрипта Python. Скрипт предназначен для установки соединения через API Telegram, но он постоянно завершается с ошибкой:
Невозможно подключиться из-за проблем с сетью: Ошибка сокета. : Существующее соединение... - 0 Ответы
- 24 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Плагин для отключения звука и улучшения устранения неполадок _load_textdomain_just_in_time/doing_it_wrong_run
Anonymous » » в форуме PhpЯ читал, что у многих разработчиков возникают проблемы с новыми улучшениями интернационализации в версии 6.7, из-за которых журнал debug.log переполняется. В наших проектах мы иногда используем плагины, созданные другими разработчиками, и, ожидая,... - 0 Ответы
- 16 Просмотры
-
Последнее сообщение Anonymous
-
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...