Оптимизация сюжетной анимации для больших данных с динамической сеткой - PullRequest
0 голосов
/ 30 июня 2019

Я пытаюсь создать анимацию для больших данных с динамической сеткой (океанские волны). Мне удалось написать сценарий, который работает, но это требует много времени и ресурсов. Я надеялся, что кто-нибудь сможет увидеть, что я могу улучшить в своем коде, чтобы ускорить его.

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib
    from matplotlib import animation as anim
    import xarray as xr
    import PySimpleGUI as sg      
    import sys      

    #file importing mechanism

    jan = xr.open_dataset('Model/Bar_mig/xboutput_equi.nc')

    ########################## labeling the variables in the data-set ##############


    nx = jan.variables['globalx']
    globaltime = jan.variables['globaltime']
    zb = jan.variables['zb'][:,0,:]
    zs = jan.variables['zs'][:,0,:]
    ccz = jan.variables['ccz'][:,:,0,:]
    uz = jan.variables['uz'][:,:,0,:]
    nz = np.array(range(0,100))
    nx = (np.array(range(0,nx.size)))


    globaltime_ar = np.array(globaltime)
    conc = np.vstack(globaltime_ar)
    newdf = pd.DataFrame(conc)
    itr = len(newdf.index)

    uz1=np.flip(uz,0)
    uz2=np.flip(np.flip(uz1,1),axis=0)

    depth1 = (zb)
    a       = np.array(depth1)
    b       = pd.DataFrame(a)
    depth = b.dropna(axis=1, how='all')



    zba1 = (np.array(zb))
    zsa1 = (np.array(-zs))
    zba = pd.DataFrame(zba1)
    zsa = pd.DataFrame(zsa1)

Вот так я настраиваю динамическую сетку. ( пример вывода )

    #dynamic grid
    for w in range(0,itr):
        AA=[]
        sizer = depth.iloc[w,]
        sizer1 = sizer.dropna(axis=0, how='all')
        for j in range(0,sizer1.size):
            maxi = -zsa.iloc[w,j]
            mini = depth.iloc[w,j]
            step = mini/nz.shape[-1]
            globals()['col_{}'.format(j)] = pd.DataFrame(np.linspace(maxi,mini,nz.shape[-1],endpoint=True))
            globals()['col_{}'.format(j)] = globals()['col_{}'.format(j)].reset_index(drop=True)
            AA.append(globals()['col_{}'.format(j)])
        globals()['df_{}'.format(w)] = pd.concat(AA, axis=1).iloc[:nz.size]
        globals()['df_{}'.format(w)].columns = range(globals()['df_{}'.format(w)].shape[1])
        AA.clear()

        sg.OneLineProgressMeter('My meter title', w, itr-1, 'key')

    from matplotlib import animation as anim

    fig = plt.figure(figsize=(15,7.5))                        # Create a dummy figure
    ax = plt.axes()          # Set the axis rigid
    mywriter = anim.FFMpegWriter()
    scale=1
    def animate(w): 
        w = w*scale
        plt.clf()

        plt.title(str(w) + 'hr')
        y = globals()['df_{}'.format(w)]
        x = np.array([nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx,nx])


        data2 = np.flip(ccz[w*1,:,:],0)
        cont = plt.pcolor(x,y,np.array(data2), cmap = 'jet',
                          vmin = 0, vmax = 0.03
                          )
        plt.colorbar(label='Concentration Profile ($m^3/m^3$)')

        plt.fill_between(nx,min(zb[0])-1,zb[w],color = 'yellow')
        point = 350
        plt.xlim(point,nx.shape[-1])
        plt.ylim(min(zb[0,point:point+1]),max(zb[0,point:]))
        plt.xlabel('Cross shore distance (m)')
        plt.ylabel('Depth (m)')
        fig.tight_layout()

        return cont,
    ani = anim.FuncAnimation(fig, animate, interval = 1, frames=itr) 


    ani.save('Sed_Con.mp4', writer=mywriter)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...