Python动态建模-(3)

上一篇参见:

Python动态建模(2)_Unconquerable&Llxy的博客-CSDN博客bool布尔值(True、False)------------默认为True,真。tmin_,t值的最小取值点;tmax_,t值的最大取值点;https://blog.csdn.net/html_finder/article/details/126069751

这一段时间我对源码进行了一些修改。这些修改你可以在一会看到。

接下来是展示结果和导出的部分了:

计划使用matplotlib库。

——1

首先我们要明确一件非常重要的事:(虚复数问题)

众所周知,在图上表示虚数有特殊的方法:

定义一个二维表。例如,复数(3+2i)是这样表示的;、
 

                                        |                [x=3,y=2]
 
                                        |
 
                                        |
 
---------------------------------------------------------------------------x
 
                                        |
 
                                        |
 
                                        |
 
                                        y

但是,很遗憾,如果只在一条轴上,复数无法表示(虚数的基本原则:无法在数轴上表示(区别于:实数))。

所以,我们只能将其:舍弃。

(把这些操作交给数据处理部分吧【手动狗头Doge】)


到了可视化的时候,自然要使用一下我们的matplotlib

(同样是第三方库,没安装的在command命令行里输入:
 

pip install matplotlib

)


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 animation

上面的是

所有的import语句……(换行隔开的是新加的import语句)

然后,是导入数据部分:

def create_img(tnum,fig=None,ax=None):
    global x,y,z,t
 
 
    if fig is None:
        fig = plt.figure()
    if ax is None:
        ax = Axes3D(fig)
        ax.legend(loc='best')
        ax.axis('off')
    if not isinstance(tnum,list):
        tnum=[tnum]
    ww=ax.cla()
 
    x1 =[]
    y1 = []
    z1=[]
    try:
        i=t.index(tnum)
    except (IndexError,ValueError) as err:
        i=0
    try:
        while t[i]==tnum:
            if isinstance(x[i],(tuple,list,set)):
                x[i]=x[i][0]
            if isinstance(x[i],complex):
                i+=1
                continue
            if isinstance(y[i],(tuple,list,set)):
                y[i]=y[i][0]
            if isinstance(y[i],complex):
                i+=1
                continue
            if isinstance(z[i],(tuple,list,set)):
                z[i]=z[i][0]
            if isinstance(z[i],complex):
                i+=1
                continue
            x1.append(x[i])
            y1.append(y[i])
            z1.append(z[i])
            i+=1
    except IndexError : pass

fig是一个matplotlib.pyplot.figure对象;

ax是一个 mpl_toolkits.mplot3d.Axes3D对象。

接下来就是显示部分了:

    ax.scatter(x1,y1,z1, c = 'r')

【这一行代码似乎与前面提取数据的代码比起来长度有些失衡 :) 】

显示出来:

    ax.show()


个人感受,似乎这一大堆函数有些乱……让我们整合一个综合版本

def Graphic_main(formula,modefunc,tmin_=-10, tmax_=10, tnums=100,
                 min_=-10, max_=10, nums=100,printout=True):

formula:公式

modefunc:函数(就是上面定义的write()._write_t、write()._write_t_x、write()._write_t_y、write()._write_t_z四选一)

tmin_:t值的最小取值

tmax_:t值的最大取值

tnums:t值的取值范围

min_:(如modefunc为write()._write_t则弃用)x/y/z值的最小取值(x/y/z取决于函数)

max_:(如modefunc为write()._write_t则弃用)x/y/z值的最大取值(x/y/z取决于函数)

nums:(如modefunc为write()._write_t则弃用)x/y/z值的取值数量(x/y/z取决于函数)

printout:是否输出。

然后是全局化变量:
 

    global x,y,z,t

函数的调用:

    try:
        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)

注:modefunc必须为一个函数对象。例,调用本Graphic_main函数时,可使用如下代码:

Graphic_main("sin(x)=y\nz=t\ncos(y)=z",modefunc=write()._write_t_x,tnums=10,nums=10)

(这里只列举了少量参数)



创建一个画图对象:

    fig = plt.figure()
    ax = Axes3D(fig,auto_add_to_figure=False)
    fig.add_axes(ax)
    ax.legend(loc='best')
    ax.axis('off')

定义一个调用函数:

    def demo(num):
        print("running")
        a=tmin_+((tmax_-tmin_)/tnums)*(num%tnums)
        print(a,(tmax_-tmin_)/tnums,num)
 
        create_img(a,fig,ax)

定时调用:(动态画面)

    print(1)
    ani = animation.FuncAnimation(fig, demo,fargs=[],
                                  interval=0)
 
    fig.show()

注:print语句是调试的语句,后来在成功运行时会删除



完整代码:

# 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 animation
 
