source: anuga_validation/convergence_study/animatesww2d_alt.py @ 4700

Last change on this file since 4700 was 4700, checked in by sexton, 16 years ago

working on converting matlab script to matplotlib

File size: 4.9 KB
Line 
1def animatesww2d_alt(sww_filename, movie_filename, range):
2    """Plot cross section of model output
3    """
4
5    # Read SWW file     
6    from Scientific.IO.NetCDF import NetCDFFile
7    fid = NetCDFFile(sww_filename, 'r')
8   
9    x = fid.variables['x']
10    y = fid.variables['y']
11    volumes = fid.variables['volumes']
12   
13    elevation = fid.variables['elevation']
14    time = fid.variables['time']
15    stage = fid.variables['stage']
16    xmomentum = fid.variables['xmomentum']
17    ymomentum = fid.variables['ymomentum']
18   
19
20    # find indices for where y = 0
21
22    #
23    # Set up plot
24
25    spacing=10 # grid interval in metres
26    hmax=5     # ??
27
28   
29#figure(1);
30
31#if nargin > 1
32#    figure(1);set(gcf,'Position',[200 400 800 300]);
33#    mov=avifile(movie_filename,'FPS',5)
34#end
35
36#i=find(V_y==0);
37
38#[xi,yi]=meshgrid(min(V_x):spacing:max(V_x),min(V_y):spacing:max(V_y));
39
40#elev=griddata(V_x,V_y,V_elevation,xi,yi);
41
42#if nargin < 3
43#    range=[min(V_x) max(V_x) min(min(V_stage))-1 max(max(V_stage))+1];
44#end
45
46#m=V_stage(1,i);
47
48#for t=1:length(V_time)
49   
50#    m=max(m,V_stage(t,i));
51#    plot(V_x(i),V_stage(t,i),V_x(i),V_elevation(i),V_x(i),m,'.');
52
53#    axis(range)
54   
55
56#    title(num2str(V_time(t)));drawnow;
57
58#    if nargin>1
59#        F=getframe(gcf);
60#        mov=addframe(mov,F);   
61#    end
62   
63#end
64
65#if nargin > 1
66#    mov=close(mov);
67#end
68
69'''
70if __name__ == '__main__':
71
72    import sys
73    animatesww2d_alt(sys.argv[1], 'cross_section_plot', 5)
74
75'''
76
77'''
78How do I make a movie with matplotlib?
79If you want to take an animated plot and turn it into a movie, the best approach is to save a series of image files (eg PNG) and use an external tool to convert them to a movie. There is a matplotlib tutorial on this subject here. You can use mencoder, which is part of the mplayer suite for this
80#fps (frames per second) controls the play speed
81mencoder 'mf://*.png' -mf type=png:fps=10 -ovc \
82   lavc -lavcopts vcodec=wmv2 -oac copy -o animation.avi
83
84The swiss army knife of image tools, ImageMagick's convert, works for this as well.
85Here is a simple example script that saves some PNGs, makes them into a movie, and then cleans up.
86
87import os, sys
88from pylab import *
89
90files = []
91figure(figsize=(5,5))
92ax = subplot(111)
93for i in range(50):  # 50 frames
94    cla()
95    imshow(rand(5,5), interpolation='nearest')
96    fname = '_tmp%03d.png'%i
97    print 'Saving frame', fname
98    savefig(fname)
99    files.append(fname)
100
101print 'Making movie animation.mpg - this make take a while'
102os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 \
103  -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg")
104
105# cleanup
106for fname in files: os.remove(fname)
107
108'''
109
110def animatesww2d(swwfile):
111    """Read in sww file and plot cross section of model output
112    """
113
114    sww_quantity = ['stage', 'elevation', 'xmomentum', 'ymomentum']
115
116    try:
117        fid = open(swwfile)
118    except Exception, e:
119        msg = 'File "%s" could not be opened: Error="%s"'\
120              %(swwfile, e)
121        raise msg
122
123    print 'swwfile', swwfile
124
125    # interpolation points are for y = 0
126    m = 100 # number of increments in x
127    max_x = 100000.
128    x = 0
129    points = []
130    x_points = []
131    for i in range(m):
132        x += max_x/m
133        points.append([x,0])
134        x_points.append(x)
135           
136    time_thinning = 1
137    use_cache = True
138    verbose = True
139
140    from anuga.abstract_2d_finite_volumes.util import file_function
141   
142    f = file_function(swwfile,
143                      quantities = sww_quantity,
144                      interpolation_points = points,
145                      time_thinning = time_thinning,
146                      verbose = verbose,
147                      use_cache = use_cache)
148
149    n = len(f.get_time()) # number of time steps
150
151    from Numeric import zeros, Float
152    from math import sqrt
153    stage = zeros((n,m), Float)
154    elevation = zeros((n,m), Float)
155    xmom = zeros((n,m), Float)
156    ymom = zeros((n,m), Float)
157    momenta = zeros((n,m), Float)
158    speed = zeros((n,m), Float)
159    max_stages = []
160    max_stage = None
161
162    for k, location in enumerate(x_points):
163        for i, t in enumerate(f.get_time()):
164            w = f(t, point_id = k)[0]
165            z = f(t, point_id = k)[1]
166            uh = f(t, point_id = k)[2]
167            vh = f(t, point_id = k)[3]
168            depth = w-z     
169            m = sqrt(uh*uh + vh*vh)
170            if depth < 0.001:
171                vel = 0.0
172            else:
173                vel = m / (depth + 1.e-6/depth)
174
175            stage[i,k] = w
176            elevation[i,k] = z
177            xmom[i,k] = uh
178            ymom[i,k] = vh
179            momenta[i,k] = m
180            speed[i,k] = vel
181
182            if w > max_stage: max_stage = w
183            max_stages.append(max_stage)
184
185    from pylab import plot, xlabel, ylabel, savefig, close, hold
186    hold(False)
187    for i in range(n):
188        plot(x_points,stage[i,:])
189        xlabel('x')
190        ylabel('stage (m)')
191        #title('')
192        name = 'time_%i' %i
193        savefig(name)
194
195    close('all')
196   
197animatesww2d('myexample2.sww')
Note: See TracBrowser for help on using the repository browser.