source: anuga_work/production/geraldton/NewScripts/build_urs_boundary.py @ 6374

Last change on this file since 6374 was 6374, checked in by nick2009, 14 years ago

Updated multimux false steps

File size: 6.7 KB
Line 
1"""
2Replacement function that wraps the legacy function urs2sts()
3and passes in the data from the EventSelection <event>.list file.
4"""
5
6import os
7import os.path
8from time import localtime, strftime, gmtime
9
10import project
11
12from Scientific.IO.NetCDF import NetCDFFile
13import Numeric as num
14
15from anuga.shallow_water.data_manager import urs2sts
16
17import Numeric as num
18
19
20#-------------------------------------------------------------------------------
21# Get gauges (timeseries of index points)
22#-------------------------------------------------------------------------------
23def get_sts_gauge_data(filename, verbose=False):
24    print 'get_sts_gauge_data: filename=%s' % filename
25    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
26    permutation = fid.variables['permutation'][:]
27    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
28    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
29    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
30    time = fid.variables['time'][:] + fid.starttime
31    elevation = fid.variables['elevation'][:]
32       
33    basename = 'sts_gauge'
34    quantity_names = ['stage', 'xmomentum', 'ymomentum']
35    quantities = {}
36    for i, name in enumerate(quantity_names):
37        quantities[name] = fid.variables[name][:]
38
39    #---------------------------------------------------------------------------
40    # Get maximum wave height throughout timeseries at each index point
41    #---------------------------------------------------------------------------
42
43    # create directory for generate STS file, if necessary
44    if not os.path.exists(project.event_sts):
45        os.mkdir(project.event_sts)
46       
47    maxname = 'max_sts_stage.csv'
48    print 'get_sts_gauge_data: maxname=%s' % maxname
49    fid_max = open(os.path.join(project.event_sts, maxname), 'w')
50    fid_max.write('index, x, y, max_stage \n')   
51    for j in range(len(x)):
52        index = permutation[j]
53        stage = quantities['stage'][:,j]
54        xmomentum = quantities['xmomentum'][:,j]
55        ymomentum = quantities['ymomentum'][:,j]
56
57        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
58     
59    #---------------------------------------------------------------------------
60    # Get minimum wave height throughout timeseries at each index point
61    #---------------------------------------------------------------------------
62
63    minname = 'min_sts_stage.csv'
64    fid_min = open(os.path.join(project.event_sts, minname), 'w')
65    fid_min.write('index, x, y, max_stage \n')   
66    for j in range(len(x)):
67        index = permutation[j]
68        stage = quantities['stage'][:,j]
69        xmomentum = quantities['xmomentum'][:,j]
70        ymomentum = quantities['ymomentum'][:,j]
71
72        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
73
74        out_file = os.path.join(project.event_sts,
75                                basename+'_'+str(index)+'.csv')
76        fid_sts = open(out_file, 'w')
77        fid_sts.write('time, stage, xmomentum, ymomentum \n')
78
79        #-----------------------------------------------------------------------
80        # End of the get gauges
81        #-----------------------------------------------------------------------
82        for k in range(len(time)-1):
83            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
84                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
85
86        fid_sts.close()     
87
88    fid.close()
89
90    return quantities,elevation,time
91
92
93##
94# @brief Build boundary STS files from one or more MUX files.
95# @param event_file Name of mux meta-file or single mux stem.
96# @param output_dir Directory to write STS data to.
97# @note 'event_file' is produced by EventSelection.
98def build_urs_boundary(event_file, output_dir):
99    '''Build a boundary STS file from a set of MUX files.'''
100
101    # if we are using an EventSelection multi-mux file
102    if project.multi_mux:
103        # get the mux+weight data from the meta-file (in <boundaries>)
104        mux_event_file = os.path.join(project.boundaries_folder, event_file)
105        print 'using multi-mux file', mux_event_file
106        try:
107            fd = open(mux_event_file, 'r')
108            mux_data = fd.readlines()
109            fd.close()
110        except IOError, e:
111            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
112            raise Exception, msg
113        except:
114            raise
115
116        # first line of file is # filenames+weight in rest of file
117        num_lines = int(mux_data[0].strip())
118        mux_data = mux_data[1:]
119        print 'number of sources %d' % num_lines
120
121        # quick sanity check on input mux meta-file
122        if num_lines != len(mux_data):
123            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
124                   % (event_file, len(mux_data), num_lines))
125            raise Exception, msg
126
127        # Create filename and weights lists.
128        # Must chop GRD filename just after '*.grd'.
129        mux_filenames = []
130        for line in mux_data:
131            muxname = line.strip().split()[0]
132            split_index = muxname.index('.grd')
133            muxname = muxname[:split_index+len('.grd')]
134            muxname = os.path.join(project.mux_data_folder, muxname)
135            mux_filenames.append(muxname)
136       
137        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
138
139        # Call legacy function to create STS file.
140        print 'creating sts file'
141        urs2sts(mux_filenames,
142                basename_out=output_dir,
143                ordering_filename=project.urs_order,
144                weights=mux_weights,
145                mean_stage=project.tide,
146                verbose=True)
147    else:                           # a single mux stem file, assume 1.0 weight
148        mux_file = os.path.join(project.event_folder, event_file)
149        mux_filenames = [mux_file]
150        print 'using single-mux file', mux_file
151
152        weight_factor = 1.0
153        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
154           
155        order_filename = project.urs_order
156
157        print 'reading', order_filename
158        # Create ordered sts file
159        urs2sts(mux_filenames,
160                basename_out=output_dir,
161                ordering_filename=order_filename,
162                weights=mux_weights,
163                mean_stage=project.tide,
164                verbose=True)
165
166    # report on progress so far
167    sts_file = os.path.join(project.event_folder, project.scenario_name)
168    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
169    print len(elevation), len(quantities['stage'][0,:])
170
171   
172
Note: See TracBrowser for help on using the repository browser.