首页 >> 大全

Python动态建模(4)

2023-10-03 大全 32 作者:考证青年

动态建模-(3)&Llxy的博客-CSDN博客:函数(就是上面定义的write().、write().、write().、write().四选一)bool布尔值(True、False)------------默认为True,真。...

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

用 库生成动画图表 - 云社区动画是一种展示现象的有趣方式。相对于静态图表,人类总是容易被动画和交互式图表所吸引。在描述多年来的股票价格、过去十年的气候变化、季节性和趋势等时间序列数据时,动画更有意义,因为我们可以看到特定的参...

video - No such : '' - Stack

~//#

~//#【】图片处理之“”库简易安装笔记_蛙鳜鸡鹳狸猿的博客-CSDN博客“”可以说是开源的代码/命令行版PS,它支持包括创建、编辑、构图再到格式转换的图片处理功能。更重要的是,它几乎完整支持大部分编程语言,其中的接口库就是“”了。具体参考。以下整理了“”库在各操作环境的简易安装方法。①RPM式

【】批量直接修改图片存储大小脚本_蛙鳜鸡鹳狸猿的博客-CSDN博客对图片的处理有的情况下是对存储大小而非纵横的“width&”有要求,这种对图片文件磁盘存储大小修改的工作也往往是批量的。借助通过“”库(参考:)可以实现需求。脚本简单如下。# !/usr/bin/#

调用“”:图片格式转换、尺寸修改、属性重构及加水印_蛙鳜鸡鹳狸猿的博客-CSDN博客 “”的库是“”,如之前的博文(,),有借用“”写过...

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

让我们解决一下...

1)关于上次报的:

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

所以马上就能解决了

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

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

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

