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
| import numpy as np from scipy.optimize import leastsq
def func_sin(x, p): a, f, theta, c = p return a * np.sin(2 * np.pi * f * x + theta) + c
def error_sin(p0, x, y): return y - func_sin(x, p0)
def fit_sin(x, y, p, t, flag, max_fev=500): x_sample = np.array(x) y_sample = np.array(y) x_max = max(x_sample)
p0 = np.array(p) para = leastsq(error_sin, p0, args=(x_sample, y_sample), maxfev=max_fev)
a1, a2, a3, a4 = para[0] a1 = round(float(a1), 3) a2 = round(float(a2), 3) a3 = round(float(a3), 3) a4 = round(float(a4), 3)
tmp = a1 / (2*np.pi*a2) temp_x = x_max + t lower = - tmp - tmp*np.cos(2*np.pi*a2*x_max + a3) + a4*x_max upper = - tmp - tmp*np.cos(2*np.pi*a2*temp_x + a3) + a4*temp_x result = round((upper-lower), 3)
if flag: return [a1, a2, a3, a4], result else: return result
def func_c(x, c): return c * np.ones(x.shape)
def error_c(p, x, y): return y - func_c(x, p)
def fit_c(x, y, p, t, flag, max_fev=500): x_sample = np.array(x) y_sample =np.array(y) para = leastsq(error_c, p, args=(x_sample, y_sample), maxfev=max_fev) a = round(float(para[0]), 3) result = round(t*a, 3) if flag: return a, result else: print("拟合结果: y_c =", a) return result
def read(sentence, quantity): assert quantity > 0 sentence_error = "格式错误, 请按照要求重新输入: " inf = [] try: inf = list(map(float, input(sentence).split())) while len(inf) != quantity: inf = list(map(float, input(sentence_error).split())) except ValueError: while True: try: inf = list(map(float, input(sentence_error).split())) while len(inf) != quantity: inf = list(map(float, input(sentence_error).split())) break except ValueError: continue
if quantity == 1: return inf[0] else: return inf
if __name__ == "__main__":
from sympy import * from matplotlib import pyplot as plt import time
sentence_1 = "请用空格分割, 按顺序输入希望的测试点 数目 & 横坐标最小值 & 横坐标最大值 & 横坐标分度值(如:15 -3.14 0 0.1): " sentence_2 = "输入w测试正弦模型, e测试直线模型, 其它键取消测试: " sentence_3 = "请用空格分割, 请按顺序输入正弦模型y = Asin(2πf*t+Θ)+c的四个参数A,f,Θ,c的真实值: " sentence_4 = "请用空格分割, 输入参数A,f,Θ,c的拟合初值: " sentence_5 = "请输入直线模型y = c中参数c的真实值: " sentence_6 = "请输入参数c的拟合初值: " sentence_7 = "请输入预测时长(单位:s): " sentence_8 = "分度值不可为0, 请重新输入: " sentence_9 = "请输入拟合次数上限: "
x_samples, y_samples, x_fit, y_fit = [], [], [], []
info = read(sentence_1, 4) if info[3] == 0: info = read(sentence_8, 4) amount, x_min, x_max, x_division = int(info[0]), info[1], info[2], info[3]
key = input(sentence_2)
if key == 'w': a, f, theta, c = read(sentence_3, 4) p0 = read(sentence_4, 4) x_samples = np.linspace(x_min, x_max, amount) y_origin = func_sin(x_samples, [a, f, theta, c]) y_samples = y_origin + 0.8 * np.random.randn(amount) t = read(sentence_7, 1) max_fev = int(read(sentence_9, 1))
time_1 = time.time() paras, result = fit_sin(x_samples, y_samples, p0, t, true, max_fev) time_2 = time.time()
x_t = symbols("x") expr = paras[0] * sin(round(2 * np.pi * paras[1], 3) * x_t + paras[2]) + paras[3]
print("\n模型: y = Asin(2πf*t+Θ)+c") print("样本点:\nx={}\ny(无噪声)={}\ny(含噪声)={}".format(x_samples, y_origin, y_samples)) print("函数原型参数: ", [a, f, theta, c]) print("拟合初值: ", p0) print("拟合结果: ", paras) print("拟合表达式: y =", expr) print("拟合耗时: {} ms".format(round((time_2-time_1)*1000, 3))) print("积分区间: [{}, {}]".format(x_max, x_max+t)) print("积分值: ", result)
if x_max > 0: x_fit = np.arange(x_min, 2*(x_max+t), x_division) x_bound = np.array([x_min, 2*(x_max+t)]) else: x_fit = np.arange(x_min, abs(-x_max+2*t), x_division) x_bound = np.array([x_min, abs(-x_max+2*t)])
y_fit = func_sin(x_fit, paras) y_bound = np.array([c, c])
plt.figure(figsize=(8, 6)) plt.scatter(x_samples, y_samples, color='red', label='Sample Points', linewidth=2) plt.plot(x_samples, y_samples, color='gray', label="Sample Lines", linewidth=2) plt.plot(x_fit, y_fit, color='orange', label="Fitting Line", linewidth=2) plt.plot(x_bound, y_bound, color='gray', linewidth=1, linestyle='--') plt.xlabel("Time") plt.ylabel("Velocity") plt.plot(x_max, func_sin(x_max, paras), "ob", color='blue', label="current") plt.plot(x_max+t, func_sin(x_max+t, paras), "ob", color='purple', label='Prediction')
plt.plot([x_max, x_max], [func_sin(x_max, paras), c], color='blue', linestyle='--') plt.plot([x_max+t, x_max+t], [func_sin(x_max+t, paras), c], color='purple', linestyle='--') x_series = np.linspace(x_max, x_max+t, amount) y_1 = c y_2 = func_sin(x_series, paras) plt.fill_between(x_series, y_1, y_2, facecolor='white', hatch='/', interpolate=true)
plt.legend() plt.show() exit(0)
elif key == 'e': c = read(sentence_5, 1) p0 = read(sentence_6, 1) x_samples = np.linspace(x_min, x_max, amount) y_origin = func_c(x_samples, c) y_samples = y_origin + 0.8 * np.random.randn(amount) t = read(sentence_7, 1) max_fev = int(read(sentence_9, 1))
time_1 = time.time() para, result = fit_c(x_samples, y_samples, p0, t, true, max_fev) time_2 = time.time()
print("\n模型: y = c") print("样本点:\nx={}\ny={}".format(x_samples, y_samples)) print("函数原型参数: ", c) print("拟合初值: ", p0) print("拟合结果: ", para) print("拟合表达式: y =", para) print("拟合耗时: {} ms".format((time_2-time_1)*1000)) print("积分区间: [{}, {}]".format(x_max, x_max+t)) print("积分值: ", result)
if x_max > 0: x_fit = np.arange(x_min, 2*(x_max+t), x_division) x_bound = np.array([x_min, 2.5*(x_max+t)]) else: x_fit = np.arange(x_min, abs(-x_max+2*t), x_division) x_bound = np.array([x_min, 1.25 * abs(-x_max+2*t)])
y_fit = func_c(x_fit, para) y_bound = np.array([c, c])
fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.spines['left'].set_position(('data', x_min)) ax.spines['bottom'].set_position(('data', min(y_samples))) ax.set_xticks(np.arange(min(x_samples), x_max+2*t, 1)) ax.scatter(x_samples, y_samples, color='red', label='Original Points', linewidth=1) plt.plot(x_bound, y_bound, color='green', label='Real Value', linewidth=1) ax.plot(x_fit, y_fit, color='orange', label="Fitting Line", linewidth=2) plt.plot(x_max, func_c(np.array([x_max]), para), "ob", color='blue', label="current") plt.plot(x_max+t, func_c(np.array([x_max+t]), para), "ob", color='purple', label='Prediction') ax.plot([x_max, x_max], [func_c(np.array([x_max]), para), min(y_samples)], color='blue', linestyle='--') ax.plot([x_max+t, x_max+t], [func_c(np.array([x_max+t]), para), min(y_samples)], color='purple', linestyle='--') x_series = np.linspace(x_max, x_max+t, amount) y_1 = min(y_samples) * np.ones(x_series.shape) y_2 = func_c(x_series, para) plt.fill_between(x_series, y_1, y_2, where=y_1<y_2, facecolor='white', hatch='/', interpolate=true) plt.xlabel("Time/s") plt.ylabel("Velocity") plt.legend() plt.show() exit(0)
else: print("已取消测试") exit(0)
|
v1.5.1