• Python动态建模(4)


    上一篇:

    Python动态建模-(3)_Unconquerable&Llxy的博客-CSDN博客modefunc:函数(就是上面定义的write()._write_t、write()._write_t_x、write()._write_t_y、write()._write_t_z四选一)bool布尔值(True、False)------------默认为True,真。...https://blog.csdn.net/html_finder/article/details/126161824

    感谢以下文章和资料作为参考:

    用 Matplotlib 库生成动画图表 - UCloud云社区动画是一种展示现象的有趣方式。相对于静态图表,人类总是容易被动画和交互式图表所吸引。在描述多年来的股票价格、过去十年的气候变化、季节性和趋势等时间序列数据时,动画更有意义,因为我们可以看到特定的参...https://www.ucloud.cn/yun/43671.htmlvideo - FFMPEG No such filter: 'palettegen' - Stack Overflowhttps://stackoverflow.com/questions/34134854/ffmpeg-no-such-filter-palettegenhttps://www.lfd.uci.edu/~gohlke/pythonlibs/#pythonmagickhttps://www.lfd.uci.edu/~gohlke/pythonlibs/#pythonmagick【Python】图片处理之“PythonMagick”库简易安装笔记_蛙鳜鸡鹳狸猿的博客-CSDN博客_pythonmagick“ImageMagick”可以说是开源的代码/命令行版PS,它支持包括创建、编辑、构图再到格式转换的图片处理功能。更重要的是,它几乎完整支持大部分编程语言,其中Python的接口库就是“PythonMagick”了。具体参考http://www.imagemagick.org/script/index.php。以下整理了“PythonMagick”库在各操作环境的简易安装方法。①RPM式https://blog.csdn.net/sweeper_freedoman/article/details/52994690【Python】批量直接修改图片存储大小脚本_蛙鳜鸡鹳狸猿的博客-CSDN博客对图片的处理有的情况下是对存储大小而非纵横的“width&height”有要求,这种对图片文件磁盘存储大小修改的工作也往往是批量的。借助Python通过“PythonMagick”库(参考:http://blog.csdn.net/sweeper_freedoman/article/details/52994690)可以实现需求。脚本简单如下。# !/usr/bin/python#https://blog.csdn.net/sweeper_freedoman/article/details/53000520Python调用“ImageMagick”:图片格式转换、尺寸修改、属性重构及加水印_蛙鳜鸡鹳狸猿的博客-CSDN博客      “ImageMagick”的Python库是“PythonMagick”,如之前的博文(http://blog.csdn.net/sweeper_freedoman/article/details/53000520,http://blog.csdn.net/sweeper_freedoman/article/details/53000145),有借用“PythonMagick”写过...https://blog.csdn.net/sweeper_freedoman/article/details/69789307

    现在明白了:缺少animation.save函数,并且在调用ImageMagick和ffmpeg库(matplotlib依赖)时出错。

    让我们解决一下...

    1)关于上次报的Warning:

    使用animation.save函数保存动态图表。

    所以马上就能解决了

    问题非常多,而且难以解决。

    至此为止,我们的项目结束了破产了

    这是完整的代码,其实基本功能都已经实现,关键在导出为图表的部分。各位大神可以以此为基础改进完善。

    1. # coding=utf-8
    2. __author__ = "Unconquerable&Llxy"
    3. __name__ = "3DGraphic_With_Formula"
    4. import sympy
    5. from tkinter.messagebox import *
    6. from tkinter import *
    7. from math import *
    8. import matplotlib.pyplot as plt
    9. from mpl_toolkits.mplot3d import Axes3D
    10. import matplotlib.animation as animation
    11. def no_ans():
    12. Tk().geometry("9x9+990000+999999")
    13. showerror("警告", "方程无解析解")
    14. x = []
    15. y = []
    16. z = []
    17. t = []
    18. def toLeg(fx):
    19. v = str(fx).split("\n")
    20. val = []
    21. for i in v:
    22. tv = i.split("=")
    23. length = len(tv)
    24. last = None
    25. while length != 0:
    26. if length == 2:
    27. val.append('='.join(tv))
    28. break
    29. if length == 1:
    30. val.append('='.join([tv[0], str(last)]))
    31. break
    32. val.append('='.join([tv[-2], tv[-1]]))
    33. length = length - 1
    34. last = tv[-1]
    35. tv.pop()
    36. return '\n'.join(val)
    37. def legalSet(fx):
    38. v = str(fx).split("\n")
    39. nw = []
    40. for l in v:
    41. tmpstr = ""
    42. tmpstr2 = ""
    43. if l == '': continue
    44. k = l.split("=")
    45. tmpstr += "((" + k[0] + ")-(" + k[1] + "))"
    46. tmpstr2 += "((" + k[1] + ")-(" + k[0] + "))"
    47. tmpstrs = [tmpstr, tmpstr2]
    48. nw.append(tmpstrs)
    49. v = nw
    50. del nw
    51. index = -1
    52. for i in v:
    53. index += 1
    54. for j in range(2):
    55. if ":" in i: v[index][j] = i[j].replace(":", "/")
    56. if "^" in i: v[index][j] = i[j].replace("^", "**")
    57. if "÷" in i: v[index][j] = i[j].replace("÷", "/")
    58. if "×" in i: v[index][j] = i[j].replace("×", "*")
    59. if "[" in i: v[index][j] = i[j].replace("[", "(")
    60. if "]" in i: v[index][j] = i[j].replace("]", ")")
    61. if "【" in i: v[index][j] = i[j].replace("【", "(")
    62. if "】" in i: v[index][j] = i[j].replace("】", ")")
    63. if "{" in i: v[index][j] = i[j].replace("{", "(")
    64. if "}" in i: v[index][j] = i[j].replace("}", ")")
    65. if "(" in i: v[index][j] = i[j].replace("(", "(")
    66. if ")" in i: v[index][j] = i[j].replace(")", ")")
    67. newlt = []
    68. lt = []
    69. for j in v:
    70. lt__ = []
    71. news = []
    72. for i_ in j:
    73. new = ""
    74. pos = -1
    75. funcs = []
    76. for i in i_:
    77. pos += 1
    78. tmpos = pos + 0
    79. string = ""
    80. while i_[tmpos].isalpha():
    81. string += i_[tmpos]
    82. tmpos = tmpos + 1
    83. if string in sympy.__all__:
    84. funcs += [i for i in range(pos, tmpos + 1)]
    85. if ((i.isalpha() or i == "(") and (i_[pos - 1].isnumeric() or i_[pos - 1].isalpha())
    86. and pos != 0 and pos not in funcs):
    87. new += "*" + " " + i
    88. else:
    89. if (i.isalpha() and pos not in funcs):
    90. new += " " + i
    91. else:
    92. new += i
    93. if i.isalpha() and pos not in funcs:
    94. lt__.append(i)
    95. news.append(new)
    96. lt__ = list(set(lt__))
    97. lt.append(lt__)
    98. newlt.append(news)
    99. return newlt, lt
    100. def sqrt(base, times=2):
    101. if base < 0:
    102. ans = (-base) ** (1 / times)
    103. return eval(f"{ans}j")
    104. return base ** (1 / times)
    105. class write:
    106. def _write_t_x(self, formula, tmin_=-10, tmax_=10, tnums=100,
    107. min_=-10, max_=10, nums=100, printout=True):
    108. global x, y, z, t
    109. self.step = (tmax_ - tmin_) / tnums
    110. self.aa = tmin_ - self.step
    111. self.xstep = (max_ - min_) / nums
    112. r"""
    113. print(un)
    114. print(lf,toLeg(formula),sep="\n\n",end="\n\n")
    115. """
    116. solves = []
    117. for iVal in range(tnums + 1):
    118. self.aa = self.aa + self.step
    119. self.aa = float("%.10f" % self.aa)
    120. xValue = min_ - self.xstep
    121. for XVAL in range(nums + 1):
    122. lf, un = legalSet(toLeg(formula))
    123. xValue += self.xstep
    124. xValue = float("%.10f" % xValue)
    125. def key(item):
    126. if "t" in item[0] or "x" in item[0]:
    127. return 1
    128. else:
    129. return 999
    130. bf = dict(enumerate(lf))
    131. lf = sorted(lf, key=key)
    132. nun = []
    133. for i in range(len(lf)):
    134. nun.insert(lf.index(bf[i]), un[i])
    135. un = nun
    136. del nun
    137. idx = -1
    138. for imp in un:
    139. idx += 1
    140. for __imp in imp:
    141. if __imp == 't':
    142. un[idx].remove("t")
    143. if __imp == 'x':
    144. un[idx].remove("x")
    145. del idx
    146. repl = {"t": [str(self.aa)], "x": [str(xValue)]}
    147. is_exit = False
    148. times = -1
    149. while not is_exit:
    150. times += 1
    151. if times >= 10:
    152. # print(f"\nmessage:目前已经循环求解超过10次,目前初始代入值为:x{repl['x']},t{repl['t']},\n"
    153. # f"已经求解{repl},剩{4-len(repl.values())}值不可求解,故不予求解并跳出循环")
    154. break
    155. indx = -1
    156. for lf_ in lf:
    157. indx += 1
    158. for i in repl.keys():
    159. for j in range(2):
    160. lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))
    161. idx = -1
    162. for imp in un:
    163. idx += 1
    164. for __imp in imp:
    165. if __imp in repl.keys():
    166. un[idx].remove(__imp)
    167. del idx
    168. if un[indx] == []:
    169. del un[indx]
    170. del lf[indx]
    171. if indx == 0 or (indx - 1) >= len(lf): break
    172. indx -= 1
    173. continue
    174. try:
    175. ams = sympy.solve(tuple(lf_), tuple(un[indx]))
    176. if ams == []:
    177. newlf = []
    178. for i in lf_:
    179. newlf.append(i.replace(str(repl["x"]), str(repl["x"]) + "*sympy.I"))
    180. ams = sympy.solve(tuple(newlf), tuple(un[indx]))
    181. except NotImplementedError as err:
    182. print(err)
    183. no_ans()
    184. return
    185. if isinstance(ams, (dict,)):
    186. for km, jj in ams.items():
    187. if not ('x' in str(jj) or
    188. 'y' in str(jj) or
    189. 'z' in str(jj) or
    190. 't' in str(jj)):
    191. if km.name in repl.keys():
    192. repl[km.name].append(str(jj))
    193. else:
    194. repl[km.name] = [str(jj)]
    195. else:
    196. ix = -1
    197. undo = 0
    198. for i in ams:
    199. ix += 1
    200. try:
    201. if isinstance(i, (sympy.core.numbers.Float,
    202. sympy.core.numbers.Integer,
    203. int, float, complex)):
    204. try:
    205. repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
    206. except IndexError:
    207. repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
    208. for i in repl.keys():
    209. if i in lf_:
    210. lf_ = lf_.replace(i, str(repl[i][0]))
    211. elif isinstance(i, (tuple, list, set)):
    212. inxx = -1
    213. for jj in i:
    214. inxx += 1
    215. if not ('x' in str(jj) or
    216. 'y' in str(jj) or
    217. 'z' in str(jj) or
    218. 't' in str(jj)):
    219. try:
    220. repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
    221. except IndexError:
    222. repl[tuple(un[indx][inxx])[undo]].append(str(jj))
    223. else:
    224. continue
    225. except TypeError as err:
    226. print("get:err", err)
    227. continue
    228. else:
    229. undo = ix
    230. if len(repl.values()) >= 4: is_exit = True;break
    231. if is_exit:
    232. solves.append(repl)
    233. if printout:
    234. print(f"\r{(iVal * (nums + 1) + XVAL + 1) / ((nums + 1) * (tnums + 1)) * 100}%", end="",
    235. flush=True)
    236. if printout:
    237. print("\nsucceed in Calculating Values...")
    238. num = 0
    239. for i in solves:
    240. if printout:
    241. print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)
    242. num += 1
    243. x_ = []
    244. for j in i["x"]:
    245. x_.append(eval(j))
    246. x.append(x_)
    247. y_ = []
    248. for j in i["y"]:
    249. y_.append(eval(j))
    250. y.append(y_)
    251. z_ = []
    252. for j in i["z"]:
    253. z_.append(eval(j))
    254. z.append(z_)
    255. t_ = []
    256. for j in i["t"]:
    257. t_.append(eval(j))
    258. t.append(t_)
    259. del x_, y_, z_, t_, solves
    260. if printout:
    261. print("\nsucceed in Saving Values...")
    262. def _write_t_y(self, formula, tmin_=-10, tmax_=10, tnums=100,
    263. min_=-10, max_=10, nums=100, printout=True):
    264. global x, y, z, t
    265. self.step = (tmax_ - tmin_) / tnums
    266. self.aa = tmin_ - self.step
    267. self.xstep = (max_ - min_) / nums
    268. r"""
    269. print(un)
    270. print(lf,toLeg(formula),sep="\n\n",end="\n\n")
    271. """
    272. solves = []
    273. for iVal in range(tnums + 1):
    274. self.aa = self.aa + self.step
    275. self.aa = float("%.10f" % self.aa)
    276. xValue = min_ - self.xstep
    277. for XVAL in range(nums + 1):
    278. lf, un = legalSet(toLeg(formula))
    279. xValue += self.xstep
    280. xValue = float("%.10f" % xValue)
    281. def key(item):
    282. if "t" in item[0] or "y" in item[0]:
    283. return 1
    284. else:
    285. return 999
    286. bf = dict(enumerate(lf))
    287. lf = sorted(lf, key=key)
    288. nun = []
    289. for i in range(len(lf)):
    290. nun.insert(lf.index(bf[i]), un[i])
    291. un = nun
    292. del nun
    293. idx = -1
    294. for imp in un:
    295. idx += 1
    296. for __imp in imp:
    297. if __imp == 't':
    298. un[idx].remove("t")
    299. if __imp == 'y':
    300. un[idx].remove("x")
    301. del idx
    302. repl = {"t": [str(self.aa)], "y": [str(xValue)]}
    303. is_exit = False
    304. times = -1
    305. while not is_exit:
    306. times += 1
    307. if times >= 20:
    308. print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:y{repl['y']},t{repl['t']},\n"
    309. f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")
    310. break
    311. indx = -1
    312. for lf_ in lf:
    313. indx += 1
    314. for i in repl.keys():
    315. for j in range(2):
    316. lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))
    317. idx = -1
    318. for imp in un:
    319. idx += 1
    320. for __imp in imp:
    321. if __imp in repl.keys():
    322. un[idx].remove(__imp)
    323. del idx
    324. if un[indx] == []:
    325. del un[indx]
    326. del lf[indx]
    327. if indx == 0 or (indx - 1) >= len(lf): break
    328. indx -= 1
    329. continue
    330. try:
    331. ams = sympy.solve(tuple(lf_), tuple(un[indx]))
    332. if ams == []:
    333. newlf = []
    334. for i in lf_:
    335. newlf.append(i.replace(str(repl["y"]), str(repl["y"]) + "*sympy.I"))
    336. ams = sympy.solve(tuple(newlf), tuple(un[indx]))
    337. except NotImplementedError as err:
    338. print(err)
    339. no_ans()
    340. return
    341. if isinstance(ams, (dict,)):
    342. for km, jj in ams.items():
    343. if not ('x' in str(jj) or
    344. 'y' in str(jj) or
    345. 'z' in str(jj) or
    346. 't' in str(jj)):
    347. if km.name in repl.keys():
    348. repl[km.name].append(str(jj))
    349. else:
    350. repl[km.name] = [str(jj)]
    351. else:
    352. ix = -1
    353. undo = 0
    354. for i in ams:
    355. ix += 1
    356. try:
    357. if isinstance(i, (sympy.core.numbers.Float,
    358. sympy.core.numbers.Integer,
    359. int, float, complex)):
    360. try:
    361. repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
    362. except IndexError:
    363. repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
    364. for i in repl.keys():
    365. if i in lf_:
    366. lf_ = lf_.replace(i, str(repl[i][0]))
    367. elif isinstance(i, (tuple, list, set)):
    368. inxx = -1
    369. for jj in i:
    370. inxx += 1
    371. if not ('x' in str(jj) or
    372. 'y' in str(jj) or
    373. 'z' in str(jj) or
    374. 't' in str(jj)):
    375. try:
    376. repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
    377. except IndexError:
    378. repl[tuple(un[indx][inxx])[undo]].append(str(jj))
    379. else:
    380. continue
    381. except TypeError as err:
    382. print("get:err", err)
    383. continue
    384. else:
    385. undo = ix
    386. if len(repl.values()) >= 4: is_exit = True;break
    387. if is_exit:
    388. solves.append(repl)
    389. if printout:
    390. print(f"\r{(iVal * (nums + 1) + XVAL + 1) / ((nums + 1) * (tnums + 1)) * 100}%", end="",
    391. flush=True)
    392. if printout:
    393. print("\nsucceed in Calculating Values...")
    394. num = 0
    395. for i in solves:
    396. if printout:
    397. print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)
    398. num += 1
    399. x_ = []
    400. for j in i["x"]:
    401. x_.append(eval(j))
    402. x.append(x_)
    403. y_ = []
    404. for j in i["y"]:
    405. y_.append(eval(j))
    406. y.append(y_)
    407. z_ = []
    408. for j in i["z"]:
    409. z_.append(eval(j))
    410. z.append(z_)
    411. t_ = []
    412. for j in i["t"]:
    413. t_.append(eval(j))
    414. t.append(t_)
    415. del x_, y_, z_, t_, solves
    416. if printout:
    417. print("\nsucceed in Saving Values...")
    418. def _write_t_z(self, formula, tmin_=-10, tmax_=10, tnums=100,
    419. min_=-10, max_=10, nums=100, printout=True):
    420. global x, y, z, t
    421. self.step = (tmax_ - tmin_) / tnums
    422. self.aa = tmin_ - self.step
    423. self.xstep = (max_ - min_) / nums
    424. r"""
    425. print(un)
    426. print(lf,toLeg(formula),sep="\n\n",end="\n\n")
    427. """
    428. solves = []
    429. for iVal in range(tnums + 1):
    430. self.aa = self.aa + self.step
    431. self.aa = float("%.10f" % self.aa)
    432. xValue = min_ - self.xstep
    433. for XVAL in range(nums + 1):
    434. lf, un = legalSet(toLeg(formula))
    435. xValue += self.xstep
    436. xValue = float("%.10f" % xValue)
    437. def key(item):
    438. if "t" in item[0] or "z" in item[0]:
    439. return 1
    440. else:
    441. return 999
    442. bf = dict(enumerate(lf))
    443. lf = sorted(lf, key=key)
    444. nun = []
    445. for i in range(len(lf)):
    446. nun.insert(lf.index(bf[i]), un[i])
    447. un = nun
    448. del nun
    449. idx = -1
    450. for imp in un:
    451. idx += 1
    452. for __imp in imp:
    453. if __imp == 't':
    454. un[idx].remove("t")
    455. if __imp == 'z':
    456. un[idx].remove("z")
    457. del idx
    458. repl = {"t": [str(self.aa)], "z": [str(xValue)]}
    459. is_exit = False
    460. times = -1
    461. while not is_exit:
    462. times += 1
    463. if times >= 20:
    464. print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:z{repl['z']},t{repl['t']},\n"
    465. f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")
    466. break
    467. indx = -1
    468. for lf_ in lf:
    469. indx += 1
    470. for i in repl.keys():
    471. for j in range(2):
    472. lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))
    473. idx = -1
    474. for imp in un:
    475. idx += 1
    476. for __imp in imp:
    477. if __imp in repl.keys():
    478. un[idx].remove(__imp)
    479. del idx
    480. if un[indx] == []:
    481. del un[indx]
    482. del lf[indx]
    483. if indx == 0 or (indx - 1) >= len(lf): break
    484. indx -= 1
    485. continue
    486. try:
    487. ams = sympy.solve(tuple(lf_), tuple(un[indx]))
    488. if ams == []:
    489. newlf = []
    490. for i in lf_:
    491. newlf.append(i.replace(str(repl["z"]), str(repl["z"]) + "*sympy.I"))
    492. ams = sympy.solve(tuple(newlf), tuple(un[indx]))
    493. except NotImplementedError as err:
    494. print(err)
    495. no_ans()
    496. return
    497. if isinstance(ams, (dict,)):
    498. for km, jj in ams.items():
    499. if not ('x' in str(jj) or
    500. 'y' in str(jj) or
    501. 'z' in str(jj) or
    502. 't' in str(jj)):
    503. if km.name in repl.keys():
    504. repl[km.name].append(str(jj))
    505. else:
    506. repl[km.name] = [str(jj)]
    507. else:
    508. ix = -1
    509. undo = 0
    510. for i in ams:
    511. ix += 1
    512. try:
    513. if isinstance(i, (sympy.core.numbers.Float,
    514. sympy.core.numbers.Integer,
    515. int, float, complex)):
    516. try:
    517. repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
    518. except IndexError:
    519. repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
    520. for i in repl.keys():
    521. if i in lf_:
    522. lf_ = lf_.replace(i, str(repl[i][0]))
    523. elif isinstance(i, (tuple, list, set)):
    524. inxx = -1
    525. for jj in i:
    526. inxx += 1
    527. if not ('x' in str(jj) or
    528. 'y' in str(jj) or
    529. 'z' in str(jj) or
    530. 't' in str(jj)):
    531. try:
    532. repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
    533. except IndexError:
    534. repl[tuple(un[indx][inxx])[undo]].append(str(jj))
    535. else:
    536. continue
    537. except TypeError as err:
    538. print("get:err", err)
    539. continue
    540. else:
    541. undo = ix
    542. if len(repl.values()) >= 4: is_exit = True;break
    543. if is_exit:
    544. solves.append(repl)
    545. if printout:
    546. print(f"\r{(iVal * (nums + 1) + XVAL + 1) / ((nums + 1) * (tnums + 1)) * 100}%", end="",
    547. flush=True)
    548. if printout:
    549. print("\nsucceed in Calculating Values...")
    550. num = 0
    551. for i in solves:
    552. if printout:
    553. print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)
    554. num += 1
    555. x_ = []
    556. for j in i["x"]:
    557. x_.append(eval(j))
    558. x.append(x_)
    559. y_ = []
    560. for j in i["y"]:
    561. y_.append(eval(j))
    562. y.append(y_)
    563. z_ = []
    564. for j in i["z"]:
    565. z_.append(eval(j))
    566. z.append(z_)
    567. t_ = []
    568. for j in i["t"]:
    569. t_.append(eval(j))
    570. t.append(t_)
    571. del x_, y_, z_, t_, solves
    572. if printout:
    573. print("\nsucceed in Saving Values...")
    574. def _write_t(self, formula, tmin_=-10, tmax_=10, tnums=100, printout=True):
    575. global x, y, z, t
    576. I = 1j
    577. oo = inf
    578. self.step = (tmax_ - tmin_) / tnums
    579. self.aa = tmin_ - self.step
    580. r"""
    581. print(un)
    582. print(lf,toLeg(formula),sep="\n\n",end="\n\n")
    583. """
    584. solves = []
    585. for iVal in range(tnums + 1):
    586. self.aa = self.aa + self.step
    587. self.aa = float("%.10f" % self.aa)
    588. lf, un = legalSet(toLeg(formula))
    589. def key(item):
    590. if "t" in item[0]:
    591. return 1
    592. else:
    593. return 999
    594. bf = dict(enumerate(lf))
    595. lf = sorted(lf, key=key)
    596. nun = []
    597. for i in range(len(lf)):
    598. nun.insert(lf.index(bf[i]), un[i])
    599. un = nun
    600. del nun
    601. idx = -1
    602. for imp in un:
    603. idx += 1
    604. for __imp in imp:
    605. if __imp == 't':
    606. un[idx].remove("t")
    607. del idx
    608. repl = {"t": [str(self.aa)]}
    609. is_exit = False
    610. times = -1
    611. while not is_exit:
    612. times += 1
    613. if times >= 20:
    614. print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:t{repl['t']},\n"
    615. f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")
    616. break
    617. indx = -1
    618. for lf_ in lf:
    619. indx += 1
    620. for i in repl.keys():
    621. for j in range(2):
    622. if str(i) in str(lf_[j]):
    623. lf_[j] = lf_[j].replace(i, str(repl[i][0]))
    624. idx = -1
    625. for imp in un:
    626. idx += 1
    627. for __imp in imp:
    628. if __imp in repl.keys():
    629. un[idx].remove(__imp)
    630. del idx
    631. if un[indx] == []:
    632. del un[indx]
    633. del lf[indx]
    634. if indx == 0 or (indx - 1) >= len(lf): break
    635. indx -= 1
    636. continue
    637. try:
    638. ams = sympy.solve(tuple(lf_), tuple(un[indx]))
    639. except NotImplementedError as err:
    640. print(err)
    641. no_ans()
    642. return
    643. if isinstance(ams, (dict,)):
    644. for km, jj in ams.items():
    645. if not ('x' in str(jj) or
    646. 'y' in str(jj) or
    647. 'z' in str(jj) or
    648. 't' in str(jj)):
    649. if km.name in repl.keys():
    650. repl[km.name].append(str(jj))
    651. else:
    652. repl[km.name] = [str(jj)]
    653. else:
    654. ix = -1
    655. undo = 0
    656. for i in ams:
    657. ix += 1
    658. try:
    659. if isinstance(i, (sympy.core.numbers.Float,
    660. sympy.core.numbers.Integer,
    661. int, float, complex)):
    662. try:
    663. repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
    664. except IndexError:
    665. repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
    666. for i in repl.keys():
    667. if i in lf_:
    668. lf_ = lf_.replace(i, str(repl[i][0]))
    669. elif isinstance(i, (tuple, list, set)):
    670. inxx = -1
    671. for jj in i:
    672. inxx += 1
    673. if not ('x' in str(jj) or
    674. 'y' in str(jj) or
    675. 'z' in str(jj) or
    676. 't' in str(jj)):
    677. try:
    678. repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
    679. except IndexError:
    680. repl[tuple(un[indx][inxx])[undo]].append(str(jj))
    681. else:
    682. continue
    683. except TypeError as err:
    684. print("get:err", err)
    685. continue
    686. else:
    687. undo = ix
    688. if len(repl.values()) >= 4: is_exit = True;break
    689. if is_exit:
    690. solves.append(repl)
    691. if printout:
    692. print(f"\r{(iVal + 1) / (tnums + 1) * 100}%", end="",
    693. flush=True)
    694. if printout:
    695. print("\nsucceed in Calculating Values...")
    696. num = 0
    697. for i in solves:
    698. if printout:
    699. print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)
    700. num += 1
    701. x_ = []
    702. for j in i["x"]:
    703. x_.append(eval(j))
    704. x.append(x_)
    705. y_ = []
    706. for j in i["y"]:
    707. y_.append(eval(j))
    708. y.append(y_)
    709. z_ = []
    710. for j in i["z"]:
    711. z_.append(eval(j))
    712. z.append(z_)
    713. t_ = []
    714. for j in i["t"]:
    715. t_.append(eval(j))
    716. t.append(t_)
    717. del x_, y_, z_, t_, solves
    718. if printout:
    719. print("\nsucceed in Saving Values...")
    720. def format():
    721. global x,y,z,t
    722. nx={}
    723. ny={}
    724. nz={}
    725. nt=[]
    726. vx=[]
    727. vy=[]
    728. vz=[]
    729. for i,j,k,v in zip(x,y,z,t):
    730. for it,jt,kt,vt in zip(i,j,k,v):
    731. if vt not in nx.keys():
    732. nx[vt]=[]
    733. if vt not in ny.keys():
    734. ny[vt]=[]
    735. if vt not in nz.keys():
    736. nz[vt]=[]
    737. nx[vt].append(it)
    738. ny[vt].append(jt)
    739. nz[vt].append(kt)
    740. nt.append(vt)
    741. nt.sort()
    742. for num in set(nt):
    743. for i,j,k in zip(nx[num],ny[num],nz[num]):
    744. vx.append(i)
    745. vy.append(j)
    746. vz.append(k)
    747. x=vx
    748. y=vy
    749. z=vz
    750. t=nt
    751. def create_img(tnum, fig=None, ax=None):
    752. global x, y, z, t
    753. if fig is None:
    754. fig = plt.figure()
    755. if ax is None:
    756. ax = Axes3D(fig)
    757. ax.legend(loc='best')
    758. ax.axis('off')
    759. if isinstance(tnum, list):
    760. tnum = tnum[0]
    761. ax.cla()
    762. x1 = []
    763. y1 = []
    764. z1 = []
    765. try:
    766. i = t.index(tnum)
    767. except (IndexError, ValueError) as err:
    768. i = 0
    769. try:
    770. while t[i] == tnum:
    771. if isinstance(x[i], (tuple, list, set)):
    772. x[i] = x[i][0]
    773. if isinstance(x[i], complex):
    774. i += 1
    775. continue
    776. if isinstance(y[i], (tuple, list, set)):
    777. y[i] = y[i][0]
    778. if isinstance(y[i], complex):
    779. i += 1
    780. continue
    781. if isinstance(z[i], (tuple, list, set)):
    782. z[i] = z[i][0]
    783. if isinstance(z[i], complex):
    784. i += 1
    785. continue
    786. x1.append(x[i])
    787. y1.append(y[i])
    788. z1.append(z[i])
    789. i += 1
    790. except IndexError:
    791. pass
    792. scatter = ax.scatter(x1, y1, z1, c='r')
    793. return scatter,
    794. # plt.savefig('./1.jpg',)
    795. def Graphic_main(formula, modefunc, tmin_=-10, tmax_=10, tnums=100,
    796. min_=-10, max_=10, nums=100, printout=True):
    797. global x, y, z, t
    798. try:
    799. modefunc(formula=formula, tmin_=tmin_, tmax_=tmax_, tnums=tnums,
    800. min_=min_, max_=max_, nums=nums, printout=printout)
    801. except Exception:
    802. modefunc(formula=formula, tmin_=tmin_, tmax_=tmax_, tnums=tnums, printout=printout)
    803. format()
    804. fig = plt.figure()
    805. ax = Axes3D(fig, auto_add_to_figure=False)
    806. print(min(x),min(y),min(z),"\n",max(x),max(y),max(z))
    807. ax.set_ylim(min(y),max(y))
    808. ax.set_xlim(xmin=min(x), xmax=max(x))
    809. ax.set_zlim(zmin=min(z), zmax=max(z))
    810. fig.add_axes(ax)
    811. # ax.legend(loc="best")
    812. def demo(num):
    813. a = tmin_ + ((tmax_ - tmin_) / tnums) * (num % tnums)
    814. print(f"\rwait:{num-tnums}/{tnums}",end="")
    815. return create_img(a, fig, ax),
    816. ani = animation.FuncAnimation(fig, demo, fargs=[],
    817. interval=int(((tmax_ - tmin_) / tnums) * 1000))
    818. ani.save('test.mp4')
    819. # 调试部分
    820. print("program running")
    821. """write()._write_t_x("z=t\n3x+y=z\nx=sin(y)",tnums=100,
    822. printout=True)
    823. print(t)
    824. create_img([0.0])"""
    825. Graphic_main("sin(x)=y\nz=t\ncos(y)=z", modefunc=write()._write_t_x, tnums=10, nums=10)
    826. print("end...")

    再次感谢各位的观看!

    ---------------------------------【完】--------------------------------------

  • 相关阅读:
    Agile Development
    使用 Selenium 或其他工具模拟浏览器使用及语法代码
    计算机毕业设计Java交通事故档案管理系统(源码+mysql数据库+系统+lw文档)
    PowerCLi 一键批量部署OVA 到esxi 7
    nodejs+vue+python+PHP+微信小程序南七街道志愿者服务平台的设计与实现-计算机毕业设计推荐
    C#中使用python(基于Process-C#自带库)
    视频监控/视频汇聚/视频云存储EasyCVR平台接入华为ivs3800平台提示400报错,该如何解决?
    Linux文件和文件夹命令详解
    java-php-python-ssm网上商城系统计算机毕业设计
    大白话讲清搞好就能“年薪百万”的SpringCloud微服务
  • 原文地址:https://blog.csdn.net/html_finder/article/details/126284437