def 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=None
        while length!=0:
            if length==2:
                val.append('='.join(tv))
                break
            if length==1:
                val.append('='.join([tv[0],str(last)]))
                break
            val.append('='.join([tv[-2],tv[-1]]))
            length=length-1
            last=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=='':continue
        k=l.split("=")
        tmpstr+="(("+k[0]+")-("+k[1]+"))"
        tmpstr2 += "((" + k[1] + ")-(" + k[0] + "))"
        tmpstrs=[tmpstr,tmpstr2]
        nw.append(tmpstrs)
    v=nw
    del nw
 
    index=-1
    for i in v:
        index+=1
        for 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 = -1
 
            funcs = []
            for i in i_:
 
                pos+=1
                tmpos=pos+0
                string=""
                while i_[tmpos].isalpha():
                    string+=i_[tmpos]
                    tmpos=tmpos+1
 
                if 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+="*"+" "+i
 
                else:
 
                    if (i.isalpha() and pos not in funcs):
                        new+=" "+i
                    else:
                        new+=i
                if 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,lt
 
def 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, t
 
        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""
        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 1):
 
            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 1):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)
 
                def key(item):
                    if "t" in item[0] or "x" in item[0]:
                        return 1
                    else:
                        return 999
 
                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun
                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'x':
                            un[idx].remove("x")
                del idx
 
                repl = {"t": [str(self.aa)], "x": [str(xValue)]}
                is_exit = False
                times=-1
                while not is_exit:
                    times+=1
 
                    if times>=10:
                        #print(f"\nmessage:目前已经循环求解超过10次,目前初始代入值为:x{repl['x']},t{repl['t']},\n"
                        #      f"已经求解{repl},剩{4-len(repl.values())}值不可求解,故不予求解并跳出循环")
                        break
                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                lf_[j] = lf_[j].replace(" "+i, str(repl[i][0]))
 
                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx
 
                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue
 
                        try:
                            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()
                            return
 
 
                        if 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 = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    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 = -1
                                        for jj in i:
                                            inxx += 1
                                            if 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:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix
                        if len(repl.values()) >= 4: is_exit = True;break
                if 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 = 0
        for i in solves:
            if printout:
                print(f"\r{(num+1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            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_, solves
 
        if 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, t
 
        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""
        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 1):
 
            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 1):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)
 
                def key(item):
                    if "t" in item[0] or "y" in item[0]:
                        return 1
                    else:
                        return 999
 
                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun
                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'y':
                            un[idx].remove("x")
                del idx
 
                repl = {"t": [str(self.aa)], "y": [str(xValue)]}
                is_exit = False
                times = -1
                while not is_exit:
                    times += 1
 
                    if times >= 20:
                        print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:y{repl['y']},t{repl['t']},\n"
                              f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")
                        break
                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))
 
                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx
 
                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue
 
                        try:
                            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()
                            return
 
                        if 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 = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    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 = -1
                                        for jj in i:
                                            inxx += 1
                                            if 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:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix
                        if len(repl.values()) >= 4: is_exit = True;break
                if 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 = 0
        for i in solves:
            if printout:
                print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            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_, solves
 
        if 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, t
 
        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""
        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 1):
 
            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 1):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)
 
                def key(item):
                    if "t" in item[0] or "z" in item[0]:
                        return 1
                    else:
                        return 999
 
                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun
                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'z':
                            un[idx].remove("z")
                del idx
 
                repl = {"t": [str(self.aa)], "z": [str(xValue)]}
                is_exit = False
                times = -1
                while not is_exit:
                    times += 1
 
                    if times >= 20:
                        print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:z{repl['z']},t{repl['t']},\n"
                              f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")
                        break
                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                lf_[j] = lf_[j].replace(" " + i, str(repl[i][0]))
 
                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx
 
                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue
 
                        try:
                            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()
                            return
 
                        if 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 = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    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 = -1
                                        for jj in i:
                                            inxx += 1
                                            if 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:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix
                        if len(repl.values()) >= 4: is_exit = True;break
                if 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 = 0
        for i in solves:
            if printout:
                print(f"\r{(num + 1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            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_, solves
 
        if printout:
            print("\nsucceed in Saving Values...")
 
    def _write_t(self,formula,tmin_=-10, tmax_=10, tnums=100,printout=True):
 
        global x, y, z, t
        I = 1j
        oo = inf
 
        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        r"""
        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 1):
 
            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            lf, un = legalSet(toLeg(formula))
 
            def key(item):
                if "t" in item[0]:
                    return 1
                else:
                    return 999
 
            bf = dict(enumerate(lf))
            lf = sorted(lf, key=key)
            nun = []
            for i in range(len(lf)):
                nun.insert(lf.index(bf[i]), un[i])
            un = nun
            del nun
            idx = -1
            for imp in un:
                idx += 1
                for __imp in imp:
                    if __imp == 't':
                        un[idx].remove("t")
            del idx
 
            repl = {"t": [str(self.aa)]}
            is_exit = False
 
            times=-1
            while not is_exit:
                times += 1
 
                if times >= 20:
                    print(f"\nmessage:目前已经循环求解超过20次,目前初始代入值为:t{repl['t']},\n"
                          f"已经求解{repl},剩{4 - len(repl.values())}值不可求解,故不予求解并跳出循环")
                    break
                indx = -1
                for lf_ in lf:
                    indx += 1
                    for 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 = -1
                    for imp in un:
                        idx += 1
                        for __imp in imp:
                            if __imp in repl.keys():
                                un[idx].remove(__imp)
                    del idx
 
                    if un[indx] == []:
                        del un[indx]
                        del lf[indx]
                        if indx == 0 or (indx - 1) >= len(lf): break
                        indx -= 1
                        continue
 
                    try:
                        ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                    except NotImplementedError as err:
                        print(err)
                        no_ans()
                        return
 
 
                    if 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 = -1
                        undo = 0
                        for i in ams:
                            ix += 1
                            try:
                                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 = -1
                                    for jj in i:
                                        inxx += 1
                                        if 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:
                                    continue
                            except TypeError as err:
                                print("get:err", err)
                                continue
                            else:
                                undo = ix
                    if len(repl.values()) >= 4: is_exit = True;break
            if 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 = 0
        for i in solves:
            if printout:
                print(f"\r{(num+1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            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_, solves
 
        if printout:
            print("\nsucceed in Saving Values...")
 
 
def create_img(tnum,fig=None,ax=None):
    global x,y,z,t
 
 
    if fig is None:
        fig = plt.figure()
    if ax is None:
        ax = Axes3D(fig)
        ax.legend(loc='best')
        ax.axis('off')
    if not isinstance(tnum,list):
        tnum=[tnum]
    ww=ax.cla()
 
    x1 =[]
    y1 = []
    z1=[]
    try:
        i=t.index(tnum)
    except (IndexError,ValueError) as err:
        i=0
    try:
        while t[i]==tnum:
            if isinstance(x[i],(tuple,list,set)):
                x[i]=x[i][0]
            if isinstance(x[i],complex):
                i+=1
                continue
            if isinstance(y[i],(tuple,list,set)):
                y[i]=y[i][0]
            if isinstance(y[i],complex):
                i+=1
                continue
            if isinstance(z[i],(tuple,list,set)):
                z[i]=z[i][0]
            if isinstance(z[i],complex):
                i+=1
                continue
            x1.append(x[i])
            y1.append(y[i])
            z1.append(z[i])
            i+=1
    except IndexError : pass
 
    ax.scatter(x1,y1,z1, c = 'r')
 
    ax.show()
 
    #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,t
    try:
        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)
    fig = plt.figure()
    ax = Axes3D(fig,auto_add_to_figure=False)
    fig.add_axes(ax)
    ax.legend(loc='best')
    ax.axis('off')
    def demo(num):
        print("running")
        a=tmin_+((tmax_-tmin_)/tnums)*(num%tnums)
        print(a,(tmax_-tmin_)/tnums,num)
 
        create_img(a,fig,ax)
    print(1)
    ani = animation.FuncAnimation(fig, demo,fargs=[],
                                  interval=0)
 
    fig.show()

程序运行结果可能有遗留的部分bug有待清理,望谅解(四天了没有搞出来),请见下篇解决部分。

附录:调试代码

if __name__ == '__main__':
    #调试部分
    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...")

运行结果:

program running
100.0%
succeed in Calculating Values...
100.0%
succeed in Saving Values...
1
end...
No handles with labels found to put in legend.
C:\Users\*****\AppData\Roaming\Python\Python39\site-packages\matplotlib\animation.py:973: UserWarning: Animation was deleted without rendering anything. This is most likely unintended. To prevent deletion, assign the Animation to a variable that exists for as long as you need the Animation.
  warnings.warn(

 似乎有哪些地方出了问题(报了Warning,大意是进程没有运行就被删除了,不知道为什么):

C:\Users\*****\AppData\Roaming\Python\Python39\site-packages\matplotlib\animation.py:973:
 UserWarning: Animation was deleted without rendering anything. This is most likely 
unintended. To prevent deletion, assign the Animation to a variable that exists for as long 
as you need the Animation.
  warnings.warn(

-------------------------------------完------------------------------------------------------------------------------

这里是Unconquerable&Llxy,原名html_finder
Unconquerable&Llxy的博客_CSDN博客-Python从负无穷到~,Vpython-3D,办公领域博主Unconquerable&Llxy擅长Python从负无穷到~,Vpython-3D,办公,等方面的知识,Unconquerable&Llxy关注算法,python,c++领域.https://blog.csdn.net/html_finder?type=blog

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unconquerable p

给点吧~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值