# coding=utf-8__author__ = "Unconquerable&Llxy"
__name__ = "3DGraphic_With_Formula"import sympy
from tkinter.messagebox import *
from tkinter import *
from math import *import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animationdef no_ans():Tk().geometry("9x9+990000+999999")showerror("警告", "方程无解析解")x = []
y = []
z = []
t = []def toLeg(fx):v = str(fx).split("\n")val = []for i in v:tv = i.split("=")length = len(tv)last = Nonewhile length != 0:if length == 2:val.append('='.join(tv))breakif length == 1:val.append('='.join([tv[0], str(last)]))breakval.append('='.join([tv[-2], tv[-1]]))length = length - 1last = tv[-1]tv.pop()return '\n'.join(val)def legalSet(fx):v = str(fx).split("\n")nw = []for l in v:tmpstr = ""tmpstr2 = ""if l == '': continuek = l.split("=")tmpstr += "((" + k[0] + ")-(" + k[1] + "))"tmpstr2 += "((" + k[1] + ")-(" + k[0] + "))"tmpstrs = [tmpstr, tmpstr2]nw.append(tmpstrs)v = nwdel nwindex = -1for i in v:index += 1for j in range(2):if ":" in i: v[index][j] = i[j].replace(":", "/")if "^" in i: v[index][j] = i[j].replace("^", "**")if "÷" in i: v[index][j] = i[j].replace("÷", "/")if "×" in i: v[index][j] = i[j].replace("×", "*")if "[" in i: v[index][j] = i[j].replace("[", "(")if "]" in i: v[index][j] = i[j].replace("]", ")")if "【" in i: v[index][j] = i[j].replace("【", "(")if "】" in i: v[index][j] = i[j].replace("】", ")")if "{" in i: v[index][j] = i[j].replace("{", "(")if "}" in i: v[index][j] = i[j].replace("}", ")")if "(" in i: v[index][j] = i[j].replace("(", "(")if ")" in i: v[index][j] = i[j].replace(")", ")")newlt = []lt = []for j in v:lt__ = []news = []for i_ in j:new = ""pos = -1funcs = []for i in i_:pos += 1tmpos = pos + 0string = ""while i_[tmpos].isalpha():string += i_[tmpos]tmpos = tmpos + 1if string in sympy.__all__:funcs += [i for i in range(pos, tmpos + 1)]if ((i.isalpha() or i == "(") and (i_[pos - 1].isnumeric() or i_[pos - 1].isalpha())and pos != 0 and pos not in funcs):new += "*" + " " + ielse:if (i.isalpha() and pos not in funcs):new += " " + ielse:new += iif i.isalpha() and pos not in funcs:lt__.append(i)news.append(new)lt__ = list(set(lt__))lt.append(lt__)newlt.append(news)return newlt, ltdef sqrt(base, times=2):if base < 0:ans = (-base) ** (1 / times)return eval(f"{ans}j")return base ** (1 / times)class write:def _write_t_x(self, formula, tmin_=-10, tmax_=10, tnums=100,min_=-10, max_=10, nums=100, printout=True):global x, y, z, tself.step = (tmax_ - tmin_) / tnumsself.aa = tmin_ - self.stepself.xstep = (max_ - min_) / numsr"""print(un)print(lf,toLeg(formula),sep="\n\n",end="\n\n")"""solves = []for iVal in range(tnums + 1):self.aa = self.aa + self.stepself.aa = float("%.10f" % self.aa)xValue = min_ - self.xstepfor XVAL in range(nums + 1):lf, un = legalSet(toLeg(formula))xValue += self.xstepxValue = float("%.10f" % xValue)def key(item):if "t" in item[0] or "x" in item[0]:return 1else:return 999bf = dict(enumerate(lf))lf = sorted(lf, key=key)nun = []for i in range(len(lf)):nun.insert(lf.index(bf[i]), un[i])un = nundel nunidx = -1for imp in un:idx += 1for __imp in imp:if __imp == 't':un[idx].remove("t")if __imp == 'x':un[idx].remove("x")del idxrepl = {"t": [str(self.aa)], "x": [str(xValue)]}is_exit = Falsetimes = -1while not is_exit:times += 1if times >= 10:# print(f"\nmessage:目前已经循环求解超过10次,目前初始代入值为:x{repl['x']},t{repl['t']},\n"#      f"已经求解{repl},剩{4-len(repl.values())}值不可求解,故不予求解并跳出循环")breakindx = -1for lf_ in lf:indx += 1for i in repl.keys():for j in range(2):lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))idx = -1for imp in un:idx += 1for __imp in imp:if __imp in repl.keys():un[idx].remove(__imp)del idxif un[indx] == []:del un[indx]del lf[indx]if indx == 0 or (indx - 1) >= len(lf): breakindx -= 1continuetry:ams = sympy.solve(tuple(lf_), tuple(un[indx]))if ams == []:newlf = []for i in lf_:newlf.append(i.replace(str(repl["x"]), str(repl["x"]) + "*sympy.I"))ams = sympy.solve(tuple(newlf), tuple(un[indx]))except NotImplementedError as err:print(err)no_ans()returnif isinstance(ams, (dict,)):for km, jj in ams.items():if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):if km.name in repl.keys():repl[km.name].append(str(jj))else:repl[km.name] = [str(jj)]else:ix = -1undo = 0for i in ams:ix += 1try:if isinstance(i, (sympy.core.numbers.Float,sympy.core.numbers.Integer,int, float, complex)):try:repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]except IndexError:repl[tuple(un[indx])[undo]].append(str(eval(str(i))))for i in repl.keys():if i in lf_:lf_ = lf_.replace(i, str(repl[i][0]))elif isinstance(i, (tuple, list, set)):inxx = -1for jj in i:inxx += 1if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):try:repl[tuple(un[indx][inxx])[ix]] = [str(jj)]except IndexError:repl[tuple(un[indx][inxx])[undo]].append(str(jj))else:continueexcept TypeError as err:print("get:err", err)continueelse:undo = ixif len(repl.values()) >= 4: is_exit = True;breakif is_exit:solves.append(repl)if printout:print(f"\r{(iVal * (nums + 1) + XVAL + 1) / ((nums + 1) * (tnums + 1)) * 100}%", end="",flush=True)if printout:print("\nsucceed in Calculating Values...")num = 0for i in solves:if printout:print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)num += 1x_ = []for j in i["x"]:x_.append(eval(j))x.append(x_)y_ = []for j in i["y"]:y_.append(eval(j))y.append(y_)z_ = []for j in i["z"]:z_.append(eval(j))z.append(z_)t_ = []for j in i["t"]:t_.append(eval(j))t.append(t_)del x_, y_, z_, t_, solvesif printout:print("\nsucceed in Saving Values...")def _write_t_y(self, formula, tmin_=-10, tmax_=10, tnums=100,min_=-10, max_=10, nums=100, printout=True):global x, y, z, tself.step = (tmax_ - tmin_) / tnumsself.aa = tmin_ - self.stepself.xstep = (max_ - min_) / numsr"""print(un)print(lf,toLeg(formula),sep="\n\n",end="\n\n")"""solves = []for iVal in range(tnums + 1):self.aa = self.aa + self.stepself.aa = float("%.10f" % self.aa)xValue = min_ - self.xstepfor XVAL in range(nums + 1):lf, un = legalSet(toLeg(formula))xValue += self.xstepxValue = float("%.10f" % xValue)def key(item):if "t" in item[0] or "y" in item[0]:return 1else:return 999bf = dict(enumerate(lf))lf = sorted(lf, key=key)nun = []for i in range(len(lf)):nun.insert(lf.index(bf[i]), un[i])un = nundel nunidx = -1for imp in un:idx += 1for __imp in imp:if __imp == 't':un[idx].remove("t")if __imp == 'y':un[idx].remove("x")del idxrepl = {"t": [str(self.aa)], "y": [str(xValue)]}is_exit = Falsetimes = -1while not is_exit:times += 1if times >= 20:print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:y{repl['y']},t{repl['t']},\n"f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")breakindx = -1for lf_ in lf:indx += 1for i in repl.keys():for j in range(2):lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))idx = -1for imp in un:idx += 1for __imp in imp:if __imp in repl.keys():un[idx].remove(__imp)del idxif un[indx] == []:del un[indx]del lf[indx]if indx == 0 or (indx - 1) >= len(lf): breakindx -= 1continuetry:ams = sympy.solve(tuple(lf_), tuple(un[indx]))if ams == []:newlf = []for i in lf_:newlf.append(i.replace(str(repl["y"]), str(repl["y"]) + "*sympy.I"))ams = sympy.solve(tuple(newlf), tuple(un[indx]))except NotImplementedError as err:print(err)no_ans()returnif isinstance(ams, (dict,)):for km, jj in ams.items():if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):if km.name in repl.keys():repl[km.name].append(str(jj))else:repl[km.name] = [str(jj)]else:ix = -1undo = 0for i in ams:ix += 1try:if isinstance(i, (sympy.core.numbers.Float,sympy.core.numbers.Integer,int, float, complex)):try:repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]except IndexError:repl[tuple(un[indx])[undo]].append(str(eval(str(i))))for i in repl.keys():if i in lf_:lf_ = lf_.replace(i, str(repl[i][0]))elif isinstance(i, (tuple, list, set)):inxx = -1for jj in i:inxx += 1if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):try:repl[tuple(un[indx][inxx])[ix]] = [str(jj)]except IndexError:repl[tuple(un[indx][inxx])[undo]].append(str(jj))else:continueexcept TypeError as err:print("get:err", err)continueelse:undo = ixif len(repl.values()) >= 4: is_exit = True;breakif is_exit:solves.append(repl)if printout:print(f"\r{(iVal * (nums + 1) + XVAL + 1) / ((nums + 1) * (tnums + 1)) * 100}%", end="",flush=True)if printout:print("\nsucceed in Calculating Values...")num = 0for i in solves:if printout:print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)num += 1x_ = []for j in i["x"]:x_.append(eval(j))x.append(x_)y_ = []for j in i["y"]:y_.append(eval(j))y.append(y_)z_ = []for j in i["z"]:z_.append(eval(j))z.append(z_)t_ = []for j in i["t"]:t_.append(eval(j))t.append(t_)del x_, y_, z_, t_, solvesif printout:print("\nsucceed in Saving Values...")def _write_t_z(self, formula, tmin_=-10, tmax_=10, tnums=100,min_=-10, max_=10, nums=100, printout=True):global x, y, z, tself.step = (tmax_ - tmin_) / tnumsself.aa = tmin_ - self.stepself.xstep = (max_ - min_) / numsr"""print(un)print(lf,toLeg(formula),sep="\n\n",end="\n\n")"""solves = []for iVal in range(tnums + 1):self.aa = self.aa + self.stepself.aa = float("%.10f" % self.aa)xValue = min_ - self.xstepfor XVAL in range(nums + 1):lf, un = legalSet(toLeg(formula))xValue += self.xstepxValue = float("%.10f" % xValue)def key(item):if "t" in item[0] or "z" in item[0]:return 1else:return 999bf = dict(enumerate(lf))lf = sorted(lf, key=key)nun = []for i in range(len(lf)):nun.insert(lf.index(bf[i]), un[i])un = nundel nunidx = -1for imp in un:idx += 1for __imp in imp:if __imp == 't':un[idx].remove("t")if __imp == 'z':un[idx].remove("z")del idxrepl = {"t": [str(self.aa)], "z": [str(xValue)]}is_exit = Falsetimes = -1while not is_exit:times += 1if times >= 20:print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:z{repl['z']},t{repl['t']},\n"f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")breakindx = -1for lf_ in lf:indx += 1for i in repl.keys():for j in range(2):lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))idx = -1for imp in un:idx += 1for __imp in imp:if __imp in repl.keys():un[idx].remove(__imp)del idxif un[indx] == []:del un[indx]del lf[indx]if indx == 0 or (indx - 1) >= len(lf): breakindx -= 1continuetry:ams = sympy.solve(tuple(lf_), tuple(un[indx]))if ams == []:newlf = []for i in lf_:newlf.append(i.replace(str(repl["z"]), str(repl["z"]) + "*sympy.I"))ams = sympy.solve(tuple(newlf), tuple(un[indx]))except NotImplementedError as err:print(err)no_ans()returnif isinstance(ams, (dict,)):for km, jj in ams.items():if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):if km.name in repl.keys():repl[km.name].append(str(jj))else:repl[km.name] = [str(jj)]else:ix = -1undo = 0for i in ams:ix += 1try:if isinstance(i, (sympy.core.numbers.Float,sympy.core.numbers.Integer,int, float, complex)):try:repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]except IndexError:repl[tuple(un[indx])[undo]].append(str(eval(str(i))))for i in repl.keys():if i in lf_:lf_ = lf_.replace(i, str(repl[i][0]))elif isinstance(i, (tuple, list, set)):inxx = -1for jj in i:inxx += 1if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):try:repl[tuple(un[indx][inxx])[ix]] = [str(jj)]except IndexError:repl[tuple(un[indx][inxx])[undo]].append(str(jj))else:continueexcept TypeError as err:print("get:err", err)continueelse:undo = ixif len(repl.values()) >= 4: is_exit = True;breakif is_exit:solves.append(repl)if printout:print(f"\r{(iVal * (nums + 1) + XVAL + 1) / ((nums + 1) * (tnums + 1)) * 100}%", end="",flush=True)if printout:print("\nsucceed in Calculating Values...")num = 0for i in solves:if printout:print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)num += 1x_ = []for j in i["x"]:x_.append(eval(j))x.append(x_)y_ = []for j in i["y"]:y_.append(eval(j))y.append(y_)z_ = []for j in i["z"]:z_.append(eval(j))z.append(z_)t_ = []for j in i["t"]:t_.append(eval(j))t.append(t_)del x_, y_, z_, t_, solvesif printout:print("\nsucceed in Saving Values...")def _write_t(self, formula, tmin_=-10, tmax_=10, tnums=100, printout=True):global x, y, z, tI = 1joo = infself.step = (tmax_ - tmin_) / tnumsself.aa = tmin_ - self.stepr"""print(un)print(lf,toLeg(formula),sep="\n\n",end="\n\n")"""solves = []for iVal in range(tnums + 1):self.aa = self.aa + self.stepself.aa = float("%.10f" % self.aa)lf, un = legalSet(toLeg(formula))def key(item):if "t" in item[0]:return 1else:return 999bf = dict(enumerate(lf))lf = sorted(lf, key=key)nun = []for i in range(len(lf)):nun.insert(lf.index(bf[i]), un[i])un = nundel nunidx = -1for imp in un:idx += 1for __imp in imp:if __imp == 't':un[idx].remove("t")del idxrepl = {"t": [str(self.aa)]}is_exit = Falsetimes = -1while not is_exit:times += 1if times >= 20:print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:t{repl['t']},\n"f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")breakindx = -1for lf_ in lf:indx += 1for i in repl.keys():for j in range(2):if str(i) in str(lf_[j]):lf_[j] = lf_[j].replace(i, str(repl[i][0]))idx = -1for imp in un:idx += 1for __imp in imp:if __imp in repl.keys():un[idx].remove(__imp)del idxif un[indx] == []:del un[indx]del lf[indx]if indx == 0 or (indx - 1) >= len(lf): breakindx -= 1continuetry:ams = sympy.solve(tuple(lf_), tuple(un[indx]))except NotImplementedError as err:print(err)no_ans()returnif isinstance(ams, (dict,)):for km, jj in ams.items():if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):if km.name in repl.keys():repl[km.name].append(str(jj))else:repl[km.name] = [str(jj)]else:ix = -1undo = 0for i in ams:ix += 1try:if isinstance(i, (sympy.core.numbers.Float,sympy.core.numbers.Integer,int, float, complex)):try:repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]except IndexError:repl[tuple(un[indx])[undo]].append(str(eval(str(i))))for i in repl.keys():if i in lf_:lf_ = lf_.replace(i, str(repl[i][0]))elif isinstance(i, (tuple, list, set)):inxx = -1for jj in i:inxx += 1if not ('x' in str(jj) or'y' in str(jj) or'z' in str(jj) or't' in str(jj)):try:repl[tuple(un[indx][inxx])[ix]] = [str(jj)]except IndexError:repl[tuple(un[indx][inxx])[undo]].append(str(jj))else:continueexcept TypeError as err:print("get:err", err)continueelse:undo = ixif len(repl.values()) >= 4: is_exit = True;breakif is_exit:solves.append(repl)if printout:print(f"\r{(iVal + 1) / (tnums + 1) * 100}%", end="",flush=True)if printout:print("\nsucceed in Calculating Values...")num = 0for i in solves:if printout:print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)num += 1x_ = []for j in i["x"]:x_.append(eval(j))x.append(x_)y_ = []for j in i["y"]:y_.append(eval(j))y.append(y_)z_ = []for j in i["z"]:z_.append(eval(j))z.append(z_)t_ = []for j in i["t"]:t_.append(eval(j))t.append(t_)del x_, y_, z_, t_, solvesif printout:print("\nsucceed in Saving Values...")def format():global x,y,z,tnx={}ny={}nz={}nt=[]vx=[]vy=[]vz=[]for i,j,k,v in zip(x,y,z,t):for it,jt,kt,vt in zip(i,j,k,v):if vt not in nx.keys():nx[vt]=[]if vt not in ny.keys():ny[vt]=[]if vt not in nz.keys():nz[vt]=[]nx[vt].append(it)ny[vt].append(jt)nz[vt].append(kt)nt.append(vt)nt.sort()for num in set(nt):for i,j,k in zip(nx[num],ny[num],nz[num]):vx.append(i)vy.append(j)vz.append(k)x=vxy=vyz=vzt=ntdef create_img(tnum, fig=None, ax=None):global x, y, z, tif fig is None:fig = plt.figure()if ax is None:ax = Axes3D(fig)ax.legend(loc='best')ax.axis('off')if isinstance(tnum, list):tnum = tnum[0]ax.cla()x1 = []y1 = []z1 = []try:i = t.index(tnum)except (IndexError, ValueError) as err:i = 0try:while t[i] == tnum:if isinstance(x[i], (tuple, list, set)):x[i] = x[i][0]if isinstance(x[i], complex):i += 1continueif isinstance(y[i], (tuple, list, set)):y[i] = y[i][0]if isinstance(y[i], complex):i += 1continueif isinstance(z[i], (tuple, list, set)):z[i] = z[i][0]if isinstance(z[i], complex):i += 1continuex1.append(x[i])y1.append(y[i])z1.append(z[i])i += 1except IndexError:passscatter = ax.scatter(x1, y1, z1, c='r')return scatter,# plt.savefig('./1.jpg',)def Graphic_main(formula, modefunc, tmin_=-10, tmax_=10, tnums=100,min_=-10, max_=10, nums=100, printout=True):global x, y, z, ttry:modefunc(formula=formula, tmin_=tmin_, tmax_=tmax_, tnums=tnums,min_=min_, max_=max_, nums=nums, printout=printout)except Exception:modefunc(formula=formula, tmin_=tmin_, tmax_=tmax_, tnums=tnums, printout=printout)format()fig = plt.figure()ax = Axes3D(fig, auto_add_to_figure=False)print(min(x),min(y),min(z),"\n",max(x),max(y),max(z))ax.set_ylim(min(y),max(y))ax.set_xlim(xmin=min(x), xmax=max(x))ax.set_zlim(zmin=min(z), zmax=max(z))fig.add_axes(ax)# ax.legend(loc="best")def demo(num):a = tmin_ + ((tmax_ - tmin_) / tnums) * (num % tnums)print(f"\rwait:{num-tnums}/{tnums}",end="")return create_img(a, fig, ax),ani = animation.FuncAnimation(fig, demo, fargs=[],interval=int(((tmax_ - tmin_) / tnums) * 1000))ani.save('test.mp4')# 调试部分print("program running")"""write()._write_t_x("z=t\n3x+y=z\nx=sin(y)",tnums=100,printout=True)
print(t)
create_img([0.0])"""
Graphic_main("sin(x)=y\nz=t\ncos(y)=z", modefunc=write()._write_t_x, tnums=10, nums=10)
print("end...")

再次感谢各位的观看!

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

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了