Changeset 2795


Ignore:
Timestamp:
May 3, 2006, 4:12:40 PM (18 years ago)
Author:
sexton
Message:

(1) inclusion of sww2timeseries which generates time series figures from sww file and which can output latex file if requested. (2) Script using sww2timeseries for sydney scenario

Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • inundation/pyvolution/util.py

    r2750 r2795  
    502502        fid.write(self.data)
    503503        fid.close()
     504
     505
     506from pylab import *
     507   
     508def sww2timeseries(swwfile,
     509                   gauge_filename,
     510                   file_loc,
     511                   label_id,
     512                   plot_quantity = None,
     513                   time_min = None,
     514                   time_max = None,
     515                   title_on = None,
     516                   verbose = False):
     517   
     518    """ Read sww file and plot the time series for the
     519    prescribed quantities at defined gauge locations and
     520    prescribed time range.
     521
     522    Input variables:
     523
     524    swwfile         - name of sww file
     525                    - assume that all conserved quantities have been stored
     526                   
     527    gauge_filename  - name of file containing gauge data
     528                        - name, easting, northing
     529                    - OR (this is not yet done)
     530                        - structure which can be converted to a Numeric array,
     531                          such as a geospatial data object
     532                         
     533    file_loc        - file location of sww file
     534                    - gauge graphs and data written to this directory
     535   
     536    plot_quantity   - list containing quantities to plot, they must
     537                      be the name of an existing quantity or one of
     538                      the following possibilities
     539                    - possibilities:
     540                        - stage; 'stage'
     541                        - depth; 'depth'
     542                        - velocity; calculated as absolute momentum
     543                         (pointwise) divided by depth; 'velocity'
     544                        - bearing; calculated as the angle of the momentum
     545                          vector (xmomentum, ymomentum) from the North; 'bearing'
     546                        - absolute momentum; calculated as
     547                          sqrt(xmomentum^2 + ymomentum^2); 'momentum'
     548                        - x momentum; 'xmomentum'
     549                        - y momentum; 'ymomentum'
     550                    - default will be ['stage', 'velocity', 'bearing']
     551
     552    time_min         - beginning of user defined time range for plotting purposes
     553                        - default will be first available time found in swwfile
     554                       
     555    time_max         - end of user defined time range for plotting purposes
     556                        - default will be last available time found in swwfile
     557                       
     558    title_on        - if True, export standard graphics
     559                    - if False, export graphics as eps and generate
     560                      latex output
     561                    - latex output to be written to same directory as
     562                      where this function is being used from and named
     563                      according to scenario name
     564                     
     565    label_id        - used in generating latex output. It will generally
     566                      be part of the directory name of file_loc (the
     567                      time stamp, if using that). Helps to differentiate
     568                      between runs within a particular scenario.
     569                     
     570    Output:
     571   
     572    - time series data stored in .csv for later use if required.
     573      Name = gauges_timeseries followed by gauge name
     574    - if title_on = False then output latex file will be generated
     575      in same directory as where script is run (usually production
     576      scenario direcotry. Name = latex_output_label_id.tex
     577
     578    Other important information:
     579   
     580    It is assumed that the used has stored all the conserved quantities
     581    and elevation during the scenario run, i.e.
     582    ['stage', 'elevation', 'xmomentum', 'ymomentum']
     583    If this has not occurred then sww2timeseries will not work.
     584                     
     585    """
     586    k = _sww2timeseries(swwfile,
     587                        gauge_filename,
     588                        file_loc,
     589                        label_id,
     590                        plot_quantity,
     591                        time_min,
     592                        time_max,
     593                        title_on,
     594                        verbose)
     595
     596    return k
     597
     598def _sww2timeseries(swwfile,
     599                    gauge_filename,
     600                    file_loc,
     601                    label_id,
     602                    plot_quantity = None,
     603                    time_min = None,
     604                    time_max = None,
     605                    title_on = None,
     606                    verbose = False):
     607
     608    assert type(swwfile) == type(''),\
     609               'The sww filename must be a string'
     610
     611    try:
     612        fid = open(swwfile)
     613    except Exception, e:
     614        msg = 'File "%s" could not be opened: Error="%s"'\
     615                  %(swwfile, e)
     616        raise msg
     617
     618    assert type(gauge_filename) == type(''),\
     619               'Gauge filename must be a string'
     620   
     621    try:
     622        fid = open(gauge_filename)
     623    except Exception, e:
     624        msg = 'File "%s" could not be opened: Error="%s"'\
     625                  %(gauge_filename, e)
     626        raise msg
     627       
     628    assert type(plot_quantity) == list,\
     629               'plot_quantity must be a list'
     630   
     631    if plot_quantity is None:
     632        plot_quantity = ['depth', 'velocity', 'bearing']
     633    else:
     634        check_list(plot_quantity)
     635
     636    if title_on is None:
     637        title_on = True
     638
     639    assert type(label_id) == type(''),\
     640               'label_id to sww2timeseries must be a string'
     641   
     642    if verbose: print '\n Gauges obtained from: %s \n' %gauge_filename
     643    gauges, locations = get_gauges_from_file(gauge_filename)
     644
     645    #from pyvolution.util import file_function
     646
     647    sww_quantity = ['stage', 'elevation', 'xmomentum', 'ymomentum']
     648
     649    f = file_function(swwfile,
     650                      quantities = sww_quantity,
     651                      interpolation_points = gauges,
     652                      verbose = True,
     653                      use_cache = True)
     654
     655    if max(f.quantities['xmomentum']) > 1.e10:
     656        msg = 'Not all conserved quantities available from sww file. \n sww2timeseries requires all conserved quantities stored in sww file'
     657        raise Exception, msg
     658       
     659    if time_min is None:
     660        time_min = min(f.T)
     661    else:
     662        if time_min < min(f.T):
     663            msg = 'Minimum time entered not correct - please try again'
     664            raise Exception, msg
     665
     666    if time_max is None:
     667        time_max = max(f.T)
     668    else:
     669        if time_max > max(f.T):
     670            msg = 'Maximum time entered not correct - please try again'
     671            raise Exception, msg
     672
     673    if verbose: print 'Inputs OK - going to generate figures'
     674   
     675    return generate_figures(plot_quantity, file_loc, f, gauges, locations,
     676                            time_min, time_max, title_on, label_id, verbose)
     677                         
     678
     679def get_gauges_from_file(filename):
     680    fid = open(filename)
     681    lines = fid.readlines()
     682    fid.close()
     683   
     684    gauges = []
     685    gaugelocation = []
     686    line1 = lines[0]
     687    line11 = line1.split(',')
     688    for i in range(len(line11)):
     689        if line11[i].strip('\n').strip(' ') == 'Easting': east_index = i
     690        if line11[i].strip('\n').strip(' ') == 'Northing': north_index = i
     691        if line11[i].strip('\n').strip(' ') == 'Name': name_index = i
     692   
     693    for line in lines[1:]:
     694        fields = line.split(',')
     695        gauges.append([float(fields[east_index]), float(fields[north_index])])
     696        loc = fields[name_index]
     697        gaugelocation.append(loc.strip('\n'))
     698   
     699    return gauges, gaugelocation
     700
     701def check_list(quantity):
     702
     703    all_quantity = ['stage', 'depth', 'momentum', 'xmomentum',
     704                    'ymomentum', 'velocity', 'bearing', 'elevation']
     705
     706    p = list(set(quantity).difference(set(all_quantity)))
     707    if len(p) <> 0:
     708        msg = 'Quantities %s do not exist - please try again' %p
     709        raise Exception, msg
     710       
     711    return
     712
     713def calc_bearing(uh, vh):
     714
     715    from math import atan, degrees
     716   
     717    angle = degrees(atan(vh/(uh+1.e-15)))
     718    if (0 < angle < 90.0):
     719        if vh > 0:
     720            bearing = 90.0 - abs(angle)
     721        if vh < 0:
     722            bearing = 270.0 - abs(angle)
     723    if (-90 < angle < 0):
     724        if vh < 0:
     725            bearing = 90.0 - abs(angle)
     726        if vh > 0:
     727            bearing = 270.0 - abs(angle)
     728    if angle == 0: bearing = 0.0
     729           
     730    return bearing
     731
     732def generate_figures(plot_quantity, file_loc, f, gauges,
     733                     locations, time_min, time_max, title_on, label_id, verbose):
     734
     735    from math import sqrt, atan, degrees
     736    from os import sep, altsep
     737
     738    filename = file_loc.split(sep)
     739       
     740    if title_on == False:
     741        ext = '.eps'
     742        texfilename = 'latex_output_%s.tex' %(label_id.replace(sep,'_'))
     743        if verbose: print '\n Latex output printed to %s \n' %texfilename
     744        fid = open(texfilename, 'w')
     745        s = '\\begin{center} \n \\begin{tabular}{|l|l|l|}\hline \n \\bf{Gauge Name} & \\bf{Easting} & \\bf{Northing} \\\\ \hline \n'
     746        fid.write(s)
     747        gauges1 = gauges
     748        for name, gauges1 in zip(locations, gauges1):
     749            east = gauges1[0]
     750            north = gauges1[1]
     751            s = '%s & %.2f & %.2f \\\\ \hline \n' %(name, east, north)
     752            fid.write(s)
     753
     754        s = '\\end{tabular} \n \\end{center} \n \n'
     755        fid.write(s)
     756    else:
     757        texfilename = ''
     758        ext = ''
     759   
     760    ##### loop over each gauge #####
     761    for k, g in enumerate(gauges):
     762        if verbose: print 'Gauge %d of %d' %(k, len(gauges))
     763        model_time = []
     764        stages = []
     765        elevations = []
     766        momenta = []
     767        xmom = []
     768        ymom = []
     769        velocity = []
     770        bearings = []
     771        depths = []
     772        max_depth = 0
     773        max_momentum = 0
     774        max_velocity = 0     
     775       
     776        #### generate quantities #######
     777        for i, t in enumerate(f.T):
     778
     779            if time_min <= t <= time_max:
     780
     781                w = f(t, point_id = k)[0]
     782                z = f(t, point_id = k)[1]
     783                uh = f(t, point_id = k)[2]
     784                vh = f(t, point_id = k)[3]
     785                gaugeloc = locations[k]
     786                depth = w-z
     787               
     788                m = sqrt(uh*uh + vh*vh)   
     789                vel = m / (depth + 1.e-30)
     790                bearing = calc_bearing(uh, vh)
     791
     792                model_time.append(t)       
     793                stages.append(w)
     794                elevations.append(z)
     795                xmom.append(uh)
     796                ymom.append(vh)
     797                momenta.append(m)
     798                velocity.append(vel)
     799                bearings.append(bearing)
     800                depths.append(depth)
     801
     802                if depth > max_depth: max_depth = w-z
     803                if m > max_momentum: max_momentum = m
     804                if vel > max_velocity: max_velocity = vel
     805
     806        #### finished generating quantities #####
     807               
     808        #### generate figures ###
     809        ion()
     810        hold(False)
     811
     812        for i in range(len(plot_quantity)):
     813            which_quantity = plot_quantity[i]
     814            figure(i+1, frameon = False)
     815            if which_quantity == 'depth':
     816                plot(model_time, depths, 'g-')
     817                units = 'm'
     818            if which_quantity == 'stage':
     819                plot(model_time, stages, 'g-')
     820                units = 'm'
     821            if which_quantity == 'momentum':
     822                plot(model_time, momenta, 'g-')
     823                units = 'm^2 / sec'
     824            if which_quantity == 'xmomentum':
     825                plot(model_time, xmom, 'g-')
     826                units = 'm^2 / sec'
     827            if which_quantity == 'ymomentum':
     828                plot(model_time, ymom, 'g-')
     829                units = 'm^2 / sec'
     830            if which_quantity == 'velocity':
     831                plot(model_time, velocity, 'g-')
     832                units = 'm / sec'
     833            if which_quantity == 'bearing':
     834                due_east = 90.0*ones([len(model_time)])
     835                due_west = 270.0*ones([len(model_time)])
     836                plot(model_time, bearings, 'r-', model_time, due_west, '-.g',
     837                     model_time, due_east, '-.b')
     838                units = 'degrees from North'
     839                ax = axis([time_min, time_max, 0, 360])
     840                legend(('Bearing','West','East'))
     841
     842            xlabel('time (secs)')
     843            ylabel('%s (%s)' %(which_quantity, units))
     844
     845            gaugeloc1 = gaugeloc.replace(' ','_')
     846            graphname = '%splot_test_%s_%s%s' %(file_loc, which_quantity, gaugeloc1, ext)
     847            latex_file_loc = file_loc.replace(sep,altsep)
     848            graphname_latex = '%splot_test_%s_%s%s' %(latex_file_loc, which_quantity, gaugeloc1, ext)
     849
     850            if title_on == True:
     851                title('%s scenario: %s at %s gauge'
     852                      %(label_id, which_quantity, gaugeloc))
     853            else:
     854                label = '%s_%s_gauge_%s' %(label_id.replace(sep,'_'), which_quantity, gaugeloc1)
     855                caption = 'Time series for %s' %(which_quantity)
     856                s = '\\begin{figure}[hbt] \n \\centerline{\includegraphics[width=75mm, height=75mm]{%s}} \n' %(graphname_latex)
     857                fid.write(s)
     858                s = '\\caption{%s} \n \label{fig:%s} \n \end{figure} \n \n' %(caption, label)
     859                fid.write(s)
     860
     861            savefig(graphname)
     862       
     863        thisfile = file_loc+sep+'gauges_time_series'+'_'+gaugeloc+'.csv'
     864        fid_out = open(thisfile, 'w')
     865        s = 'Time, Depth, Momentum, Velocity \n'
     866        fid_out.write(s)
     867        for i_t, i_d, i_m, i_vel in zip(model_time, depths, momenta, velocity):
     868            s = '%.2f, %.2f, %.2f, %.2f\n' %(i_t, i_d, i_m, i_vel)
     869            fid_out.write(s)
     870           
     871        #### finished generating figures ###
     872
     873    close('all')
     874   
     875    return texfilename
Note: See TracChangeset for help on using the changeset viewer.