1 | """datamanager.py - input output for AnuGA |
---|
2 | |
---|
3 | |
---|
4 | This module takes care of reading and writing datafiles such as topograhies, |
---|
5 | model output, etc |
---|
6 | |
---|
7 | |
---|
8 | Formats used within AnuGA: |
---|
9 | |
---|
10 | .sww: Netcdf format for storing model output f(t,x,y) |
---|
11 | .tms: Netcdf format for storing time series f(t) |
---|
12 | |
---|
13 | .csv: ASCII format for storing arbitrary points and associated attributes |
---|
14 | .pts: NetCDF format for storing arbitrary points and associated attributes |
---|
15 | |
---|
16 | .asc: ASCII format of regular DEMs as output from ArcView |
---|
17 | .prj: Associated ArcView file giving more meta data for asc format |
---|
18 | .ers: ERMapper header format of regular DEMs for ArcView |
---|
19 | |
---|
20 | .dem: NetCDF representation of regular DEM data |
---|
21 | |
---|
22 | .tsh: ASCII format for storing meshes and associated boundary and region info |
---|
23 | .msh: NetCDF format for storing meshes and associated boundary and region info |
---|
24 | |
---|
25 | .nc: Native ferret NetCDF format |
---|
26 | .geo: Houdinis ascii geometry format (?) |
---|
27 | |
---|
28 | |
---|
29 | A typical dataflow can be described as follows |
---|
30 | |
---|
31 | Manually created files: |
---|
32 | ASC, PRJ:Â Â Â Digital elevation models (gridded) |
---|
33 | TSH:Â Â Â Â Â Triangular meshes (e.g. created from anuga.pmesh) |
---|
34 | NCÂ Â Â Â Â Â Model outputs for use as boundary conditions (e.g from MOST) |
---|
35 | |
---|
36 | |
---|
37 | AUTOMATICALLY CREATED FILES: |
---|
38 | |
---|
39 | ASC, PRJÂ ->Â DEMÂ ->Â PTS: Conversion of DEM's to native pts file |
---|
40 | |
---|
41 | NC -> SWW: Conversion of MOST bundary files to boundary sww |
---|
42 | |
---|
43 | PTS + TSH -> TSH with elevation: Least squares fit |
---|
44 | |
---|
45 | TSH -> SWW:Â Conversion of TSH to sww viewable using Swollen |
---|
46 | |
---|
47 | TSH + Boundary SWW -> SWW: Simluation using abstract_2d_finite_volumes |
---|
48 | |
---|
49 | """ |
---|
50 | |
---|
51 | import exceptions |
---|
52 | class TitleValueError(exceptions.Exception): pass |
---|
53 | class DataMissingValuesError(exceptions.Exception): pass |
---|
54 | class DataFileNotOpenError(exceptions.Exception): pass |
---|
55 | class DataTimeError(exceptions.Exception): pass |
---|
56 | class DataDomainError(exceptions.Exception): pass |
---|
57 | class NewQuantity(exceptions.Exception): pass |
---|
58 | |
---|
59 | |
---|
60 | |
---|
61 | import csv |
---|
62 | import os, sys |
---|
63 | import shutil |
---|
64 | from struct import unpack |
---|
65 | import array as p_array |
---|
66 | #import time, os |
---|
67 | from os import sep, path, remove, mkdir, access, F_OK, W_OK, getcwd |
---|
68 | |
---|
69 | |
---|
70 | from Numeric import concatenate, array, Float, Int, Int32, resize, \ |
---|
71 |    sometrue, searchsorted, zeros, allclose, around, reshape, \ |
---|
72 |    transpose, sort, NewAxis, ArrayType, compress, take, arange, \ |
---|
73 |    argmax, alltrue, shape, Float32, size |
---|
74 | |
---|
75 | import string |
---|
76 | |
---|
77 | from Scientific.IO.NetCDF import NetCDFFile |
---|
78 | #from shutil import copy |
---|
79 | from os.path import exists, basename, join |
---|
80 | from os import getcwd |
---|
81 | |
---|
82 | |
---|
83 | from anuga.coordinate_transforms.redfearn import redfearn, \ |
---|
84 | Â Â Â convert_from_latlon_to_utm |
---|
85 | from anuga.coordinate_transforms.geo_reference import Geo_reference, \ |
---|
86 |    write_NetCDF_georeference, ensure_geo_reference |
---|
87 | from anuga.geospatial_data.geospatial_data import Geospatial_data,\ |
---|
88 | Â Â Â ensure_absolute |
---|
89 | from anuga.config import minimum_storable_height as default_minimum_storable_height |
---|
90 | from anuga.config import max_float |
---|
91 | from anuga.utilities.numerical_tools import ensure_numeric, mean |
---|
92 | from anuga.caching.caching import myhash |
---|
93 | from anuga.utilities.anuga_exceptions import ANUGAError |
---|
94 | from anuga.shallow_water import Domain |
---|
95 | from anuga.abstract_2d_finite_volumes.pmesh2domain import \ |
---|
96 | Â Â Â pmesh_to_domain_instance |
---|
97 | from anuga.abstract_2d_finite_volumes.util import get_revision_number, \ |
---|
98 |    remove_lone_verts, sww2timeseries, get_centroid_values |
---|
99 | from anuga.load_mesh.loadASCII import export_mesh_file |
---|
100 | from anuga.utilities.polygon import intersection |
---|
101 | |
---|
102 | |
---|
103 | # formula mappings |
---|
104 | |
---|
105 | quantity_formula =Â {'momentum':'(xmomentum**2 + ymomentum**2)**0.5', |
---|
106 | Â Â Â Â Â Â Â Â Â Â 'depth':'stage-elevation', |
---|
107 | Â Â Â Â Â Â Â Â Â Â 'speed':Â \ |
---|
108 | Â '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'} |
---|
109 | |
---|
110 | |
---|
111 | Â Â |
---|
112 | def make_filename(s): |
---|
113 | Â Â """Transform argument string into a Sexsuitable filename |
---|
114 | Â Â """ |
---|
115 | |
---|
116 | Â Â s =Â s.strip() |
---|
117 |   s = s.replace(' ', '_') |
---|
118 |   s = s.replace('(', '') |
---|
119 |   s = s.replace(')', '') |
---|
120 |   s = s.replace('__', '_') |
---|
121 | |
---|
122 |   return s |
---|
123 | |
---|
124 | |
---|
125 | def check_dir(path, verbose=None): |
---|
126 | Â Â """Check that specified path exists. |
---|
127 | Â Â If path does not exist it will be created if possible |
---|
128 | |
---|
129 | Â Â USAGE: |
---|
130 | Â Â Â Â checkdir(path, verbose): |
---|
131 | |
---|
132 | Â Â ARGUMENTS: |
---|
133 | Â Â Â Â path -- Directory |
---|
134 | Â Â Â Â verbose -- Flag verbose output (default: None) |
---|
135 | |
---|
136 | Â Â RETURN VALUE: |
---|
137 | Â Â Â Â Verified path including trailing separator |
---|
138 | |
---|
139 | Â Â """ |
---|
140 | |
---|
141 |   import os.path |
---|
142 | |
---|
143 |   if sys.platform in ['nt', 'dos', 'win32', 'what else?']: |
---|
144 | Â Â Â Â unix =Â 0 |
---|
145 | Â Â else: |
---|
146 | Â Â Â Â unix =Â 1 |
---|
147 | |
---|
148 | |
---|
149 |   if path[-1] != os.sep: |
---|
150 |     path = path + os.sep # Add separator for directories |
---|
151 | |
---|
152 | Â Â path =Â os.path.expanduser(path)Â # Expand ~ or ~user in pathname |
---|
153 |   if not (os.access(path,os.R_OK and os.W_OK) or path == ''): |
---|
154 | Â Â Â Â try: |
---|
155 | Â Â Â Â Â Â exitcode=os.mkdir(path) |
---|
156 | |
---|
157 | Â Â Â Â Â Â # Change access rights if possible |
---|
158 | Â Â Â Â Â Â # |
---|
159 |       if unix: |
---|
160 | Â Â Â Â Â Â Â Â exitcode=os.system('chmod 775 '+path) |
---|
161 | Â Â Â Â Â Â else: |
---|
162 |         pass # FIXME: What about acces rights under Windows? |
---|
163 | |
---|
164 |       if verbose: print 'MESSAGE: Directory', path, 'created.' |
---|
165 | |
---|
166 | Â Â Â Â except: |
---|
167 |       print 'WARNING: Directory', path, 'could not be created.' |
---|
168 |       if unix: |
---|
169 | Â Â Â Â Â Â Â Â path =Â '/tmp/' |
---|
170 | Â Â Â Â Â Â else: |
---|
171 | Â Â Â Â Â Â Â Â path =Â 'C:' |
---|
172 | |
---|
173 |       print 'Using directory %s instead' %path |
---|
174 | |
---|
175 | Â Â return(path) |
---|
176 | |
---|
177 | |
---|
178 | |
---|
179 | def del_dir(path): |
---|
180 | Â Â """Recursively delete directory path and all its contents |
---|
181 | Â Â """ |
---|
182 | |
---|
183 |   import os |
---|
184 | |
---|
185 |   if os.path.isdir(path): |
---|
186 |     for file in os.listdir(path): |
---|
187 |       X = os.path.join(path, file) |
---|
188 | |
---|
189 | |
---|
190 |       if os.path.isdir(X) and not os.path.islink(X): |
---|
191 | Â Â Â Â Â Â Â Â del_dir(X) |
---|
192 | Â Â Â Â Â Â else: |
---|
193 | Â Â Â Â Â Â Â Â try: |
---|
194 | Â Â Â Â Â Â Â Â Â Â os.remove(X) |
---|
195 | Â Â Â Â Â Â Â Â except: |
---|
196 |           print "Could not remove file %s" %X |
---|
197 | |
---|
198 | Â Â Â Â os.rmdir(path) |
---|
199 | Â Â Â Â |
---|
200 | Â Â Â Â |
---|
201 | # ANOTHER OPTION, IF NEED IN THE FUTURE, Nick B 7/2007Â Â |
---|
202 | def rmgeneric(path, __func__,verbose=False): |
---|
203 |   ERROR_STR= """Error removing %(path)s, %(error)s """ |
---|
204 | |
---|
205 | Â Â try: |
---|
206 | Â Â Â Â __func__(path) |
---|
207 |     if verbose: print 'Removed ', path |
---|
208 |   except OSError, (errno, strerror): |
---|
209 |     print ERROR_STR % {'path' : path, 'error': strerror } |
---|
210 | Â Â Â Â Â Â |
---|
211 | def removeall(path,verbose=False): |
---|
212 | |
---|
213 |   if not os.path.isdir(path): |
---|
214 | Â Â Â Â return |
---|
215 | Â Â |
---|
216 | Â Â files=os.listdir(path) |
---|
217 | |
---|
218 |   for x in files: |
---|
219 |     fullpath=os.path.join(path, x) |
---|
220 |     if os.path.isfile(fullpath): |
---|
221 | Â Â Â Â Â Â f=os.remove |
---|
222 |       rmgeneric(fullpath, f) |
---|
223 |     elif os.path.isdir(fullpath): |
---|
224 | Â Â Â Â Â Â removeall(fullpath) |
---|
225 | Â Â Â Â Â Â f=os.rmdir |
---|
226 |       rmgeneric(fullpath, f,verbose) |
---|
227 | |
---|
228 | |
---|
229 | |
---|
230 | def create_filename(datadir, filename, format, size=None, time=None): |
---|
231 | |
---|
232 |   import os |
---|
233 | Â Â #from anuga.config import data_dir |
---|
234 | |
---|
235 | Â Â FN =Â check_dir(datadir)Â +Â filename |
---|
236 | |
---|
237 |   if size is not None: |
---|
238 | Â Â Â Â FN +=Â '_size%d'Â %size |
---|
239 | |
---|
240 |   if time is not None: |
---|
241 | Â Â Â Â FN +=Â '_time%.2f'Â %time |
---|
242 | |
---|
243 | Â Â FN +=Â '.'Â +Â format |
---|
244 |   return FN |
---|
245 | |
---|
246 | |
---|
247 | def get_files(datadir, filename, format, size): |
---|
248 | Â Â """Get all file (names) with given name, size and format |
---|
249 | Â Â """ |
---|
250 | |
---|
251 |   import glob |
---|
252 | |
---|
253 |   import os |
---|
254 | Â Â #from anuga.config import data_dir |
---|
255 | |
---|
256 |   dir = check_dir(datadir) |
---|
257 | |
---|
258 |   pattern = dir + os.sep + filename + '_size=%d*.%s' %(size, format) |
---|
259 |   return glob.glob(pattern) |
---|
260 | |
---|
261 | |
---|
262 | |
---|
263 | #Generic class for storing output to e.g. visualisation or checkpointing |
---|
264 | class Data_format: |
---|
265 | Â Â """Generic interface to data formats |
---|
266 | Â Â """ |
---|
267 | |
---|
268 | |
---|
269 |   def __init__(self, domain, extension, mode = 'w'): |
---|
270 |     assert mode in ['r', 'w', 'a'], '''Mode %s must be either:''' %mode +\ |
---|
271 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â '''Â Â 'w' (write)'''+\ |
---|
272 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â '''Â Â 'r' (read)'''Â +\ |
---|
273 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â '''Â Â 'a' (append)''' |
---|
274 | |
---|
275 | Â Â Â Â #Create filename |
---|
276 | Â Â Â Â self.filename =Â create_filename(domain.get_datadir(), |
---|
277 |                     domain.get_name(), extension) |
---|
278 | |
---|
279 | Â Â Â Â #print 'F', self.filename |
---|
280 | Â Â Â Â self.timestep =Â 0 |
---|
281 | Â Â Â Â self.domain =Â domain |
---|
282 | Â Â Â Â |
---|
283 | |
---|
284 | |
---|
285 | Â Â Â Â # Exclude ghosts in case this is a parallel domain |
---|
286 |     self.number_of_nodes = domain.number_of_full_nodes    |
---|
287 | Â Â Â Â self.number_of_volumes =Â domain.number_of_full_triangles |
---|
288 | Â Â Â Â #self.number_of_volumes = len(domain)Â Â Â Â |
---|
289 | |
---|
290 | |
---|
291 | |
---|
292 | |
---|
293 | Â Â Â Â #FIXME: Should we have a general set_precision function? |
---|
294 | |
---|
295 | |
---|
296 | |
---|
297 | #Class for storing output to e.g. visualisation |
---|
298 | class Data_format_sww(Data_format): |
---|
299 | Â Â """Interface to native NetCDF format (.sww) for storing model output |
---|
300 | |
---|
301 | Â Â There are two kinds of data |
---|
302 | |
---|
303 | Â Â 1: Constant data: Vertex coordinates and field values. Stored once |
---|
304 | Â Â 2: Variable data: Conserved quantities. Stored once per timestep. |
---|
305 | |
---|
306 | Â Â All data is assumed to reside at vertex locations. |
---|
307 | Â Â """ |
---|
308 | |
---|
309 | |
---|
310 |   def __init__(self, domain, mode = 'w',\ |
---|
311 | Â Â Â Â Â Â Â Â Â max_size =Â 2000000000, |
---|
312 | Â Â Â Â Â Â Â Â Â recursion =Â False): |
---|
313 |     from Scientific.IO.NetCDF import NetCDFFile |
---|
314 |     from Numeric import Int, Float, Float32 |
---|
315 | |
---|
316 | Â Â Â Â self.precision =Â Float32 #Use single precision for quantities |
---|
317 |     if hasattr(domain, 'max_size'): |
---|
318 | Â Â Â Â Â Â self.max_size =Â domain.max_size #file size max is 2Gig |
---|
319 | Â Â Â Â else: |
---|
320 | Â Â Â Â Â Â self.max_size =Â max_size |
---|
321 | Â Â Â Â self.recursion =Â recursion |
---|
322 | Â Â Â Â self.mode =Â mode |
---|
323 | |
---|
324 |     Data_format.__init__(self, domain, 'sww', mode) |
---|
325 | |
---|
326 |     if hasattr(domain, 'minimum_storable_height'): |
---|
327 | Â Â Â Â Â Â self.minimum_storable_height =Â domain.minimum_storable_height |
---|
328 | Â Â Â Â else: |
---|
329 | Â Â Â Â Â Â self.minimum_storable_height =Â default_minimum_storable_height |
---|
330 | |
---|
331 | Â Â Â Â # NetCDF file definition |
---|
332 |     fid = NetCDFFile(self.filename, mode) |
---|
333 | |
---|
334 |     if mode == 'w': |
---|
335 | Â Â Â Â Â Â description =Â 'Output from anuga.abstract_2d_finite_volumes suitable for plotting' |
---|
336 | Â Â Â Â Â Â self.writer =Â Write_sww() |
---|
337 | Â Â Â Â Â Â self.writer.store_header(fid, |
---|
338 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â domain.starttime, |
---|
339 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â self.number_of_volumes, |
---|
340 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â self.domain.number_of_full_nodes, |
---|
341 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â description=description, |
---|
342 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â smoothing=domain.smooth, |
---|
343 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â order=domain.default_order, |
---|
344 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â sww_precision=self.precision) |
---|
345 | |
---|
346 | Â Â Â Â Â Â # Extra optional information |
---|
347 |       if hasattr(domain, 'texture'): |
---|
348 | Â Â Â Â Â Â Â Â fid.texture =Â domain.texture |
---|
349 | |
---|
350 |       if domain.quantities_to_be_monitored is not None: |
---|
351 |         fid.createDimension('singleton', 1) |
---|
352 |         fid.createDimension('two', 2)        |
---|
353 | |
---|
354 | Â Â Â Â Â Â Â Â poly =Â domain.monitor_polygon |
---|
355 |         if poly is not None: |
---|
356 | Â Â Â Â Â Â Â Â Â Â N =Â len(poly) |
---|
357 |           fid.createDimension('polygon_length', N) |
---|
358 | Â Â Â Â Â Â Â Â Â Â fid.createVariable('extrema.polygon', |
---|
359 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â self.precision, |
---|
360 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('polygon_length', |
---|
361 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'two')) |
---|
362 |           fid.variables['extrema.polygon'][:] = poly                  |
---|
363 | |
---|
364 | Â Â Â Â Â Â Â Â Â Â |
---|
365 | Â Â Â Â Â Â Â Â interval =Â domain.monitor_time_interval |
---|
366 |         if interval is not None: |
---|
367 | Â Â Â Â Â Â Â Â Â Â fid.createVariable('extrema.time_interval', |
---|
368 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â self.precision, |
---|
369 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('two',)) |
---|
370 | Â Â Â Â Â Â Â Â Â Â fid.variables['extrema.time_interval'][:]Â =Â interval |
---|
371 | |
---|
372 | Â Â Â Â Â Â Â Â |
---|
373 |         for q in domain.quantities_to_be_monitored: |
---|
374 | Â Â Â Â Â Â Â Â Â Â #print 'doing', q |
---|
375 |           fid.createVariable(q+'.extrema', self.precision, |
---|
376 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('numbers_in_range',)) |
---|
377 |           fid.createVariable(q+'.min_location', self.precision, |
---|
378 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('numbers_in_range',)) |
---|
379 |           fid.createVariable(q+'.max_location', self.precision, |
---|
380 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('numbers_in_range',)) |
---|
381 |           fid.createVariable(q+'.min_time', self.precision, |
---|
382 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('singleton',)) |
---|
383 |           fid.createVariable(q+'.max_time', self.precision, |
---|
384 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('singleton',)) |
---|
385 | |
---|
386 | Â Â Â Â Â Â Â Â Â Â |
---|
387 | Â Â Â Â fid.close() |
---|
388 | |
---|
389 | |
---|
390 |   def store_connectivity(self): |
---|
391 | Â Â Â Â """Specialisation of store_connectivity for net CDF format |
---|
392 | |
---|
393 | Â Â Â Â Writes x,y,z coordinates of triangles constituting |
---|
394 | Â Â Â Â the bed elevation. |
---|
395 | Â Â Â Â """ |
---|
396 | |
---|
397 |     from Scientific.IO.NetCDF import NetCDFFile |
---|
398 | |
---|
399 |     from Numeric import concatenate, Int |
---|
400 | |
---|
401 | Â Â Â Â domain =Â self.domain |
---|
402 | |
---|
403 | Â Â Â Â #Get NetCDF |
---|
404 |     fid = NetCDFFile(self.filename, 'a') #Open existing file for append |
---|
405 | |
---|
406 | Â Â Â Â # Get the variables |
---|
407 | Â Â Â Â x =Â fid.variables['x'] |
---|
408 | Â Â Â Â y =Â fid.variables['y'] |
---|
409 | Â Â Â Â z =Â fid.variables['elevation'] |
---|
410 | |
---|
411 | Â Â Â Â volumes =Â fid.variables['volumes'] |
---|
412 | |
---|
413 | Â Â Â Â # Get X, Y and bed elevation Z |
---|
414 | Â Â Â Â Q =Â domain.quantities['elevation'] |
---|
415 | Â Â Â Â X,Y,Z,V =Â Q.get_vertex_values(xy=True, |
---|
416 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â precision=self.precision) |
---|
417 | |
---|
418 | Â Â Â Â # |
---|
419 |     points = concatenate( (X[:,NewAxis],Y[:,NewAxis]), axis=1 ) |
---|
420 | Â Â Â Â self.writer.store_triangulation(fid, |
---|
421 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â points, |
---|
422 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â V.astype(volumes.typecode()), |
---|
423 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Z, |
---|
424 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â points_georeference=Â \ |
---|
425 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â domain.geo_reference) |
---|
426 | |
---|
427 | Â Â Â Â # Close |
---|
428 | Â Â Â Â fid.close() |
---|
429 | |
---|
430 | |
---|
431 |   def store_timestep(self, names=None): |
---|
432 | Â Â Â Â """Store time and named quantities to file |
---|
433 | Â Â Â Â """ |
---|
434 | Â Â Â Â |
---|
435 |     from Scientific.IO.NetCDF import NetCDFFile |
---|
436 |     import types |
---|
437 |     from time import sleep |
---|
438 |     from os import stat |
---|
439 | |
---|
440 |     from Numeric import choose |
---|
441 | |
---|
442 | |
---|
443 |     if names is None: |
---|
444 | Â Â Â Â Â Â # Standard shallow water wave equation quantitites in ANUGA |
---|
445 |       names = ['stage', 'xmomentum', 'ymomentum'] |
---|
446 | Â Â Â Â |
---|
447 | Â Â Â Â # Get NetCDFÂ Â Â Â |
---|
448 | Â Â Â Â retries =Â 0 |
---|
449 | Â Â Â Â file_open =Â False |
---|
450 |     while not file_open and retries < 10: |
---|
451 | Â Â Â Â Â Â try: |
---|
452 |         fid = NetCDFFile(self.filename, 'a') # Open existing file |
---|
453 |       except IOError: |
---|
454 | Â Â Â Â Â Â Â Â # This could happen if someone was reading the file. |
---|
455 | Â Â Â Â Â Â Â Â # In that case, wait a while and try again |
---|
456 |         msg = 'Warning (store_timestep): File %s could not be opened'\ |
---|
457 | Â Â Â Â Â Â Â Â Â Â Â %self.filename |
---|
458 |         msg += ' - trying step %s again' %self.domain.time |
---|
459 |         print msg |
---|
460 | Â Â Â Â Â Â Â Â retries +=Â 1 |
---|
461 | Â Â Â Â Â Â Â Â sleep(1) |
---|
462 | Â Â Â Â Â Â else: |
---|
463 | Â Â Â Â Â Â Â Â file_open =Â True |
---|
464 | |
---|
465 |     if not file_open: |
---|
466 |       msg = 'File %s could not be opened for append' %self.filename |
---|
467 |       raise DataFileNotOpenError, msg |
---|
468 | |
---|
469 | |
---|
470 | |
---|
471 | Â Â Â Â # Check to see if the file is already too big: |
---|
472 | Â Â Â Â time =Â fid.variables['time'] |
---|
473 | Â Â Â Â i =Â len(time)+1 |
---|
474 | Â Â Â Â file_size =Â stat(self.filename)[6] |
---|
475 | Â Â Â Â file_size_increase =Â file_size/i |
---|
476 |     if file_size + file_size_increase > self.max_size*(2**self.recursion): |
---|
477 | Â Â Â Â Â Â # In order to get the file name and start time correct, |
---|
478 | Â Â Â Â Â Â # I change the domain.filename and domain.starttime. |
---|
479 | Â Â Â Â Â Â # This is the only way to do this without changing |
---|
480 | Â Â Â Â Â Â # other modules (I think). |
---|
481 | |
---|
482 | Â Â Â Â Â Â # Write a filename addon that won't break swollens reader |
---|
483 | Â Â Â Â Â Â # (10.sww is bad) |
---|
484 | Â Â Â Â Â Â filename_ext =Â '_time_%s'%self.domain.time |
---|
485 |       filename_ext = filename_ext.replace('.', '_') |
---|
486 | Â Â Â Â Â Â |
---|
487 | Â Â Â Â Â Â # Remember the old filename, then give domain a |
---|
488 | Â Â Â Â Â Â # name with the extension |
---|
489 | Â Â Â Â Â Â old_domain_filename =Â self.domain.get_name() |
---|
490 |       if not self.recursion: |
---|
491 | Â Â Â Â Â Â Â Â self.domain.set_name(old_domain_filename+filename_ext) |
---|
492 | |
---|
493 | |
---|
494 | Â Â Â Â Â Â # Change the domain starttime to the current time |
---|
495 | Â Â Â Â Â Â old_domain_starttime =Â self.domain.starttime |
---|
496 | Â Â Â Â Â Â self.domain.starttime =Â self.domain.time |
---|
497 | |
---|
498 | Â Â Â Â Â Â # Build a new data_structure. |
---|
499 | Â Â Â Â Â Â next_data_structure=\ |
---|
500 |         Data_format_sww(self.domain, mode=self.mode,\ |
---|
501 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â max_size =Â self.max_size,\ |
---|
502 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â recursion =Â self.recursion+1) |
---|
503 |       if not self.recursion: |
---|
504 |         print '  file_size = %s'%file_size |
---|
505 |         print '  saving file to %s'%next_data_structure.filename |
---|
506 | Â Â Â Â Â Â #set up the new data_structure |
---|
507 | Â Â Â Â Â Â self.domain.writer =Â next_data_structure |
---|
508 | |
---|
509 | Â Â Â Â Â Â #FIXME - could be cleaner to use domain.store_timestep etc. |
---|
510 | Â Â Â Â Â Â next_data_structure.store_connectivity() |
---|
511 | Â Â Â Â Â Â next_data_structure.store_timestep(names) |
---|
512 | Â Â Â Â Â Â fid.sync() |
---|
513 | Â Â Â Â Â Â fid.close() |
---|
514 | |
---|
515 | Â Â Â Â Â Â #restore the old starttime and filename |
---|
516 | Â Â Â Â Â Â self.domain.starttime =Â old_domain_starttime |
---|
517 | Â Â Â Â Â Â self.domain.set_name(old_domain_filename)Â Â Â Â Â Â |
---|
518 | Â Â Â Â else: |
---|
519 | Â Â Â Â Â Â self.recursion =Â False |
---|
520 | Â Â Â Â Â Â domain =Â self.domain |
---|
521 | |
---|
522 | Â Â Â Â Â Â # Get the variables |
---|
523 | Â Â Â Â Â Â time =Â fid.variables['time'] |
---|
524 | Â Â Â Â Â Â stage =Â fid.variables['stage'] |
---|
525 | Â Â Â Â Â Â xmomentum =Â fid.variables['xmomentum'] |
---|
526 | Â Â Â Â Â Â ymomentum =Â fid.variables['ymomentum'] |
---|
527 | Â Â Â Â Â Â i =Â len(time) |
---|
528 |       if type(names) not in [types.ListType, types.TupleType]: |
---|
529 | Â Â Â Â Â Â Â Â names =Â [names] |
---|
530 | |
---|
531 |       if 'stage' in names and 'xmomentum' in names and \ |
---|
532 |         'ymomentum' in names: |
---|
533 | |
---|
534 | Â Â Â Â Â Â Â Â # Get stage, elevation, depth and select only those |
---|
535 | Â Â Â Â Â Â Â Â # values where minimum_storable_height is exceeded |
---|
536 | Â Â Â Â Â Â Â Â Q =Â domain.quantities['stage'] |
---|
537 |         A, _ = Q.get_vertex_values(xy = False, |
---|
538 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â precision =Â self.precision) |
---|
539 | Â Â Â Â Â Â Â Â z =Â fid.variables['elevation'] |
---|
540 | |
---|
541 | Â Â Â Â Â Â Â Â storable_indices =Â A-z[:]Â >=Â self.minimum_storable_height |
---|
542 |         stage = choose(storable_indices, (z[:], A)) |
---|
543 | Â Â Â Â Â Â Â Â |
---|
544 | Â Â Â Â Â Â Â Â # Define a zero vector of same size and type as A |
---|
545 | Â Â Â Â Â Â Â Â # for use with momenta |
---|
546 |         null = zeros(size(A), A.typecode()) |
---|
547 | Â Â Â Â Â Â Â Â |
---|
548 | Â Â Â Â Â Â Â Â # Get xmomentum where depth exceeds minimum_storable_height |
---|
549 | Â Â Â Â Â Â Â Â Q =Â domain.quantities['xmomentum'] |
---|
550 |         xmom, _ = Q.get_vertex_values(xy = False, |
---|
551 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â precision =Â self.precision) |
---|
552 |         xmomentum = choose(storable_indices, (null, xmom)) |
---|
553 | Â Â Â Â Â Â Â Â |
---|
554 | |
---|
555 | Â Â Â Â Â Â Â Â # Get ymomentum where depth exceeds minimum_storable_height |
---|
556 | Â Â Â Â Â Â Â Â Q =Â domain.quantities['ymomentum'] |
---|
557 |         ymom, _ = Q.get_vertex_values(xy = False, |
---|
558 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â precision =Â self.precision) |
---|
559 |         ymomentum = choose(storable_indices, (null, ymom))        |
---|
560 | Â Â Â Â Â Â Â Â |
---|
561 | Â Â Â Â Â Â Â Â # Write quantities to NetCDF |
---|
562 |         self.writer.store_quantities(fid, |
---|
563 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â time=self.domain.time, |
---|
564 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â sww_precision=self.precision, |
---|
565 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â stage=stage, |
---|
566 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â xmomentum=xmomentum, |
---|
567 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ymomentum=ymomentum) |
---|
568 | Â Â Â Â Â Â else: |
---|
569 | Â Â Â Â Â Â Â Â msg =Â 'Quantities stored must be: stage, xmomentum, ymomentum.' |
---|
570 | Â Â Â Â Â Â Â Â msg +=Â ' Instead I got: 'Â +Â str(names) |
---|
571 |         raise Exception, msg |
---|
572 | Â Â Â Â Â Â |
---|
573 | |
---|
574 | |
---|
575 | Â Â Â Â Â Â # Update extrema if requested |
---|
576 | Â Â Â Â Â Â domain =Â self.domain |
---|
577 |       if domain.quantities_to_be_monitored is not None: |
---|
578 |         for q, info in domain.quantities_to_be_monitored.items(): |
---|
579 | |
---|
580 |           if info['min'] is not None: |
---|
581 | Â Â Â Â Â Â Â Â Â Â Â Â fid.variables[q +Â '.extrema'][0]Â =Â info['min'] |
---|
582 | Â Â Â Â Â Â Â Â Â Â Â Â fid.variables[q +Â '.min_location'][:]Â =\ |
---|
583 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â info['min_location'] |
---|
584 | Â Â Â Â Â Â Â Â Â Â Â Â fid.variables[q +Â '.min_time'][0]Â =Â info['min_time'] |
---|
585 | Â Â Â Â Â Â Â Â Â Â Â Â |
---|
586 |           if info['max'] is not None: |
---|
587 | Â Â Â Â Â Â Â Â Â Â Â Â fid.variables[q +Â '.extrema'][1]Â =Â info['max'] |
---|
588 | Â Â Â Â Â Â Â Â Â Â Â Â fid.variables[q +Â '.max_location'][:]Â =\ |
---|
589 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â info['max_location'] |
---|
590 | Â Â Â Â Â Â Â Â Â Â Â Â fid.variables[q +Â '.max_time'][0]Â =Â info['max_time'] |
---|
591 | |
---|
592 | Â Â Â Â Â Â |
---|
593 | |
---|
594 | Â Â Â Â Â Â # Flush and close |
---|
595 | Â Â Â Â Â Â fid.sync() |
---|
596 | Â Â Â Â Â Â fid.close() |
---|
597 | |
---|
598 | |
---|
599 | |
---|
600 | # Class for handling checkpoints data |
---|
601 | class Data_format_cpt(Data_format): |
---|
602 | Â Â """Interface to native NetCDF format (.cpt) |
---|
603 | Â Â """ |
---|
604 | |
---|
605 | |
---|
606 |   def __init__(self, domain, mode = 'w'): |
---|
607 |     from Scientific.IO.NetCDF import NetCDFFile |
---|
608 |     from Numeric import Int, Float, Float |
---|
609 | |
---|
610 | Â Â Â Â self.precision =Â Float #Use full precision |
---|
611 | |
---|
612 |     Data_format.__init__(self, domain, 'sww', mode) |
---|
613 | |
---|
614 | |
---|
615 | Â Â Â Â # NetCDF file definition |
---|
616 |     fid = NetCDFFile(self.filename, mode) |
---|
617 | |
---|
618 |     if mode == 'w': |
---|
619 | Â Â Â Â Â Â #Create new file |
---|
620 | Â Â Â Â Â Â fid.institution =Â 'Geoscience Australia' |
---|
621 | Â Â Â Â Â Â fid.description =Â 'Checkpoint data' |
---|
622 | Â Â Â Â Â Â #fid.smooth = domain.smooth |
---|
623 | Â Â Â Â Â Â fid.order =Â domain.default_order |
---|
624 | |
---|
625 | Â Â Â Â Â Â # dimension definitions |
---|
626 |       fid.createDimension('number_of_volumes', self.number_of_volumes) |
---|
627 |       fid.createDimension('number_of_vertices', 3) |
---|
628 | |
---|
629 | Â Â Â Â Â Â #Store info at all vertices (no smoothing) |
---|
630 |       fid.createDimension('number_of_points', 3*self.number_of_volumes) |
---|
631 |       fid.createDimension('number_of_timesteps', None) #extensible |
---|
632 | |
---|
633 | Â Â Â Â Â Â # variable definitions |
---|
634 | |
---|
635 | Â Â Â Â Â Â #Mesh |
---|
636 |       fid.createVariable('x', self.precision, ('number_of_points',)) |
---|
637 |       fid.createVariable('y', self.precision, ('number_of_points',)) |
---|
638 | |
---|
639 | |
---|
640 |       fid.createVariable('volumes', Int, ('number_of_volumes', |
---|
641 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_vertices')) |
---|
642 | |
---|
643 |       fid.createVariable('time', self.precision, |
---|
644 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps',)) |
---|
645 | |
---|
646 | Â Â Â Â Â Â #Allocate space for all quantities |
---|
647 |       for name in domain.quantities.keys(): |
---|
648 |         fid.createVariable(name, self.precision, |
---|
649 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps', |
---|
650 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_points')) |
---|
651 | |
---|
652 | Â Â Â Â #Close |
---|
653 | Â Â Â Â fid.close() |
---|
654 | |
---|
655 | |
---|
656 |   def store_checkpoint(self): |
---|
657 | Â Â Â Â """ |
---|
658 | Â Â Â Â Write x,y coordinates of triangles. |
---|
659 | Â Â Â Â Write connectivity ( |
---|
660 | Â Â Â Â constituting |
---|
661 | Â Â Â Â the bed elevation. |
---|
662 | Â Â Â Â """ |
---|
663 | |
---|
664 |     from Scientific.IO.NetCDF import NetCDFFile |
---|
665 | |
---|
666 |     from Numeric import concatenate |
---|
667 | |
---|
668 | Â Â Â Â domain =Â self.domain |
---|
669 | |
---|
670 | Â Â Â Â #Get NetCDF |
---|
671 |     fid = NetCDFFile(self.filename, 'a') #Open existing file for append |
---|
672 | |
---|
673 | Â Â Â Â # Get the variables |
---|
674 | Â Â Â Â x =Â fid.variables['x'] |
---|
675 | Â Â Â Â y =Â fid.variables['y'] |
---|
676 | |
---|
677 | Â Â Â Â volumes =Â fid.variables['volumes'] |
---|
678 | |
---|
679 | Â Â Â Â # Get X, Y and bed elevation Z |
---|
680 | Â Â Â Â Q =Â domain.quantities['elevation'] |
---|
681 | Â Â Â Â X,Y,Z,V =Â Q.get_vertex_values(xy=True, |
---|
682 | Â Â Â Â Â Â Â Â Â Â Â precision =Â self.precision) |
---|
683 | |
---|
684 | |
---|
685 | |
---|
686 | Â Â Â Â x[:]Â =Â X.astype(self.precision) |
---|
687 | Â Â Â Â y[:]Â =Â Y.astype(self.precision) |
---|
688 | Â Â Â Â z[:]Â =Â Z.astype(self.precision) |
---|
689 | |
---|
690 | Â Â Â Â volumes[:]Â =Â V |
---|
691 | |
---|
692 | Â Â Â Â #Close |
---|
693 | Â Â Â Â fid.close() |
---|
694 | |
---|
695 | |
---|
696 |   def store_timestep(self, name): |
---|
697 | Â Â Â Â """Store time and named quantity to file |
---|
698 | Â Â Â Â """ |
---|
699 |     from Scientific.IO.NetCDF import NetCDFFile |
---|
700 |     from time import sleep |
---|
701 | |
---|
702 | Â Â Â Â #Get NetCDF |
---|
703 | Â Â Â Â retries =Â 0 |
---|
704 | Â Â Â Â file_open =Â False |
---|
705 |     while not file_open and retries < 10: |
---|
706 | Â Â Â Â Â Â try: |
---|
707 |         fid = NetCDFFile(self.filename, 'a') #Open existing file |
---|
708 |       except IOError: |
---|
709 | Â Â Â Â Â Â Â Â #This could happen if someone was reading the file. |
---|
710 | Â Â Â Â Â Â Â Â #In that case, wait a while and try again |
---|
711 |         msg = 'Warning (store_timestep): File %s could not be opened'\ |
---|
712 | Â Â Â Â Â Â Â Â Â %self.filename |
---|
713 | Â Â Â Â Â Â Â Â msg +=Â ' - trying again' |
---|
714 |         print msg |
---|
715 | Â Â Â Â Â Â Â Â retries +=Â 1 |
---|
716 | Â Â Â Â Â Â Â Â sleep(1) |
---|
717 | Â Â Â Â Â Â else: |
---|
718 | Â Â Â Â Â Â Â Â file_open =Â True |
---|
719 | |
---|
720 |     if not file_open: |
---|
721 |       msg = 'File %s could not be opened for append' %self.filename |
---|
722 |       raise DataFileNotOPenError, msg |
---|
723 | |
---|
724 | |
---|
725 | Â Â Â Â domain =Â self.domain |
---|
726 | |
---|
727 | Â Â Â Â # Get the variables |
---|
728 | Â Â Â Â time =Â fid.variables['time'] |
---|
729 | Â Â Â Â stage =Â fid.variables['stage'] |
---|
730 | Â Â Â Â i =Â len(time) |
---|
731 | |
---|
732 | Â Â Â Â #Store stage |
---|
733 | Â Â Â Â time[i]Â =Â self.domain.time |
---|
734 | |
---|
735 | Â Â Â Â # Get quantity |
---|
736 | Â Â Â Â Q =Â domain.quantities[name] |
---|
737 | Â Â Â Â A,V =Â Q.get_vertex_values(xy=False, |
---|
738 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â precision =Â self.precision) |
---|
739 | |
---|
740 | Â Â Â Â stage[i,:]Â =Â A.astype(self.precision) |
---|
741 | |
---|
742 | Â Â Â Â #Flush and close |
---|
743 | Â Â Â Â fid.sync() |
---|
744 | Â Â Â Â fid.close() |
---|
745 | |
---|
746 | |
---|
747 | #### NED is national exposure database (name changed to NEXIS) |
---|
748 | Â Â |
---|
749 | LAT_TITLE =Â 'LATITUDE' |
---|
750 | LONG_TITLE =Â 'LONGITUDE' |
---|
751 | X_TITLE =Â 'x' |
---|
752 | Y_TITLE =Â 'y' |
---|
753 | class Exposure_csv: |
---|
754 |   def __init__(self,file_name, latitude_title=LAT_TITLE, |
---|
755 |          longitude_title=LONG_TITLE, is_x_y_locations=None, |
---|
756 |          x_title=X_TITLE, y_title=Y_TITLE, |
---|
757 |          refine_polygon=None, title_check_list=None): |
---|
758 | Â Â Â Â """ |
---|
759 | Â Â Â Â This class is for handling the exposure csv file. |
---|
760 | Â Â Â Â It reads the file in and converts the lats and longs to a geospatial |
---|
761 | Â Â Â Â data object. |
---|
762 | Â Â Â Â Use the methods to read and write columns. |
---|
763 | |
---|
764 | Â Â Â Â The format of the csv files it reads is; |
---|
765 | Â Â Â Â Â Â The first row is a title row. |
---|
766 | Â Â Â Â Â Â comma's are the delimiters |
---|
767 | Â Â Â Â Â Â each column is a 'set' of data |
---|
768 | |
---|
769 | Â Â Â Â Feel free to use/expand it to read other csv files. |
---|
770 | Â Â Â Â Â Â |
---|
771 | Â Â Â Â Â Â |
---|
772 | Â Â Â Â It is not for adding and deleting rows |
---|
773 | Â Â Â Â |
---|
774 | Â Â Â Â Can geospatial handle string attributes? It's not made for them. |
---|
775 | Â Â Â Â Currently it can't load and save string att's. |
---|
776 | |
---|
777 | Â Â Â Â So just use geospatial to hold the x, y and georef? Bad, since |
---|
778 |     different att's are in diferent structures. Not so bad, the info |
---|
779 | Â Â Â Â to write if the .csv file is saved is in attribute_dic |
---|
780 | |
---|
781 | Â Â Â Â The location info is in the geospatial attribute. |
---|
782 | Â Â Â Â |
---|
783 | Â Â Â Â |
---|
784 | Â Â Â Â """ |
---|
785 | Â Â Â Â self._file_name =Â file_name |
---|
786 |     self._geospatial = None # |
---|
787 | |
---|
788 | Â Â Â Â # self._attribute_dic is a dictionary. |
---|
789 | Â Â Â Â #The keys are the column titles. |
---|
790 | Â Â Â Â #The values are lists of column data |
---|
791 | Â Â Â Â |
---|
792 | Â Â Â Â # self._title_index_dic is a dictionary. |
---|
793 | Â Â Â Â #The keys are the column titles. |
---|
794 | Â Â Â Â #The values are the index positions of file columns. |
---|
795 |     self._attribute_dic, self._title_index_dic = \ |
---|
796 |       csv2dict(self._file_name, title_check_list=title_check_list) |
---|
797 | Â Â Â Â try: |
---|
798 | Â Â Â Â Â Â #Have code here that handles caps or lower |
---|
799 | Â Â Â Â Â Â lats =Â self._attribute_dic[latitude_title] |
---|
800 | Â Â Â Â Â Â longs =Â self._attribute_dic[longitude_title] |
---|
801 | Â Â Â Â Â Â |
---|
802 |     except KeyError: |
---|
803 | Â Â Â Â Â Â # maybe a warning.. |
---|
804 | Â Â Â Â Â Â #Let's see if this works.. |
---|
805 |       if False != is_x_y_locations: |
---|
806 | Â Â Â Â Â Â Â Â is_x_y_locations =Â True |
---|
807 | Â Â Â Â Â Â pass |
---|
808 | Â Â Â Â else: |
---|
809 | Â Â Â Â Â Â self._geospatial =Â Geospatial_data(latitudes =Â lats, |
---|
810 | Â Â Â Â Â Â Â Â Â longitudes =Â longs) |
---|
811 | |
---|
812 |     if is_x_y_locations is True: |
---|
813 |       if self._geospatial is not None: |
---|
814 |         pass #fixme throw an error |
---|
815 | Â Â Â Â Â Â try: |
---|
816 | Â Â Â Â Â Â Â Â xs =Â self._attribute_dic[x_title] |
---|
817 | Â Â Â Â Â Â Â Â ys =Â self._attribute_dic[y_title] |
---|
818 |         points = [[float(i),float(j)] for i,j in map(None,xs,ys)] |
---|
819 |       except KeyError: |
---|
820 | Â Â Â Â Â Â Â Â # maybe a warning.. |
---|
821 | Â Â Â Â Â Â Â Â msg =Â "Could not find location information." |
---|
822 |         raise TitleValueError, msg |
---|
823 | Â Â Â Â Â Â else: |
---|
824 | Â Â Â Â Â Â Â Â self._geospatial =Â Geospatial_data(data_points=points) |
---|
825 | Â Â Â Â Â Â |
---|
826 | Â Â Â Â # create a list of points that are in the refining_polygon |
---|
827 | Â Â Â Â # described by a list of indexes representing the points |
---|
828 | |
---|
829 |   def __cmp__(self, other): |
---|
830 | Â Â Â Â #print "self._attribute_dic",self._attribute_dic |
---|
831 | Â Â Â Â #print "other._attribute_dic",other._attribute_dic |
---|
832 | Â Â Â Â #print "self._title_index_dic", self._title_index_dic |
---|
833 | Â Â Â Â #print "other._title_index_dic", other._title_index_dic |
---|
834 | Â Â Â Â |
---|
835 | Â Â Â Â #check that a is an instance of this class |
---|
836 |     if isinstance(self, type(other)): |
---|
837 |       result = cmp(self._attribute_dic, other._attribute_dic) |
---|
838 |       if result <>0: |
---|
839 |         return result |
---|
840 | Â Â Â Â Â Â # The order of the columns is important. Therefore.. |
---|
841 |       result = cmp(self._title_index_dic, other._title_index_dic) |
---|
842 |       if result <>0: |
---|
843 |         return result |
---|
844 |       for self_ls, other_ls in map(None,self._attribute_dic, \ |
---|
845 | Â Â Â Â Â Â Â Â Â Â other._attribute_dic): |
---|
846 | Â Â Â Â Â Â Â Â result =Â cmp(self._attribute_dic[self_ls], |
---|
847 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â other._attribute_dic[other_ls]) |
---|
848 |         if result <>0: |
---|
849 |           return result |
---|
850 |       return 0 |
---|
851 | Â Â Â Â else: |
---|
852 |       return 1 |
---|
853 | Â Â |
---|
854 | |
---|
855 |   def get_column(self, column_name, use_refind_polygon=False): |
---|
856 | Â Â Â Â """ |
---|
857 | Â Â Â Â Given a column name return a list of the column values |
---|
858 | |
---|
859 | Â Â Â Â Note, the type of the values will be String! |
---|
860 | Â Â Â Â do this to change a list of strings to a list of floats |
---|
861 | Â Â Â Â time = [float(x) for x in time] |
---|
862 | Â Â Â Â |
---|
863 | Â Â Â Â Not implemented: |
---|
864 | Â Â Â Â if use_refind_polygon is True, only return values in the |
---|
865 | Â Â Â Â refined polygon |
---|
866 | Â Â Â Â """ |
---|
867 |     if not self._attribute_dic.has_key(column_name): |
---|
868 |       msg = 'Therer is no column called %s!' %column_name |
---|
869 |       raise TitleValueError, msg |
---|
870 |     return self._attribute_dic[column_name] |
---|
871 | |
---|
872 | |
---|
873 |   def get_value(self, value_column_name, |
---|
874 | Â Â Â Â Â Â Â Â Â known_column_name, |
---|
875 | Â Â Â Â Â Â Â Â Â known_values, |
---|
876 | Â Â Â Â Â Â Â Â Â use_refind_polygon=False): |
---|
877 | Â Â Â Â """ |
---|
878 | Â Â Â Â Do linear interpolation on the known_colum, using the known_value, |
---|
879 | Â Â Â Â to return a value of the column_value_name. |
---|
880 | Â Â Â Â """ |
---|
881 | Â Â Â Â pass |
---|
882 | |
---|
883 | |
---|
884 |   def get_location(self, use_refind_polygon=False): |
---|
885 | Â Â Â Â """ |
---|
886 | Â Â Â Â Return a geospatial object which describes the |
---|
887 | Â Â Â Â locations of the location file. |
---|
888 | |
---|
889 | Â Â Â Â Note, if there is not location info, this returns None. |
---|
890 | Â Â Â Â |
---|
891 | Â Â Â Â Not implemented: |
---|
892 | Â Â Â Â if use_refind_polygon is True, only return values in the |
---|
893 | Â Â Â Â refined polygon |
---|
894 | Â Â Â Â """ |
---|
895 |     return self._geospatial |
---|
896 | |
---|
897 |   def set_column(self, column_name, column_values, overwrite=False): |
---|
898 | Â Â Â Â """ |
---|
899 | Â Â Â Â Add a column to the 'end' (with the right most column being the end) |
---|
900 | Â Â Â Â of the csv file. |
---|
901 | |
---|
902 | Â Â Â Â Set overwrite to True if you want to overwrite a column. |
---|
903 | Â Â Â Â |
---|
904 | Â Â Â Â Note, in column_name white space is removed and case is not checked. |
---|
905 | Â Â Â Â Precondition |
---|
906 | Â Â Â Â The column_name and column_values cannot have comma's in it. |
---|
907 | Â Â Â Â """ |
---|
908 | Â Â Â Â |
---|
909 | Â Â Â Â value_row_count =Â \ |
---|
910 | Â Â Â Â Â Â len(self._attribute_dic[self._title_index_dic.keys()[0]]) |
---|
911 |     if len(column_values) <> value_row_count: |
---|
912 | Â Â Â Â Â Â msg =Â 'The number of column values must equal the number of rows.' |
---|
913 |       raise DataMissingValuesError, msg |
---|
914 | Â Â Â Â |
---|
915 |     if self._attribute_dic.has_key(column_name): |
---|
916 |       if not overwrite: |
---|
917 |         msg = 'Column name %s already in use!' %column_name |
---|
918 |         raise TitleValueError, msg |
---|
919 | Â Â Â Â else: |
---|
920 |       # New title. Add it to the title index. |
---|
921 | Â Â Â Â Â Â self._title_index_dic[column_name]Â =Â len(self._title_index_dic) |
---|
922 | Â Â Â Â self._attribute_dic[column_name]Â =Â column_values |
---|
923 | Â Â Â Â #print "self._title_index_dic[column_name]",self._title_index_dic |
---|
924 | |
---|
925 |   def save(self, file_name=None): |
---|
926 | Â Â Â Â """ |
---|
927 | Â Â Â Â Save the exposure csv file |
---|
928 | Â Â Â Â """ |
---|
929 |     if file_name is None: |
---|
930 | Â Â Â Â Â Â file_name =Â self._file_name |
---|
931 | Â Â Â Â |
---|
932 | Â Â Â Â fd =Â open(file_name,'wb') |
---|
933 | Â Â Â Â writer =Â csv.writer(fd) |
---|
934 | Â Â Â Â |
---|
935 | Â Â Â Â #Write the title to a cvs file |
---|
936 | Â Â Â Â line =Â [None]*Â len(self._title_index_dic) |
---|
937 |     for title in self._title_index_dic.iterkeys(): |
---|
938 | Â Â Â Â Â Â line[self._title_index_dic[title]]=Â title |
---|
939 | Â Â Â Â writer.writerow(line) |
---|
940 | Â Â Â Â |
---|
941 | Â Â Â Â # Write the values to a cvs file |
---|
942 | Â Â Â Â value_row_count =Â \ |
---|
943 | Â Â Â Â Â Â len(self._attribute_dic[self._title_index_dic.keys()[0]]) |
---|
944 |     for row_i in range(value_row_count): |
---|
945 | Â Â Â Â Â Â line =Â [None]*Â len(self._title_index_dic) |
---|
946 |       for title in self._title_index_dic.iterkeys(): |
---|
947 | Â Â Â Â Â Â Â Â line[self._title_index_dic[title]]=Â \ |
---|
948 | Â Â Â Â Â Â Â Â Â Â Â self._attribute_dic[title][row_i] |
---|
949 | Â Â Â Â Â Â writer.writerow(line) |
---|
950 | |
---|
951 | |
---|
952 | def csv2dict(file_name, title_check_list=None): |
---|
953 | Â Â """ |
---|
954 | Â Â Load in the csv as a dic, title as key and column info as value, . |
---|
955 | Â Â Also, create a dic, title as key and column index as value, |
---|
956 | Â Â to keep track of the column order. |
---|
957 | |
---|
958 | Â Â Two dictionaries are returned. |
---|
959 | Â Â |
---|
960 | Â Â WARNING: Vaules are returned as strings. |
---|
961 | Â Â do this to change a list of strings to a list of floats |
---|
962 | Â Â Â Â time = [float(x) for x in time] |
---|
963 | |
---|
964 | Â Â Â Â |
---|
965 | Â Â """ |
---|
966 | Â Â |
---|
967 | Â Â # |
---|
968 | Â Â attribute_dic =Â {} |
---|
969 | Â Â title_index_dic =Â {} |
---|
970 | Â Â titles_stripped =Â []Â # list of titles |
---|
971 | Â Â reader =Â csv.reader(file(file_name)) |
---|
972 | |
---|
973 | Â Â # Read in and manipulate the title info |
---|
974 | Â Â titles =Â reader.next() |
---|
975 |   for i,title in enumerate(titles): |
---|
976 | Â Â Â Â titles_stripped.append(title.strip()) |
---|
977 | Â Â Â Â title_index_dic[title.strip()]Â =Â i |
---|
978 | Â Â title_count =Â len(titles_stripped)Â Â Â Â |
---|
979 | Â Â #print "title_index_dic",title_index_dic |
---|
980 |   if title_check_list is not None: |
---|
981 |     for title_check in title_check_list: |
---|
982 |       #msg = "Reading error. This row is not present ", title_check |
---|
983 | Â Â Â Â Â Â #assert title_index_dic.has_key(title_check), msg |
---|
984 |       if not title_index_dic.has_key(title_check): |
---|
985 | Â Â Â Â Â Â Â Â #reader.close() |
---|
986 |         msg = "Reading error. This row is not present ", \ |
---|
987 |            title_check           |
---|
988 |         raise IOError, msg |
---|
989 | Â Â Â Â Â Â Â Â |
---|
990 | Â Â |
---|
991 | Â Â |
---|
992 | Â Â #create a dic of colum values, indexed by column title |
---|
993 |   for line in reader: |
---|
994 |     if len(line) <> title_count: |
---|
995 |       raise IOError #FIXME make this nicer |
---|
996 |     for i, value in enumerate(line): |
---|
997 | Â Â Â Â Â Â attribute_dic.setdefault(titles_stripped[i],[]).append(value) |
---|
998 | Â Â Â Â |
---|
999 |   return attribute_dic, title_index_dic |
---|
1000 | |
---|
1001 | |
---|
1002 | #Auxiliary |
---|
1003 | def write_obj(filename,x,y,z): |
---|
1004 | Â Â """Store x,y,z vectors into filename (obj format) |
---|
1005 | Â Â Â Â Vectors are assumed to have dimension (M,3) where |
---|
1006 | Â Â Â Â M corresponds to the number elements. |
---|
1007 | Â Â Â Â triangles are assumed to be disconnected |
---|
1008 | |
---|
1009 | Â Â Â Â The three numbers in each vector correspond to three vertices, |
---|
1010 | |
---|
1011 | Â Â Â Â e.g. the x coordinate of vertex 1 of element i is in x[i,1] |
---|
1012 | |
---|
1013 | Â Â """ |
---|
1014 | Â Â #print 'Writing obj to %s' % filename |
---|
1015 | |
---|
1016 |   import os.path |
---|
1017 | |
---|
1018 |   root, ext = os.path.splitext(filename) |
---|
1019 |   if ext == '.obj': |
---|
1020 | Â Â Â Â FN =Â filename |
---|
1021 | Â Â else: |
---|
1022 | Â Â Â Â FN =Â filename +Â '.obj' |
---|
1023 | |
---|
1024 | |
---|
1025 |   outfile = open(FN, 'wb') |
---|
1026 | Â Â outfile.write("# Triangulation as an obj file\n") |
---|
1027 | |
---|
1028 |   M, N = x.shape |
---|
1029 |   assert N==3 #Assuming three vertices per element |
---|
1030 | |
---|
1031 |   for i in range(M): |
---|
1032 |     for j in range(N): |
---|
1033 |       outfile.write("v %f %f %f\n" % (x[i,j],y[i,j],z[i,j])) |
---|
1034 | |
---|
1035 |   for i in range(M): |
---|
1036 | Â Â Â Â base =Â i*N |
---|
1037 |     outfile.write("f %d %d %d\n" % (base+1,base+2,base+3)) |
---|
1038 | |
---|
1039 | Â Â outfile.close() |
---|
1040 | |
---|
1041 | |
---|
1042 | ######################################################### |
---|
1043 | #Conversion routines |
---|
1044 | ######################################################## |
---|
1045 | |
---|
1046 | def sww2obj(basefilename, size): |
---|
1047 | Â Â """Convert netcdf based data output to obj |
---|
1048 | Â Â """ |
---|
1049 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
1050 | |
---|
1051 |   from Numeric import Float, zeros |
---|
1052 | |
---|
1053 | Â Â #Get NetCDF |
---|
1054 |   FN = create_filename('.', basefilename, 'sww', size) |
---|
1055 |   print 'Reading from ', FN |
---|
1056 |   fid = NetCDFFile(FN, 'r') #Open existing file for read |
---|
1057 | |
---|
1058 | |
---|
1059 | Â Â # Get the variables |
---|
1060 | Â Â x =Â fid.variables['x'] |
---|
1061 | Â Â y =Â fid.variables['y'] |
---|
1062 | Â Â z =Â fid.variables['elevation'] |
---|
1063 | Â Â time =Â fid.variables['time'] |
---|
1064 | Â Â stage =Â fid.variables['stage'] |
---|
1065 | |
---|
1066 |   M = size #Number of lines |
---|
1067 |   xx = zeros((M,3), Float) |
---|
1068 |   yy = zeros((M,3), Float) |
---|
1069 |   zz = zeros((M,3), Float) |
---|
1070 | |
---|
1071 |   for i in range(M): |
---|
1072 |     for j in range(3): |
---|
1073 | Â Â Â Â Â Â xx[i,j]Â =Â x[i+j*M] |
---|
1074 | Â Â Â Â Â Â yy[i,j]Â =Â y[i+j*M] |
---|
1075 | Â Â Â Â Â Â zz[i,j]Â =Â z[i+j*M] |
---|
1076 | |
---|
1077 | Â Â #Write obj for bathymetry |
---|
1078 |   FN = create_filename('.', basefilename, 'obj', size) |
---|
1079 | Â Â write_obj(FN,xx,yy,zz) |
---|
1080 | |
---|
1081 | |
---|
1082 | Â Â #Now read all the data with variable information, combine with |
---|
1083 | Â Â #x,y info and store as obj |
---|
1084 | |
---|
1085 |   for k in range(len(time)): |
---|
1086 | Â Â Â Â t =Â time[k] |
---|
1087 |     print 'Processing timestep %f' %t |
---|
1088 | |
---|
1089 |     for i in range(M): |
---|
1090 |       for j in range(3): |
---|
1091 | Â Â Â Â Â Â Â Â zz[i,j]Â =Â stage[k,i+j*M] |
---|
1092 | |
---|
1093 | |
---|
1094 | Â Â Â Â #Write obj for variable data |
---|
1095 | Â Â Â Â #FN = create_filename(basefilename, 'obj', size, time=t) |
---|
1096 |     FN = create_filename('.', basefilename[:5], 'obj', size, time=t) |
---|
1097 | Â Â Â Â write_obj(FN,xx,yy,zz) |
---|
1098 | |
---|
1099 | |
---|
1100 | def dat2obj(basefilename): |
---|
1101 | Â Â """Convert line based data output to obj |
---|
1102 | Â Â FIXME: Obsolete? |
---|
1103 | Â Â """ |
---|
1104 | |
---|
1105 |   import glob, os |
---|
1106 |   from anuga.config import data_dir |
---|
1107 | |
---|
1108 | |
---|
1109 | Â Â #Get bathymetry and x,y's |
---|
1110 |   lines = open(data_dir+os.sep+basefilename+'_geometry.dat', 'r').readlines() |
---|
1111 | |
---|
1112 |   from Numeric import zeros, Float |
---|
1113 | |
---|
1114 | Â Â M =Â len(lines)Â #Number of lines |
---|
1115 |   x = zeros((M,3), Float) |
---|
1116 |   y = zeros((M,3), Float) |
---|
1117 |   z = zeros((M,3), Float) |
---|
1118 | |
---|
1119 | Â Â ##i = 0 |
---|
1120 |   for i, line in enumerate(lines): |
---|
1121 | Â Â Â Â tokens =Â line.split() |
---|
1122 | Â Â Â Â values =Â map(float,tokens) |
---|
1123 | |
---|
1124 |     for j in range(3): |
---|
1125 | Â Â Â Â Â Â x[i,j]Â =Â values[j*3] |
---|
1126 | Â Â Â Â Â Â y[i,j]Â =Â values[j*3+1] |
---|
1127 | Â Â Â Â Â Â z[i,j]Â =Â values[j*3+2] |
---|
1128 | |
---|
1129 | Â Â Â Â ##i += 1 |
---|
1130 | |
---|
1131 | |
---|
1132 | Â Â #Write obj for bathymetry |
---|
1133 | Â Â write_obj(data_dir+os.sep+basefilename+'_geometry',x,y,z) |
---|
1134 | |
---|
1135 | |
---|
1136 | Â Â #Now read all the data files with variable information, combine with |
---|
1137 | Â Â #x,y info |
---|
1138 | Â Â #and store as obj |
---|
1139 | |
---|
1140 | Â Â files =Â glob.glob(data_dir+os.sep+basefilename+'*.dat') |
---|
1141 | |
---|
1142 |   for filename in files: |
---|
1143 |     print 'Processing %s' % filename |
---|
1144 | |
---|
1145 | Â Â Â Â lines =Â open(data_dir+os.sep+filename,'r').readlines() |
---|
1146 |     assert len(lines) == M |
---|
1147 |     root, ext = os.path.splitext(filename) |
---|
1148 | |
---|
1149 | Â Â Â Â #Get time from filename |
---|
1150 | Â Â Â Â i0 =Â filename.find('_time=') |
---|
1151 |     if i0 == -1: |
---|
1152 | Â Â Â Â Â Â #Skip bathymetry file |
---|
1153 | Â Â Â Â Â Â continue |
---|
1154 | |
---|
1155 | Â Â Â Â i0 +=Â 6Â #Position where time starts |
---|
1156 | Â Â Â Â i1 =Â filename.find('.dat') |
---|
1157 | |
---|
1158 |     if i1 > i0: |
---|
1159 | Â Â Â Â Â Â t =Â float(filename[i0:i1]) |
---|
1160 | Â Â Â Â else: |
---|
1161 |       raise DataTimeError, 'Hmmmm' |
---|
1162 | |
---|
1163 | |
---|
1164 | |
---|
1165 | Â Â Â Â ##i = 0 |
---|
1166 |     for i, line in enumerate(lines): |
---|
1167 | Â Â Â Â Â Â tokens =Â line.split() |
---|
1168 | Â Â Â Â Â Â values =Â map(float,tokens) |
---|
1169 | |
---|
1170 |       for j in range(3): |
---|
1171 | Â Â Â Â Â Â Â Â z[i,j]Â =Â values[j] |
---|
1172 | |
---|
1173 | Â Â Â Â Â Â ##i += 1 |
---|
1174 | |
---|
1175 | Â Â Â Â #Write obj for variable data |
---|
1176 | Â Â Â Â write_obj(data_dir+os.sep+basefilename+'_time=%.4f'Â %t,x,y,z) |
---|
1177 | |
---|
1178 | |
---|
1179 | def filter_netcdf(filename1, filename2, first=0, last=None, step = 1): |
---|
1180 | Â Â """Read netcdf filename1, pick timesteps first:step:last and save to |
---|
1181 | Â Â nettcdf file filename2 |
---|
1182 | Â Â """ |
---|
1183 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
1184 | |
---|
1185 | Â Â #Get NetCDF |
---|
1186 |   infile = NetCDFFile(filename1, 'r') #Open existing file for read |
---|
1187 |   outfile = NetCDFFile(filename2, 'w') #Open new file |
---|
1188 | |
---|
1189 | |
---|
1190 | Â Â #Copy dimensions |
---|
1191 |   for d in infile.dimensions: |
---|
1192 |     outfile.createDimension(d, infile.dimensions[d]) |
---|
1193 | |
---|
1194 |   for name in infile.variables: |
---|
1195 | Â Â Â Â var =Â infile.variables[name] |
---|
1196 |     outfile.createVariable(name, var.typecode(), var.dimensions) |
---|
1197 | |
---|
1198 | |
---|
1199 | Â Â #Copy the static variables |
---|
1200 |   for name in infile.variables: |
---|
1201 |     if name == 'time' or name == 'stage': |
---|
1202 | Â Â Â Â Â Â pass |
---|
1203 | Â Â Â Â else: |
---|
1204 | Â Â Â Â Â Â #Copy |
---|
1205 | Â Â Â Â Â Â outfile.variables[name][:]Â =Â infile.variables[name][:] |
---|
1206 | |
---|
1207 | Â Â #Copy selected timesteps |
---|
1208 | Â Â time =Â infile.variables['time'] |
---|
1209 | Â Â stage =Â infile.variables['stage'] |
---|
1210 | |
---|
1211 | Â Â newtime =Â outfile.variables['time'] |
---|
1212 | Â Â newstage =Â outfile.variables['stage'] |
---|
1213 | |
---|
1214 |   if last is None: |
---|
1215 | Â Â Â Â last =Â len(time) |
---|
1216 | |
---|
1217 |   selection = range(first, last, step) |
---|
1218 |   for i, j in enumerate(selection): |
---|
1219 |     print 'Copying timestep %d of %d (%f)' %(j, last-first, time[j]) |
---|
1220 | Â Â Â Â newtime[i]Â =Â time[j] |
---|
1221 | Â Â Â Â newstage[i,:]Â =Â stage[j,:] |
---|
1222 | |
---|
1223 | Â Â #Close |
---|
1224 | Â Â infile.close() |
---|
1225 | Â Â outfile.close() |
---|
1226 | |
---|
1227 | |
---|
1228 | #Get data objects |
---|
1229 | def get_dataobject(domain, mode='w'): |
---|
1230 | Â Â """Return instance of class of given format using filename |
---|
1231 | Â Â """ |
---|
1232 | |
---|
1233 | Â Â cls =Â eval('Data_format_%s'Â %domain.format) |
---|
1234 |   return cls(domain, mode) |
---|
1235 | |
---|
1236 | |
---|
1237 | |
---|
1238 | |
---|
1239 | def dem2pts(basename_in, basename_out=None, |
---|
1240 |       easting_min=None, easting_max=None, |
---|
1241 |       northing_min=None, northing_max=None, |
---|
1242 |       use_cache=False, verbose=False,): |
---|
1243 | Â Â """Read Digitial Elevation model from the following NetCDF format (.dem) |
---|
1244 | |
---|
1245 | Â Â Example: |
---|
1246 | |
---|
1247 |   ncols     3121 |
---|
1248 |   nrows     1800 |
---|
1249 |   xllcorner   722000 |
---|
1250 |   yllcorner   5893000 |
---|
1251 |   cellsize   25 |
---|
1252 |   NODATA_value -9999 |
---|
1253 | Â Â 138.3698 137.4194 136.5062 135.5558 .......... |
---|
1254 | |
---|
1255 | Â Â Convert to NetCDF pts format which is |
---|
1256 | |
---|
1257 | Â Â points:Â (Nx2) Float array |
---|
1258 | Â Â elevation: N Float array |
---|
1259 | Â Â """ |
---|
1260 | |
---|
1261 | |
---|
1262 | |
---|
1263 | Â Â kwargs =Â {'basename_out':Â basename_out, |
---|
1264 | Â Â Â Â Â Â Â 'easting_min':Â easting_min, |
---|
1265 | Â Â Â Â Â Â Â 'easting_max':Â easting_max, |
---|
1266 | Â Â Â Â Â Â Â 'northing_min':Â northing_min, |
---|
1267 | Â Â Â Â Â Â Â 'northing_max':Â northing_max, |
---|
1268 | Â Â Â Â Â Â Â 'verbose':Â verbose} |
---|
1269 | |
---|
1270 |   if use_cache is True: |
---|
1271 |     from caching import cache |
---|
1272 |     result = cache(_dem2pts, basename_in, kwargs, |
---|
1273 | Â Â Â Â Â Â Â Â Â Â Â Â dependencies =Â [basename_in +Â '.dem'], |
---|
1274 | Â Â Â Â Â Â Â Â Â Â Â Â verbose =Â verbose) |
---|
1275 | |
---|
1276 | Â Â else: |
---|
1277 |     result = apply(_dem2pts, [basename_in], kwargs) |
---|
1278 | |
---|
1279 |   return result |
---|
1280 | |
---|
1281 | |
---|
1282 | def _dem2pts(basename_in, basename_out=None, verbose=False, |
---|
1283 |       easting_min=None, easting_max=None, |
---|
1284 |       northing_min=None, northing_max=None): |
---|
1285 | Â Â """Read Digitial Elevation model from the following NetCDF format (.dem) |
---|
1286 | |
---|
1287 | Â Â Internal function. See public function dem2pts for details. |
---|
1288 | Â Â """ |
---|
1289 | |
---|
1290 | Â Â # FIXME: Can this be written feasibly using write_pts? |
---|
1291 | |
---|
1292 |   import os |
---|
1293 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
1294 |   from Numeric import Float, zeros, reshape, sum |
---|
1295 | |
---|
1296 | Â Â root =Â basename_in |
---|
1297 | |
---|
1298 | Â Â # Get NetCDF |
---|
1299 |   infile = NetCDFFile(root + '.dem', 'r') # Open existing netcdf file for read |
---|
1300 | |
---|
1301 |   if verbose: print 'Reading DEM from %s' %(root + '.dem') |
---|
1302 | |
---|
1303 | Â Â ncols =Â infile.ncols[0] |
---|
1304 | Â Â nrows =Â infile.nrows[0] |
---|
1305 | Â Â xllcorner =Â infile.xllcorner[0]Â # Easting of lower left corner |
---|
1306 | Â Â yllcorner =Â infile.yllcorner[0]Â # Northing of lower left corner |
---|
1307 | Â Â cellsize =Â infile.cellsize[0] |
---|
1308 | Â Â NODATA_value =Â infile.NODATA_value[0] |
---|
1309 | Â Â dem_elevation =Â infile.variables['elevation'] |
---|
1310 | |
---|
1311 | Â Â zone =Â infile.zone[0] |
---|
1312 | Â Â false_easting =Â infile.false_easting[0] |
---|
1313 | Â Â false_northing =Â infile.false_northing[0] |
---|
1314 | |
---|
1315 | Â Â # Text strings |
---|
1316 | Â Â projection =Â infile.projection |
---|
1317 | Â Â datum =Â infile.datum |
---|
1318 | Â Â units =Â infile.units |
---|
1319 | |
---|
1320 | |
---|
1321 | Â Â # Get output file |
---|
1322 |   if basename_out == None: |
---|
1323 | Â Â Â Â ptsname =Â root +Â '.pts' |
---|
1324 | Â Â else: |
---|
1325 | Â Â Â Â ptsname =Â basename_out +Â '.pts' |
---|
1326 | |
---|
1327 |   if verbose: print 'Store to NetCDF file %s' %ptsname |
---|
1328 | Â Â # NetCDF file definition |
---|
1329 |   outfile = NetCDFFile(ptsname, 'w') |
---|
1330 | |
---|
1331 | Â Â # Create new file |
---|
1332 | Â Â outfile.institution =Â 'Geoscience Australia' |
---|
1333 | Â Â outfile.description =Â 'NetCDF pts format for compact and portable storage 'Â +\ |
---|
1334 | Â Â Â Â Â Â Â Â Â Â Â 'of spatial point data' |
---|
1335 | Â Â # Assign default values |
---|
1336 |   if easting_min is None: easting_min = xllcorner |
---|
1337 |   if easting_max is None: easting_max = xllcorner + ncols*cellsize |
---|
1338 |   if northing_min is None: northing_min = yllcorner |
---|
1339 |   if northing_max is None: northing_max = yllcorner + nrows*cellsize |
---|
1340 | |
---|
1341 | Â Â # Compute offsets to update georeferencing |
---|
1342 | Â Â easting_offset =Â xllcorner -Â easting_min |
---|
1343 | Â Â northing_offset =Â yllcorner -Â northing_min |
---|
1344 | |
---|
1345 | Â Â # Georeferencing |
---|
1346 | Â Â outfile.zone =Â zone |
---|
1347 | Â Â outfile.xllcorner =Â easting_min # Easting of lower left corner |
---|
1348 | Â Â outfile.yllcorner =Â northing_min # Northing of lower left corner |
---|
1349 | Â Â outfile.false_easting =Â false_easting |
---|
1350 | Â Â outfile.false_northing =Â false_northing |
---|
1351 | |
---|
1352 | Â Â outfile.projection =Â projection |
---|
1353 | Â Â outfile.datum =Â datum |
---|
1354 | Â Â outfile.units =Â units |
---|
1355 | |
---|
1356 | |
---|
1357 | Â Â # Grid info (FIXME: probably not going to be used, but heck) |
---|
1358 | Â Â outfile.ncols =Â ncols |
---|
1359 | Â Â outfile.nrows =Â nrows |
---|
1360 | |
---|
1361 |   dem_elevation_r = reshape(dem_elevation, (nrows, ncols)) |
---|
1362 | Â Â totalnopoints =Â nrows*ncols |
---|
1363 | |
---|
1364 | Â Â # Calculating number of NODATA_values for each row in clipped region |
---|
1365 | Â Â # FIXME: use array operations to do faster |
---|
1366 | Â Â nn =Â 0 |
---|
1367 | Â Â k =Â 0 |
---|
1368 | Â Â i1_0 =Â 0 |
---|
1369 | Â Â j1_0 =Â 0 |
---|
1370 | Â Â thisj =Â 0 |
---|
1371 | Â Â thisi =Â 0 |
---|
1372 |   for i in range(nrows): |
---|
1373 | Â Â Â Â y =Â (nrows-i-1)*cellsize +Â yllcorner |
---|
1374 |     for j in range(ncols): |
---|
1375 | Â Â Â Â Â Â x =Â j*cellsize +Â xllcorner |
---|
1376 |       if easting_min <= x <= easting_max and \ |
---|
1377 | Â Â Â Â Â Â Â Â northing_min <=Â y <=Â northing_max: |
---|
1378 | Â Â Â Â Â Â Â Â thisj =Â j |
---|
1379 | Â Â Â Â Â Â Â Â thisi =Â i |
---|
1380 |         if dem_elevation_r[i,j] == NODATA_value: nn += 1 |
---|
1381 | |
---|
1382 |         if k == 0: |
---|
1383 | Â Â Â Â Â Â Â Â Â Â i1_0 =Â i |
---|
1384 | Â Â Â Â Â Â Â Â Â Â j1_0 =Â j |
---|
1385 | Â Â Â Â Â Â Â Â k +=Â 1 |
---|
1386 | |
---|
1387 | Â Â index1 =Â j1_0 |
---|
1388 | Â Â index2 =Â thisj |
---|
1389 | |
---|
1390 | Â Â # Dimension definitions |
---|
1391 | Â Â nrows_in_bounding_box =Â int(round((northing_max-northing_min)/cellsize)) |
---|
1392 | Â Â ncols_in_bounding_box =Â int(round((easting_max-easting_min)/cellsize)) |
---|
1393 | |
---|
1394 | Â Â clippednopoints =Â (thisi+1-i1_0)*(thisj+1-j1_0) |
---|
1395 | Â Â nopoints =Â clippednopoints-nn |
---|
1396 | |
---|
1397 | Â Â clipped_dem_elev =Â dem_elevation_r[i1_0:thisi+1,j1_0:thisj+1] |
---|
1398 | |
---|
1399 |   if verbose: |
---|
1400 |     print 'There are %d values in the elevation' %totalnopoints |
---|
1401 |     print 'There are %d values in the clipped elevation' %clippednopoints |
---|
1402 |     print 'There are %d NODATA_values in the clipped elevation' %nn |
---|
1403 | |
---|
1404 |   outfile.createDimension('number_of_points', nopoints) |
---|
1405 |   outfile.createDimension('number_of_dimensions', 2) #This is 2d data |
---|
1406 | |
---|
1407 | Â Â # Variable definitions |
---|
1408 |   outfile.createVariable('points', Float, ('number_of_points', |
---|
1409 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_dimensions')) |
---|
1410 |   outfile.createVariable('elevation', Float, ('number_of_points',)) |
---|
1411 | |
---|
1412 | Â Â # Get handles to the variables |
---|
1413 | Â Â points =Â outfile.variables['points'] |
---|
1414 | Â Â elevation =Â outfile.variables['elevation'] |
---|
1415 | |
---|
1416 | Â Â lenv =Â index2-index1+1 |
---|
1417 | Â Â # Store data |
---|
1418 | Â Â global_index =Â 0 |
---|
1419 | Â Â # for i in range(nrows): |
---|
1420 |   for i in range(i1_0,thisi+1,1): |
---|
1421 |     if verbose and i%((nrows+10)/10)==0: |
---|
1422 |       print 'Processing row %d of %d' %(i, nrows) |
---|
1423 | |
---|
1424 | Â Â Â Â lower_index =Â global_index |
---|
1425 | |
---|
1426 | Â Â Â Â v =Â dem_elevation_r[i,index1:index2+1] |
---|
1427 | Â Â Â Â no_NODATA =Â sum(v ==Â NODATA_value) |
---|
1428 |     if no_NODATA > 0: |
---|
1429 | Â Â Â Â Â Â newcols =Â lenv -Â no_NODATA # ncols_in_bounding_box - no_NODATA |
---|
1430 | Â Â Â Â else: |
---|
1431 | Â Â Â Â Â Â newcols =Â lenv # ncols_in_bounding_box |
---|
1432 | |
---|
1433 |     telev = zeros(newcols, Float) |
---|
1434 |     tpoints = zeros((newcols, 2), Float) |
---|
1435 | |
---|
1436 | Â Â Â Â local_index =Â 0 |
---|
1437 | |
---|
1438 | Â Â Â Â y =Â (nrows-i-1)*cellsize +Â yllcorner |
---|
1439 | Â Â Â Â #for j in range(ncols): |
---|
1440 |     for j in range(j1_0,index2+1,1): |
---|
1441 | |
---|
1442 | Â Â Â Â Â Â x =Â j*cellsize +Â xllcorner |
---|
1443 |       if easting_min <= x <= easting_max and \ |
---|
1444 |         northing_min <= y <= northing_max and \ |
---|
1445 | Â Â Â Â Â Â Â Â dem_elevation_r[i,j]Â <>Â NODATA_value: |
---|
1446 |         tpoints[local_index, :] = [x-easting_min,y-northing_min] |
---|
1447 |         telev[local_index] = dem_elevation_r[i, j] |
---|
1448 | Â Â Â Â Â Â Â Â global_index +=Â 1 |
---|
1449 | Â Â Â Â Â Â Â Â local_index +=Â 1 |
---|
1450 | |
---|
1451 | Â Â Â Â upper_index =Â global_index |
---|
1452 | |
---|
1453 |     if upper_index == lower_index + newcols: |
---|
1454 |       points[lower_index:upper_index, :] = tpoints |
---|
1455 | Â Â Â Â Â Â elevation[lower_index:upper_index]Â =Â telev |
---|
1456 | |
---|
1457 |   assert global_index == nopoints, 'index not equal to number of points' |
---|
1458 | |
---|
1459 | Â Â infile.close() |
---|
1460 | Â Â outfile.close() |
---|
1461 | |
---|
1462 | |
---|
1463 | |
---|
1464 | def _read_hecras_cross_sections(lines): |
---|
1465 | Â Â """Return block of surface lines for each cross section |
---|
1466 | Â Â Starts with SURFACE LINE, |
---|
1467 | Â Â Ends with END CROSS-SECTION |
---|
1468 | Â Â """ |
---|
1469 | |
---|
1470 | Â Â points =Â [] |
---|
1471 | |
---|
1472 | Â Â reading_surface =Â False |
---|
1473 |   for i, line in enumerate(lines): |
---|
1474 | |
---|
1475 |     if len(line.strip()) == 0:  #Ignore blanks |
---|
1476 | Â Â Â Â Â Â continue |
---|
1477 | |
---|
1478 |     if lines[i].strip().startswith('SURFACE LINE'): |
---|
1479 | Â Â Â Â Â Â reading_surface =Â True |
---|
1480 | Â Â Â Â Â Â continue |
---|
1481 | |
---|
1482 |     if lines[i].strip().startswith('END') and reading_surface: |
---|
1483 |       yield points |
---|
1484 | Â Â Â Â Â Â reading_surface =Â False |
---|
1485 | Â Â Â Â Â Â points =Â [] |
---|
1486 | |
---|
1487 |     if reading_surface: |
---|
1488 | Â Â Â Â Â Â fields =Â line.strip().split(',') |
---|
1489 | Â Â Â Â Â Â easting =Â float(fields[0]) |
---|
1490 | Â Â Â Â Â Â northing =Â float(fields[1]) |
---|
1491 | Â Â Â Â Â Â elevation =Â float(fields[2]) |
---|
1492 |       points.append([easting, northing, elevation]) |
---|
1493 | |
---|
1494 | |
---|
1495 | |
---|
1496 | |
---|
1497 | def hecras_cross_sections2pts(basename_in, |
---|
1498 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â basename_out=None, |
---|
1499 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=False): |
---|
1500 | Â Â """Read HEC-RAS Elevation datal from the following ASCII format (.sdf) |
---|
1501 | |
---|
1502 | Â Â Example: |
---|
1503 | |
---|
1504 | |
---|
1505 | # RAS export file created on Mon 15Aug2005 11:42 |
---|
1506 | # by HEC-RAS Version 3.1.1 |
---|
1507 | |
---|
1508 | BEGIN HEADER: |
---|
1509 | Â UNITS: METRIC |
---|
1510 | Â DTM TYPE: TIN |
---|
1511 | Â DTM: v:\1\cit\perth_topo\river_tin |
---|
1512 | Â STREAM LAYER: c:\local\hecras\21_02_03\up_canning_cent3d.shp |
---|
1513 | Â CROSS-SECTION LAYER: c:\local\hecras\21_02_03\up_can_xs3d.shp |
---|
1514 | Â MAP PROJECTION: UTM |
---|
1515 | Â PROJECTION ZONE: 50 |
---|
1516 | Â DATUM: AGD66 |
---|
1517 | Â VERTICAL DATUM: |
---|
1518 | Â NUMBER OF REACHES:Â 19 |
---|
1519 | Â NUMBER OF CROSS-SECTIONS:Â 14206 |
---|
1520 | END HEADER: |
---|
1521 | |
---|
1522 | |
---|
1523 | Only the SURFACE LINE data of the following form will be utilised |
---|
1524 | |
---|
1525 | Â CROSS-SECTION: |
---|
1526 | Â Â STREAM ID:Southern-Wungong |
---|
1527 | Â Â REACH ID:Southern-Wungong |
---|
1528 | Â Â STATION:19040.* |
---|
1529 | Â Â CUT LINE: |
---|
1530 | Â Â Â 405548.671603161 , 6438142.7594925 |
---|
1531 | Â Â Â 405734.536092045 , 6438326.10404912 |
---|
1532 | Â Â Â 405745.130459356 , 6438331.48627354 |
---|
1533 | Â Â Â 405813.89633823 , 6438368.6272789 |
---|
1534 | Â Â SURFACE LINE: |
---|
1535 |    405548.67,  6438142.76,  35.37 |
---|
1536 |    405552.24,  6438146.28,  35.41 |
---|
1537 |    405554.78,  6438148.78,  35.44 |
---|
1538 |    405555.80,  6438149.79,  35.44 |
---|
1539 |    405559.37,  6438153.31,  35.45 |
---|
1540 |    405560.88,  6438154.81,  35.44 |
---|
1541 |    405562.93,  6438156.83,  35.42 |
---|
1542 |    405566.50,  6438160.35,  35.38 |
---|
1543 |    405566.99,  6438160.83,  35.37 |
---|
1544 | Â Â Â ... |
---|
1545 | Â Â END CROSS-SECTION |
---|
1546 | |
---|
1547 | Â Â Convert to NetCDF pts format which is |
---|
1548 | |
---|
1549 | Â Â points:Â (Nx2) Float array |
---|
1550 | Â Â elevation: N Float array |
---|
1551 | Â Â """ |
---|
1552 | |
---|
1553 |   import os |
---|
1554 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
1555 |   from Numeric import Float, zeros, reshape |
---|
1556 | |
---|
1557 | Â Â root =Â basename_in |
---|
1558 | |
---|
1559 | Â Â #Get ASCII file |
---|
1560 |   infile = open(root + '.sdf', 'r') #Open SDF file for read |
---|
1561 | |
---|
1562 |   if verbose: print 'Reading DEM from %s' %(root + '.sdf') |
---|
1563 | |
---|
1564 | Â Â lines =Â infile.readlines() |
---|
1565 | Â Â infile.close() |
---|
1566 | |
---|
1567 |   if verbose: print 'Converting to pts format' |
---|
1568 | |
---|
1569 | Â Â i =Â 0 |
---|
1570 |   while lines[i].strip() == '' or lines[i].strip().startswith('#'): |
---|
1571 | Â Â Â Â i +=Â 1 |
---|
1572 | |
---|
1573 |   assert lines[i].strip().upper() == 'BEGIN HEADER:' |
---|
1574 | Â Â i +=Â 1 |
---|
1575 | |
---|
1576 |   assert lines[i].strip().upper().startswith('UNITS:') |
---|
1577 | Â Â units =Â lines[i].strip().split()[1] |
---|
1578 | Â Â i +=Â 1 |
---|
1579 | |
---|
1580 |   assert lines[i].strip().upper().startswith('DTM TYPE:') |
---|
1581 | Â Â i +=Â 1 |
---|
1582 | |
---|
1583 |   assert lines[i].strip().upper().startswith('DTM:') |
---|
1584 | Â Â i +=Â 1 |
---|
1585 | |
---|
1586 |   assert lines[i].strip().upper().startswith('STREAM') |
---|
1587 | Â Â i +=Â 1 |
---|
1588 | |
---|
1589 |   assert lines[i].strip().upper().startswith('CROSS') |
---|
1590 | Â Â i +=Â 1 |
---|
1591 | |
---|
1592 |   assert lines[i].strip().upper().startswith('MAP PROJECTION:') |
---|
1593 | Â Â projection =Â lines[i].strip().split(':')[1] |
---|
1594 | Â Â i +=Â 1 |
---|
1595 | |
---|
1596 |   assert lines[i].strip().upper().startswith('PROJECTION ZONE:') |
---|
1597 | Â Â zone =Â int(lines[i].strip().split(':')[1]) |
---|
1598 | Â Â i +=Â 1 |
---|
1599 | |
---|
1600 |   assert lines[i].strip().upper().startswith('DATUM:') |
---|
1601 | Â Â datum =Â lines[i].strip().split(':')[1] |
---|
1602 | Â Â i +=Â 1 |
---|
1603 | |
---|
1604 |   assert lines[i].strip().upper().startswith('VERTICAL DATUM:') |
---|
1605 | Â Â i +=Â 1 |
---|
1606 | |
---|
1607 |   assert lines[i].strip().upper().startswith('NUMBER OF REACHES:') |
---|
1608 | Â Â i +=Â 1 |
---|
1609 | |
---|
1610 |   assert lines[i].strip().upper().startswith('NUMBER OF CROSS-SECTIONS:') |
---|
1611 | Â Â number_of_cross_sections =Â int(lines[i].strip().split(':')[1]) |
---|
1612 | Â Â i +=Â 1 |
---|
1613 | |
---|
1614 | |
---|
1615 | Â Â #Now read all points |
---|
1616 | Â Â points =Â [] |
---|
1617 | Â Â elevation =Â [] |
---|
1618 |   for j, entries in enumerate(_read_hecras_cross_sections(lines[i:])): |
---|
1619 |     for k, entry in enumerate(entries): |
---|
1620 | Â Â Â Â Â Â points.append(entry[:2]) |
---|
1621 | Â Â Â Â Â Â elevation.append(entry[2]) |
---|
1622 | |
---|
1623 | |
---|
1624 | Â Â msg =Â 'Actual #number_of_cross_sections == %d, Reported as %d'\ |
---|
1625 |      %(j+1, number_of_cross_sections) |
---|
1626 |   assert j+1 == number_of_cross_sections, msg |
---|
1627 | |
---|
1628 | Â Â #Get output file |
---|
1629 |   if basename_out == None: |
---|
1630 | Â Â Â Â ptsname =Â root +Â '.pts' |
---|
1631 | Â Â else: |
---|
1632 | Â Â Â Â ptsname =Â basename_out +Â '.pts' |
---|
1633 | |
---|
1634 |   geo_ref = Geo_reference(zone, 0, 0, datum, projection, units) |
---|
1635 |   geo = Geospatial_data(points, {"elevation":elevation}, |
---|
1636 |              verbose=verbose, geo_reference=geo_ref) |
---|
1637 | Â Â geo.export_points_file(ptsname) |
---|
1638 | |
---|
1639 | def export_grid(basename_in, extra_name_out = None, |
---|
1640 |         quantities = None, # defaults to elevation |
---|
1641 | Â Â Â Â Â Â Â Â timestep =Â None, |
---|
1642 | Â Â Â Â Â Â Â Â reduction =Â None, |
---|
1643 | Â Â Â Â Â Â Â Â cellsize =Â 10, |
---|
1644 | Â Â Â Â Â Â Â Â NODATA_value =Â -9999, |
---|
1645 | Â Â Â Â Â Â Â Â easting_min =Â None, |
---|
1646 | Â Â Â Â Â Â Â Â easting_max =Â None, |
---|
1647 | Â Â Â Â Â Â Â Â northing_min =Â None, |
---|
1648 | Â Â Â Â Â Â Â Â northing_max =Â None, |
---|
1649 | Â Â Â Â Â Â Â Â verbose =Â False, |
---|
1650 | Â Â Â Â Â Â Â Â origin =Â None, |
---|
1651 | Â Â Â Â Â Â Â Â datum =Â 'WGS84', |
---|
1652 | Â Â Â Â Â Â Â Â format =Â 'ers'): |
---|
1653 | Â Â """ |
---|
1654 | Â Â |
---|
1655 | Â Â Wrapper for sww2dem. - see sww2dem to find out what most of the |
---|
1656 | Â Â parameters do. |
---|
1657 | |
---|
1658 |   Quantities is a list of quantities. Each quantity will be |
---|
1659 | Â Â calculated for each sww file. |
---|
1660 | |
---|
1661 | Â Â This returns the basenames of the files returned, which is made up |
---|
1662 | Â Â of the dir and all of the file name, except the extension. |
---|
1663 | |
---|
1664 | Â Â This function returns the names of the files produced. |
---|
1665 | |
---|
1666 | Â Â It will also produce as many output files as there are input sww files. |
---|
1667 | Â Â """ |
---|
1668 | Â Â |
---|
1669 |   if quantities is None: |
---|
1670 | Â Â Â Â quantities =Â ['elevation'] |
---|
1671 | Â Â Â Â |
---|
1672 |   if type(quantities) is str: |
---|
1673 | Â Â Â Â Â Â quantities =Â [quantities] |
---|
1674 | |
---|
1675 | Â Â # How many sww files are there? |
---|
1676 |   dir, base = os.path.split(basename_in) |
---|
1677 | Â Â #print "basename_in",basename_in |
---|
1678 | Â Â #print "base",base |
---|
1679 | |
---|
1680 | Â Â iterate_over =Â get_all_swwfiles(dir,base,verbose) |
---|
1681 | Â Â |
---|
1682 |   if dir == "": |
---|
1683 |     dir = "." # Unix compatibility |
---|
1684 | Â Â |
---|
1685 | Â Â files_out =Â [] |
---|
1686 | Â Â #print 'sww_file',iterate_over |
---|
1687 |   for sww_file in iterate_over: |
---|
1688 |     for quantity in quantities: |
---|
1689 |       if extra_name_out is None: |
---|
1690 | Â Â Â Â Â Â Â Â basename_out =Â sww_file +Â '_'Â +Â quantity |
---|
1691 | Â Â Â Â Â Â else: |
---|
1692 | Â Â Â Â Â Â Â Â basename_out =Â sww_file +Â '_'Â +Â quantity +Â '_'Â \ |
---|
1693 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â +Â extra_name_out |
---|
1694 | #Â Â Â Â Â Â print "basename_out", basename_out |
---|
1695 | Â Â Â Â |
---|
1696 |       file_out = sww2dem(dir+sep+sww_file, dir+sep+basename_out, |
---|
1697 |                 quantity, |
---|
1698 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â timestep, |
---|
1699 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â reduction, |
---|
1700 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â cellsize, |
---|
1701 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â NODATA_value, |
---|
1702 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â easting_min, |
---|
1703 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â easting_max, |
---|
1704 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â northing_min, |
---|
1705 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â northing_max, |
---|
1706 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose, |
---|
1707 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â origin, |
---|
1708 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â datum, |
---|
1709 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â format) |
---|
1710 | Â Â Â Â Â Â files_out.append(file_out) |
---|
1711 | Â Â #print "basenames_out after",basenames_out |
---|
1712 |   return files_out |
---|
1713 | |
---|
1714 | |
---|
1715 | def get_timeseries(production_dirs, output_dir, scenario_name, gauges_dir_name, |
---|
1716 |           plot_quantity, generate_fig = False, |
---|
1717 |           reportname = None, surface = False, time_min = None, |
---|
1718 |           time_max = None, title_on = False, verbose = True, |
---|
1719 | Â Â Â Â Â Â Â Â Â Â nodes=None): |
---|
1720 | Â Â """ |
---|
1721 | Â Â nodes - number of processes used. |
---|
1722 | |
---|
1723 | Â Â warning - this function has no tests |
---|
1724 | Â Â """ |
---|
1725 |   if reportname == None: |
---|
1726 | Â Â Â Â report =Â False |
---|
1727 | Â Â else: |
---|
1728 | Â Â Â Â report =Â True |
---|
1729 | Â Â Â Â |
---|
1730 |   if nodes is None: |
---|
1731 | Â Â Â Â is_parallel =Â False |
---|
1732 | Â Â else: |
---|
1733 | Â Â Â Â is_parallel =Â True |
---|
1734 | Â Â Â Â |
---|
1735 | Â Â # Generate figures |
---|
1736 | Â Â swwfiles =Â {} |
---|
1737 | Â Â |
---|
1738 |   if is_parallel is True:  |
---|
1739 |     for i in range(nodes): |
---|
1740 |       print 'Sending node %d of %d' %(i,nodes) |
---|
1741 | Â Â Â Â Â Â swwfiles =Â {} |
---|
1742 |       if not reportname == None: |
---|
1743 | Â Â Â Â Â Â Â Â reportname =Â report_name +Â '_%s'Â %(i) |
---|
1744 |       for label_id in production_dirs.keys(): |
---|
1745 |         if label_id == 'boundaries': |
---|
1746 | Â Â Â Â Â Â Â Â Â Â swwfile =Â best_boundary_sww |
---|
1747 | Â Â Â Â Â Â Â Â else: |
---|
1748 | Â Â Â Â Â Â Â Â Â Â file_loc =Â output_dir +Â label_id +Â sep |
---|
1749 | Â Â Â Â Â Â Â Â Â Â sww_extra =Â '_P%s_%s'Â %(i,nodes) |
---|
1750 | Â Â Â Â Â Â Â Â Â Â swwfile =Â file_loc +Â scenario_name +Â sww_extra +Â '.sww' |
---|
1751 |           print 'swwfile',swwfile |
---|
1752 | Â Â Â Â Â Â Â Â Â Â swwfiles[swwfile]Â =Â label_id |
---|
1753 | |
---|
1754 |         texname, elev_output = sww2timeseries(swwfiles, |
---|
1755 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â gauges_dir_name, |
---|
1756 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â production_dirs, |
---|
1757 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â report =Â report, |
---|
1758 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â reportname =Â reportname, |
---|
1759 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â plot_quantity =Â plot_quantity, |
---|
1760 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â generate_fig =Â generate_fig, |
---|
1761 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â surface =Â surface, |
---|
1762 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â time_min =Â time_min, |
---|
1763 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â time_max =Â time_max, |
---|
1764 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â title_on =Â title_on, |
---|
1765 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose =Â verbose) |
---|
1766 | Â Â else:Â Â |
---|
1767 |     for label_id in production_dirs.keys():    |
---|
1768 |       if label_id == 'boundaries': |
---|
1769 |         print 'boundaries' |
---|
1770 | Â Â Â Â Â Â Â Â file_loc =Â project.boundaries_in_dir |
---|
1771 | Â Â Â Â Â Â Â Â swwfile =Â project.boundaries_dir_name3 +Â '.sww' |
---|
1772 | Â Â Â Â Â Â Â Â #Â swwfile = boundary_dir_filename |
---|
1773 | Â Â Â Â Â Â else: |
---|
1774 | Â Â Â Â Â Â Â Â file_loc =Â output_dir +Â label_id +Â sep |
---|
1775 | Â Â Â Â Â Â Â Â swwfile =Â file_loc +Â scenario_name +Â '.sww' |
---|
1776 | Â Â Â Â Â Â swwfiles[swwfile]Â =Â label_id |
---|
1777 | Â Â Â Â |
---|
1778 |     texname, elev_output = sww2timeseries(swwfiles, |
---|
1779 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â gauges_dir_name, |
---|
1780 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â production_dirs, |
---|
1781 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â report =Â report, |
---|
1782 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â reportname =Â reportname, |
---|
1783 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â plot_quantity =Â plot_quantity, |
---|
1784 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â generate_fig =Â generate_fig, |
---|
1785 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â surface =Â surface, |
---|
1786 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â time_min =Â time_min, |
---|
1787 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â time_max =Â time_max, |
---|
1788 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â title_on =Â title_on, |
---|
1789 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose =Â verbose) |
---|
1790 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â |
---|
1791 | |
---|
1792 | Â Â |
---|
1793 | def sww2dem(basename_in, basename_out = None, |
---|
1794 |       quantity = None, # defaults to elevation |
---|
1795 | Â Â Â Â Â Â timestep =Â None, |
---|
1796 | Â Â Â Â Â Â reduction =Â None, |
---|
1797 | Â Â Â Â Â Â cellsize =Â 10, |
---|
1798 | Â Â Â Â Â Â NODATA_value =Â -9999, |
---|
1799 | Â Â Â Â Â Â easting_min =Â None, |
---|
1800 | Â Â Â Â Â Â easting_max =Â None, |
---|
1801 | Â Â Â Â Â Â northing_min =Â None, |
---|
1802 | Â Â Â Â Â Â northing_max =Â None, |
---|
1803 | Â Â Â Â Â Â verbose =Â False, |
---|
1804 | Â Â Â Â Â Â origin =Â None, |
---|
1805 | Â Â Â Â Â Â datum =Â 'WGS84', |
---|
1806 | Â Â Â Â Â Â format =Â 'ers'): |
---|
1807 | |
---|
1808 | Â Â """Read SWW file and convert to Digitial Elevation model format |
---|
1809 | Â Â (.asc or .ers) |
---|
1810 | |
---|
1811 | Â Â Example (ASC): |
---|
1812 | |
---|
1813 |   ncols     3121 |
---|
1814 |   nrows     1800 |
---|
1815 |   xllcorner   722000 |
---|
1816 |   yllcorner   5893000 |
---|
1817 |   cellsize   25 |
---|
1818 |   NODATA_value -9999 |
---|
1819 | Â Â 138.3698 137.4194 136.5062 135.5558 .......... |
---|
1820 | |
---|
1821 | Â Â Also write accompanying file with same basename_in but extension .prj |
---|
1822 | Â Â used to fix the UTM zone, datum, false northings and eastings. |
---|
1823 | |
---|
1824 | Â Â The prj format is assumed to be as |
---|
1825 | |
---|
1826 |   Projection  UTM |
---|
1827 |   Zone     56 |
---|
1828 |   Datum     WGS84 |
---|
1829 |   Zunits    NO |
---|
1830 |   Units     METERS |
---|
1831 |   Spheroid   WGS84 |
---|
1832 |   Xshift    0.0000000000 |
---|
1833 |   Yshift    10000000.0000000000 |
---|
1834 | Â Â Parameters |
---|
1835 | |
---|
1836 | |
---|
1837 | Â Â The parameter quantity must be the name of an existing quantity or |
---|
1838 | Â Â an expression involving existing quantities. The default is |
---|
1839 | Â Â 'elevation'. Quantity is not a list of quantities. |
---|
1840 | |
---|
1841 | Â Â if timestep (an index) is given, output quantity at that timestep |
---|
1842 | |
---|
1843 | Â Â if reduction is given use that to reduce quantity over all timesteps. |
---|
1844 | |
---|
1845 | Â Â datum |
---|
1846 | |
---|
1847 | Â Â format can be either 'asc' or 'ers' |
---|
1848 | Â Â """ |
---|
1849 | |
---|
1850 |   import sys |
---|
1851 |   from Numeric import array, Float, concatenate, NewAxis, zeros, reshape, \ |
---|
1852 | Â Â Â Â Â sometrue |
---|
1853 |   from Numeric import array2string |
---|
1854 | |
---|
1855 |   from anuga.utilities.polygon import inside_polygon, outside_polygon, \ |
---|
1856 | Â Â Â Â Â separate_points_by_polygon |
---|
1857 |   from anuga.abstract_2d_finite_volumes.util import \ |
---|
1858 | Â Â Â Â Â apply_expression_to_dictionary |
---|
1859 | |
---|
1860 | Â Â msg =Â 'Format must be either asc or ers' |
---|
1861 |   assert format.lower() in ['asc', 'ers'], msg |
---|
1862 | |
---|
1863 | |
---|
1864 | Â Â false_easting =Â 500000 |
---|
1865 | Â Â false_northing =Â 10000000 |
---|
1866 | |
---|
1867 |   if quantity is None: |
---|
1868 | Â Â Â Â quantity =Â 'elevation' |
---|
1869 | Â Â Â Â |
---|
1870 |   if reduction is None: |
---|
1871 | Â Â Â Â reduction =Â max |
---|
1872 | |
---|
1873 |   if basename_out is None: |
---|
1874 | Â Â Â Â basename_out =Â basename_in +Â '_%s'Â %quantity |
---|
1875 | |
---|
1876 |   if quantity_formula.has_key(quantity): |
---|
1877 | Â Â Â Â quantity =Â quantity_formula[quantity] |
---|
1878 | Â Â Â Â |
---|
1879 | Â Â swwfile =Â basename_in +Â '.sww' |
---|
1880 | Â Â demfile =Â basename_out +Â '.'Â +Â format |
---|
1881 | Â Â # Note the use of a .ers extension is optional (write_ermapper_grid will |
---|
1882 | Â Â # deal with either option |
---|
1883 | Â Â |
---|
1884 | Â Â #if verbose: bye= nsuadsfd[0] # uncomment to check catching verbose errors |
---|
1885 | Â Â |
---|
1886 | Â Â # Read sww file |
---|
1887 |   if verbose: |
---|
1888 |     print 'Reading from %s' %swwfile |
---|
1889 |     print 'Output directory is %s' %basename_out |
---|
1890 | Â Â |
---|
1891 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
1892 | Â Â fid =Â NetCDFFile(swwfile) |
---|
1893 | |
---|
1894 | Â Â #Get extent and reference |
---|
1895 | Â Â x =Â fid.variables['x'][:] |
---|
1896 | Â Â y =Â fid.variables['y'][:] |
---|
1897 | Â Â volumes =Â fid.variables['volumes'][:] |
---|
1898 |   if timestep is not None: |
---|
1899 | Â Â Â Â times =Â fid.variables['time'][timestep] |
---|
1900 | Â Â else: |
---|
1901 | Â Â Â Â times =Â fid.variables['time'][:] |
---|
1902 | |
---|
1903 | Â Â number_of_timesteps =Â fid.dimensions['number_of_timesteps'] |
---|
1904 | Â Â number_of_points =Â fid.dimensions['number_of_points'] |
---|
1905 | Â Â |
---|
1906 |   if origin is None: |
---|
1907 | |
---|
1908 | Â Â Â Â # Get geo_reference |
---|
1909 | Â Â Â Â # sww files don't have to have a geo_ref |
---|
1910 | Â Â Â Â try: |
---|
1911 | Â Â Â Â Â Â geo_reference =Â Geo_reference(NetCDFObject=fid) |
---|
1912 |     except AttributeError, e: |
---|
1913 | Â Â Â Â Â Â geo_reference =Â Geo_reference()Â # Default georef object |
---|
1914 | |
---|
1915 | Â Â Â Â xllcorner =Â geo_reference.get_xllcorner() |
---|
1916 | Â Â Â Â yllcorner =Â geo_reference.get_yllcorner() |
---|
1917 | Â Â Â Â zone =Â geo_reference.get_zone() |
---|
1918 | Â Â else: |
---|
1919 | Â Â Â Â zone =Â origin[0] |
---|
1920 | Â Â Â Â xllcorner =Â origin[1] |
---|
1921 | Â Â Â Â yllcorner =Â origin[2] |
---|
1922 | |
---|
1923 | |
---|
1924 | |
---|
1925 | Â Â # FIXME: Refactor using code from Interpolation_function.statistics |
---|
1926 | Â Â # (in interpolate.py) |
---|
1927 | Â Â # Something like print swwstats(swwname) |
---|
1928 |   if verbose: |
---|
1929 |     print '------------------------------------------------' |
---|
1930 |     print 'Statistics of SWW file:' |
---|
1931 |     print ' Name: %s' %swwfile |
---|
1932 |     print ' Reference:' |
---|
1933 |     print '  Lower left corner: [%f, %f]'\ |
---|
1934 |        %(xllcorner, yllcorner) |
---|
1935 |     if timestep is not None: |
---|
1936 |       print '  Time: %f' %(times) |
---|
1937 | Â Â Â Â else: |
---|
1938 |       print '  Start time: %f' %fid.starttime[0] |
---|
1939 |     print ' Extent:' |
---|
1940 |     print '  x [m] in [%f, %f], len(x) == %d'\ |
---|
1941 |        %(min(x.flat), max(x.flat), len(x.flat)) |
---|
1942 |     print '  y [m] in [%f, %f], len(y) == %d'\ |
---|
1943 |        %(min(y.flat), max(y.flat), len(y.flat)) |
---|
1944 |     if timestep is not None: |
---|
1945 |       print '  t [s] = %f, len(t) == %d' %(times, 1) |
---|
1946 | Â Â Â Â else: |
---|
1947 |       print '  t [s] in [%f, %f], len(t) == %d'\ |
---|
1948 |        %(min(times), max(times), len(times)) |
---|
1949 |     print ' Quantities [SI units]:' |
---|
1950 | Â Â Â Â # Comment out for reduced memory consumption |
---|
1951 |     for name in ['stage', 'xmomentum', 'ymomentum']: |
---|
1952 | Â Â Â Â Â Â q =Â fid.variables[name][:].flat |
---|
1953 |       if timestep is not None: |
---|
1954 | Â Â Â Â Â Â Â Â q =Â q[timestep*len(x):(timestep+1)*len(x)] |
---|
1955 |       if verbose: print '  %s in [%f, %f]' %(name, min(q), max(q)) |
---|
1956 |     for name in ['elevation']: |
---|
1957 | Â Â Â Â Â Â q =Â fid.variables[name][:].flat |
---|
1958 |       if verbose: print '  %s in [%f, %f]' %(name, min(q), max(q)) |
---|
1959 | Â Â Â Â Â Â |
---|
1960 | Â Â # Get quantity and reduce if applicable |
---|
1961 |   if verbose: print 'Processing quantity %s' %quantity |
---|
1962 | |
---|
1963 | Â Â # Turn NetCDF objects into Numeric arrays |
---|
1964 | Â Â try: |
---|
1965 | Â Â Â Â q =Â fid.variables[quantity][:]Â |
---|
1966 | Â Â Â Â |
---|
1967 | Â Â Â Â |
---|
1968 | Â Â except: |
---|
1969 | Â Â Â Â quantity_dict =Â {} |
---|
1970 |     for name in fid.variables.keys(): |
---|
1971 | Â Â Â Â Â Â quantity_dict[name]Â =Â fid.variables[name][:]Â |
---|
1972 |     #Convert quantity expression to quantities found in sww file  |
---|
1973 |     q = apply_expression_to_dictionary(quantity, quantity_dict) |
---|
1974 | Â Â #print "q.shape",q.shape |
---|
1975 |   if len(q.shape) == 2: |
---|
1976 | Â Â Â Â #q has a time component and needs to be reduced along |
---|
1977 | Â Â Â Â #the temporal dimension |
---|
1978 |     if verbose: print 'Reducing quantity %s' %quantity |
---|
1979 |     q_reduced = zeros( number_of_points, Float ) |
---|
1980 | Â Â Â Â |
---|
1981 |     if timestep is not None: |
---|
1982 |       for k in range(number_of_points): |
---|
1983 | Â Â Â Â Â Â Â Â q_reduced[k]Â =Â q[timestep,k]Â |
---|
1984 | Â Â Â Â else: |
---|
1985 |       for k in range(number_of_points): |
---|
1986 | Â Â Â Â Â Â Â Â q_reduced[k]Â =Â reduction(Â q[:,k]Â ) |
---|
1987 | |
---|
1988 | Â Â Â Â q =Â q_reduced |
---|
1989 | |
---|
1990 | Â Â #Post condition: Now q has dimension: number_of_points |
---|
1991 |   assert len(q.shape) == 1 |
---|
1992 |   assert q.shape[0] == number_of_points |
---|
1993 | |
---|
1994 |   if verbose: |
---|
1995 |     print 'Processed values for %s are in [%f, %f]' %(quantity, min(q), max(q)) |
---|
1996 | |
---|
1997 | |
---|
1998 | Â Â #Create grid and update xll/yll corner and x,y |
---|
1999 | |
---|
2000 | Â Â #Relative extent |
---|
2001 |   if easting_min is None: |
---|
2002 | Â Â Â Â xmin =Â min(x) |
---|
2003 | Â Â else: |
---|
2004 | Â Â Â Â xmin =Â easting_min -Â xllcorner |
---|
2005 | |
---|
2006 |   if easting_max is None: |
---|
2007 | Â Â Â Â xmax =Â max(x) |
---|
2008 | Â Â else: |
---|
2009 | Â Â Â Â xmax =Â easting_max -Â xllcorner |
---|
2010 | |
---|
2011 |   if northing_min is None: |
---|
2012 | Â Â Â Â ymin =Â min(y) |
---|
2013 | Â Â else: |
---|
2014 | Â Â Â Â ymin =Â northing_min -Â yllcorner |
---|
2015 | |
---|
2016 |   if northing_max is None: |
---|
2017 | Â Â Â Â ymax =Â max(y) |
---|
2018 | Â Â else: |
---|
2019 | Â Â Â Â ymax =Â northing_max -Â yllcorner |
---|
2020 | |
---|
2021 | |
---|
2022 | |
---|
2023 |   if verbose: print 'Creating grid' |
---|
2024 | Â Â ncols =Â int((xmax-xmin)/cellsize)+1 |
---|
2025 | Â Â nrows =Â int((ymax-ymin)/cellsize)+1 |
---|
2026 | |
---|
2027 | |
---|
2028 | Â Â #New absolute reference and coordinates |
---|
2029 | Â Â newxllcorner =Â xmin+xllcorner |
---|
2030 | Â Â newyllcorner =Â ymin+yllcorner |
---|
2031 | |
---|
2032 | Â Â x =Â x+xllcorner-newxllcorner |
---|
2033 | Â Â y =Â y+yllcorner-newyllcorner |
---|
2034 | Â Â |
---|
2035 |   vertex_points = concatenate ((x[:, NewAxis] ,y[:, NewAxis]), axis = 1) |
---|
2036 |   assert len(vertex_points.shape) == 2 |
---|
2037 | |
---|
2038 |   grid_points = zeros ( (ncols*nrows, 2), Float ) |
---|
2039 | |
---|
2040 | |
---|
2041 |   for i in xrange(nrows): |
---|
2042 |     if format.lower() == 'asc': |
---|
2043 | Â Â Â Â Â Â yg =Â i*cellsize |
---|
2044 | Â Â Â Â else: |
---|
2045 | Â Â Â Â #this will flip the order of the y values for ers |
---|
2046 | Â Â Â Â Â Â yg =Â (nrows-i)*cellsize |
---|
2047 | |
---|
2048 |     for j in xrange(ncols): |
---|
2049 | Â Â Â Â Â Â xg =Â j*cellsize |
---|
2050 | Â Â Â Â Â Â k =Â i*ncols +Â j |
---|
2051 | |
---|
2052 | Â Â Â Â Â Â grid_points[k,0]Â =Â xg |
---|
2053 | Â Â Â Â Â Â grid_points[k,1]Â =Â yg |
---|
2054 | |
---|
2055 | Â Â #Interpolate |
---|
2056 |   from anuga.fit_interpolate.interpolate import Interpolate |
---|
2057 | |
---|
2058 | Â Â # Remove loners from vertex_points, volumes here |
---|
2059 |   vertex_points, volumes = remove_lone_verts(vertex_points, volumes) |
---|
2060 | Â Â #export_mesh_file('monkey.tsh',{'vertices':vertex_points, 'triangles':volumes}) |
---|
2061 | Â Â #import sys; sys.exit() |
---|
2062 |   interp = Interpolate(vertex_points, volumes, verbose = verbose) |
---|
2063 | |
---|
2064 | Â Â #Interpolate using quantity values |
---|
2065 |   if verbose: print 'Interpolating' |
---|
2066 |   grid_values = interp.interpolate(q, grid_points).flat |
---|
2067 | |
---|
2068 | |
---|
2069 |   if verbose: |
---|
2070 |     print 'Interpolated values are in [%f, %f]' %(min(grid_values), |
---|
2071 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â max(grid_values)) |
---|
2072 | |
---|
2073 | Â Â #Assign NODATA_value to all points outside bounding polygon (from interpolation mesh) |
---|
2074 | Â Â P =Â interp.mesh.get_boundary_polygon() |
---|
2075 |   outside_indices = outside_polygon(grid_points, P, closed=True) |
---|
2076 | |
---|
2077 |   for i in outside_indices: |
---|
2078 | Â Â Â Â grid_values[i]Â =Â NODATA_value |
---|
2079 | |
---|
2080 | |
---|
2081 | |
---|
2082 | |
---|
2083 |   if format.lower() == 'ers': |
---|
2084 | Â Â Â Â # setup ERS header information |
---|
2085 |     grid_values = reshape(grid_values,(nrows, ncols)) |
---|
2086 | Â Â Â Â header =Â {} |
---|
2087 | Â Â Â Â header['datum']Â =Â '"'Â +Â datum +Â '"' |
---|
2088 | Â Â Â Â # FIXME The use of hardwired UTM and zone number needs to be made optional |
---|
2089 | Â Â Â Â # FIXME Also need an automatic test for coordinate type (i.e. EN or LL) |
---|
2090 | Â Â Â Â header['projection']Â =Â '"UTM-'Â +Â str(zone)Â +Â '"' |
---|
2091 | Â Â Â Â header['coordinatetype']Â =Â 'EN' |
---|
2092 |     if header['coordinatetype'] == 'LL': |
---|
2093 | Â Â Â Â Â Â header['longitude']Â =Â str(newxllcorner) |
---|
2094 | Â Â Â Â Â Â header['latitude']Â =Â str(newyllcorner) |
---|
2095 |     elif header['coordinatetype'] == 'EN': |
---|
2096 | Â Â Â Â Â Â header['eastings']Â =Â str(newxllcorner) |
---|
2097 | Â Â Â Â Â Â header['northings']Â =Â str(newyllcorner) |
---|
2098 | Â Â Â Â header['nullcellvalue']Â =Â str(NODATA_value) |
---|
2099 | Â Â Â Â header['xdimension']Â =Â str(cellsize) |
---|
2100 | Â Â Â Â header['ydimension']Â =Â str(cellsize) |
---|
2101 | Â Â Â Â header['value']Â =Â '"'Â +Â quantity +Â '"' |
---|
2102 | Â Â Â Â #header['celltype'] = 'IEEE8ByteReal'Â #FIXME: Breaks unit test |
---|
2103 | |
---|
2104 | |
---|
2105 | Â Â Â Â #Write |
---|
2106 |     if verbose: print 'Writing %s' %demfile |
---|
2107 |     import ermapper_grids |
---|
2108 |     ermapper_grids.write_ermapper_grid(demfile, grid_values, header) |
---|
2109 | |
---|
2110 | Â Â Â Â fid.close() |
---|
2111 | Â Â else: |
---|
2112 | Â Â Â Â #Write to Ascii format |
---|
2113 | |
---|
2114 | Â Â Â Â #Write prj file |
---|
2115 | Â Â Â Â prjfile =Â basename_out +Â '.prj' |
---|
2116 | |
---|
2117 |     if verbose: print 'Writing %s' %prjfile |
---|
2118 |     prjid = open(prjfile, 'w') |
---|
2119 |     prjid.write('Projection  %s\n' %'UTM') |
---|
2120 |     prjid.write('Zone     %d\n' %zone) |
---|
2121 |     prjid.write('Datum     %s\n' %datum) |
---|
2122 |     prjid.write('Zunits    NO\n') |
---|
2123 |     prjid.write('Units     METERS\n') |
---|
2124 |     prjid.write('Spheroid   %s\n' %datum) |
---|
2125 |     prjid.write('Xshift    %d\n' %false_easting) |
---|
2126 |     prjid.write('Yshift    %d\n' %false_northing) |
---|
2127 | Â Â Â Â prjid.write('Parameters\n') |
---|
2128 | Â Â Â Â prjid.close() |
---|
2129 | |
---|
2130 | |
---|
2131 | |
---|
2132 |     if verbose: print 'Writing %s' %demfile |
---|
2133 | |
---|
2134 |     ascid = open(demfile, 'w') |
---|
2135 | |
---|
2136 |     ascid.write('ncols     %d\n' %ncols) |
---|
2137 |     ascid.write('nrows     %d\n' %nrows) |
---|
2138 |     ascid.write('xllcorner   %d\n' %newxllcorner) |
---|
2139 |     ascid.write('yllcorner   %d\n' %newyllcorner) |
---|
2140 |     ascid.write('cellsize   %f\n' %cellsize) |
---|
2141 |     ascid.write('NODATA_value %d\n' %NODATA_value) |
---|
2142 | |
---|
2143 | |
---|
2144 | Â Â Â Â #Get bounding polygon from mesh |
---|
2145 | Â Â Â Â #P = interp.mesh.get_boundary_polygon() |
---|
2146 | Â Â Â Â #inside_indices = inside_polygon(grid_points, P) |
---|
2147 | |
---|
2148 |     for i in range(nrows): |
---|
2149 |       if verbose and i%((nrows+10)/10)==0: |
---|
2150 |         print 'Doing row %d of %d' %(i, nrows) |
---|
2151 | |
---|
2152 | Â Â Â Â Â Â base_index =Â (nrows-i-1)*ncols |
---|
2153 | |
---|
2154 |       slice = grid_values[base_index:base_index+ncols] |
---|
2155 |       s = array2string(slice, max_line_width=sys.maxint) |
---|
2156 | Â Â Â Â Â Â ascid.write(s[1:-1]Â +Â '\n') |
---|
2157 | |
---|
2158 | |
---|
2159 | Â Â Â Â Â Â #print |
---|
2160 | Â Â Â Â Â Â #for j in range(ncols): |
---|
2161 | Â Â Â Â Â Â #Â Â index = base_index+j# |
---|
2162 | Â Â Â Â Â Â #Â Â print grid_values[index], |
---|
2163 | Â Â Â Â Â Â #Â Â ascid.write('%f ' %grid_values[index]) |
---|
2164 | Â Â Â Â Â Â #ascid.write('\n') |
---|
2165 | |
---|
2166 | Â Â Â Â #Close |
---|
2167 | Â Â Â Â ascid.close() |
---|
2168 | Â Â Â Â fid.close() |
---|
2169 |     return basename_out |
---|
2170 | |
---|
2171 | |
---|
2172 | #Backwards compatibility |
---|
2173 | def sww2asc(basename_in, basename_out = None, |
---|
2174 | Â Â Â Â Â Â quantity =Â None, |
---|
2175 | Â Â Â Â Â Â timestep =Â None, |
---|
2176 | Â Â Â Â Â Â reduction =Â None, |
---|
2177 | Â Â Â Â Â Â cellsize =Â 10, |
---|
2178 | Â Â Â Â Â Â verbose =Â False, |
---|
2179 | Â Â Â Â Â Â origin =Â None): |
---|
2180 |   print 'sww2asc will soon be obsoleted - please use sww2dem' |
---|
2181 | Â Â sww2dem(basename_in, |
---|
2182 | Â Â Â Â Â Â basename_out =Â basename_out, |
---|
2183 | Â Â Â Â Â Â quantity =Â quantity, |
---|
2184 | Â Â Â Â Â Â timestep =Â timestep, |
---|
2185 | Â Â Â Â Â Â reduction =Â reduction, |
---|
2186 | Â Â Â Â Â Â cellsize =Â cellsize, |
---|
2187 | Â Â Â Â Â Â verbose =Â verbose, |
---|
2188 | Â Â Â Â Â Â origin =Â origin, |
---|
2189 | Â Â Â Â datum =Â 'WGS84', |
---|
2190 | Â Â Â Â format =Â 'asc') |
---|
2191 | |
---|
2192 | def sww2ers(basename_in, basename_out = None, |
---|
2193 | Â Â Â Â Â Â quantity =Â None, |
---|
2194 | Â Â Â Â Â Â timestep =Â None, |
---|
2195 | Â Â Â Â Â Â reduction =Â None, |
---|
2196 | Â Â Â Â Â Â cellsize =Â 10, |
---|
2197 | Â Â Â Â Â Â verbose =Â False, |
---|
2198 | Â Â Â Â Â Â origin =Â None, |
---|
2199 | Â Â Â Â Â Â datum =Â 'WGS84'): |
---|
2200 |   print 'sww2ers will soon be obsoleted - please use sww2dem' |
---|
2201 | Â Â sww2dem(basename_in, |
---|
2202 | Â Â Â Â Â Â basename_out =Â basename_out, |
---|
2203 | Â Â Â Â Â Â quantity =Â quantity, |
---|
2204 | Â Â Â Â Â Â timestep =Â timestep, |
---|
2205 | Â Â Â Â Â Â reduction =Â reduction, |
---|
2206 | Â Â Â Â Â Â cellsize =Â cellsize, |
---|
2207 | Â Â Â Â Â Â verbose =Â verbose, |
---|
2208 | Â Â Â Â Â Â origin =Â origin, |
---|
2209 | Â Â Â Â Â Â datum =Â datum, |
---|
2210 | Â Â Â Â Â Â format =Â 'ers') |
---|
2211 | ################################# END COMPATIBILITY ############## |
---|
2212 | |
---|
2213 | |
---|
2214 | |
---|
2215 | def sww2pts(basename_in, basename_out=None, |
---|
2216 | Â Â Â Â Â Â data_points=None, |
---|
2217 | Â Â Â Â Â Â quantity=None, |
---|
2218 | Â Â Â Â Â Â timestep=None, |
---|
2219 | Â Â Â Â Â Â reduction=None, |
---|
2220 | Â Â Â Â Â Â NODATA_value=-9999, |
---|
2221 | Â Â Â Â Â Â verbose=False, |
---|
2222 | Â Â Â Â Â Â origin=None): |
---|
2223 | Â Â Â Â Â Â #datum = 'WGS84') |
---|
2224 | |
---|
2225 | |
---|
2226 | Â Â """Read SWW file and convert to interpolated values at selected points |
---|
2227 | |
---|
2228 | Â Â The parameter quantity' must be the name of an existing quantity or |
---|
2229 | Â Â an expression involving existing quantities. The default is |
---|
2230 | Â Â 'elevation'. |
---|
2231 | |
---|
2232 | Â Â if timestep (an index) is given, output quantity at that timestep |
---|
2233 | |
---|
2234 | Â Â if reduction is given use that to reduce quantity over all timesteps. |
---|
2235 | |
---|
2236 | Â Â data_points (Nx2 array) give locations of points where quantity is to be computed. |
---|
2237 | Â Â |
---|
2238 | Â Â """ |
---|
2239 | |
---|
2240 |   import sys |
---|
2241 |   from Numeric import array, Float, concatenate, NewAxis, zeros, reshape, sometrue |
---|
2242 |   from Numeric import array2string |
---|
2243 | |
---|
2244 |   from anuga.utilities.polygon import inside_polygon, outside_polygon, separate_points_by_polygon |
---|
2245 |   from anuga.abstract_2d_finite_volumes.util import apply_expression_to_dictionary |
---|
2246 | |
---|
2247 |   from anuga.geospatial_data.geospatial_data import Geospatial_data |
---|
2248 | |
---|
2249 |   if quantity is None: |
---|
2250 | Â Â Â Â quantity =Â 'elevation' |
---|
2251 | |
---|
2252 |   if reduction is None: |
---|
2253 | Â Â Â Â reduction =Â max |
---|
2254 | |
---|
2255 |   if basename_out is None: |
---|
2256 | Â Â Â Â basename_out =Â basename_in +Â '_%s'Â %quantity |
---|
2257 | |
---|
2258 | Â Â swwfile =Â basename_in +Â '.sww' |
---|
2259 | Â Â ptsfile =Â basename_out +Â '.pts' |
---|
2260 | |
---|
2261 | Â Â # Read sww file |
---|
2262 |   if verbose: print 'Reading from %s' %swwfile |
---|
2263 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
2264 | Â Â fid =Â NetCDFFile(swwfile) |
---|
2265 | |
---|
2266 | Â Â # Get extent and reference |
---|
2267 | Â Â x =Â fid.variables['x'][:] |
---|
2268 | Â Â y =Â fid.variables['y'][:] |
---|
2269 | Â Â volumes =Â fid.variables['volumes'][:] |
---|
2270 | |
---|
2271 | Â Â number_of_timesteps =Â fid.dimensions['number_of_timesteps'] |
---|
2272 | Â Â number_of_points =Â fid.dimensions['number_of_points'] |
---|
2273 |   if origin is None: |
---|
2274 | |
---|
2275 | Â Â Â Â # Get geo_reference |
---|
2276 | Â Â Â Â # sww files don't have to have a geo_ref |
---|
2277 | Â Â Â Â try: |
---|
2278 | Â Â Â Â Â Â geo_reference =Â Geo_reference(NetCDFObject=fid) |
---|
2279 |     except AttributeError, e: |
---|
2280 | Â Â Â Â Â Â geo_reference =Â Geo_reference()Â #Default georef object |
---|
2281 | |
---|
2282 | Â Â Â Â xllcorner =Â geo_reference.get_xllcorner() |
---|
2283 | Â Â Â Â yllcorner =Â geo_reference.get_yllcorner() |
---|
2284 | Â Â Â Â zone =Â geo_reference.get_zone() |
---|
2285 | Â Â else: |
---|
2286 | Â Â Â Â zone =Â origin[0] |
---|
2287 | Â Â Â Â xllcorner =Â origin[1] |
---|
2288 | Â Â Â Â yllcorner =Â origin[2] |
---|
2289 | |
---|
2290 | |
---|
2291 | |
---|
2292 | Â Â # FIXME: Refactor using code from file_function.statistics |
---|
2293 | Â Â # Something like print swwstats(swwname) |
---|
2294 |   if verbose: |
---|
2295 | Â Â Â Â x =Â fid.variables['x'][:] |
---|
2296 | Â Â Â Â y =Â fid.variables['y'][:] |
---|
2297 | Â Â Â Â times =Â fid.variables['time'][:] |
---|
2298 |     print '------------------------------------------------' |
---|
2299 |     print 'Statistics of SWW file:' |
---|
2300 |     print ' Name: %s' %swwfile |
---|
2301 |     print ' Reference:' |
---|
2302 |     print '  Lower left corner: [%f, %f]'\ |
---|
2303 |        %(xllcorner, yllcorner) |
---|
2304 |     print '  Start time: %f' %fid.starttime[0] |
---|
2305 |     print ' Extent:' |
---|
2306 |     print '  x [m] in [%f, %f], len(x) == %d'\ |
---|
2307 |        %(min(x.flat), max(x.flat), len(x.flat)) |
---|
2308 |     print '  y [m] in [%f, %f], len(y) == %d'\ |
---|
2309 |        %(min(y.flat), max(y.flat), len(y.flat)) |
---|
2310 |     print '  t [s] in [%f, %f], len(t) == %d'\ |
---|
2311 |        %(min(times), max(times), len(times)) |
---|
2312 |     print ' Quantities [SI units]:' |
---|
2313 |     for name in ['stage', 'xmomentum', 'ymomentum', 'elevation']: |
---|
2314 | Â Â Â Â Â Â q =Â fid.variables[name][:].flat |
---|
2315 |       print '  %s in [%f, %f]' %(name, min(q), max(q)) |
---|
2316 | |
---|
2317 | |
---|
2318 | |
---|
2319 | Â Â # Get quantity and reduce if applicable |
---|
2320 |   if verbose: print 'Processing quantity %s' %quantity |
---|
2321 | |
---|
2322 | Â Â # Turn NetCDF objects into Numeric arrays |
---|
2323 | Â Â quantity_dict =Â {} |
---|
2324 |   for name in fid.variables.keys(): |
---|
2325 | Â Â Â Â quantity_dict[name]Â =Â fid.variables[name][:] |
---|
2326 | |
---|
2327 | |
---|
2328 | |
---|
2329 |   # Convert quantity expression to quantities found in sww file  |
---|
2330 |   q = apply_expression_to_dictionary(quantity, quantity_dict) |
---|
2331 | |
---|
2332 | |
---|
2333 | |
---|
2334 |   if len(q.shape) == 2: |
---|
2335 | Â Â Â Â # q has a time component and needs to be reduced along |
---|
2336 | Â Â Â Â # the temporal dimension |
---|
2337 |     if verbose: print 'Reducing quantity %s' %quantity |
---|
2338 |     q_reduced = zeros( number_of_points, Float ) |
---|
2339 | |
---|
2340 |     for k in range(number_of_points): |
---|
2341 | Â Â Â Â Â Â q_reduced[k]Â =Â reduction(Â q[:,k]Â ) |
---|
2342 | |
---|
2343 | Â Â Â Â q =Â q_reduced |
---|
2344 | |
---|
2345 | Â Â # Post condition: Now q has dimension: number_of_points |
---|
2346 |   assert len(q.shape) == 1 |
---|
2347 |   assert q.shape[0] == number_of_points |
---|
2348 | |
---|
2349 | |
---|
2350 |   if verbose: |
---|
2351 |     print 'Processed values for %s are in [%f, %f]' %(quantity, min(q), max(q)) |
---|
2352 | |
---|
2353 | |
---|
2354 | Â Â # Create grid and update xll/yll corner and x,y |
---|
2355 |   vertex_points = concatenate ((x[:, NewAxis] ,y[:, NewAxis]), axis = 1) |
---|
2356 |   assert len(vertex_points.shape) == 2 |
---|
2357 | |
---|
2358 | Â Â # Interpolate |
---|
2359 |   from anuga.fit_interpolate.interpolate import Interpolate |
---|
2360 |   interp = Interpolate(vertex_points, volumes, verbose = verbose) |
---|
2361 | |
---|
2362 | Â Â # Interpolate using quantity values |
---|
2363 |   if verbose: print 'Interpolating' |
---|
2364 |   interpolated_values = interp.interpolate(q, data_points).flat |
---|
2365 | |
---|
2366 | |
---|
2367 |   if verbose: |
---|
2368 |     print 'Interpolated values are in [%f, %f]' %(min(interpolated_values), |
---|
2369 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â max(interpolated_values)) |
---|
2370 | |
---|
2371 | Â Â # Assign NODATA_value to all points outside bounding polygon (from interpolation mesh) |
---|
2372 | Â Â P =Â interp.mesh.get_boundary_polygon() |
---|
2373 |   outside_indices = outside_polygon(data_points, P, closed=True) |
---|
2374 | |
---|
2375 |   for i in outside_indices: |
---|
2376 | Â Â Â Â interpolated_values[i]Â =Â NODATA_value |
---|
2377 | |
---|
2378 | |
---|
2379 |   # Store results  |
---|
2380 | Â Â G =Â Geospatial_data(data_points=data_points, |
---|
2381 | Â Â Â Â Â Â Â Â Â Â Â Â attributes=interpolated_values) |
---|
2382 | |
---|
2383 |   G.export_points_file(ptsfile, absolute = True) |
---|
2384 | |
---|
2385 | Â Â fid.close() |
---|
2386 | |
---|
2387 | |
---|
2388 | def convert_dem_from_ascii2netcdf(basename_in, basename_out = None, |
---|
2389 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â use_cache =Â False, |
---|
2390 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose =Â False): |
---|
2391 | Â Â """Read Digitial Elevation model from the following ASCII format (.asc) |
---|
2392 | |
---|
2393 | Â Â Example: |
---|
2394 | |
---|
2395 |   ncols     3121 |
---|
2396 |   nrows     1800 |
---|
2397 |   xllcorner   722000 |
---|
2398 |   yllcorner   5893000 |
---|
2399 |   cellsize   25 |
---|
2400 |   NODATA_value -9999 |
---|
2401 | Â Â 138.3698 137.4194 136.5062 135.5558 .......... |
---|
2402 | |
---|
2403 | Â Â Convert basename_in + '.asc' to NetCDF format (.dem) |
---|
2404 | Â Â mimicking the ASCII format closely. |
---|
2405 | |
---|
2406 | |
---|
2407 | Â Â An accompanying file with same basename_in but extension .prj must exist |
---|
2408 | Â Â and is used to fix the UTM zone, datum, false northings and eastings. |
---|
2409 | |
---|
2410 | Â Â The prj format is assumed to be as |
---|
2411 | |
---|
2412 |   Projection  UTM |
---|
2413 |   Zone     56 |
---|
2414 |   Datum     WGS84 |
---|
2415 |   Zunits    NO |
---|
2416 |   Units     METERS |
---|
2417 |   Spheroid   WGS84 |
---|
2418 |   Xshift    0.0000000000 |
---|
2419 |   Yshift    10000000.0000000000 |
---|
2420 | Â Â Parameters |
---|
2421 | Â Â """ |
---|
2422 | |
---|
2423 | |
---|
2424 | |
---|
2425 |   kwargs = {'basename_out': basename_out, 'verbose': verbose} |
---|
2426 | |
---|
2427 |   if use_cache is True: |
---|
2428 |     from caching import cache |
---|
2429 |     result = cache(_convert_dem_from_ascii2netcdf, basename_in, kwargs, |
---|
2430 | Â Â Â Â Â Â Â Â Â Â Â Â dependencies =Â [basename_in +Â '.asc', |
---|
2431 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â basename_in +Â '.prj'], |
---|
2432 | Â Â Â Â Â Â Â Â Â Â Â Â verbose =Â verbose) |
---|
2433 | |
---|
2434 | Â Â else: |
---|
2435 |     result = apply(_convert_dem_from_ascii2netcdf, [basename_in], kwargs) |
---|
2436 | |
---|
2437 |   return result |
---|
2438 | |
---|
2439 | |
---|
2440 | |
---|
2441 | |
---|
2442 | |
---|
2443 | |
---|
2444 | def _convert_dem_from_ascii2netcdf(basename_in, basename_out = None, |
---|
2445 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose =Â False): |
---|
2446 | Â Â """Read Digitial Elevation model from the following ASCII format (.asc) |
---|
2447 | |
---|
2448 | Â Â Internal function. See public function convert_dem_from_ascii2netcdf for details. |
---|
2449 | Â Â """ |
---|
2450 | |
---|
2451 |   import os |
---|
2452 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
2453 |   from Numeric import Float, array |
---|
2454 | |
---|
2455 | Â Â #root, ext = os.path.splitext(basename_in) |
---|
2456 | Â Â root =Â basename_in |
---|
2457 | |
---|
2458 | Â Â ########################################### |
---|
2459 | Â Â # Read Meta data |
---|
2460 |   if verbose: print 'Reading METADATA from %s' %root + '.prj' |
---|
2461 | Â Â metadatafile =Â open(root +Â '.prj') |
---|
2462 | Â Â metalines =Â metadatafile.readlines() |
---|
2463 | Â Â metadatafile.close() |
---|
2464 | |
---|
2465 | Â Â L =Â metalines[0].strip().split() |
---|
2466 |   assert L[0].strip().lower() == 'projection' |
---|
2467 | Â Â projection =Â L[1].strip()Â Â Â Â Â Â Â Â Â Â #TEXT |
---|
2468 | |
---|
2469 | Â Â L =Â metalines[1].strip().split() |
---|
2470 |   assert L[0].strip().lower() == 'zone' |
---|
2471 | Â Â zone =Â int(L[1].strip()) |
---|
2472 | |
---|
2473 | Â Â L =Â metalines[2].strip().split() |
---|
2474 |   assert L[0].strip().lower() == 'datum' |
---|
2475 | Â Â datum =Â L[1].strip()Â Â Â Â Â Â Â Â Â Â Â Â #TEXT |
---|
2476 | |
---|
2477 | Â Â L =Â metalines[3].strip().split() |
---|
2478 |   assert L[0].strip().lower() == 'zunits'   #IGNORE |
---|
2479 | Â Â zunits =Â L[1].strip()Â Â Â Â Â Â Â Â Â Â Â Â #TEXT |
---|
2480 | |
---|
2481 | Â Â L =Â metalines[4].strip().split() |
---|
2482 |   assert L[0].strip().lower() == 'units' |
---|
2483 | Â Â units =Â L[1].strip()Â Â Â Â Â Â Â Â Â Â Â Â #TEXT |
---|
2484 | |
---|
2485 | Â Â L =Â metalines[5].strip().split() |
---|
2486 |   assert L[0].strip().lower() == 'spheroid'  #IGNORE |
---|
2487 | Â Â spheroid =Â L[1].strip()Â Â Â Â Â Â Â Â Â Â Â #TEXT |
---|
2488 | |
---|
2489 | Â Â L =Â metalines[6].strip().split() |
---|
2490 |   assert L[0].strip().lower() == 'xshift' |
---|
2491 | Â Â false_easting =Â float(L[1].strip()) |
---|
2492 | |
---|
2493 | Â Â L =Â metalines[7].strip().split() |
---|
2494 |   assert L[0].strip().lower() == 'yshift' |
---|
2495 | Â Â false_northing =Â float(L[1].strip()) |
---|
2496 | |
---|
2497 | Â Â #print false_easting, false_northing, zone, datum |
---|
2498 | |
---|
2499 | |
---|
2500 | Â Â ########################################### |
---|
2501 | Â Â #Read DEM data |
---|
2502 | |
---|
2503 | Â Â datafile =Â open(basename_in +Â '.asc') |
---|
2504 | |
---|
2505 |   if verbose: print 'Reading DEM from %s' %(basename_in + '.asc') |
---|
2506 | Â Â lines =Â datafile.readlines() |
---|
2507 | Â Â datafile.close() |
---|
2508 | |
---|
2509 |   if verbose: print 'Got', len(lines), ' lines' |
---|
2510 | |
---|
2511 | Â Â ncols =Â int(lines[0].split()[1].strip()) |
---|
2512 | Â Â nrows =Â int(lines[1].split()[1].strip()) |
---|
2513 | |
---|
2514 | Â Â # Do cellsize (line 4) before line 2 and 3 |
---|
2515 | Â Â cellsize =Â float(lines[4].split()[1].strip())Â Â |
---|
2516 | |
---|
2517 | Â Â # Checks suggested by Joaquim Luis |
---|
2518 | Â Â # Our internal representation of xllcorner |
---|
2519 | Â Â # and yllcorner is non-standard. |
---|
2520 | Â Â xref =Â lines[2].split() |
---|
2521 |   if xref[0].strip() == 'xllcorner': |
---|
2522 | Â Â Â Â xllcorner =Â float(xref[1].strip())Â # + 0.5*cellsize # Correct offset |
---|
2523 |   elif xref[0].strip() == 'xllcenter': |
---|
2524 | Â Â Â Â xllcorner =Â float(xref[1].strip()) |
---|
2525 | Â Â else: |
---|
2526 | Â Â Â Â msg =Â 'Unknown keyword: %s'Â %xref[0].strip() |
---|
2527 |     raise Exception, msg |
---|
2528 | |
---|
2529 | Â Â yref =Â lines[3].split() |
---|
2530 |   if yref[0].strip() == 'yllcorner': |
---|
2531 | Â Â Â Â yllcorner =Â float(yref[1].strip())Â # + 0.5*cellsize # Correct offset |
---|
2532 |   elif yref[0].strip() == 'yllcenter': |
---|
2533 | Â Â Â Â yllcorner =Â float(yref[1].strip()) |
---|
2534 | Â Â else: |
---|
2535 | Â Â Â Â msg =Â 'Unknown keyword: %s'Â %yref[0].strip() |
---|
2536 |     raise Exception, msg |
---|
2537 | Â Â Â Â |
---|
2538 | |
---|
2539 | Â Â NODATA_value =Â int(lines[5].split()[1].strip()) |
---|
2540 | |
---|
2541 |   assert len(lines) == nrows + 6 |
---|
2542 | |
---|
2543 | |
---|
2544 | Â Â ########################################## |
---|
2545 | |
---|
2546 | |
---|
2547 |   if basename_out == None: |
---|
2548 | Â Â Â Â netcdfname =Â root +Â '.dem' |
---|
2549 | Â Â else: |
---|
2550 | Â Â Â Â netcdfname =Â basename_out +Â '.dem' |
---|
2551 | |
---|
2552 |   if verbose: print 'Store to NetCDF file %s' %netcdfname |
---|
2553 | Â Â # NetCDF file definition |
---|
2554 |   fid = NetCDFFile(netcdfname, 'w') |
---|
2555 | |
---|
2556 | Â Â #Create new file |
---|
2557 | Â Â fid.institution =Â 'Geoscience Australia' |
---|
2558 | Â Â fid.description =Â 'NetCDF DEM format for compact and portable storage 'Â +\ |
---|
2559 | Â Â Â Â Â Â Â Â Â Â Â 'of spatial point data' |
---|
2560 | |
---|
2561 | Â Â fid.ncols =Â ncols |
---|
2562 | Â Â fid.nrows =Â nrows |
---|
2563 | Â Â fid.xllcorner =Â xllcorner |
---|
2564 | Â Â fid.yllcorner =Â yllcorner |
---|
2565 | Â Â fid.cellsize =Â cellsize |
---|
2566 | Â Â fid.NODATA_value =Â NODATA_value |
---|
2567 | |
---|
2568 | Â Â fid.zone =Â zone |
---|
2569 | Â Â fid.false_easting =Â false_easting |
---|
2570 | Â Â fid.false_northing =Â false_northing |
---|
2571 | Â Â fid.projection =Â projection |
---|
2572 | Â Â fid.datum =Â datum |
---|
2573 | Â Â fid.units =Â units |
---|
2574 | |
---|
2575 | |
---|
2576 | Â Â # dimension definitions |
---|
2577 |   fid.createDimension('number_of_rows', nrows) |
---|
2578 |   fid.createDimension('number_of_columns', ncols) |
---|
2579 | |
---|
2580 | Â Â # variable definitions |
---|
2581 |   fid.createVariable('elevation', Float, ('number_of_rows', |
---|
2582 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_columns')) |
---|
2583 | |
---|
2584 | Â Â # Get handles to the variables |
---|
2585 | Â Â elevation =Â fid.variables['elevation'] |
---|
2586 | |
---|
2587 | Â Â #Store data |
---|
2588 | Â Â n =Â len(lines[6:]) |
---|
2589 |   for i, line in enumerate(lines[6:]): |
---|
2590 | Â Â Â Â fields =Â line.split() |
---|
2591 |     if verbose and i%((n+10)/10)==0: |
---|
2592 |       print 'Processing row %d of %d' %(i, nrows) |
---|
2593 | |
---|
2594 |     elevation[i, :] = array([float(x) for x in fields]) |
---|
2595 | |
---|
2596 | Â Â fid.close() |
---|
2597 | |
---|
2598 | |
---|
2599 | |
---|
2600 | |
---|
2601 | |
---|
2602 | def ferret2sww(basename_in, basename_out = None, |
---|
2603 | Â Â Â Â Â Â Â Â verbose =Â False, |
---|
2604 |         minlat = None, maxlat = None, |
---|
2605 |         minlon = None, maxlon = None, |
---|
2606 |         mint = None, maxt = None, mean_stage = 0, |
---|
2607 |         origin = None, zscale = 1, |
---|
2608 | Â Â Â Â Â Â Â Â fail_on_NaN =Â True, |
---|
2609 | Â Â Â Â Â Â Â Â NaN_filler =Â 0, |
---|
2610 | Â Â Â Â Â Â Â Â elevation =Â None, |
---|
2611 | Â Â Â Â Â Â Â Â inverted_bathymetry =Â True |
---|
2612 | Â Â Â Â Â Â Â Â ):Â #FIXME: Bathymetry should be obtained |
---|
2613 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #from MOST somehow. |
---|
2614 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #Alternatively from elsewhere |
---|
2615 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #or, as a last resort, |
---|
2616 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #specified here. |
---|
2617 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #The value of -100 will work |
---|
2618 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #for the Wollongong tsunami |
---|
2619 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #scenario but is very hacky |
---|
2620 | Â Â """Convert MOST and 'Ferret' NetCDF format for wave propagation to |
---|
2621 | Â Â sww format native to abstract_2d_finite_volumes. |
---|
2622 | |
---|
2623 | Â Â Specify only basename_in and read files of the form |
---|
2624 | Â Â basefilename_ha.nc, basefilename_ua.nc, basefilename_va.nc containing |
---|
2625 | Â Â relative height, x-velocity and y-velocity, respectively. |
---|
2626 | |
---|
2627 | Â Â Also convert latitude and longitude to UTM. All coordinates are |
---|
2628 | Â Â assumed to be given in the GDA94 datum. |
---|
2629 | |
---|
2630 | Â Â min's and max's: If omitted - full extend is used. |
---|
2631 | Â Â To include a value min may equal it, while max must exceed it. |
---|
2632 | Â Â Lat and lon are assuemd to be in decimal degrees |
---|
2633 | |
---|
2634 | Â Â origin is a 3-tuple with geo referenced |
---|
2635 | Â Â UTM coordinates (zone, easting, northing) |
---|
2636 | |
---|
2637 | Â Â nc format has values organised as HA[TIME, LATITUDE, LONGITUDE] |
---|
2638 | Â Â which means that longitude is the fastest |
---|
2639 | Â Â varying dimension (row major order, so to speak) |
---|
2640 | |
---|
2641 | Â Â ferret2sww uses grid points as vertices in a triangular grid |
---|
2642 | Â Â counting vertices from lower left corner upwards, then right |
---|
2643 | Â Â """ |
---|
2644 | |
---|
2645 |   import os |
---|
2646 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
2647 |   from Numeric import Float, Int, Int32, searchsorted, zeros, array |
---|
2648 |   from Numeric import allclose, around |
---|
2649 | |
---|
2650 | Â Â precision =Â Float |
---|
2651 | |
---|
2652 | Â Â msg =Â 'Must use latitudes and longitudes for minlat, maxlon etc' |
---|
2653 | |
---|
2654 |   if minlat != None: |
---|
2655 |     assert -90 < minlat < 90 , msg |
---|
2656 |   if maxlat != None: |
---|
2657 |     assert -90 < maxlat < 90 , msg |
---|
2658 |     if minlat != None: |
---|
2659 |       assert maxlat > minlat |
---|
2660 |   if minlon != None: |
---|
2661 |     assert -180 < minlon < 180 , msg |
---|
2662 |   if maxlon != None: |
---|
2663 |     assert -180 < maxlon < 180 , msg |
---|
2664 |     if minlon != None: |
---|
2665 |       assert maxlon > minlon |
---|
2666 | Â Â Â Â |
---|
2667 | |
---|
2668 | |
---|
2669 | Â Â #Get NetCDF data |
---|
2670 |   if verbose: print 'Reading files %s_*.nc' %basename_in |
---|
2671 | Â Â #print "basename_in + '_ha.nc'",basename_in + '_ha.nc' |
---|
2672 |   file_h = NetCDFFile(basename_in + '_ha.nc', 'r') #Wave amplitude (cm) |
---|
2673 |   file_u = NetCDFFile(basename_in + '_ua.nc', 'r') #Velocity (x) (cm/s) |
---|
2674 |   file_v = NetCDFFile(basename_in + '_va.nc', 'r') #Velocity (y) (cm/s) |
---|
2675 |   file_e = NetCDFFile(basename_in + '_e.nc', 'r') #Elevation (z) (m) |
---|
2676 | |
---|
2677 |   if basename_out is None: |
---|
2678 | Â Â Â Â swwname =Â basename_in +Â '.sww' |
---|
2679 | Â Â else: |
---|
2680 | Â Â Â Â swwname =Â basename_out +Â '.sww' |
---|
2681 | |
---|
2682 | Â Â # Get dimensions of file_h |
---|
2683 |   for dimension in file_h.dimensions.keys(): |
---|
2684 |     if dimension[:3] == 'LON': |
---|
2685 | Â Â Â Â Â Â dim_h_longitude =Â dimension |
---|
2686 |     if dimension[:3] == 'LAT': |
---|
2687 | Â Â Â Â Â Â dim_h_latitude =Â dimension |
---|
2688 |     if dimension[:4] == 'TIME': |
---|
2689 | Â Â Â Â Â Â dim_h_time =Â dimension |
---|
2690 | |
---|
2691 | #Â Â print 'long:', dim_h_longitude |
---|
2692 | #Â Â print 'lats:', dim_h_latitude |
---|
2693 | #Â Â print 'times:', dim_h_time |
---|
2694 | |
---|
2695 | Â Â times =Â file_h.variables[dim_h_time] |
---|
2696 | Â Â latitudes =Â file_h.variables[dim_h_latitude] |
---|
2697 | Â Â longitudes =Â file_h.variables[dim_h_longitude] |
---|
2698 | |
---|
2699 |   kmin, kmax, lmin, lmax = _get_min_max_indexes(latitudes[:], |
---|
2700 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â longitudes[:], |
---|
2701 |                          minlat, maxlat, |
---|
2702 |                          minlon, maxlon) |
---|
2703 | Â Â # get dimensions for file_e |
---|
2704 |   for dimension in file_e.dimensions.keys(): |
---|
2705 |     if dimension[:3] == 'LON': |
---|
2706 | Â Â Â Â Â Â dim_e_longitude =Â dimension |
---|
2707 |     if dimension[:3] == 'LAT': |
---|
2708 | Â Â Â Â Â Â dim_e_latitude =Â dimension |
---|
2709 | |
---|
2710 | Â Â # get dimensions for file_u |
---|
2711 |   for dimension in file_u.dimensions.keys(): |
---|
2712 |     if dimension[:3] == 'LON': |
---|
2713 | Â Â Â Â Â Â dim_u_longitude =Â dimension |
---|
2714 |     if dimension[:3] == 'LAT': |
---|
2715 | Â Â Â Â Â Â dim_u_latitude =Â dimension |
---|
2716 |     if dimension[:4] == 'TIME': |
---|
2717 | Â Â Â Â Â Â dim_u_time =Â dimension |
---|
2718 | Â Â Â Â Â Â |
---|
2719 | Â Â # get dimensions for file_v |
---|
2720 |   for dimension in file_v.dimensions.keys(): |
---|
2721 |     if dimension[:3] == 'LON': |
---|
2722 | Â Â Â Â Â Â dim_v_longitude =Â dimension |
---|
2723 |     if dimension[:3] == 'LAT': |
---|
2724 | Â Â Â Â Â Â dim_v_latitude =Â dimension |
---|
2725 |     if dimension[:4] == 'TIME': |
---|
2726 | Â Â Â Â Â Â dim_v_time =Â dimension |
---|
2727 | |
---|
2728 | |
---|
2729 | Â Â # Precision used by most for lat/lon is 4 or 5 decimals |
---|
2730 |   e_lat = around(file_e.variables[dim_e_latitude][:], 5) |
---|
2731 |   e_lon = around(file_e.variables[dim_e_longitude][:], 5) |
---|
2732 | |
---|
2733 | Â Â # Check that files are compatible |
---|
2734 |   assert allclose(latitudes, file_u.variables[dim_u_latitude]) |
---|
2735 |   assert allclose(latitudes, file_v.variables[dim_v_latitude]) |
---|
2736 |   assert allclose(latitudes, e_lat) |
---|
2737 | |
---|
2738 |   assert allclose(longitudes, file_u.variables[dim_u_longitude]) |
---|
2739 |   assert allclose(longitudes, file_v.variables[dim_v_longitude]) |
---|
2740 |   assert allclose(longitudes, e_lon) |
---|
2741 | |
---|
2742 |   if mint is None: |
---|
2743 | Â Â Â Â jmin =Â 0 |
---|
2744 | Â Â Â Â mint =Â times[0]Â Â Â Â |
---|
2745 | Â Â else: |
---|
2746 |     jmin = searchsorted(times, mint) |
---|
2747 | Â Â Â Â |
---|
2748 |   if maxt is None: |
---|
2749 | Â Â Â Â jmax =Â len(times) |
---|
2750 | Â Â Â Â maxt =Â times[-1] |
---|
2751 | Â Â else: |
---|
2752 |     jmax = searchsorted(times, maxt) |
---|
2753 | |
---|
2754 | Â Â #print "latitudes[:]",latitudes[:] |
---|
2755 | Â Â #print "longitudes[:]",longitudes [:] |
---|
2756 |   kmin, kmax, lmin, lmax = _get_min_max_indexes(latitudes[:], |
---|
2757 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â longitudes[:], |
---|
2758 |                          minlat, maxlat, |
---|
2759 |                          minlon, maxlon) |
---|
2760 | |
---|
2761 | |
---|
2762 | Â Â times =Â times[jmin:jmax] |
---|
2763 | Â Â latitudes =Â latitudes[kmin:kmax] |
---|
2764 | Â Â longitudes =Â longitudes[lmin:lmax] |
---|
2765 | |
---|
2766 | Â Â #print "latitudes[:]",latitudes[:] |
---|
2767 | Â Â #print "longitudes[:]",longitudes [:] |
---|
2768 | |
---|
2769 |   if verbose: print 'cropping' |
---|
2770 | Â Â zname =Â 'ELEVATION' |
---|
2771 | |
---|
2772 |   amplitudes = file_h.variables['HA'][jmin:jmax, kmin:kmax, lmin:lmax] |
---|
2773 |   uspeed = file_u.variables['UA'][jmin:jmax, kmin:kmax, lmin:lmax] #Lon |
---|
2774 |   vspeed = file_v.variables['VA'][jmin:jmax, kmin:kmax, lmin:lmax] #Lat |
---|
2775 |   elevations = file_e.variables[zname][kmin:kmax, lmin:lmax] |
---|
2776 | |
---|
2777 | Â Â #Â Â if latitudes2[0]==latitudes[0] and latitudes2[-1]==latitudes[-1]: |
---|
2778 | Â Â #Â Â Â Â elevations = file_e.variables['ELEVATION'][kmin:kmax, lmin:lmax] |
---|
2779 | Â Â #Â Â elif latitudes2[0]==latitudes[-1] and latitudes2[-1]==latitudes[0]: |
---|
2780 | Â Â #Â Â Â Â from Numeric import asarray |
---|
2781 | Â Â #Â Â Â Â elevations=elevations.tolist() |
---|
2782 | Â Â #Â Â Â Â elevations.reverse() |
---|
2783 | Â Â #Â Â Â Â elevations=asarray(elevations) |
---|
2784 | Â Â #Â Â else: |
---|
2785 | Â Â #Â Â Â Â from Numeric import asarray |
---|
2786 | Â Â #Â Â Â Â elevations=elevations.tolist() |
---|
2787 | Â Â #Â Â Â Â elevations.reverse() |
---|
2788 | Â Â #Â Â Â Â elevations=asarray(elevations) |
---|
2789 | Â Â #Â Â Â Â 'print hmmm' |
---|
2790 | |
---|
2791 | |
---|
2792 | |
---|
2793 | Â Â #Get missing values |
---|
2794 | Â Â nan_ha =Â file_h.variables['HA'].missing_value[0] |
---|
2795 | Â Â nan_ua =Â file_u.variables['UA'].missing_value[0] |
---|
2796 | Â Â nan_va =Â file_v.variables['VA'].missing_value[0] |
---|
2797 |   if hasattr(file_e.variables[zname],'missing_value'): |
---|
2798 |     nan_e = file_e.variables[zname].missing_value[0] |
---|
2799 | Â Â else: |
---|
2800 | Â Â Â Â nan_e =Â None |
---|
2801 | |
---|
2802 | Â Â #Cleanup |
---|
2803 |   from Numeric import sometrue |
---|
2804 | |
---|
2805 | Â Â missing =Â (amplitudes ==Â nan_ha) |
---|
2806 |   if sometrue (missing): |
---|
2807 |     if fail_on_NaN: |
---|
2808 |       msg = 'NetCDFFile %s contains missing values'\ |
---|
2809 | Â Â Â Â Â Â Â Â Â %(basename_in+'_ha.nc') |
---|
2810 |       raise DataMissingValuesError, msg |
---|
2811 | Â Â Â Â else: |
---|
2812 | Â Â Â Â Â Â amplitudes =Â amplitudes*(missing==0)Â +Â missing*NaN_filler |
---|
2813 | |
---|
2814 | Â Â missing =Â (uspeed ==Â nan_ua) |
---|
2815 |   if sometrue (missing): |
---|
2816 |     if fail_on_NaN: |
---|
2817 |       msg = 'NetCDFFile %s contains missing values'\ |
---|
2818 | Â Â Â Â Â Â Â Â Â %(basename_in+'_ua.nc') |
---|
2819 |       raise DataMissingValuesError, msg |
---|
2820 | Â Â Â Â else: |
---|
2821 | Â Â Â Â Â Â uspeed =Â uspeed*(missing==0)Â +Â missing*NaN_filler |
---|
2822 | |
---|
2823 | Â Â missing =Â (vspeed ==Â nan_va) |
---|
2824 |   if sometrue (missing): |
---|
2825 |     if fail_on_NaN: |
---|
2826 |       msg = 'NetCDFFile %s contains missing values'\ |
---|
2827 | Â Â Â Â Â Â Â Â Â %(basename_in+'_va.nc') |
---|
2828 |       raise DataMissingValuesError, msg |
---|
2829 | Â Â Â Â else: |
---|
2830 | Â Â Â Â Â Â vspeed =Â vspeed*(missing==0)Â +Â missing*NaN_filler |
---|
2831 | |
---|
2832 | |
---|
2833 | Â Â missing =Â (elevations ==Â nan_e) |
---|
2834 |   if sometrue (missing): |
---|
2835 |     if fail_on_NaN: |
---|
2836 |       msg = 'NetCDFFile %s contains missing values'\ |
---|
2837 | Â Â Â Â Â Â Â Â Â %(basename_in+'_e.nc') |
---|
2838 |       raise DataMissingValuesError, msg |
---|
2839 | Â Â Â Â else: |
---|
2840 | Â Â Â Â Â Â elevations =Â elevations*(missing==0)Â +Â missing*NaN_filler |
---|
2841 | |
---|
2842 | Â Â ####### |
---|
2843 | |
---|
2844 | |
---|
2845 | |
---|
2846 | Â Â number_of_times =Â times.shape[0] |
---|
2847 | Â Â number_of_latitudes =Â latitudes.shape[0] |
---|
2848 | Â Â number_of_longitudes =Â longitudes.shape[0] |
---|
2849 | |
---|
2850 |   assert amplitudes.shape[0] == number_of_times |
---|
2851 |   assert amplitudes.shape[1] == number_of_latitudes |
---|
2852 |   assert amplitudes.shape[2] == number_of_longitudes |
---|
2853 | |
---|
2854 |   if verbose: |
---|
2855 |     print '------------------------------------------------' |
---|
2856 |     print 'Statistics:' |
---|
2857 |     print ' Extent (lat/lon):' |
---|
2858 |     print '  lat in [%f, %f], len(lat) == %d'\ |
---|
2859 |        %(min(latitudes.flat), max(latitudes.flat), |
---|
2860 | Â Â Â Â Â Â Â Â len(latitudes.flat)) |
---|
2861 |     print '  lon in [%f, %f], len(lon) == %d'\ |
---|
2862 |        %(min(longitudes.flat), max(longitudes.flat), |
---|
2863 | Â Â Â Â Â Â Â Â len(longitudes.flat)) |
---|
2864 |     print '  t in [%f, %f], len(t) == %d'\ |
---|
2865 |        %(min(times.flat), max(times.flat), len(times.flat)) |
---|
2866 | |
---|
2867 | Â Â Â Â q =Â amplitudes.flat |
---|
2868 | Â Â Â Â name =Â 'Amplitudes (ha) [cm]' |
---|
2869 |     print ' %s in [%f, %f]' %(name, min(q), max(q)) |
---|
2870 | |
---|
2871 | Â Â Â Â q =Â uspeed.flat |
---|
2872 | Â Â Â Â name =Â 'Speeds (ua) [cm/s]' |
---|
2873 |     print ' %s in [%f, %f]' %(name, min(q), max(q)) |
---|
2874 | |
---|
2875 | Â Â Â Â q =Â vspeed.flat |
---|
2876 | Â Â Â Â name =Â 'Speeds (va) [cm/s]' |
---|
2877 |     print ' %s in [%f, %f]' %(name, min(q), max(q)) |
---|
2878 | |
---|
2879 | Â Â Â Â q =Â elevations.flat |
---|
2880 | Â Â Â Â name =Â 'Elevations (e) [m]' |
---|
2881 |     print ' %s in [%f, %f]' %(name, min(q), max(q)) |
---|
2882 | |
---|
2883 | |
---|
2884 | Â Â # print number_of_latitudes, number_of_longitudes |
---|
2885 | Â Â number_of_points =Â number_of_latitudes*number_of_longitudes |
---|
2886 | Â Â number_of_volumes =Â (number_of_latitudes-1)*(number_of_longitudes-1)*2 |
---|
2887 | |
---|
2888 | |
---|
2889 | Â Â file_h.close() |
---|
2890 | Â Â file_u.close() |
---|
2891 | Â Â file_v.close() |
---|
2892 | Â Â file_e.close() |
---|
2893 | |
---|
2894 | |
---|
2895 | Â Â # NetCDF file definition |
---|
2896 |   outfile = NetCDFFile(swwname, 'w') |
---|
2897 | |
---|
2898 | Â Â description =Â 'Converted from Ferret files: %s, %s, %s, %s'\ |
---|
2899 | Â Â Â Â Â Â Â Â Â %(basename_in +Â '_ha.nc', |
---|
2900 | Â Â Â Â Â Â Â Â Â Â basename_in +Â '_ua.nc', |
---|
2901 | Â Â Â Â Â Â Â Â Â Â basename_in +Â '_va.nc', |
---|
2902 | Â Â Â Â Â Â Â Â Â Â basename_in +Â '_e.nc') |
---|
2903 | Â Â |
---|
2904 | Â Â # Create new file |
---|
2905 | Â Â starttime =Â times[0] |
---|
2906 | Â Â |
---|
2907 | Â Â sww =Â Write_sww() |
---|
2908 |   sww.store_header(outfile, times, number_of_volumes, |
---|
2909 |            number_of_points, description=description, |
---|
2910 | Â Â Â Â Â Â Â Â Â Â Â verbose=verbose,sww_precision=Float) |
---|
2911 | |
---|
2912 | Â Â # Store |
---|
2913 |   from anuga.coordinate_transforms.redfearn import redfearn |
---|
2914 |   x = zeros(number_of_points, Float) #Easting |
---|
2915 |   y = zeros(number_of_points, Float) #Northing |
---|
2916 | |
---|
2917 | |
---|
2918 |   if verbose: print 'Making triangular grid' |
---|
2919 | |
---|
2920 | Â Â # Check zone boundaries |
---|
2921 |   refzone, _, _ = redfearn(latitudes[0],longitudes[0]) |
---|
2922 | |
---|
2923 | Â Â vertices =Â {} |
---|
2924 | Â Â i =Â 0 |
---|
2925 |   for k, lat in enumerate(latitudes):    #Y direction |
---|
2926 |     for l, lon in enumerate(longitudes): #X direction |
---|
2927 | |
---|
2928 | Â Â Â Â Â Â vertices[l,k]Â =Â i |
---|
2929 | |
---|
2930 |       zone, easting, northing = redfearn(lat,lon) |
---|
2931 | |
---|
2932 |       msg = 'Zone boundary crossed at longitude =', lon |
---|
2933 | Â Â Â Â Â Â #assert zone == refzone, msg |
---|
2934 | Â Â Â Â Â Â #print '%7.2f %7.2f %8.2f %8.2f' %(lon, lat, easting, northing) |
---|
2935 | Â Â Â Â Â Â x[i]Â =Â easting |
---|
2936 | Â Â Â Â Â Â y[i]Â =Â northing |
---|
2937 | Â Â Â Â Â Â i +=Â 1 |
---|
2938 | |
---|
2939 | Â Â #Construct 2 triangles per 'rectangular' element |
---|
2940 | Â Â volumes =Â [] |
---|
2941 |   for l in range(number_of_longitudes-1):  #X direction |
---|
2942 |     for k in range(number_of_latitudes-1): #Y direction |
---|
2943 | Â Â Â Â Â Â v1 =Â vertices[l,k+1] |
---|
2944 | Â Â Â Â Â Â v2 =Â vertices[l,k] |
---|
2945 | Â Â Â Â Â Â v3 =Â vertices[l+1,k+1] |
---|
2946 | Â Â Â Â Â Â v4 =Â vertices[l+1,k] |
---|
2947 | |
---|
2948 | Â Â Â Â Â Â volumes.append([v1,v2,v3])Â #Upper element |
---|
2949 | Â Â Â Â Â Â volumes.append([v4,v3,v2])Â #Lower element |
---|
2950 | |
---|
2951 | Â Â volumes =Â array(volumes) |
---|
2952 | |
---|
2953 |   if origin is None: |
---|
2954 | Â Â Â Â origin =Â Geo_reference(refzone,min(x),min(y)) |
---|
2955 |   geo_ref = write_NetCDF_georeference(origin, outfile) |
---|
2956 | Â Â |
---|
2957 |   if elevation is not None: |
---|
2958 | Â Â Â Â z =Â elevation |
---|
2959 | Â Â else: |
---|
2960 |     if inverted_bathymetry: |
---|
2961 | Â Â Â Â Â Â z =Â -1*elevations |
---|
2962 | Â Â Â Â else: |
---|
2963 | Â Â Â Â Â Â z =Â elevations |
---|
2964 | Â Â #FIXME: z should be obtained from MOST and passed in here |
---|
2965 | |
---|
2966 | Â Â #FIXME use the Write_sww instance(sww) to write this info |
---|
2967 |   from Numeric import resize |
---|
2968 | Â Â z =Â resize(z,outfile.variables['z'][:].shape) |
---|
2969 | Â Â outfile.variables['x'][:]Â =Â x -Â geo_ref.get_xllcorner() |
---|
2970 | Â Â outfile.variables['y'][:]Â =Â y -Â geo_ref.get_yllcorner() |
---|
2971 |   outfile.variables['z'][:] = z       #FIXME HACK for bacwards compat. |
---|
2972 | Â Â outfile.variables['elevation'][:]Â =Â z |
---|
2973 | Â Â outfile.variables['volumes'][:]Â =Â volumes.astype(Int32)Â #For Opteron 64 |
---|
2974 | |
---|
2975 | |
---|
2976 | |
---|
2977 | Â Â #Time stepping |
---|
2978 | Â Â stage =Â outfile.variables['stage'] |
---|
2979 | Â Â xmomentum =Â outfile.variables['xmomentum'] |
---|
2980 | Â Â ymomentum =Â outfile.variables['ymomentum'] |
---|
2981 | |
---|
2982 |   if verbose: print 'Converting quantities' |
---|
2983 | Â Â n =Â len(times) |
---|
2984 |   for j in range(n): |
---|
2985 |     if verbose and j%((n+10)/10)==0: print ' Doing %d of %d' %(j, n) |
---|
2986 | Â Â Â Â i =Â 0 |
---|
2987 |     for k in range(number_of_latitudes):   #Y direction |
---|
2988 |       for l in range(number_of_longitudes): #X direction |
---|
2989 | Â Â Â Â Â Â Â Â w =Â zscale*amplitudes[j,k,l]/100Â +Â mean_stage |
---|
2990 | Â Â Â Â Â Â Â Â stage[j,i]Â =Â w |
---|
2991 | Â Â Â Â Â Â Â Â h =Â w -Â z[i] |
---|
2992 | Â Â Â Â Â Â Â Â xmomentum[j,i]Â =Â uspeed[j,k,l]/100*h |
---|
2993 | Â Â Â Â Â Â Â Â ymomentum[j,i]Â =Â vspeed[j,k,l]/100*h |
---|
2994 | Â Â Â Â Â Â Â Â i +=Â 1 |
---|
2995 | |
---|
2996 | Â Â #outfile.close() |
---|
2997 | |
---|
2998 | Â Â #FIXME: Refactor using code from file_function.statistics |
---|
2999 | Â Â #Something like print swwstats(swwname) |
---|
3000 |   if verbose: |
---|
3001 | Â Â Â Â x =Â outfile.variables['x'][:] |
---|
3002 | Â Â Â Â y =Â outfile.variables['y'][:] |
---|
3003 |     print '------------------------------------------------' |
---|
3004 |     print 'Statistics of output file:' |
---|
3005 |     print ' Name: %s' %swwname |
---|
3006 |     print ' Reference:' |
---|
3007 |     print '  Lower left corner: [%f, %f]'\ |
---|
3008 |        %(geo_ref.get_xllcorner(), geo_ref.get_yllcorner()) |
---|
3009 |     print ' Start time: %f' %starttime |
---|
3010 |     print '  Min time: %f' %mint |
---|
3011 |     print '  Max time: %f' %maxt |
---|
3012 |     print ' Extent:' |
---|
3013 |     print '  x [m] in [%f, %f], len(x) == %d'\ |
---|
3014 |        %(min(x.flat), max(x.flat), len(x.flat)) |
---|
3015 |     print '  y [m] in [%f, %f], len(y) == %d'\ |
---|
3016 |        %(min(y.flat), max(y.flat), len(y.flat)) |
---|
3017 |     print '  t [s] in [%f, %f], len(t) == %d'\ |
---|
3018 |        %(min(times), max(times), len(times)) |
---|
3019 |     print ' Quantities [SI units]:' |
---|
3020 |     for name in ['stage', 'xmomentum', 'ymomentum', 'elevation']: |
---|
3021 | Â Â Â Â Â Â q =Â outfile.variables[name][:].flat |
---|
3022 |       print '  %s in [%f, %f]' %(name, min(q), max(q)) |
---|
3023 | |
---|
3024 | |
---|
3025 | |
---|
3026 | Â Â outfile.close() |
---|
3027 | |
---|
3028 | |
---|
3029 | |
---|
3030 | |
---|
3031 | |
---|
3032 | def timefile2netcdf(filename, quantity_names=None, time_as_seconds=False): |
---|
3033 | Â Â """Template for converting typical text files with time series to |
---|
3034 | Â Â NetCDF tms file. |
---|
3035 | |
---|
3036 | |
---|
3037 | Â Â The file format is assumed to be either two fields separated by a comma: |
---|
3038 | |
---|
3039 | Â Â Â Â time [DD/MM/YY hh:mm:ss], value0 value1 value2 ... |
---|
3040 | |
---|
3041 | Â Â E.g |
---|
3042 | |
---|
3043 | Â Â Â 31/08/04 00:00:00, 1.328223 0 0 |
---|
3044 | Â Â Â 31/08/04 00:15:00, 1.292912 0 0 |
---|
3045 | |
---|
3046 | Â Â or time (seconds), value0 value1 value2 ... |
---|
3047 | Â Â |
---|
3048 | Â Â Â 0.0, 1.328223 0 0 |
---|
3049 | Â Â Â 0.1, 1.292912 0 0 |
---|
3050 | |
---|
3051 | Â Â will provide a time dependent function f(t) with three attributes |
---|
3052 | |
---|
3053 | Â Â filename is assumed to be the rootname with extenisons .txt and .sww |
---|
3054 | Â Â """ |
---|
3055 | |
---|
3056 |   import time, calendar |
---|
3057 |   from Numeric import array |
---|
3058 |   from anuga.config import time_format |
---|
3059 |   from anuga.utilities.numerical_tools import ensure_numeric |
---|
3060 | |
---|
3061 | |
---|
3062 | |
---|
3063 | Â Â fid =Â open(filename +Â '.txt') |
---|
3064 | Â Â line =Â fid.readline() |
---|
3065 | Â Â fid.close() |
---|
3066 | |
---|
3067 | Â Â fields =Â line.split(',') |
---|
3068 |   msg = 'File %s must have the format date, value0 value1 value2 ...' |
---|
3069 |   assert len(fields) == 2, msg |
---|
3070 | |
---|
3071 |   if not time_as_seconds: |
---|
3072 | Â Â Â Â try: |
---|
3073 |       starttime = calendar.timegm(time.strptime(fields[0], time_format)) |
---|
3074 |     except ValueError: |
---|
3075 |       msg = 'First field in file %s must be' %filename |
---|
3076 | Â Â Â Â Â Â msg +=Â ' date-time with format %s.\n'Â %time_format |
---|
3077 |       msg += 'I got %s instead.' %fields[0] |
---|
3078 |       raise DataTimeError, msg |
---|
3079 | Â Â else: |
---|
3080 | Â Â Â Â try: |
---|
3081 | Â Â Â Â Â Â starttime =Â float(fields[0]) |
---|
3082 |     except Error: |
---|
3083 | Â Â Â Â Â Â msg =Â "Bad time format" |
---|
3084 |       raise DataTimeError, msg |
---|
3085 | |
---|
3086 | |
---|
3087 | Â Â #Split values |
---|
3088 | Â Â values =Â [] |
---|
3089 |   for value in fields[1].split(): |
---|
3090 | Â Â Â Â values.append(float(value)) |
---|
3091 | |
---|
3092 | Â Â q =Â ensure_numeric(values) |
---|
3093 | |
---|
3094 | Â Â msg =Â 'ERROR: File must contain at least one independent value' |
---|
3095 |   assert len(q.shape) == 1, msg |
---|
3096 | |
---|
3097 | |
---|
3098 | |
---|
3099 | Â Â #Read times proper |
---|
3100 |   from Numeric import zeros, Float, alltrue |
---|
3101 |   from anuga.config import time_format |
---|
3102 |   import time, calendar |
---|
3103 | |
---|
3104 | Â Â fid =Â open(filename +Â '.txt') |
---|
3105 | Â Â lines =Â fid.readlines() |
---|
3106 | Â Â fid.close() |
---|
3107 | |
---|
3108 | Â Â N =Â len(lines) |
---|
3109 | Â Â d =Â len(q) |
---|
3110 | |
---|
3111 |   T = zeros(N, Float)    #Time |
---|
3112 |   Q = zeros((N, d), Float) #Values |
---|
3113 | |
---|
3114 |   for i, line in enumerate(lines): |
---|
3115 | Â Â Â Â fields =Â line.split(',') |
---|
3116 |     if not time_as_seconds: |
---|
3117 |       realtime = calendar.timegm(time.strptime(fields[0], time_format)) |
---|
3118 | Â Â Â Â else: |
---|
3119 | Â Â Â Â Â Â Â realtime =Â float(fields[0]) |
---|
3120 | Â Â Â Â T[i]Â =Â realtime -Â starttime |
---|
3121 | |
---|
3122 |     for j, value in enumerate(fields[1].split()): |
---|
3123 |       Q[i, j] = float(value) |
---|
3124 | |
---|
3125 |   msg = 'File %s must list time as a monotonuosly ' %filename |
---|
3126 | Â Â msg +=Â 'increasing sequence' |
---|
3127 |   assert alltrue( T[1:] - T[:-1] > 0 ), msg |
---|
3128 | |
---|
3129 | Â Â #Create NetCDF file |
---|
3130 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
3131 | |
---|
3132 |   fid = NetCDFFile(filename + '.tms', 'w') |
---|
3133 | |
---|
3134 | |
---|
3135 | Â Â fid.institution =Â 'Geoscience Australia' |
---|
3136 | Â Â fid.description =Â 'Time series' |
---|
3137 | |
---|
3138 | |
---|
3139 | Â Â #Reference point |
---|
3140 | Â Â #Start time in seconds since the epoch (midnight 1/1/1970) |
---|
3141 | Â Â #FIXME: Use Georef |
---|
3142 | Â Â fid.starttime =Â starttime |
---|
3143 | |
---|
3144 | Â Â # dimension definitions |
---|
3145 | Â Â #fid.createDimension('number_of_volumes', self.number_of_volumes) |
---|
3146 | Â Â #fid.createDimension('number_of_vertices', 3) |
---|
3147 | |
---|
3148 | |
---|
3149 |   fid.createDimension('number_of_timesteps', len(T)) |
---|
3150 | |
---|
3151 |   fid.createVariable('time', Float, ('number_of_timesteps',)) |
---|
3152 | |
---|
3153 | Â Â fid.variables['time'][:]Â =Â T |
---|
3154 | |
---|
3155 |   for i in range(Q.shape[1]): |
---|
3156 | Â Â Â Â try: |
---|
3157 | Â Â Â Â Â Â name =Â quantity_names[i] |
---|
3158 | Â Â Â Â except: |
---|
3159 | Â Â Â Â Â Â name =Â 'Attribute%d'%i |
---|
3160 | |
---|
3161 |     fid.createVariable(name, Float, ('number_of_timesteps',)) |
---|
3162 | Â Â Â Â fid.variables[name][:]Â =Â Q[:,i] |
---|
3163 | |
---|
3164 | Â Â fid.close() |
---|
3165 | |
---|
3166 | |
---|
3167 | def extent_sww(file_name): |
---|
3168 | Â Â """ |
---|
3169 | Â Â Read in an sww file. |
---|
3170 | |
---|
3171 | Â Â Input; |
---|
3172 | Â Â file_name - the sww file |
---|
3173 | |
---|
3174 | Â Â Output; |
---|
3175 | Â Â z - Vector of bed elevation |
---|
3176 |   volumes - Array. Each row has 3 values, representing |
---|
3177 | Â Â the vertices that define the volume |
---|
3178 | Â Â time - Vector of the times where there is stage information |
---|
3179 | Â Â stage - array with respect to time and vertices (x,y) |
---|
3180 | Â Â """ |
---|
3181 | |
---|
3182 | |
---|
3183 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
3184 | |
---|
3185 | Â Â #Check contents |
---|
3186 | Â Â #Get NetCDF |
---|
3187 |   fid = NetCDFFile(file_name, 'r') |
---|
3188 | |
---|
3189 | Â Â # Get the variables |
---|
3190 | Â Â x =Â fid.variables['x'][:] |
---|
3191 | Â Â y =Â fid.variables['y'][:] |
---|
3192 | Â Â stage =Â fid.variables['stage'][:] |
---|
3193 | Â Â #print "stage",stage |
---|
3194 | Â Â #print "stage.shap",stage.shape |
---|
3195 | Â Â #print "min(stage.flat), mpythonax(stage.flat)",min(stage.flat), max(stage.flat) |
---|
3196 | Â Â #print "min(stage)",min(stage) |
---|
3197 | |
---|
3198 | Â Â fid.close() |
---|
3199 | |
---|
3200 |   return [min(x),max(x),min(y),max(y),min(stage.flat),max(stage.flat)] |
---|
3201 | |
---|
3202 | |
---|
3203 | def sww2domain(filename, boundary=None, t=None, |
---|
3204 |         fail_if_NaN=True ,NaN_filler=0, |
---|
3205 |         verbose = False, very_verbose = False): |
---|
3206 | Â Â """ |
---|
3207 | Â Â Usage: domain = sww2domain('file.sww',t=time (default = last time in file)) |
---|
3208 | |
---|
3209 | Â Â Boundary is not recommended if domain.smooth is not selected, as it |
---|
3210 | Â Â uses unique coordinates, but not unique boundaries. This means that |
---|
3211 | Â Â the boundary file will not be compatable with the coordinates, and will |
---|
3212 | Â Â give a different final boundary, or crash. |
---|
3213 | Â Â """ |
---|
3214 | Â Â NaN=9.969209968386869e+036 |
---|
3215 | Â Â #initialise NaN. |
---|
3216 | |
---|
3217 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
3218 |   from shallow_water import Domain |
---|
3219 |   from Numeric import asarray, transpose, resize |
---|
3220 | |
---|
3221 |   if verbose: print 'Reading from ', filename |
---|
3222 |   fid = NetCDFFile(filename, 'r')  #Open existing file for read |
---|
3223 | Â Â time =Â fid.variables['time']Â Â Â Â #Timesteps |
---|
3224 |   if t is None: |
---|
3225 | Â Â Â Â t =Â time[-1] |
---|
3226 | Â Â time_interp =Â get_time_interp(time,t) |
---|
3227 | |
---|
3228 | Â Â # Get the variables as Numeric arrays |
---|
3229 | Â Â x =Â fid.variables['x'][:]Â Â Â Â Â Â Â #x-coordinates of vertices |
---|
3230 | Â Â y =Â fid.variables['y'][:]Â Â Â Â Â Â Â #y-coordinates of vertices |
---|
3231 | Â Â elevation =Â fid.variables['elevation']Â Â Â #Elevation |
---|
3232 | Â Â stage =Â fid.variables['stage']Â Â Â #Water level |
---|
3233 | Â Â xmomentum =Â fid.variables['xmomentum']Â Â #Momentum in the x-direction |
---|
3234 | Â Â ymomentum =Â fid.variables['ymomentum']Â Â #Momentum in the y-direction |
---|
3235 | |
---|
3236 | Â Â starttime =Â fid.starttime[0] |
---|
3237 | Â Â volumes =Â fid.variables['volumes'][:]Â #Connectivity |
---|
3238 | Â Â coordinates =Â transpose(asarray([x.tolist(),y.tolist()])) |
---|
3239 | Â Â #FIXME (Ole): Something like this might be better: concatenate( (x, y), axis=1 ) |
---|
3240 | Â Â # or concatenate( (x[:,NewAxis],x[:,NewAxis]), axis=1 ) |
---|
3241 | |
---|
3242 | Â Â conserved_quantities =Â [] |
---|
3243 | Â Â interpolated_quantities =Â {} |
---|
3244 | Â Â other_quantities =Â [] |
---|
3245 | |
---|
3246 | Â Â # get geo_reference |
---|
3247 | Â Â #sww files don't have to have a geo_ref |
---|
3248 | Â Â try: |
---|
3249 | Â Â Â Â geo_reference =Â Geo_reference(NetCDFObject=fid) |
---|
3250 | Â Â except:Â #AttributeError, e: |
---|
3251 | Â Â Â Â geo_reference =Â None |
---|
3252 | |
---|
3253 |   if verbose: print '  getting quantities' |
---|
3254 |   for quantity in fid.variables.keys(): |
---|
3255 | Â Â Â Â dimensions =Â fid.variables[quantity].dimensions |
---|
3256 |     if 'number_of_timesteps' in dimensions: |
---|
3257 | Â Â Â Â Â Â conserved_quantities.append(quantity) |
---|
3258 | Â Â Â Â Â Â interpolated_quantities[quantity]=\ |
---|
3259 | Â Â Â Â Â Â Â Â Â interpolated_quantity(fid.variables[quantity][:],time_interp) |
---|
3260 | Â Â Â Â else:Â other_quantities.append(quantity) |
---|
3261 | |
---|
3262 | Â Â other_quantities.remove('x') |
---|
3263 | Â Â other_quantities.remove('y') |
---|
3264 | Â Â other_quantities.remove('z') |
---|
3265 | Â Â other_quantities.remove('volumes') |
---|
3266 | Â Â try: |
---|
3267 | Â Â Â Â other_quantities.remove('stage_range') |
---|
3268 | Â Â Â Â other_quantities.remove('xmomentum_range') |
---|
3269 | Â Â Â Â other_quantities.remove('ymomentum_range') |
---|
3270 | Â Â Â Â other_quantities.remove('elevation_range') |
---|
3271 | Â Â except: |
---|
3272 | Â Â Â Â pass |
---|
3273 | Â Â Â Â |
---|
3274 | |
---|
3275 | Â Â conserved_quantities.remove('time') |
---|
3276 | |
---|
3277 |   if verbose: print '  building domain' |
---|
3278 | Â Â #Â Â From domain.Domain: |
---|
3279 | Â Â #Â Â domain = Domain(coordinates, volumes,\ |
---|
3280 | Â Â #Â Â Â Â Â Â Â Â Â Â conserved_quantities = conserved_quantities,\ |
---|
3281 | Â Â #Â Â Â Â Â Â Â Â Â Â other_quantities = other_quantities,zone=zone,\ |
---|
3282 | Â Â #Â Â Â Â Â Â Â Â Â Â xllcorner=xllcorner, yllcorner=yllcorner) |
---|
3283 | |
---|
3284 | Â Â #Â Â From shallow_water.Domain: |
---|
3285 | Â Â coordinates=coordinates.tolist() |
---|
3286 | Â Â volumes=volumes.tolist() |
---|
3287 | Â Â #FIXME:should this be in mesh?(peter row) |
---|
3288 |   if fid.smoothing == 'Yes': unique = False |
---|
3289 | Â Â else:Â unique =Â True |
---|
3290 |   if unique: |
---|
3291 | Â Â Â Â coordinates,volumes,boundary=weed(coordinates,volumes,boundary) |
---|
3292 | |
---|
3293 | |
---|
3294 | Â Â try: |
---|
3295 |     domain = Domain(coordinates, volumes, boundary) |
---|
3296 |   except AssertionError, e: |
---|
3297 | Â Â Â Â fid.close() |
---|
3298 | Â Â Â Â msg =Â 'Domain could not be created: %s. Perhaps use "fail_if_NaN=False and NaN_filler = ..."'Â %e |
---|
3299 |     raise DataDomainError, msg |
---|
3300 | |
---|
3301 |   if not boundary is None: |
---|
3302 | Â Â Â Â domain.boundary =Â boundary |
---|
3303 | |
---|
3304 | Â Â domain.geo_reference =Â geo_reference |
---|
3305 | |
---|
3306 | Â Â domain.starttime=float(starttime)+float(t) |
---|
3307 | Â Â domain.time=0.0 |
---|
3308 | |
---|
3309 |   for quantity in other_quantities: |
---|
3310 | Â Â Â Â try: |
---|
3311 | Â Â Â Â Â Â NaN =Â fid.variables[quantity].missing_value |
---|
3312 | Â Â Â Â except: |
---|
3313 |       pass #quantity has no missing_value number |
---|
3314 | Â Â Â Â X =Â fid.variables[quantity][:] |
---|
3315 |     if very_verbose: |
---|
3316 |       print '    ',quantity |
---|
3317 |       print '    NaN =',NaN |
---|
3318 |       print '    max(X)' |
---|
3319 |       print '    ',max(X) |
---|
3320 |       print '    max(X)==NaN' |
---|
3321 |       print '    ',max(X)==NaN |
---|
3322 |       print '' |
---|
3323 |     if (max(X)==NaN) or (min(X)==NaN): |
---|
3324 |       if fail_if_NaN: |
---|
3325 | Â Â Â Â Â Â Â Â msg =Â 'quantity "%s" contains no_data entry'%quantity |
---|
3326 |         raise DataMissingValuesError, msg |
---|
3327 | Â Â Â Â Â Â else: |
---|
3328 | Â Â Â Â Â Â Â Â data =Â (X<>NaN) |
---|
3329 | Â Â Â Â Â Â Â Â X =Â (X*data)+(data==0)*NaN_filler |
---|
3330 |     if unique: |
---|
3331 | Â Â Â Â Â Â X =Â resize(X,(len(X)/3,3)) |
---|
3332 | Â Â Â Â domain.set_quantity(quantity,X) |
---|
3333 | Â Â # |
---|
3334 |   for quantity in conserved_quantities: |
---|
3335 | Â Â Â Â try: |
---|
3336 | Â Â Â Â Â Â NaN =Â fid.variables[quantity].missing_value |
---|
3337 | Â Â Â Â except: |
---|
3338 |       pass #quantity has no missing_value number |
---|
3339 | Â Â Â Â X =Â interpolated_quantities[quantity] |
---|
3340 |     if very_verbose: |
---|
3341 |       print '    ',quantity |
---|
3342 |       print '    NaN =',NaN |
---|
3343 |       print '    max(X)' |
---|
3344 |       print '    ',max(X) |
---|
3345 |       print '    max(X)==NaN' |
---|
3346 |       print '    ',max(X)==NaN |
---|
3347 |       print '' |
---|
3348 |     if (max(X)==NaN) or (min(X)==NaN): |
---|
3349 |       if fail_if_NaN: |
---|
3350 | Â Â Â Â Â Â Â Â msg =Â 'quantity "%s" contains no_data entry'%quantity |
---|
3351 |         raise DataMissingValuesError, msg |
---|
3352 | Â Â Â Â Â Â else: |
---|
3353 | Â Â Â Â Â Â Â Â data =Â (X<>NaN) |
---|
3354 | Â Â Â Â Â Â Â Â X =Â (X*data)+(data==0)*NaN_filler |
---|
3355 |     if unique: |
---|
3356 | Â Â Â Â Â Â X =Â resize(X,(X.shape[0]/3,3)) |
---|
3357 | Â Â Â Â domain.set_quantity(quantity,X) |
---|
3358 | |
---|
3359 | Â Â fid.close() |
---|
3360 |   return domain |
---|
3361 | |
---|
3362 | |
---|
3363 | def interpolated_quantity(saved_quantity,time_interp): |
---|
3364 | |
---|
3365 | Â Â #given an index and ratio, interpolate quantity with respect to time. |
---|
3366 | Â Â index,ratio =Â time_interp |
---|
3367 | Â Â Q =Â saved_quantity |
---|
3368 |   if ratio > 0: |
---|
3369 | Â Â Â Â q =Â (1-ratio)*Q[index]+Â ratio*Q[index+1] |
---|
3370 | Â Â else: |
---|
3371 | Â Â Â Â q =Â Q[index] |
---|
3372 | Â Â #Return vector of interpolated values |
---|
3373 |   return q |
---|
3374 | |
---|
3375 | |
---|
3376 | def get_time_interp(time,t=None): |
---|
3377 | Â Â #Finds the ratio and index for time interpolation. |
---|
3378 | Â Â #It is borrowed from previous abstract_2d_finite_volumes code. |
---|
3379 |   if t is None: |
---|
3380 | Â Â Â Â t=time[-1] |
---|
3381 | Â Â Â Â index =Â -1 |
---|
3382 | Â Â Â Â ratio =Â 0. |
---|
3383 | Â Â else: |
---|
3384 | Â Â Â Â T =Â time |
---|
3385 | Â Â Â Â tau =Â t |
---|
3386 | Â Â Â Â index=0 |
---|
3387 |     msg = 'Time interval derived from file %s [%s:%s]'\ |
---|
3388 |       %('FIXMEfilename', T[0], T[-1]) |
---|
3389 | Â Â Â Â msg +=Â ' does not match model time: %s'Â %tau |
---|
3390 |     if tau < time[0]: raise DataTimeError, msg |
---|
3391 |     if tau > time[-1]: raise DataTimeError, msg |
---|
3392 |     while tau > time[index]: index += 1 |
---|
3393 |     while tau < time[index]: index -= 1 |
---|
3394 |     if tau == time[index]: |
---|
3395 | Â Â Â Â Â Â #Protect against case where tau == time[-1] (last time) |
---|
3396 | Â Â Â Â Â Â # - also works in general when tau == time[i] |
---|
3397 | Â Â Â Â Â Â ratio =Â 0 |
---|
3398 | Â Â Â Â else: |
---|
3399 | Â Â Â Â Â Â #t is now between index and index+1 |
---|
3400 | Â Â Â Â Â Â ratio =Â (tau -Â time[index])/(time[index+1]Â -Â time[index]) |
---|
3401 |   return (index,ratio) |
---|
3402 | |
---|
3403 | |
---|
3404 | def weed(coordinates,volumes,boundary = None): |
---|
3405 |   if type(coordinates)==ArrayType: |
---|
3406 | Â Â Â Â coordinates =Â coordinates.tolist() |
---|
3407 |   if type(volumes)==ArrayType: |
---|
3408 | Â Â Â Â volumes =Â volumes.tolist() |
---|
3409 | |
---|
3410 | Â Â unique =Â False |
---|
3411 | Â Â point_dict =Â {} |
---|
3412 | Â Â same_point =Â {} |
---|
3413 |   for i in range(len(coordinates)): |
---|
3414 | Â Â Â Â point =Â tuple(coordinates[i]) |
---|
3415 |     if point_dict.has_key(point): |
---|
3416 | Â Â Â Â Â Â unique =Â True |
---|
3417 | Â Â Â Â Â Â same_point[i]=point |
---|
3418 | Â Â Â Â Â Â #to change all point i references to point j |
---|
3419 | Â Â Â Â else: |
---|
3420 | Â Â Â Â Â Â point_dict[point]=i |
---|
3421 | Â Â Â Â Â Â same_point[i]=point |
---|
3422 | |
---|
3423 | Â Â coordinates =Â [] |
---|
3424 | Â Â i =Â 0 |
---|
3425 |   for point in point_dict.keys(): |
---|
3426 | Â Â Â Â point =Â tuple(point) |
---|
3427 | Â Â Â Â coordinates.append(list(point)) |
---|
3428 | Â Â Â Â point_dict[point]=i |
---|
3429 | Â Â Â Â i+=1 |
---|
3430 | |
---|
3431 | |
---|
3432 |   for volume in volumes: |
---|
3433 |     for i in range(len(volume)): |
---|
3434 | Â Â Â Â Â Â index =Â volume[i] |
---|
3435 |       if index>-1: |
---|
3436 | Â Â Â Â Â Â Â Â volume[i]=point_dict[same_point[index]] |
---|
3437 | |
---|
3438 | Â Â new_boundary =Â {} |
---|
3439 |   if not boundary is None: |
---|
3440 |     for segment in boundary.keys(): |
---|
3441 | Â Â Â Â Â Â point0 =Â point_dict[same_point[segment[0]]] |
---|
3442 | Â Â Â Â Â Â point1 =Â point_dict[same_point[segment[1]]] |
---|
3443 | Â Â Â Â Â Â label =Â boundary[segment] |
---|
3444 | Â Â Â Â Â Â #FIXME should the bounday attributes be concaterated |
---|
3445 | Â Â Â Â Â Â #('exterior, pond') or replaced ('pond')(peter row) |
---|
3446 | |
---|
3447 |       if new_boundary.has_key((point0,point1)): |
---|
3448 | Â Â Â Â Â Â Â Â new_boundary[(point0,point1)]=new_boundary[(point0,point1)]#\ |
---|
3449 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #+','+label |
---|
3450 | |
---|
3451 |       elif new_boundary.has_key((point1,point0)): |
---|
3452 | Â Â Â Â Â Â Â Â new_boundary[(point1,point0)]=new_boundary[(point1,point0)]#\ |
---|
3453 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â #+','+label |
---|
3454 | Â Â Â Â Â Â else:Â new_boundary[(point0,point1)]=label |
---|
3455 | |
---|
3456 | Â Â Â Â boundary =Â new_boundary |
---|
3457 | |
---|
3458 |   return coordinates,volumes,boundary |
---|
3459 | |
---|
3460 | |
---|
3461 | def decimate_dem(basename_in, stencil, cellsize_new, basename_out=None, |
---|
3462 | Â Â Â Â Â Â Â Â Â verbose=False): |
---|
3463 | Â Â """Read Digitial Elevation model from the following NetCDF format (.dem) |
---|
3464 | |
---|
3465 | Â Â Example: |
---|
3466 | |
---|
3467 |   ncols     3121 |
---|
3468 |   nrows     1800 |
---|
3469 |   xllcorner   722000 |
---|
3470 |   yllcorner   5893000 |
---|
3471 |   cellsize   25 |
---|
3472 |   NODATA_value -9999 |
---|
3473 | Â Â 138.3698 137.4194 136.5062 135.5558 .......... |
---|
3474 | |
---|
3475 | Â Â Decimate data to cellsize_new using stencil and write to NetCDF dem format. |
---|
3476 | Â Â """ |
---|
3477 | |
---|
3478 |   import os |
---|
3479 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
3480 |   from Numeric import Float, zeros, sum, reshape, equal |
---|
3481 | |
---|
3482 | Â Â root =Â basename_in |
---|
3483 | Â Â inname =Â root +Â '.dem' |
---|
3484 | |
---|
3485 | Â Â #Open existing netcdf file to read |
---|
3486 |   infile = NetCDFFile(inname, 'r') |
---|
3487 |   if verbose: print 'Reading DEM from %s' %inname |
---|
3488 | |
---|
3489 | Â Â #Read metadata |
---|
3490 | Â Â ncols =Â infile.ncols[0] |
---|
3491 | Â Â nrows =Â infile.nrows[0] |
---|
3492 | Â Â xllcorner =Â infile.xllcorner[0] |
---|
3493 | Â Â yllcorner =Â infile.yllcorner[0] |
---|
3494 | Â Â cellsize =Â infile.cellsize[0] |
---|
3495 | Â Â NODATA_value =Â infile.NODATA_value[0] |
---|
3496 | Â Â zone =Â infile.zone[0] |
---|
3497 | Â Â false_easting =Â infile.false_easting[0] |
---|
3498 | Â Â false_northing =Â infile.false_northing[0] |
---|
3499 | Â Â projection =Â infile.projection |
---|
3500 | Â Â datum =Â infile.datum |
---|
3501 | Â Â units =Â infile.units |
---|
3502 | |
---|
3503 | Â Â dem_elevation =Â infile.variables['elevation'] |
---|
3504 | |
---|
3505 | Â Â #Get output file name |
---|
3506 |   if basename_out == None: |
---|
3507 | Â Â Â Â outname =Â root +Â '_'Â +Â repr(cellsize_new)Â +Â '.dem' |
---|
3508 | Â Â else: |
---|
3509 | Â Â Â Â outname =Â basename_out +Â '.dem' |
---|
3510 | |
---|
3511 |   if verbose: print 'Write decimated NetCDF file to %s' %outname |
---|
3512 | |
---|
3513 | Â Â #Determine some dimensions for decimated grid |
---|
3514 |   (nrows_stencil, ncols_stencil) = stencil.shape |
---|
3515 | Â Â x_offset =Â ncols_stencil /Â 2 |
---|
3516 | Â Â y_offset =Â nrows_stencil /Â 2 |
---|
3517 | Â Â cellsize_ratio =Â int(cellsize_new /Â cellsize) |
---|
3518 | Â Â ncols_new =Â 1Â +Â (ncols -Â ncols_stencil)Â /Â cellsize_ratio |
---|
3519 | Â Â nrows_new =Â 1Â +Â (nrows -Â nrows_stencil)Â /Â cellsize_ratio |
---|
3520 | |
---|
3521 | Â Â #Open netcdf file for output |
---|
3522 |   outfile = NetCDFFile(outname, 'w') |
---|
3523 | |
---|
3524 | Â Â #Create new file |
---|
3525 | Â Â outfile.institution =Â 'Geoscience Australia' |
---|
3526 | Â Â outfile.description =Â 'NetCDF DEM format for compact and portable storage 'Â +\ |
---|
3527 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'of spatial point data' |
---|
3528 | Â Â #Georeferencing |
---|
3529 | Â Â outfile.zone =Â zone |
---|
3530 | Â Â outfile.projection =Â projection |
---|
3531 | Â Â outfile.datum =Â datum |
---|
3532 | Â Â outfile.units =Â units |
---|
3533 | |
---|
3534 | Â Â outfile.cellsize =Â cellsize_new |
---|
3535 | Â Â outfile.NODATA_value =Â NODATA_value |
---|
3536 | Â Â outfile.false_easting =Â false_easting |
---|
3537 | Â Â outfile.false_northing =Â false_northing |
---|
3538 | |
---|
3539 | Â Â outfile.xllcorner =Â xllcorner +Â (x_offset *Â cellsize) |
---|
3540 | Â Â outfile.yllcorner =Â yllcorner +Â (y_offset *Â cellsize) |
---|
3541 | Â Â outfile.ncols =Â ncols_new |
---|
3542 | Â Â outfile.nrows =Â nrows_new |
---|
3543 | |
---|
3544 | Â Â # dimension definition |
---|
3545 |   outfile.createDimension('number_of_points', nrows_new*ncols_new) |
---|
3546 | |
---|
3547 | Â Â # variable definition |
---|
3548 |   outfile.createVariable('elevation', Float, ('number_of_points',)) |
---|
3549 | |
---|
3550 | Â Â # Get handle to the variable |
---|
3551 | Â Â elevation =Â outfile.variables['elevation'] |
---|
3552 | |
---|
3553 |   dem_elevation_r = reshape(dem_elevation, (nrows, ncols)) |
---|
3554 | |
---|
3555 | Â Â #Store data |
---|
3556 | Â Â global_index =Â 0 |
---|
3557 |   for i in range(nrows_new): |
---|
3558 |     if verbose: print 'Processing row %d of %d' %(i, nrows_new) |
---|
3559 | Â Â Â Â lower_index =Â global_index |
---|
3560 |     telev = zeros(ncols_new, Float) |
---|
3561 | Â Â Â Â local_index =Â 0 |
---|
3562 | Â Â Â Â trow =Â i *Â cellsize_ratio |
---|
3563 | |
---|
3564 |     for j in range(ncols_new): |
---|
3565 | Â Â Â Â Â Â tcol =Â j *Â cellsize_ratio |
---|
3566 |       tmp = dem_elevation_r[trow:trow+nrows_stencil, tcol:tcol+ncols_stencil] |
---|
3567 | |
---|
3568 | Â Â Â Â Â Â #if dem contains 1 or more NODATA_values set value in |
---|
3569 | Â Â Â Â Â Â #decimated dem to NODATA_value, else compute decimated |
---|
3570 | Â Â Â Â Â Â #value using stencil |
---|
3571 |       if sum(sum(equal(tmp, NODATA_value))) > 0: |
---|
3572 | Â Â Â Â Â Â Â Â telev[local_index]Â =Â NODATA_value |
---|
3573 | Â Â Â Â Â Â else: |
---|
3574 | Â Â Â Â Â Â Â Â telev[local_index]Â =Â sum(sum(tmp *Â stencil)) |
---|
3575 | |
---|
3576 | Â Â Â Â Â Â global_index +=Â 1 |
---|
3577 | Â Â Â Â Â Â local_index +=Â 1 |
---|
3578 | |
---|
3579 | Â Â Â Â upper_index =Â global_index |
---|
3580 | |
---|
3581 | Â Â Â Â elevation[lower_index:upper_index]Â =Â telev |
---|
3582 | |
---|
3583 |   assert global_index == nrows_new*ncols_new, 'index not equal to number of points' |
---|
3584 | |
---|
3585 | Â Â infile.close() |
---|
3586 | Â Â outfile.close() |
---|
3587 | |
---|
3588 | |
---|
3589 | |
---|
3590 | |
---|
3591 | def tsh2sww(filename, verbose=False): |
---|
3592 | Â Â """ |
---|
3593 | Â Â to check if a tsh/msh file 'looks' good. |
---|
3594 | Â Â """ |
---|
3595 | |
---|
3596 | |
---|
3597 |   if verbose == True:print 'Creating domain from', filename |
---|
3598 |   domain = pmesh_to_domain_instance(filename, Domain) |
---|
3599 |   if verbose == True:print "Number of triangles = ", len(domain) |
---|
3600 | |
---|
3601 | Â Â domain.smooth =Â True |
---|
3602 | Â Â domain.format =Â 'sww'Â Â #Native netcdf visualisation format |
---|
3603 |   file_path, filename = path.split(filename) |
---|
3604 |   filename, ext = path.splitext(filename) |
---|
3605 | Â Â domain.set_name(filename)Â Â |
---|
3606 | Â Â domain.reduction =Â mean |
---|
3607 |   if verbose == True:print "file_path",file_path |
---|
3608 |   if file_path == "":file_path = "." |
---|
3609 | Â Â domain.set_datadir(file_path) |
---|
3610 | |
---|
3611 |   if verbose == True: |
---|
3612 |     print "Output written to " + domain.get_datadir() + sep + \ |
---|
3613 | Â Â Â Â Â Â Â domain.get_name()Â +Â "."Â +Â domain.format |
---|
3614 | Â Â sww =Â get_dataobject(domain) |
---|
3615 | Â Â sww.store_connectivity() |
---|
3616 | Â Â sww.store_timestep() |
---|
3617 | |
---|
3618 | |
---|
3619 | def asc_csiro2sww(bath_dir, |
---|
3620 | Â Â Â Â Â Â Â Â Â elevation_dir, |
---|
3621 | Â Â Â Â Â Â Â Â Â ucur_dir, |
---|
3622 | Â Â Â Â Â Â Â Â Â vcur_dir, |
---|
3623 | Â Â Â Â Â Â Â Â Â sww_file, |
---|
3624 |          minlat = None, maxlat = None, |
---|
3625 |          minlon = None, maxlon = None, |
---|
3626 | Â Â Â Â Â Â Â Â Â zscale=1, |
---|
3627 | Â Â Â Â Â Â Â Â Â mean_stage =Â 0, |
---|
3628 | Â Â Â Â Â Â Â Â Â fail_on_NaN =Â True, |
---|
3629 | Â Â Â Â Â Â Â Â Â elevation_NaN_filler =Â 0, |
---|
3630 | Â Â Â Â Â Â Â Â Â bath_prefix='ba', |
---|
3631 | Â Â Â Â Â Â Â Â Â elevation_prefix='el', |
---|
3632 | Â Â Â Â Â Â Â Â Â verbose=False): |
---|
3633 | Â Â """ |
---|
3634 | Â Â Produce an sww boundary file, from esri ascii data from CSIRO. |
---|
3635 | |
---|
3636 | Â Â Also convert latitude and longitude to UTM. All coordinates are |
---|
3637 | Â Â assumed to be given in the GDA94 datum. |
---|
3638 | |
---|
3639 | Â Â assume: |
---|
3640 | Â Â All files are in esri ascii format |
---|
3641 | |
---|
3642 | Â Â 4 types of information |
---|
3643 | Â Â bathymetry |
---|
3644 | Â Â elevation |
---|
3645 | Â Â u velocity |
---|
3646 | Â Â v velocity |
---|
3647 | |
---|
3648 | Â Â Assumptions |
---|
3649 | Â Â The metadata of all the files is the same |
---|
3650 | Â Â Each type is in a seperate directory |
---|
3651 | Â Â One bath file with extention .000 |
---|
3652 | Â Â The time period is less than 24hrs and uniform. |
---|
3653 | Â Â """ |
---|
3654 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
3655 | |
---|
3656 |   from anuga.coordinate_transforms.redfearn import redfearn |
---|
3657 | |
---|
3658 | Â Â precision =Â Float # So if we want to change the precision its done here |
---|
3659 | |
---|
3660 | Â Â # go in to the bath dir and load the only file, |
---|
3661 | Â Â bath_files =Â os.listdir(bath_dir) |
---|
3662 | |
---|
3663 | Â Â bath_file =Â bath_files[0] |
---|
3664 | Â Â bath_dir_file =Â bath_dir +Â os.sep +Â bath_file |
---|
3665 | Â Â bath_metadata,bath_grid =Â _read_asc(bath_dir_file) |
---|
3666 | |
---|
3667 | Â Â #Use the date.time of the bath file as a basis for |
---|
3668 | Â Â #the start time for other files |
---|
3669 | Â Â base_start =Â bath_file[-12:] |
---|
3670 | |
---|
3671 | Â Â #go into the elevation dir and load the 000 file |
---|
3672 |   elevation_dir_file = elevation_dir + os.sep + elevation_prefix \ |
---|
3673 | Â Â Â Â Â Â Â Â Â Â Â Â Â +Â base_start |
---|
3674 | |
---|
3675 | Â Â elevation_files =Â os.listdir(elevation_dir) |
---|
3676 | Â Â ucur_files =Â os.listdir(ucur_dir) |
---|
3677 | Â Â vcur_files =Â os.listdir(vcur_dir) |
---|
3678 | Â Â elevation_files.sort() |
---|
3679 | Â Â # the first elevation file should be the |
---|
3680 | Â Â # file with the same base name as the bath data |
---|
3681 |   assert elevation_files[0] == 'el' + base_start |
---|
3682 | |
---|
3683 | Â Â number_of_latitudes =Â bath_grid.shape[0] |
---|
3684 | Â Â number_of_longitudes =Â bath_grid.shape[1] |
---|
3685 | Â Â number_of_volumes =Â (number_of_latitudes-1)*(number_of_longitudes-1)*2 |
---|
3686 | |
---|
3687 | Â Â longitudes =Â [bath_metadata['xllcorner']+x*bath_metadata['cellsize']Â \ |
---|
3688 |          for x in range(number_of_longitudes)] |
---|
3689 | Â Â latitudes =Â [bath_metadata['yllcorner']+y*bath_metadata['cellsize']Â \ |
---|
3690 |          for y in range(number_of_latitudes)] |
---|
3691 | |
---|
3692 | Â Â Â # reverse order of lat, so the fist lat represents the first grid row |
---|
3693 | Â Â latitudes.reverse() |
---|
3694 | |
---|
3695 |   kmin, kmax, lmin, lmax = _get_min_max_indexes(latitudes[:],longitudes[:], |
---|
3696 |                          minlat=minlat, maxlat=maxlat, |
---|
3697 |                          minlon=minlon, maxlon=maxlon) |
---|
3698 | |
---|
3699 | |
---|
3700 | Â Â bath_grid =Â bath_grid[kmin:kmax,lmin:lmax] |
---|
3701 | Â Â latitudes =Â latitudes[kmin:kmax] |
---|
3702 | Â Â longitudes =Â longitudes[lmin:lmax] |
---|
3703 | Â Â number_of_latitudes =Â len(latitudes) |
---|
3704 | Â Â number_of_longitudes =Â len(longitudes) |
---|
3705 | Â Â number_of_times =Â len(os.listdir(elevation_dir)) |
---|
3706 | Â Â number_of_points =Â number_of_latitudes*number_of_longitudes |
---|
3707 | Â Â number_of_volumes =Â (number_of_latitudes-1)*(number_of_longitudes-1)*2 |
---|
3708 | |
---|
3709 | Â Â #Work out the times |
---|
3710 |   if len(elevation_files) > 1: |
---|
3711 | Â Â Â Â # Assume: The time period is less than 24hrs. |
---|
3712 | Â Â Â Â time_period =Â (int(elevation_files[1][-3:])Â -Â \ |
---|
3713 | Â Â Â Â Â Â Â Â Â Â Â int(elevation_files[0][-3:]))*60*60 |
---|
3714 |     times = [x*time_period for x in range(len(elevation_files))] |
---|
3715 | Â Â else: |
---|
3716 | Â Â Â Â times =Â [0.0] |
---|
3717 | |
---|
3718 | |
---|
3719 |   if verbose: |
---|
3720 |     print '------------------------------------------------' |
---|
3721 |     print 'Statistics:' |
---|
3722 |     print ' Extent (lat/lon):' |
---|
3723 |     print '  lat in [%f, %f], len(lat) == %d'\ |
---|
3724 |        %(min(latitudes), max(latitudes), |
---|
3725 | Â Â Â Â Â Â Â Â len(latitudes)) |
---|
3726 |     print '  lon in [%f, %f], len(lon) == %d'\ |
---|
3727 |        %(min(longitudes), max(longitudes), |
---|
3728 | Â Â Â Â Â Â Â Â len(longitudes)) |
---|
3729 |     print '  t in [%f, %f], len(t) == %d'\ |
---|
3730 |        %(min(times), max(times), len(times)) |
---|
3731 | |
---|
3732 | Â Â ######### WRITE THE SWW FILE ############# |
---|
3733 | Â Â # NetCDF file definition |
---|
3734 |   outfile = NetCDFFile(sww_file, 'w') |
---|
3735 | |
---|
3736 | Â Â #Create new file |
---|
3737 | Â Â outfile.institution =Â 'Geoscience Australia' |
---|
3738 | Â Â outfile.description =Â 'Converted from XXX' |
---|
3739 | |
---|
3740 | |
---|
3741 | Â Â #For sww compatibility |
---|
3742 | Â Â outfile.smoothing =Â 'Yes' |
---|
3743 | Â Â outfile.order =Â 1 |
---|
3744 | |
---|
3745 | Â Â #Start time in seconds since the epoch (midnight 1/1/1970) |
---|
3746 | Â Â outfile.starttime =Â starttime =Â times[0] |
---|
3747 | |
---|
3748 | |
---|
3749 | Â Â # dimension definitions |
---|
3750 |   outfile.createDimension('number_of_volumes', number_of_volumes) |
---|
3751 | |
---|
3752 |   outfile.createDimension('number_of_vertices', 3) |
---|
3753 |   outfile.createDimension('number_of_points', number_of_points) |
---|
3754 |   outfile.createDimension('number_of_timesteps', number_of_times) |
---|
3755 | |
---|
3756 | Â Â # variable definitions |
---|
3757 |   outfile.createVariable('x', precision, ('number_of_points',)) |
---|
3758 |   outfile.createVariable('y', precision, ('number_of_points',)) |
---|
3759 |   outfile.createVariable('elevation', precision, ('number_of_points',)) |
---|
3760 | |
---|
3761 | Â Â #FIXME: Backwards compatibility |
---|
3762 |   outfile.createVariable('z', precision, ('number_of_points',)) |
---|
3763 | Â Â ################################# |
---|
3764 | |
---|
3765 |   outfile.createVariable('volumes', Int, ('number_of_volumes', |
---|
3766 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_vertices')) |
---|
3767 | |
---|
3768 |   outfile.createVariable('time', precision, |
---|
3769 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps',)) |
---|
3770 | |
---|
3771 |   outfile.createVariable('stage', precision, |
---|
3772 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps', |
---|
3773 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_points')) |
---|
3774 | |
---|
3775 |   outfile.createVariable('xmomentum', precision, |
---|
3776 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps', |
---|
3777 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_points')) |
---|
3778 | |
---|
3779 |   outfile.createVariable('ymomentum', precision, |
---|
3780 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps', |
---|
3781 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_points')) |
---|
3782 | |
---|
3783 | Â Â #Store |
---|
3784 |   from anuga.coordinate_transforms.redfearn import redfearn |
---|
3785 |   x = zeros(number_of_points, Float) #Easting |
---|
3786 |   y = zeros(number_of_points, Float) #Northing |
---|
3787 | |
---|
3788 |   if verbose: print 'Making triangular grid' |
---|
3789 | Â Â #Get zone of 1st point. |
---|
3790 |   refzone, _, _ = redfearn(latitudes[0],longitudes[0]) |
---|
3791 | |
---|
3792 | Â Â vertices =Â {} |
---|
3793 | Â Â i =Â 0 |
---|
3794 |   for k, lat in enumerate(latitudes): |
---|
3795 |     for l, lon in enumerate(longitudes): |
---|
3796 | |
---|
3797 | Â Â Â Â Â Â vertices[l,k]Â =Â i |
---|
3798 | |
---|
3799 |       zone, easting, northing = redfearn(lat,lon) |
---|
3800 | |
---|
3801 |       msg = 'Zone boundary crossed at longitude =', lon |
---|
3802 | Â Â Â Â Â Â #assert zone == refzone, msg |
---|
3803 | Â Â Â Â Â Â #print '%7.2f %7.2f %8.2f %8.2f' %(lon, lat, easting, northing) |
---|
3804 | Â Â Â Â Â Â x[i]Â =Â easting |
---|
3805 | Â Â Â Â Â Â y[i]Â =Â northing |
---|
3806 | Â Â Â Â Â Â i +=Â 1 |
---|
3807 | |
---|
3808 | |
---|
3809 | Â Â #Construct 2 triangles per 'rectangular' element |
---|
3810 | Â Â volumes =Â [] |
---|
3811 |   for l in range(number_of_longitudes-1):  #X direction |
---|
3812 |     for k in range(number_of_latitudes-1): #Y direction |
---|
3813 | Â Â Â Â Â Â v1 =Â vertices[l,k+1] |
---|
3814 | Â Â Â Â Â Â v2 =Â vertices[l,k] |
---|
3815 | Â Â Â Â Â Â v3 =Â vertices[l+1,k+1] |
---|
3816 | Â Â Â Â Â Â v4 =Â vertices[l+1,k] |
---|
3817 | |
---|
3818 | Â Â Â Â Â Â #Note, this is different to the ferrit2sww code |
---|
3819 | Â Â Â Â Â Â #since the order of the lats is reversed. |
---|
3820 | Â Â Â Â Â Â volumes.append([v1,v3,v2])Â #Upper element |
---|
3821 | Â Â Â Â Â Â volumes.append([v4,v2,v3])Â #Lower element |
---|
3822 | |
---|
3823 | Â Â volumes =Â array(volumes) |
---|
3824 | |
---|
3825 | Â Â geo_ref =Â Geo_reference(refzone,min(x),min(y)) |
---|
3826 | Â Â geo_ref.write_NetCDF(outfile) |
---|
3827 | |
---|
3828 | Â Â # This will put the geo ref in the middle |
---|
3829 | Â Â #geo_ref = Geo_reference(refzone,(max(x)+min(x))/2.0,(max(x)+min(y))/2.) |
---|
3830 | |
---|
3831 | |
---|
3832 |   if verbose: |
---|
3833 |     print '------------------------------------------------' |
---|
3834 |     print 'More Statistics:' |
---|
3835 |     print ' Extent (/lon):' |
---|
3836 |     print '  x in [%f, %f], len(lat) == %d'\ |
---|
3837 |        %(min(x), max(x), |
---|
3838 | Â Â Â Â Â Â Â Â len(x)) |
---|
3839 |     print '  y in [%f, %f], len(lon) == %d'\ |
---|
3840 |        %(min(y), max(y), |
---|
3841 | Â Â Â Â Â Â Â Â len(y)) |
---|
3842 |     print 'geo_ref: ',geo_ref |
---|
3843 | |
---|
3844 | Â Â z =Â resize(bath_grid,outfile.variables['z'][:].shape) |
---|
3845 | Â Â outfile.variables['x'][:]Â =Â x -Â geo_ref.get_xllcorner() |
---|
3846 | Â Â outfile.variables['y'][:]Â =Â y -Â geo_ref.get_yllcorner() |
---|
3847 | Â Â outfile.variables['z'][:]Â =Â z |
---|
3848 |   outfile.variables['elevation'][:] = z #FIXME HACK |
---|
3849 | Â Â outfile.variables['volumes'][:]Â =Â volumes.astype(Int32)Â #On Opteron 64 |
---|
3850 | |
---|
3851 | Â Â stage =Â outfile.variables['stage'] |
---|
3852 | Â Â xmomentum =Â outfile.variables['xmomentum'] |
---|
3853 | Â Â ymomentum =Â outfile.variables['ymomentum'] |
---|
3854 | |
---|
3855 |   outfile.variables['time'][:] = times  #Store time relative |
---|
3856 | |
---|
3857 |   if verbose: print 'Converting quantities' |
---|
3858 | Â Â n =Â number_of_times |
---|
3859 |   for j in range(number_of_times): |
---|
3860 | Â Â Â Â # load in files |
---|
3861 |     elevation_meta, elevation_grid = \ |
---|
3862 | Â Â Â Â Â Â _read_asc(elevation_dir +Â os.sep +Â elevation_files[j]) |
---|
3863 | |
---|
3864 |     _, u_momentum_grid = _read_asc(ucur_dir + os.sep + ucur_files[j]) |
---|
3865 |     _, v_momentum_grid = _read_asc(vcur_dir + os.sep + vcur_files[j]) |
---|
3866 | |
---|
3867 | Â Â Â Â #cut matrix to desired size |
---|
3868 | Â Â Â Â elevation_grid =Â elevation_grid[kmin:kmax,lmin:lmax] |
---|
3869 | Â Â Â Â u_momentum_grid =Â u_momentum_grid[kmin:kmax,lmin:lmax] |
---|
3870 | Â Â Â Â v_momentum_grid =Â v_momentum_grid[kmin:kmax,lmin:lmax] |
---|
3871 | Â Â Â Â |
---|
3872 | Â Â Â Â # handle missing values |
---|
3873 | Â Â Â Â missing =Â (elevation_grid ==Â elevation_meta['NODATA_value']) |
---|
3874 |     if sometrue (missing): |
---|
3875 |       if fail_on_NaN: |
---|
3876 |         msg = 'File %s contains missing values'\ |
---|
3877 | Â Â Â Â Â Â Â Â Â Â Â %(elevation_files[j]) |
---|
3878 |         raise DataMissingValuesError, msg |
---|
3879 | Â Â Â Â Â Â else: |
---|
3880 | Â Â Â Â Â Â Â Â elevation_grid =Â elevation_grid*(missing==0)Â +Â \ |
---|
3881 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â missing*elevation_NaN_filler |
---|
3882 | |
---|
3883 | |
---|
3884 |     if verbose and j%((n+10)/10)==0: print ' Doing %d of %d' %(j, n) |
---|
3885 | Â Â Â Â i =Â 0 |
---|
3886 |     for k in range(number_of_latitudes):   #Y direction |
---|
3887 |       for l in range(number_of_longitudes): #X direction |
---|
3888 | Â Â Â Â Â Â Â Â w =Â zscale*elevation_grid[k,l]Â +Â mean_stage |
---|
3889 | Â Â Â Â Â Â Â Â stage[j,i]Â =Â w |
---|
3890 | Â Â Â Â Â Â Â Â h =Â w -Â z[i] |
---|
3891 | Â Â Â Â Â Â Â Â xmomentum[j,i]Â =Â u_momentum_grid[k,l]*h |
---|
3892 | Â Â Â Â Â Â Â Â ymomentum[j,i]Â =Â v_momentum_grid[k,l]*h |
---|
3893 | Â Â Â Â Â Â Â Â i +=Â 1 |
---|
3894 | Â Â outfile.close() |
---|
3895 | |
---|
3896 | def _get_min_max_indexes(latitudes_ref,longitudes_ref, |
---|
3897 |             minlat=None, maxlat=None, |
---|
3898 |             minlon=None, maxlon=None): |
---|
3899 | Â Â """ |
---|
3900 | Â Â return max, min indexes (for slicing) of the lat and long arrays to cover the area |
---|
3901 | Â Â specified with min/max lat/long |
---|
3902 | |
---|
3903 | Â Â Think of the latitudes and longitudes describing a 2d surface. |
---|
3904 | Â Â The area returned is, if possible, just big enough to cover the |
---|
3905 | Â Â inputed max/min area. (This will not be possible if the max/min area |
---|
3906 | Â Â has a section outside of the latitudes/longitudes area.) |
---|
3907 | |
---|
3908 |   asset longitudes are sorted, |
---|
3909 | Â Â long - from low to high (west to east, eg 148 - 151) |
---|
3910 | Â Â assert latitudes are sorted, ascending or decending |
---|
3911 | Â Â """ |
---|
3912 | Â Â latitudes =Â latitudes_ref[:] |
---|
3913 | Â Â longitudes =Â longitudes_ref[:] |
---|
3914 | |
---|
3915 | Â Â latitudes =Â ensure_numeric(latitudes) |
---|
3916 | Â Â longitudes =Â ensure_numeric(longitudes) |
---|
3917 | |
---|
3918 |   assert allclose(sort(longitudes), longitudes) |
---|
3919 | |
---|
3920 | Â Â #print latitudes[0],longitudes[0] |
---|
3921 | Â Â #print len(latitudes),len(longitudes) |
---|
3922 | Â Â #print latitudes[len(latitudes)-1],longitudes[len(longitudes)-1] |
---|
3923 | Â Â |
---|
3924 | Â Â lat_ascending =Â True |
---|
3925 |   if not allclose(sort(latitudes), latitudes): |
---|
3926 | Â Â Â Â lat_ascending =Â False |
---|
3927 |     # reverse order of lat, so it's in ascending order     |
---|
3928 | Â Â Â Â latitudes =Â latitudes[::-1] |
---|
3929 |     assert allclose(sort(latitudes), latitudes) |
---|
3930 |   #print "latitudes in funct", latitudes |
---|
3931 | Â Â |
---|
3932 | Â Â largest_lat_index =Â len(latitudes)-1 |
---|
3933 | Â Â #Cut out a smaller extent. |
---|
3934 |   if minlat == None: |
---|
3935 | Â Â Â Â lat_min_index =Â 0 |
---|
3936 | Â Â else: |
---|
3937 |     lat_min_index = searchsorted(latitudes, minlat)-1 |
---|
3938 |     if lat_min_index <0: |
---|
3939 | Â Â Â Â Â Â lat_min_index =Â 0 |
---|
3940 | |
---|
3941 | |
---|
3942 |   if maxlat == None: |
---|
3943 | Â Â Â Â lat_max_index =Â largest_lat_index #len(latitudes) |
---|
3944 | Â Â else: |
---|
3945 |     lat_max_index = searchsorted(latitudes, maxlat) |
---|
3946 |     if lat_max_index > largest_lat_index: |
---|
3947 | Â Â Â Â Â Â lat_max_index =Â largest_lat_index |
---|
3948 | |
---|
3949 |   if minlon == None: |
---|
3950 | Â Â Â Â lon_min_index =Â 0 |
---|
3951 | Â Â else: |
---|
3952 |     lon_min_index = searchsorted(longitudes, minlon)-1 |
---|
3953 |     if lon_min_index <0: |
---|
3954 | Â Â Â Â Â Â lon_min_index =Â 0 |
---|
3955 | |
---|
3956 |   if maxlon == None: |
---|
3957 | Â Â Â Â lon_max_index =Â len(longitudes) |
---|
3958 | Â Â else: |
---|
3959 |     lon_max_index = searchsorted(longitudes, maxlon) |
---|
3960 | |
---|
3961 | Â Â # Reversing the indexes, if the lat array is decending |
---|
3962 |   if lat_ascending is False: |
---|
3963 |     lat_min_index, lat_max_index = largest_lat_index - lat_max_index , \ |
---|
3964 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â largest_lat_index -Â lat_min_index |
---|
3965 | Â Â lat_max_index =Â lat_max_index +Â 1Â # taking into account how slicing works |
---|
3966 | Â Â lon_max_index =Â lon_max_index +Â 1Â # taking into account how slicing works |
---|
3967 | |
---|
3968 |   return lat_min_index, lat_max_index, lon_min_index, lon_max_index |
---|
3969 | |
---|
3970 | |
---|
3971 | def _read_asc(filename, verbose=False): |
---|
3972 | Â Â """Read esri file from the following ASCII format (.asc) |
---|
3973 | |
---|
3974 | Â Â Example: |
---|
3975 | |
---|
3976 |   ncols     3121 |
---|
3977 |   nrows     1800 |
---|
3978 |   xllcorner   722000 |
---|
3979 |   yllcorner   5893000 |
---|
3980 |   cellsize   25 |
---|
3981 |   NODATA_value -9999 |
---|
3982 | Â Â 138.3698 137.4194 136.5062 135.5558 .......... |
---|
3983 | |
---|
3984 | Â Â """ |
---|
3985 | |
---|
3986 | Â Â datafile =Â open(filename) |
---|
3987 | |
---|
3988 |   if verbose: print 'Reading DEM from %s' %(filename) |
---|
3989 | Â Â lines =Â datafile.readlines() |
---|
3990 | Â Â datafile.close() |
---|
3991 | |
---|
3992 |   if verbose: print 'Got', len(lines), ' lines' |
---|
3993 | |
---|
3994 | Â Â ncols =Â int(lines.pop(0).split()[1].strip()) |
---|
3995 | Â Â nrows =Â int(lines.pop(0).split()[1].strip()) |
---|
3996 | Â Â xllcorner =Â float(lines.pop(0).split()[1].strip()) |
---|
3997 | Â Â yllcorner =Â float(lines.pop(0).split()[1].strip()) |
---|
3998 | Â Â cellsize =Â float(lines.pop(0).split()[1].strip()) |
---|
3999 | Â Â NODATA_value =Â float(lines.pop(0).split()[1].strip()) |
---|
4000 | |
---|
4001 |   assert len(lines) == nrows |
---|
4002 | |
---|
4003 | Â Â #Store data |
---|
4004 | Â Â grid =Â [] |
---|
4005 | |
---|
4006 | Â Â n =Â len(lines) |
---|
4007 |   for i, line in enumerate(lines): |
---|
4008 | Â Â Â Â cells =Â line.split() |
---|
4009 |     assert len(cells) == ncols |
---|
4010 |     grid.append(array([float(x) for x in cells])) |
---|
4011 | Â Â grid =Â array(grid) |
---|
4012 | |
---|
4013 |   return {'xllcorner':xllcorner, |
---|
4014 | Â Â Â Â Â Â 'yllcorner':yllcorner, |
---|
4015 | Â Â Â Â Â Â 'cellsize':cellsize, |
---|
4016 |       'NODATA_value':NODATA_value}, grid |
---|
4017 | |
---|
4018 | |
---|
4019 | |
---|
4020 | Â Â ####Â URS 2 SWWÂ ### |
---|
4021 | |
---|
4022 | lon_name =Â 'LON' |
---|
4023 | lat_name =Â 'LAT' |
---|
4024 | time_name =Â 'TIME' |
---|
4025 | precision = Float # So if we want to change the precision its done here    |
---|
4026 | class Write_nc: |
---|
4027 | Â Â """ |
---|
4028 | Â Â Write an nc file. |
---|
4029 | Â Â |
---|
4030 | Â Â Note, this should be checked to meet cdc netcdf conventions for gridded |
---|
4031 | Â Â data. http://www.cdc.noaa.gov/cdc/conventions/cdc_netcdf_standard.shtml |
---|
4032 | Â Â |
---|
4033 | Â Â """ |
---|
4034 |   def __init__(self, |
---|
4035 | Â Â Â Â Â Â Â Â Â quantity_name, |
---|
4036 | Â Â Â Â Â Â Â Â Â file_name, |
---|
4037 | Â Â Â Â Â Â Â Â Â time_step_count, |
---|
4038 | Â Â Â Â Â Â Â Â Â time_step, |
---|
4039 | Â Â Â Â Â Â Â Â Â lon, |
---|
4040 | Â Â Â Â Â Â Â Â Â lat): |
---|
4041 | Â Â Â Â """ |
---|
4042 | Â Â Â Â time_step_count is the number of time steps. |
---|
4043 | Â Â Â Â time_step is the time step size |
---|
4044 | Â Â Â Â |
---|
4045 | Â Â Â Â pre-condition: quantity_name must be 'HA' 'UA'or 'VA'. |
---|
4046 | Â Â Â Â """ |
---|
4047 | Â Â Â Â self.quantity_name =Â quantity_name |
---|
4048 | Â Â Â Â quantity_units =Â {'HA':'CENTIMETERS', |
---|
4049 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'UA':'CENTIMETERS/SECOND', |
---|
4050 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'VA':'CENTIMETERS/SECOND'}Â Â Â Â |
---|
4051 | Â Â Â Â |
---|
4052 |     multiplier_dic = {'HA':100.0, # To convert from m to cm |
---|
4053 |                'UA':100.0, # m/s to cm/sec |
---|
4054 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'VA':-100.0}Â # MUX files have positve x in the |
---|
4055 |     # Southern direction. This corrects for it, when writing nc files. |
---|
4056 | Â Â Â Â |
---|
4057 | Â Â Â Â self.quantity_multiplier =Â multiplier_dic[self.quantity_name] |
---|
4058 | Â Â Â Â |
---|
4059 | Â Â Â Â #self.file_name = file_name |
---|
4060 | Â Â Â Â self.time_step_count =Â time_step_count |
---|
4061 | Â Â Â Â self.time_step =Â time_step |
---|
4062 | |
---|
4063 | Â Â Â Â # NetCDF file definition |
---|
4064 |     self.outfile = NetCDFFile(file_name, 'w') |
---|
4065 |     outfile = self.outfile    |
---|
4066 | |
---|
4067 | Â Â Â Â #Create new file |
---|
4068 |     nc_lon_lat_header(outfile, lon, lat) |
---|
4069 | Â Â |
---|
4070 | Â Â Â Â # TIME |
---|
4071 |     outfile.createDimension(time_name, None) |
---|
4072 |     outfile.createVariable(time_name, precision, (time_name,)) |
---|
4073 | |
---|
4074 | Â Â Â Â #QUANTITY |
---|
4075 |     outfile.createVariable(self.quantity_name, precision, |
---|
4076 |                 (time_name, lat_name, lon_name)) |
---|
4077 | Â Â Â Â outfile.variables[self.quantity_name].missing_value=-1.e+034 |
---|
4078 | Â Â Â Â outfile.variables[self.quantity_name].units=Â \ |
---|
4079 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â quantity_units[self.quantity_name] |
---|
4080 | Â Â Â Â outfile.variables[lon_name][:]=Â ensure_numeric(lon) |
---|
4081 | Â Â Â Â outfile.variables[lat_name][:]=Â ensure_numeric(lat) |
---|
4082 | |
---|
4083 | Â Â Â Â #Assume no one will be wanting to read this, while we are writing |
---|
4084 | Â Â Â Â #outfile.close() |
---|
4085 | Â Â Â Â |
---|
4086 |   def store_timestep(self, quantity_slice): |
---|
4087 | Â Â Â Â """ |
---|
4088 | Â Â Â Â Write a time slice of quantity info |
---|
4089 | Â Â Â Â quantity_slice is the data to be stored at this time step |
---|
4090 | Â Â Â Â """ |
---|
4091 | Â Â Â Â |
---|
4092 | Â Â Â Â outfile =Â self.outfile |
---|
4093 | Â Â Â Â |
---|
4094 | Â Â Â Â # Get the variables |
---|
4095 | Â Â Â Â time =Â outfile.variables[time_name] |
---|
4096 | Â Â Â Â quantity =Â outfile.variables[self.quantity_name] |
---|
4097 | Â Â Â Â Â Â |
---|
4098 | Â Â Â Â i =Â len(time) |
---|
4099 | |
---|
4100 | Â Â Â Â #Store time |
---|
4101 | Â Â Â Â time[i]Â =Â i*self.time_step #self.domain.time |
---|
4102 | Â Â Â Â quantity[i,:]Â =Â quantity_slice*Â self.quantity_multiplier |
---|
4103 | Â Â Â Â |
---|
4104 |   def close(self): |
---|
4105 | Â Â Â Â self.outfile.close() |
---|
4106 | |
---|
4107 | def urs2sww(basename_in='o', basename_out=None, verbose=False, |
---|
4108 | Â Â Â Â Â Â remove_nc_files=True, |
---|
4109 |       minlat=None, maxlat=None, |
---|
4110 |       minlon= None, maxlon=None, |
---|
4111 |       mint=None, maxt=None, |
---|
4112 | Â Â Â Â Â Â mean_stage=0, |
---|
4113 | Â Â Â Â Â Â origin =Â None, |
---|
4114 | Â Â Â Â Â Â zscale=1, |
---|
4115 | Â Â Â Â Â Â fail_on_NaN=True, |
---|
4116 | Â Â Â Â Â Â NaN_filler=0, |
---|
4117 | Â Â Â Â Â Â elevation=None): |
---|
4118 | Â Â """ |
---|
4119 | Â Â Convert URS C binary format for wave propagation to |
---|
4120 | Â Â sww format native to abstract_2d_finite_volumes. |
---|
4121 | |
---|
4122 | Â Â Specify only basename_in and read files of the form |
---|
4123 | Â Â basefilename_velocity-z-mux, basefilename_velocity-e-mux and |
---|
4124 | Â Â basefilename_waveheight-n-mux containing relative height, |
---|
4125 | Â Â x-velocity and y-velocity, respectively. |
---|
4126 | |
---|
4127 | Â Â Also convert latitude and longitude to UTM. All coordinates are |
---|
4128 | Â Â assumed to be given in the GDA94 datum. The latitude and longitude |
---|
4129 |   information is for a grid. |
---|
4130 | |
---|
4131 | Â Â min's and max's: If omitted - full extend is used. |
---|
4132 | Â Â To include a value min may equal it, while max must exceed it. |
---|
4133 | Â Â Lat and lon are assumed to be in decimal degrees. |
---|
4134 | Â Â NOTE: minlon is the most east boundary. |
---|
4135 | Â Â |
---|
4136 | Â Â origin is a 3-tuple with geo referenced |
---|
4137 | Â Â UTM coordinates (zone, easting, northing) |
---|
4138 | Â Â It will be the origin of the sww file. This shouldn't be used, |
---|
4139 | Â Â since all of anuga should be able to handle an arbitary origin. |
---|
4140 | |
---|
4141 | |
---|
4142 | Â Â URS C binary format has data orgainised as TIME, LONGITUDE, LATITUDE |
---|
4143 | Â Â which means that latitude is the fastest |
---|
4144 | Â Â varying dimension (row major order, so to speak) |
---|
4145 | |
---|
4146 | Â Â In URS C binary the latitudes and longitudes are in assending order. |
---|
4147 | Â Â """ |
---|
4148 |   if basename_out == None: |
---|
4149 | Â Â Â Â basename_out =Â basename_in |
---|
4150 |   files_out = urs2nc(basename_in, basename_out) |
---|
4151 | Â Â ferret2sww(basename_out, |
---|
4152 | Â Â Â Â Â Â Â Â minlat=minlat, |
---|
4153 | Â Â Â Â Â Â Â Â maxlat=maxlat, |
---|
4154 | Â Â Â Â Â Â Â Â minlon=minlon, |
---|
4155 | Â Â Â Â Â Â Â Â maxlon=maxlon, |
---|
4156 | Â Â Â Â Â Â Â Â mint=mint, |
---|
4157 | Â Â Â Â Â Â Â Â maxt=maxt, |
---|
4158 | Â Â Â Â Â Â Â Â mean_stage=mean_stage, |
---|
4159 | Â Â Â Â Â Â Â Â origin=origin, |
---|
4160 | Â Â Â Â Â Â Â Â zscale=zscale, |
---|
4161 | Â Â Â Â Â Â Â Â fail_on_NaN=fail_on_NaN, |
---|
4162 | Â Â Â Â Â Â Â Â NaN_filler=NaN_filler, |
---|
4163 | Â Â Â Â Â Â Â Â inverted_bathymetry=True, |
---|
4164 | Â Â Â Â Â Â Â Â verbose=verbose) |
---|
4165 | Â Â #print "files_out",files_out |
---|
4166 |   if remove_nc_files: |
---|
4167 |     for file_out in files_out: |
---|
4168 | Â Â Â Â Â Â os.remove(file_out) |
---|
4169 | Â Â |
---|
4170 | def urs2nc(basename_in = 'o', basename_out = 'urs'): |
---|
4171 | Â Â """ |
---|
4172 | Â Â Convert the 3 urs files to 4 nc files. |
---|
4173 | |
---|
4174 | Â Â The name of the urs file names must be; |
---|
4175 | Â Â [basename_in]_velocity-z-mux |
---|
4176 | Â Â [basename_in]_velocity-e-mux |
---|
4177 | Â Â [basename_in]_waveheight-n-mux |
---|
4178 | Â Â |
---|
4179 | Â Â """ |
---|
4180 | Â Â |
---|
4181 | Â Â files_in =Â [basename_in +Â WAVEHEIGHT_MUX_LABEL, |
---|
4182 | Â Â Â Â Â Â Â Â basename_in +Â EAST_VELOCITY_LABEL, |
---|
4183 | Â Â Â Â Â Â Â Â basename_in +Â NORTH_VELOCITY_LABEL] |
---|
4184 | Â Â files_out =Â [basename_out+'_ha.nc', |
---|
4185 | Â Â Â Â Â Â Â Â Â basename_out+'_ua.nc', |
---|
4186 | Â Â Â Â Â Â Â Â Â basename_out+'_va.nc'] |
---|
4187 | Â Â quantities =Â ['HA','UA','VA'] |
---|
4188 | |
---|
4189 | Â Â #if os.access(files_in[0]+'.mux', os.F_OK) == 0 : |
---|
4190 |   for i, file_name in enumerate(files_in): |
---|
4191 |     if os.access(file_name, os.F_OK) == 0: |
---|
4192 |       if os.access(file_name+'.mux', os.F_OK) == 0 : |
---|
4193 |         msg = 'File %s does not exist or is not accessible' %file_name |
---|
4194 |         raise IOError, msg |
---|
4195 | Â Â Â Â Â Â else: |
---|
4196 | Â Â Â Â Â Â Â Â files_in[i]Â +=Â '.mux' |
---|
4197 |         print "file_name", file_name |
---|
4198 | Â Â hashed_elevation =Â None |
---|
4199 |   for file_in, file_out, quantity in map(None, files_in, |
---|
4200 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â files_out, |
---|
4201 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â quantities): |
---|
4202 |     lonlatdep, lon, lat, depth = _binary_c2nc(file_in, |
---|
4203 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â file_out, |
---|
4204 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â quantity) |
---|
4205 | Â Â Â Â #print "lonlatdep", lonlatdep |
---|
4206 |     if hashed_elevation == None: |
---|
4207 | Â Â Â Â Â Â elevation_file =Â basename_out+'_e.nc' |
---|
4208 | Â Â Â Â Â Â write_elevation_nc(elevation_file, |
---|
4209 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â lon, |
---|
4210 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â lat, |
---|
4211 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â depth) |
---|
4212 | Â Â Â Â Â Â hashed_elevation =Â myhash(lonlatdep) |
---|
4213 | Â Â Â Â else: |
---|
4214 | Â Â Â Â Â Â msg =Â "The elevation information in the mux files is inconsistent" |
---|
4215 |       assert hashed_elevation == myhash(lonlatdep), msg |
---|
4216 | Â Â files_out.append(elevation_file) |
---|
4217 |   return files_out |
---|
4218 | Â Â |
---|
4219 | def _binary_c2nc(file_in, file_out, quantity): |
---|
4220 | Â Â """ |
---|
4221 | Â Â Reads in a quantity urs file and writes a quantity nc file. |
---|
4222 | Â Â additionally, returns the depth and lat, long info, |
---|
4223 | Â Â so it can be written to a file. |
---|
4224 | Â Â """ |
---|
4225 | Â Â columns =Â 3Â # long, lat , depth |
---|
4226 |   mux_file = open(file_in, 'rb') |
---|
4227 | Â Â |
---|
4228 | Â Â # Number of points/stations |
---|
4229 | Â Â (points_num,)=Â unpack('i',mux_file.read(4)) |
---|
4230 | |
---|
4231 | Â Â # nt, int - Number of time steps |
---|
4232 | Â Â (time_step_count,)=Â unpack('i',mux_file.read(4)) |
---|
4233 | |
---|
4234 | Â Â #dt, float - time step, seconds |
---|
4235 |   (time_step,) = unpack('f', mux_file.read(4)) |
---|
4236 | Â Â |
---|
4237 | Â Â msg =Â "Bad data in the mux file." |
---|
4238 |   if points_num < 0: |
---|
4239 | Â Â Â Â mux_file.close() |
---|
4240 |     raise ANUGAError, msg |
---|
4241 |   if time_step_count < 0: |
---|
4242 | Â Â Â Â mux_file.close() |
---|
4243 |     raise ANUGAError, msg |
---|
4244 |   if time_step < 0: |
---|
4245 | Â Â Â Â mux_file.close() |
---|
4246 |     raise ANUGAError, msg |
---|
4247 | Â Â |
---|
4248 | Â Â lonlatdep =Â p_array.array('f') |
---|
4249 |   lonlatdep.read(mux_file, columns * points_num) |
---|
4250 |   lonlatdep = array(lonlatdep, typecode=Float)  |
---|
4251 |   lonlatdep = reshape(lonlatdep, (points_num, columns)) |
---|
4252 | Â Â |
---|
4253 |   lon, lat, depth = lon_lat2grid(lonlatdep) |
---|
4254 | Â Â lon_sorted =Â list(lon) |
---|
4255 | Â Â lon_sorted.sort() |
---|
4256 | |
---|
4257 |   if not lon == lon_sorted: |
---|
4258 | Â Â Â Â msg =Â "Longitudes in mux file are not in ascending order" |
---|
4259 |     raise IOError, msg |
---|
4260 | Â Â lat_sorted =Â list(lat) |
---|
4261 | Â Â lat_sorted.sort() |
---|
4262 | |
---|
4263 |   if not lat == lat_sorted: |
---|
4264 | Â Â Â Â msg =Â "Latitudes in mux file are not in ascending order" |
---|
4265 | Â Â |
---|
4266 | Â Â nc_file =Â Write_nc(quantity, |
---|
4267 | Â Â Â Â Â Â Â Â Â Â Â Â file_out, |
---|
4268 | Â Â Â Â Â Â Â Â Â Â Â Â time_step_count, |
---|
4269 | Â Â Â Â Â Â Â Â Â Â Â Â time_step, |
---|
4270 | Â Â Â Â Â Â Â Â Â Â Â Â lon, |
---|
4271 | Â Â Â Â Â Â Â Â Â Â Â Â lat) |
---|
4272 | |
---|
4273 |   for i in range(time_step_count): |
---|
4274 |     #Read in a time slice from mux file |
---|
4275 | Â Â Â Â hz_p_array =Â p_array.array('f') |
---|
4276 |     hz_p_array.read(mux_file, points_num) |
---|
4277 |     hz_p = array(hz_p_array, typecode=Float) |
---|
4278 |     hz_p = reshape(hz_p, (len(lon), len(lat))) |
---|
4279 | Â Â Â Â hz_p =Â transpose(hz_p)Â #mux has lat varying fastest, nc has long v.f. |
---|
4280 | |
---|
4281 | Â Â Â Â #write time slice to nc file |
---|
4282 | Â Â Â Â nc_file.store_timestep(hz_p) |
---|
4283 | Â Â mux_file.close() |
---|
4284 | Â Â nc_file.close() |
---|
4285 | |
---|
4286 |   return lonlatdep, lon, lat, depth |
---|
4287 | Â Â |
---|
4288 | |
---|
4289 | def write_elevation_nc(file_out, lon, lat, depth_vector): |
---|
4290 | Â Â """ |
---|
4291 | Â Â Write an nc elevation file. |
---|
4292 | Â Â """ |
---|
4293 | Â Â |
---|
4294 | Â Â # NetCDF file definition |
---|
4295 |   outfile = NetCDFFile(file_out, 'w') |
---|
4296 | |
---|
4297 | Â Â #Create new file |
---|
4298 |   nc_lon_lat_header(outfile, lon, lat) |
---|
4299 | Â Â |
---|
4300 | Â Â # ELEVATION |
---|
4301 | Â Â zname =Â 'ELEVATION' |
---|
4302 |   outfile.createVariable(zname, precision, (lat_name, lon_name)) |
---|
4303 | Â Â outfile.variables[zname].units='CENTIMETERS' |
---|
4304 | Â Â outfile.variables[zname].missing_value=-1.e+034 |
---|
4305 | |
---|
4306 | Â Â outfile.variables[lon_name][:]=Â ensure_numeric(lon) |
---|
4307 | Â Â outfile.variables[lat_name][:]=Â ensure_numeric(lat) |
---|
4308 | |
---|
4309 |   depth = reshape(depth_vector, ( len(lat), len(lon))) |
---|
4310 | Â Â outfile.variables[zname][:]=Â depth |
---|
4311 | Â Â |
---|
4312 | Â Â outfile.close() |
---|
4313 | Â Â |
---|
4314 | def nc_lon_lat_header(outfile, lon, lat): |
---|
4315 | Â Â """ |
---|
4316 | Â Â outfile is the netcdf file handle. |
---|
4317 | Â Â lon - a list/array of the longitudes |
---|
4318 | Â Â lat - a list/array of the latitudes |
---|
4319 | Â Â """ |
---|
4320 | Â Â |
---|
4321 | Â Â outfile.institution =Â 'Geoscience Australia' |
---|
4322 | Â Â outfile.description =Â 'Converted from URS binary C' |
---|
4323 | Â Â |
---|
4324 | Â Â # Longitude |
---|
4325 |   outfile.createDimension(lon_name, len(lon)) |
---|
4326 |   outfile.createVariable(lon_name, precision, (lon_name,)) |
---|
4327 | Â Â outfile.variables[lon_name].point_spacing='uneven' |
---|
4328 | Â Â outfile.variables[lon_name].units='degrees_east' |
---|
4329 | Â Â outfile.variables[lon_name].assignValue(lon) |
---|
4330 | |
---|
4331 | |
---|
4332 | Â Â # Latitude |
---|
4333 |   outfile.createDimension(lat_name, len(lat)) |
---|
4334 |   outfile.createVariable(lat_name, precision, (lat_name,)) |
---|
4335 | Â Â outfile.variables[lat_name].point_spacing='uneven' |
---|
4336 | Â Â outfile.variables[lat_name].units='degrees_north' |
---|
4337 | Â Â outfile.variables[lat_name].assignValue(lat) |
---|
4338 | |
---|
4339 | |
---|
4340 | Â Â |
---|
4341 | def lon_lat2grid(long_lat_dep): |
---|
4342 | Â Â """ |
---|
4343 | Â Â given a list of points that are assumed to be an a grid, |
---|
4344 | Â Â return the long's and lat's of the grid. |
---|
4345 | Â Â long_lat_dep is an array where each row is a position. |
---|
4346 | Â Â The first column is longitudes. |
---|
4347 | Â Â The second column is latitudes. |
---|
4348 | |
---|
4349 | Â Â The latitude is the fastest varying dimension - in mux files |
---|
4350 | Â Â """ |
---|
4351 | Â Â LONG =Â 0 |
---|
4352 | Â Â LAT =Â 1 |
---|
4353 | Â Â QUANTITY =Â 2 |
---|
4354 | |
---|
4355 |   long_lat_dep = ensure_numeric(long_lat_dep, Float) |
---|
4356 | Â Â |
---|
4357 | Â Â num_points =Â long_lat_dep.shape[0] |
---|
4358 | Â Â this_rows_long =Â long_lat_dep[0,LONG] |
---|
4359 | |
---|
4360 | Â Â # Count the length of unique latitudes |
---|
4361 | Â Â i =Â 0 |
---|
4362 |   while long_lat_dep[i,LONG] == this_rows_long and i < num_points: |
---|
4363 | Â Â Â Â i +=Â 1 |
---|
4364 | Â Â # determine the lats and longsfrom the grid |
---|
4365 |   lat = long_lat_dep[:i, LAT]    |
---|
4366 |   long = long_lat_dep[::i, LONG] |
---|
4367 | Â Â |
---|
4368 | Â Â lenlong =Â len(long) |
---|
4369 | Â Â lenlat =Â len(lat) |
---|
4370 | Â Â #print 'len lat', lat, len(lat) |
---|
4371 | Â Â #print 'len long', long, len(long) |
---|
4372 | Â Â Â Â Â |
---|
4373 | Â Â msg =Â 'Input data is not gridded'Â Â Â |
---|
4374 |   assert num_points % lenlat == 0, msg |
---|
4375 |   assert num_points % lenlong == 0, msg |
---|
4376 | Â Â Â Â Â |
---|
4377 |   # Test that data is gridded    |
---|
4378 |   for i in range(lenlong): |
---|
4379 |     msg = 'Data is not gridded. It must be for this operation' |
---|
4380 | Â Â Â Â first =Â i*lenlat |
---|
4381 | Â Â Â Â last =Â first +Â lenlat |
---|
4382 | Â Â Â Â Â Â Â Â |
---|
4383 |     assert allclose(long_lat_dep[first:last,LAT], lat), msg |
---|
4384 |     assert allclose(long_lat_dep[first:last,LONG], long[i]), msg |
---|
4385 | Â Â |
---|
4386 | Â Â |
---|
4387 | #Â Â print 'range long', min(long), max(long) |
---|
4388 | #Â Â print 'range lat', min(lat), max(lat) |
---|
4389 | #Â Â print 'ref long', min(long_lat_dep[:,0]), max(long_lat_dep[:,0]) |
---|
4390 | #Â Â print 'ref lat', min(long_lat_dep[:,1]), max(long_lat_dep[:,1]) |
---|
4391 | Â Â |
---|
4392 | Â Â |
---|
4393 | Â Â |
---|
4394 | Â Â msg =Â 'Out of range latitudes/longitudes' |
---|
4395 |   for l in lat:assert -90 < l < 90 , msg |
---|
4396 |   for l in long:assert -180 < l < 180 , msg |
---|
4397 | |
---|
4398 | Â Â # Changing quantity from lat being the fastest varying dimension to |
---|
4399 | Â Â # long being the fastest varying dimension |
---|
4400 | Â Â # FIXME - make this faster/do this a better way |
---|
4401 | Â Â # use numeric transpose, after reshaping the quantity vector |
---|
4402 | #Â Â quantity = zeros(len(long_lat_dep), Float) |
---|
4403 |   quantity = zeros(num_points, Float) |
---|
4404 | Â Â |
---|
4405 | #Â Â print 'num',num_points |
---|
4406 |   for lat_i, _ in enumerate(lat): |
---|
4407 |     for long_i, _ in enumerate(long): |
---|
4408 | Â Â Â Â Â Â q_index =Â lat_i*lenlong+long_i |
---|
4409 | Â Â Â Â Â Â lld_index =Â long_i*lenlat+lat_i |
---|
4410 | #Â Â Â Â Â Â print 'lat_i', lat_i, 'long_i',long_i, 'q_index', q_index, 'lld_index', lld_index |
---|
4411 |       temp = long_lat_dep[lld_index, QUANTITY] |
---|
4412 | Â Â Â Â Â Â quantity[q_index]Â =Â temp |
---|
4413 | Â Â Â Â Â Â |
---|
4414 |   return long, lat, quantity |
---|
4415 | |
---|
4416 | ####Â END URS 2 SWWÂ ### |
---|
4417 | |
---|
4418 | #### URS UNGRIDDED 2 SWW ### |
---|
4419 | |
---|
4420 | ### PRODUCING THE POINTS NEEDED FILE ### |
---|
4421 | |
---|
4422 | # Ones used for FESA 2007 results |
---|
4423 | #LL_LAT = -50.0 |
---|
4424 | #LL_LONG = 80.0 |
---|
4425 | #GRID_SPACING = 1.0/60.0 |
---|
4426 | #LAT_AMOUNT = 4800 |
---|
4427 | #LONG_AMOUNT = 3600 |
---|
4428 | |
---|
4429 | def URS_points_needed_to_file(file_name, boundary_polygon, zone, |
---|
4430 |                ll_lat, ll_long, |
---|
4431 |                grid_spacing, |
---|
4432 |                lat_amount, long_amount, |
---|
4433 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â isSouthernHemisphere=True, |
---|
4434 |                export_csv=False, use_cache=False, |
---|
4435 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=False): |
---|
4436 | Â Â """ |
---|
4437 | Â Â Given the info to replicate the URS grid and a polygon output |
---|
4438 | Â Â a file that specifies the cloud of boundary points for URS. |
---|
4439 | |
---|
4440 |   This creates a .urs file. This is in the format used by URS; |
---|
4441 | Â Â 1st line is the number of points, |
---|
4442 | Â Â each line after represents a point,in lats and longs. |
---|
4443 | Â Â |
---|
4444 | Â Â Note: The polygon cannot cross zones or hemispheres. |
---|
4445 | |
---|
4446 | Â Â A work-a-round for different zones or hemispheres is to run this twice, |
---|
4447 | Â Â once for each zone, and then combine the output. |
---|
4448 | Â Â |
---|
4449 | Â Â file_name - name of the urs file produced for David. |
---|
4450 | Â Â boundary_polygon - a list of points that describes a polygon. |
---|
4451 | Â Â Â Â Â Â Â Â Â Â Â The last point is assumed ot join the first point. |
---|
4452 | Â Â Â Â Â Â Â Â Â Â Â This is in UTM (lat long would be better though) |
---|
4453 | |
---|
4454 | Â Â Â This is info about the URS model that needs to be inputted. |
---|
4455 | Â Â Â |
---|
4456 | Â Â ll_lat - lower left latitude, in decimal degrees |
---|
4457 | Â Â ll-long - lower left longitude, in decimal degrees |
---|
4458 | Â Â grid_spacing - in deciamal degrees |
---|
4459 | Â Â lat_amount - number of latitudes |
---|
4460 | Â Â long_amount- number of longs |
---|
4461 | |
---|
4462 | |
---|
4463 |   Don't add the file extension. It will be added. |
---|
4464 | Â Â """ |
---|
4465 |   geo = URS_points_needed(boundary_polygon, zone, ll_lat, ll_long, |
---|
4466 |               grid_spacing, |
---|
4467 |               lat_amount, long_amount, isSouthernHemisphere, |
---|
4468 |               use_cache, verbose) |
---|
4469 |   if not file_name[-4:] == ".urs": |
---|
4470 | Â Â Â Â file_name +=Â ".urs" |
---|
4471 |   geo.export_points_file(file_name, isSouthHemisphere=isSouthernHemisphere) |
---|
4472 |   if export_csv: |
---|
4473 |     if file_name[-4:] == ".urs": |
---|
4474 | Â Â Â Â Â Â file_name =Â file_name[:-4]Â +Â ".csv" |
---|
4475 | Â Â Â Â geo.export_points_file(file_name) |
---|
4476 |   return geo |
---|
4477 | |
---|
4478 | def URS_points_needed(boundary_polygon, zone, ll_lat, |
---|
4479 |            ll_long, grid_spacing, |
---|
4480 |            lat_amount, long_amount, isSouthHemisphere=True, |
---|
4481 |            use_cache=False, verbose=False): |
---|
4482 | Â Â args =Â (boundary_polygon, |
---|
4483 |       zone, ll_lat, |
---|
4484 |       ll_long, grid_spacing, |
---|
4485 |       lat_amount, long_amount, isSouthHemisphere) |
---|
4486 | Â Â kwargs =Â {}Â |
---|
4487 |   if use_cache is True: |
---|
4488 | Â Â Â Â try: |
---|
4489 |       from anuga.caching import cache |
---|
4490 | Â Â Â Â except: |
---|
4491 | Â Â Â Â Â Â msg =Â 'Caching was requested, but caching module'+\ |
---|
4492 | Â Â Â Â Â Â Â Â Â 'could not be imported' |
---|
4493 |       raise msg |
---|
4494 | |
---|
4495 | |
---|
4496 | Â Â Â Â geo =Â cache(_URS_points_needed, |
---|
4497 |          args, kwargs, |
---|
4498 | Â Â Â Â Â Â Â Â Â verbose=verbose, |
---|
4499 | Â Â Â Â Â Â Â Â Â compression=False) |
---|
4500 | Â Â else: |
---|
4501 |     geo = apply(_URS_points_needed, args, kwargs) |
---|
4502 | |
---|
4503 |   return geo |
---|
4504 | |
---|
4505 | def _URS_points_needed(boundary_polygon, |
---|
4506 |            zone, ll_lat, |
---|
4507 |            ll_long, grid_spacing, |
---|
4508 |            lat_amount, long_amount, |
---|
4509 | Â Â Â Â Â Â Â Â Â Â Â Â isSouthHemisphere): |
---|
4510 | Â Â """ |
---|
4511 | Â Â boundary_polygon - a list of points that describes a polygon. |
---|
4512 | Â Â Â Â Â Â Â Â Â Â Â The last point is assumed ot join the first point. |
---|
4513 | Â Â Â Â Â Â Â Â Â Â Â This is in UTM (lat long would b better though) |
---|
4514 | |
---|
4515 | Â Â ll_lat - lower left latitude, in decimal degrees |
---|
4516 | Â Â ll-long - lower left longitude, in decimal degrees |
---|
4517 | Â Â grid_spacing - in deciamal degrees |
---|
4518 | |
---|
4519 | Â Â """ |
---|
4520 | Â Â |
---|
4521 |   from sets import ImmutableSet |
---|
4522 | Â Â |
---|
4523 | Â Â msg =Â "grid_spacing can not be zero" |
---|
4524 |   assert not grid_spacing == 0, msg |
---|
4525 | Â Â a =Â boundary_polygon |
---|
4526 |   # List of segments. Each segment is two points. |
---|
4527 |   segs = [i and [a[i-1], a[i]] or [a[len(a)-1], a[0]] for i in range(len(a))] |
---|
4528 | Â Â # convert the segs to Lat's and longs. |
---|
4529 | Â Â |
---|
4530 | Â Â # Don't assume the zone of the segments is the same as the lower left |
---|
4531 |   # corner of the lat long data!! They can easily be in different zones |
---|
4532 | Â Â |
---|
4533 | Â Â lat_long_set =Â ImmutableSet() |
---|
4534 |   for seg in segs: |
---|
4535 |     points_lat_long = points_needed(seg, ll_lat, ll_long, grid_spacing, |
---|
4536 |            lat_amount, long_amount, zone, isSouthHemisphere) |
---|
4537 | Â Â Â Â lat_long_set |=Â ImmutableSet(points_lat_long) |
---|
4538 |   if lat_long_set == ImmutableSet([]): |
---|
4539 | Â Â Â Â msg =Â """URS region specified and polygon does not overlap.""" |
---|
4540 |     raise ValueError, msg |
---|
4541 | |
---|
4542 | Â Â # Warning there is no info in geospatial saying the hemisphere of |
---|
4543 |   # these points. There should be. |
---|
4544 | Â Â geo =Â Geospatial_data(data_points=list(lat_long_set), |
---|
4545 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â points_are_lats_longs=True) |
---|
4546 |   return geo |
---|
4547 | Â Â |
---|
4548 | def points_needed(seg, ll_lat, ll_long, grid_spacing, |
---|
4549 |          lat_amount, long_amount, zone, |
---|
4550 | Â Â Â Â Â Â Â Â Â isSouthHemisphere): |
---|
4551 | Â Â """ |
---|
4552 | Â Â seg is two points, in UTM |
---|
4553 | Â Â return a list of the points, in lats and longs that are needed to |
---|
4554 | Â Â interpolate any point on the segment. |
---|
4555 | Â Â """ |
---|
4556 |   from math import sqrt |
---|
4557 | Â Â #print "zone",zone |
---|
4558 | Â Â geo_reference =Â Geo_reference(zone=zone) |
---|
4559 | Â Â #print "seg", seg |
---|
4560 | Â Â geo =Â Geospatial_data(seg,geo_reference=geo_reference) |
---|
4561 | Â Â seg_lat_long =Â geo.get_data_points(as_lat_long=True, |
---|
4562 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â isSouthHemisphere=isSouthHemisphere) |
---|
4563 | Â Â #print "seg_lat_long", seg_lat_long |
---|
4564 | Â Â # 1.415 = 2^0.5, rounded up.... |
---|
4565 | Â Â sqrt_2_rounded_up =Â 1.415 |
---|
4566 |   buffer = sqrt_2_rounded_up * grid_spacing |
---|
4567 | Â Â |
---|
4568 |   max_lat = max(seg_lat_long[0][0], seg_lat_long[1][0]) + buffer |
---|
4569 |   max_long = max(seg_lat_long[0][1], seg_lat_long[1][1]) + buffer |
---|
4570 |   min_lat = min(seg_lat_long[0][0], seg_lat_long[1][0]) - buffer |
---|
4571 |   min_long = min(seg_lat_long[0][1], seg_lat_long[1][1]) - buffer |
---|
4572 | |
---|
4573 | Â Â #print "min_long", min_long |
---|
4574 | Â Â #print "ll_long", ll_long |
---|
4575 | Â Â #print "grid_spacing", grid_spacing |
---|
4576 | Â Â first_row =Â (min_long -Â ll_long)/grid_spacing |
---|
4577 | Â Â # To round up |
---|
4578 | Â Â first_row_long =Â int(round(first_row +Â 0.5)) |
---|
4579 | Â Â #print "first_row", first_row_long |
---|
4580 | |
---|
4581 | Â Â last_row =Â (max_long -Â ll_long)/grid_spacing # round down |
---|
4582 | Â Â last_row_long =Â int(round(last_row)) |
---|
4583 | Â Â #print "last_row",last_row _long |
---|
4584 | Â Â |
---|
4585 | Â Â first_row =Â (min_lat -Â ll_lat)/grid_spacing |
---|
4586 | Â Â # To round up |
---|
4587 | Â Â first_row_lat =Â int(round(first_row +Â 0.5)) |
---|
4588 | Â Â #print "first_row", first_row_lat |
---|
4589 | |
---|
4590 | Â Â last_row =Â (max_lat -Â ll_lat)/grid_spacing # round down |
---|
4591 | Â Â last_row_lat =Â int(round(last_row)) |
---|
4592 | Â Â #print "last_row",last_row_lat |
---|
4593 | |
---|
4594 | Â Â # to work out the max distance - |
---|
4595 | Â Â # 111120 - horizontal distance between 1 deg latitude. |
---|
4596 | Â Â #max_distance = sqrt_2_rounded_up * 111120 * grid_spacing |
---|
4597 | Â Â max_distance =Â 157147.4112Â *Â grid_spacing |
---|
4598 | Â Â #print "max_distance", max_distance #2619.12 m for 1 minute |
---|
4599 | Â Â points_lat_long =Â [] |
---|
4600 | Â Â # Create a list of the lat long points to include. |
---|
4601 |   for index_lat in range(first_row_lat, last_row_lat + 1): |
---|
4602 |     for index_long in range(first_row_long, last_row_long + 1): |
---|
4603 | Â Â Â Â Â Â #print "index_lat", index_lat |
---|
4604 | Â Â Â Â Â Â #print "index_long", index_long |
---|
4605 | Â Â Â Â Â Â lat =Â ll_lat +Â index_lat*grid_spacing |
---|
4606 |       long = ll_long + index_long*grid_spacing |
---|
4607 | |
---|
4608 | Â Â Â Â Â Â #filter here to keep good points |
---|
4609 |       if keep_point(lat, long, seg, max_distance): |
---|
4610 |         points_lat_long.append((lat, long)) #must be hashable |
---|
4611 | Â Â #print "points_lat_long", points_lat_long |
---|
4612 | |
---|
4613 | Â Â # Now that we have these points, lets throw ones out that are too far away |
---|
4614 |   return points_lat_long |
---|
4615 | |
---|
4616 | def keep_point(lat, long, seg, max_distance): |
---|
4617 | Â Â """ |
---|
4618 | Â Â seg is two points, UTM |
---|
4619 | Â Â """ |
---|
4620 |   from math import sqrt |
---|
4621 |   _ , x0, y0 = redfearn(lat, long) |
---|
4622 | Â Â x1 =Â seg[0][0] |
---|
4623 | Â Â y1 =Â seg[0][1] |
---|
4624 | Â Â x2 =Â seg[1][0] |
---|
4625 | Â Â y2 =Â seg[1][1] |
---|
4626 | Â Â x2_1 =Â x2-x1 |
---|
4627 | Â Â y2_1 =Â y2-y1 |
---|
4628 | Â Â try: |
---|
4629 | Â Â Â Â d =Â abs((x2_1)*(y1-y0)-(x1-x0)*(y2_1))/sqrt(Â \ |
---|
4630 | Â Â Â Â Â Â (x2_1)*(x2_1)+(y2_1)*(y2_1)) |
---|
4631 |   except ZeroDivisionError: |
---|
4632 | Â Â Â Â #print "seg", seg |
---|
4633 | Â Â Â Â #print "x0", x0 |
---|
4634 | Â Â Â Â #print "y0", y0 |
---|
4635 |     if sqrt((x2_1)*(x2_1)+(y2_1)*(y2_1)) == 0 and \ |
---|
4636 | Â Â Â Â Â Â abs((x2_1)*(y1-y0)-(x1-x0)*(y2_1))Â ==Â 0: |
---|
4637 |       return True |
---|
4638 | Â Â Â Â else: |
---|
4639 |       return False |
---|
4640 | Â Â |
---|
4641 |   if d <= max_distance: |
---|
4642 |     return True |
---|
4643 | Â Â else: |
---|
4644 |     return False |
---|
4645 | Â Â |
---|
4646 | Â Â #### CONVERTING UNGRIDDED URS DATA TO AN SWW FILE #### |
---|
4647 | Â Â |
---|
4648 | WAVEHEIGHT_MUX_LABEL =Â '_waveheight-z-mux' |
---|
4649 | EAST_VELOCITY_LABEL =Â '_velocity-e-mux' |
---|
4650 | NORTH_VELOCITY_LABEL =Â '_velocity-n-mux'Â |
---|
4651 | def urs_ungridded2sww(basename_in='o', basename_out=None, verbose=False, |
---|
4652 |            mint=None, maxt=None, |
---|
4653 | Â Â Â Â Â Â Â Â Â Â Â mean_stage=0, |
---|
4654 | Â Â Â Â Â Â Â Â Â Â Â origin=None, |
---|
4655 | Â Â Â Â Â Â Â Â Â Â Â hole_points_UTM=None, |
---|
4656 | Â Â Â Â Â Â Â Â Â Â Â zscale=1): |
---|
4657 | Â Â """Â Â |
---|
4658 | Â Â Convert URS C binary format for wave propagation to |
---|
4659 | Â Â sww format native to abstract_2d_finite_volumes. |
---|
4660 | |
---|
4661 | |
---|
4662 | Â Â Specify only basename_in and read files of the form |
---|
4663 | Â Â basefilename_velocity-z-mux, basefilename_velocity-e-mux and |
---|
4664 | Â Â basefilename_waveheight-n-mux containing relative height, |
---|
4665 | Â Â x-velocity and y-velocity, respectively. |
---|
4666 | |
---|
4667 | Â Â Also convert latitude and longitude to UTM. All coordinates are |
---|
4668 | Â Â assumed to be given in the GDA94 datum. The latitude and longitude |
---|
4669 | Â Â information is assumed ungridded grid. |
---|
4670 | |
---|
4671 | Â Â min's and max's: If omitted - full extend is used. |
---|
4672 | Â Â To include a value min ans max may equal it. |
---|
4673 | Â Â Lat and lon are assumed to be in decimal degrees. |
---|
4674 | Â Â |
---|
4675 | Â Â origin is a 3-tuple with geo referenced |
---|
4676 | Â Â UTM coordinates (zone, easting, northing) |
---|
4677 | Â Â It will be the origin of the sww file. This shouldn't be used, |
---|
4678 | Â Â since all of anuga should be able to handle an arbitary origin. |
---|
4679 | Â Â The mux point info is NOT relative to this origin. |
---|
4680 | |
---|
4681 | |
---|
4682 | Â Â URS C binary format has data orgainised as TIME, LONGITUDE, LATITUDE |
---|
4683 | Â Â which means that latitude is the fastest |
---|
4684 | Â Â varying dimension (row major order, so to speak) |
---|
4685 | |
---|
4686 | Â Â In URS C binary the latitudes and longitudes are in assending order. |
---|
4687 | |
---|
4688 | Â Â Note, interpolations of the resulting sww file will be different |
---|
4689 |   from results of urs2sww. This is due to the interpolation |
---|
4690 | Â Â function used, and the different grid structure between urs2sww |
---|
4691 | Â Â and this function. |
---|
4692 | Â Â |
---|
4693 | Â Â Interpolating data that has an underlying gridded source can |
---|
4694 | Â Â easily end up with different values, depending on the underlying |
---|
4695 | Â Â mesh. |
---|
4696 | |
---|
4697 | Â Â consider these 4 points |
---|
4698 | Â Â 50Â -50 |
---|
4699 | |
---|
4700 | Â Â 0Â Â Â 0 |
---|
4701 | |
---|
4702 | Â Â The grid can be |
---|
4703 | Â Â Â - |
---|
4704 | Â Â |\|Â Â A |
---|
4705 | Â Â Â - |
---|
4706 | Â Â Â or; |
---|
4707 | Â Â Â - |
---|
4708 | Â Â Â |/|Â Â B |
---|
4709 | Â Â Â - |
---|
4710 | Â Â Â If a point is just below the center of the midpoint, it will have a |
---|
4711 | Â Â Â +ve value in grid A and a -ve value in grid B. |
---|
4712 | Â Â """Â |
---|
4713 |   from anuga.mesh_engine.mesh_engine import NoTrianglesError |
---|
4714 |   from anuga.pmesh.mesh import Mesh |
---|
4715 | |
---|
4716 | Â Â files_in =Â [basename_in +Â WAVEHEIGHT_MUX_LABEL, |
---|
4717 | Â Â Â Â Â Â Â Â basename_in +Â EAST_VELOCITY_LABEL, |
---|
4718 | Â Â Â Â Â Â Â Â basename_in +Â NORTH_VELOCITY_LABEL] |
---|
4719 | Â Â quantities =Â ['HA','UA','VA'] |
---|
4720 | |
---|
4721 | Â Â # instanciate urs_points of the three mux files. |
---|
4722 | Â Â mux =Â {} |
---|
4723 |   for quantity, file in map(None, quantities, files_in): |
---|
4724 | Â Â Â Â mux[quantity]Â =Â Urs_points(file) |
---|
4725 | Â Â Â Â |
---|
4726 | Â Â # Could check that the depth is the same. (hashing) |
---|
4727 | |
---|
4728 | Â Â # handle to a mux file to do depth stuff |
---|
4729 | Â Â a_mux =Â mux[quantities[0]] |
---|
4730 | Â Â |
---|
4731 | Â Â # Convert to utm |
---|
4732 | Â Â lat =Â a_mux.lonlatdep[:,1] |
---|
4733 |   long = a_mux.lonlatdep[:,0] |
---|
4734 |   points_utm, zone = convert_from_latlon_to_utm( \ |
---|
4735 |     latitudes=lat, longitudes=long) |
---|
4736 | Â Â #print "points_utm", points_utm |
---|
4737 | Â Â #print "zone", zone |
---|
4738 | |
---|
4739 | Â Â elevation =Â a_mux.lonlatdep[:,2]Â *Â -1Â # |
---|
4740 | Â Â |
---|
4741 | Â Â # grid ( create a mesh from the selected points) |
---|
4742 |   # This mesh has a problem. Triangles are streched over ungridded areas. |
---|
4743 | Â Â #Â If these areas could be described as holes in pmesh, that would be great |
---|
4744 | |
---|
4745 | Â Â # I can't just get the user to selection a point in the middle. |
---|
4746 | Â Â # A boundary is needed around these points. |
---|
4747 | Â Â # But if the zone of points is obvious enough auto-segment should do |
---|
4748 | Â Â # a good boundary. |
---|
4749 | Â Â mesh =Â Mesh() |
---|
4750 | Â Â mesh.add_vertices(points_utm) |
---|
4751 |   mesh.auto_segment(smooth_indents=True, expand_pinch=True) |
---|
4752 | Â Â # To try and avoid alpha shape 'hugging' too much |
---|
4753 | Â Â mesh.auto_segment(Â mesh.shape.get_alpha()*1.1Â ) |
---|
4754 |   if hole_points_UTM is not None: |
---|
4755 | Â Â Â Â point =Â ensure_absolute(hole_points_UTM) |
---|
4756 |     mesh.add_hole(point[0], point[1]) |
---|
4757 | Â Â try: |
---|
4758 |     mesh.generate_mesh(minimum_triangle_angle=0.0, verbose=False) |
---|
4759 |   except NoTrianglesError: |
---|
4760 | Â Â Â Â # This is a bit of a hack, going in and changing the |
---|
4761 | Â Â Â Â # data structure. |
---|
4762 | Â Â Â Â mesh.holes =Â [] |
---|
4763 |     mesh.generate_mesh(minimum_triangle_angle=0.0, verbose=False) |
---|
4764 | Â Â mesh_dic =Â mesh.Mesh2MeshList() |
---|
4765 | |
---|
4766 | Â Â #mesh.export_mesh_file(basename_in + '_168.tsh') |
---|
4767 | Â Â #import sys; sys.exit() |
---|
4768 | Â Â # These are the times of the mux file |
---|
4769 | Â Â mux_times =Â [] |
---|
4770 |   for i in range(a_mux.time_step_count): |
---|
4771 | Â Â Â Â mux_times.append(a_mux.time_step *Â i)Â |
---|
4772 |   mux_times_start_i, mux_times_fin_i = mux2sww_time(mux_times, mint, maxt) |
---|
4773 | Â Â times =Â mux_times[mux_times_start_i:mux_times_fin_i] |
---|
4774 | Â Â |
---|
4775 |   if mux_times_start_i == mux_times_fin_i: |
---|
4776 | Â Â Â Â # Close the mux files |
---|
4777 |     for quantity, file in map(None, quantities, files_in): |
---|
4778 | Â Â Â Â Â Â mux[quantity].close() |
---|
4779 | Â Â Â Â msg="Due to mint and maxt there's no time info in the boundary SWW." |
---|
4780 |     raise Exception, msg |
---|
4781 | Â Â Â Â |
---|
4782 | Â Â # If this raise is removed there is currently no downstream errors |
---|
4783 | Â Â Â Â Â Â |
---|
4784 | Â Â points_utm=ensure_numeric(points_utm) |
---|
4785 |   assert ensure_numeric(mesh_dic['generatedpointlist']) == \ |
---|
4786 | Â Â Â Â Â Â ensure_numeric(points_utm) |
---|
4787 | Â Â |
---|
4788 | Â Â volumes =Â mesh_dic['generatedtrianglelist'] |
---|
4789 | Â Â |
---|
4790 |   # write sww intro and grid stuff.  |
---|
4791 |   if basename_out is None: |
---|
4792 | Â Â Â Â swwname =Â basename_in +Â '.sww' |
---|
4793 | Â Â else: |
---|
4794 | Â Â Â Â swwname =Â basename_out +Â '.sww' |
---|
4795 | |
---|
4796 |   if verbose: print 'Output to ', swwname |
---|
4797 |   outfile = NetCDFFile(swwname, 'w') |
---|
4798 | Â Â # For a different way of doing this, check out tsh2sww |
---|
4799 | Â Â # work out sww_times and the index range this covers |
---|
4800 | Â Â sww =Â Write_sww() |
---|
4801 |   sww.store_header(outfile, times, len(volumes), len(points_utm), |
---|
4802 | Â Â Â Â Â Â Â Â Â Â Â verbose=verbose,sww_precision=Float) |
---|
4803 | Â Â outfile.mean_stage =Â mean_stage |
---|
4804 | Â Â outfile.zscale =Â zscale |
---|
4805 | |
---|
4806 |   sww.store_triangulation(outfile, points_utm, volumes, |
---|
4807 |               elevation, zone, new_origin=origin, |
---|
4808 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=verbose) |
---|
4809 | Â Â |
---|
4810 |   if verbose: print 'Converting quantities' |
---|
4811 | Â Â j =Â 0 |
---|
4812 | Â Â # Read in a time slice from each mux file and write it to the sww file |
---|
4813 |   for ha, ua, va in map(None, mux['HA'], mux['UA'], mux['VA']): |
---|
4814 |     if j >= mux_times_start_i and j < mux_times_fin_i: |
---|
4815 | Â Â Â Â Â Â stage =Â zscale*ha +Â mean_stage |
---|
4816 | Â Â Â Â Â Â h =Â stage -Â elevation |
---|
4817 | Â Â Â Â Â Â xmomentum =Â ua*h |
---|
4818 | Â Â Â Â Â Â ymomentum =Â -1*va*h # -1 since in mux files south is positive. |
---|
4819 |       sww.store_quantities(outfile, |
---|
4820 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â slice_index=j -Â mux_times_start_i, |
---|
4821 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=verbose, |
---|
4822 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â stage=stage, |
---|
4823 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â xmomentum=xmomentum, |
---|
4824 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ymomentum=ymomentum, |
---|
4825 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â sww_precision=Float) |
---|
4826 | Â Â Â Â j +=Â 1 |
---|
4827 |   if verbose: sww.verbose_quantities(outfile) |
---|
4828 | Â Â outfile.close() |
---|
4829 | Â Â # |
---|
4830 | Â Â # Do some conversions while writing the sww file |
---|
4831 | |
---|
4832 | Â Â ################################## |
---|
4833 | Â Â # READ MUX2 FILES line of points # |
---|
4834 | Â Â ################################## |
---|
4835 | |
---|
4836 | WAVEHEIGHT_MUX2_LABEL =Â '_waveheight-z-mux2' |
---|
4837 | EAST_VELOCITY_MUX2_LABEL =Â '_velocity-e-mux2' |
---|
4838 | NORTH_VELOCITY_MUX2_LABEL =Â '_velocity-n-mux2'Â Â |
---|
4839 | |
---|
4840 | def read_mux2_py(filenames,weights): |
---|
4841 | |
---|
4842 |   from Numeric import ones,Float,compress,zeros,arange |
---|
4843 |   from urs_ext import read_mux2 |
---|
4844 | |
---|
4845 | Â Â numSrc=len(filenames) |
---|
4846 | |
---|
4847 | Â Â file_params=-1*ones(3,Float)#[nsta,dt,nt] |
---|
4848 | Â Â write=0Â #if true write txt files to current directory as well |
---|
4849 | Â Â data=read_mux2(numSrc,filenames,weights,file_params,write) |
---|
4850 | |
---|
4851 | Â Â msg='File parameter values were not read in correctly from c file' |
---|
4852 |   assert len(compress(file_params>0,file_params))!=0,msg |
---|
4853 | Â Â msg='The number of stations specifed in the c array and in the file are inconsitent' |
---|
4854 |   assert file_params[0]==data.shape[0],msg |
---|
4855 | Â Â |
---|
4856 | Â Â nsta=int(file_params[0]) |
---|
4857 | Â Â msg='Must have at least one station' |
---|
4858 |   assert nsta>0,msg |
---|
4859 | Â Â dt=file_params[1] |
---|
4860 | Â Â msg='Must have a postive timestep' |
---|
4861 |   assert dt>0,msg |
---|
4862 | Â Â nt=int(file_params[2]) |
---|
4863 | Â Â msg='Must have at least one gauge value' |
---|
4864 |   assert nt>0,msg |
---|
4865 | Â Â |
---|
4866 | Â Â OFFSET=5Â #number of site parameters p passed back with data |
---|
4867 | Â Â #p=[geolat,geolon,depth,start_tstep,finish_tstep] |
---|
4868 | |
---|
4869 | Â Â times=dt*arange(1,(data.shape[1]-OFFSET)+1) |
---|
4870 | Â Â latitudes=zeros(data.shape[0],Float) |
---|
4871 | Â Â longitudes=zeros(data.shape[0],Float) |
---|
4872 | Â Â elevation=zeros(data.shape[0],Float) |
---|
4873 | Â Â quantity=zeros((data.shape[0],data.shape[1]-OFFSET),Float) |
---|
4874 | Â Â starttime=1e16 |
---|
4875 |   for i in range(0,data.shape[0]): |
---|
4876 | Â Â Â Â latitudes[i]=data[i][data.shape[1]-OFFSET] |
---|
4877 | Â Â Â Â longitudes[i]=data[i][data.shape[1]-OFFSET+1] |
---|
4878 | Â Â Â Â elevation[i]=-data[i][data.shape[1]-OFFSET+2] |
---|
4879 | Â Â Â Â quantity[i]=data[i][:-OFFSET] |
---|
4880 | Â Â Â Â starttime=min(dt*data[i][data.shape[1]-OFFSET+3],starttime) |
---|
4881 | Â Â Â Â |
---|
4882 |   return times, latitudes, longitudes, elevation, quantity, starttime |
---|
4883 | |
---|
4884 | def mux2sww_time(mux_times, mint, maxt): |
---|
4885 | Â Â """ |
---|
4886 | Â Â """ |
---|
4887 | |
---|
4888 |   if mint == None: |
---|
4889 | Â Â Â Â mux_times_start_i =Â 0 |
---|
4890 | Â Â else: |
---|
4891 |     mux_times_start_i = searchsorted(mux_times, mint) |
---|
4892 | Â Â Â Â |
---|
4893 |   if maxt == None: |
---|
4894 | Â Â Â Â mux_times_fin_i =Â len(mux_times) |
---|
4895 | Â Â else: |
---|
4896 | Â Â Â Â maxt +=Â 0.5Â # so if you specify a time where there is |
---|
4897 | Â Â Â Â Â Â Â Â Â Â # data that time will be included |
---|
4898 |     mux_times_fin_i = searchsorted(mux_times, maxt) |
---|
4899 | |
---|
4900 |   return mux_times_start_i, mux_times_fin_i |
---|
4901 | |
---|
4902 | |
---|
4903 | def urs2sts(basename_in, basename_out = None, weights=None, |
---|
4904 |       verbose = False, origin = None, |
---|
4905 | Â Â Â Â Â Â mean_stage=0.0,zscale=1.0, |
---|
4906 |       minlat = None, maxlat = None, |
---|
4907 |       minlon = None, maxlon = None): |
---|
4908 | Â Â """Convert URS mux2 format for wave propagation to sts format |
---|
4909 | |
---|
4910 | Â Â Also convert latitude and longitude to UTM. All coordinates are |
---|
4911 | Â Â assumed to be given in the GDA94 datum |
---|
4912 | |
---|
4913 | Â Â origin is a 3-tuple with geo referenced |
---|
4914 | Â Â UTM coordinates (zone, easting, northing) |
---|
4915 | Â Â """ |
---|
4916 |   import os |
---|
4917 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
4918 |   from Numeric import Float, Int, Int32, searchsorted, zeros, array |
---|
4919 |   from Numeric import allclose, around,ones,Float |
---|
4920 |   from types import ListType,StringType |
---|
4921 |   from operator import __and__ |
---|
4922 | Â Â |
---|
4923 |   if not isinstance(basename_in, ListType): |
---|
4924 |     if verbose: print 'Reading single source' |
---|
4925 | Â Â Â Â basename_in=[basename_in] |
---|
4926 | |
---|
4927 | Â Â # Check that basename is a list of strings |
---|
4928 |   if not reduce(__and__, map(lambda z:isinstance(z,StringType),basename_in)): |
---|
4929 | Â Â Â Â msg=Â 'basename_in must be a string or list of strings' |
---|
4930 |     raise Exception, msg |
---|
4931 | |
---|
4932 | Â Â # Find the number of sources to be used |
---|
4933 | Â Â numSrc=len(basename_in) |
---|
4934 | |
---|
4935 | Â Â # A weight must be specified for each source |
---|
4936 |   if weights is None: |
---|
4937 | Â Â Â Â weights=ones(numSrc,Float)/numSrc |
---|
4938 | Â Â else: |
---|
4939 | Â Â Â Â weights =Â ensure_numeric(weights) |
---|
4940 | Â Â Â Â msg =Â 'When combining multiple sources must specify a weight for '+\ |
---|
4941 | Â Â Â Â Â Â Â 'mux2 source file' |
---|
4942 |     assert len(weights)== numSrc, msg |
---|
4943 | |
---|
4944 | Â Â precision =Â Float |
---|
4945 | |
---|
4946 | Â Â msg =Â 'Must use latitudes and longitudes for minlat, maxlon etc' |
---|
4947 | |
---|
4948 |   if minlat != None: |
---|
4949 |     assert -90 < minlat < 90 , msg |
---|
4950 |   if maxlat != None: |
---|
4951 |     assert -90 < maxlat < 90 , msg |
---|
4952 |     if minlat != None: |
---|
4953 |       assert maxlat > minlat |
---|
4954 |   if minlon != None: |
---|
4955 |     assert -180 < minlon < 180 , msg |
---|
4956 |   if maxlon != None: |
---|
4957 |     assert -180 < maxlon < 180 , msg |
---|
4958 |     if minlon != None: |
---|
4959 |       assert maxlon > minlon |
---|
4960 | |
---|
4961 |   if basename_out is None: |
---|
4962 | Â Â Â Â stsname =Â basename_in[0]Â +Â '.sts' |
---|
4963 | Â Â else: |
---|
4964 | Â Â Â Â stsname =Â basename_out +Â '.sts' |
---|
4965 | |
---|
4966 | Â Â files_in=[[],[],[]] |
---|
4967 |   for files in basename_in: |
---|
4968 | Â Â Â Â files_in[0].append(files +Â WAVEHEIGHT_MUX2_LABEL), |
---|
4969 | Â Â Â Â files_in[1].append(files +Â EAST_VELOCITY_MUX2_LABEL) |
---|
4970 | Â Â Â Â files_in[2].append(files +Â NORTH_VELOCITY_MUX2_LABEL) |
---|
4971 | Â Â Â Â |
---|
4972 | Â Â #files_in = [basename_in + WAVEHEIGHT_MUX2_LABEL, |
---|
4973 | Â Â #Â Â Â Â Â Â basename_in + EAST_VELOCITY_MUX2_LABEL, |
---|
4974 | Â Â #Â Â Â Â Â Â basename_in + NORTH_VELOCITY_MUX2_LABEL] |
---|
4975 | Â Â |
---|
4976 | Â Â quantities =Â ['HA','UA','VA'] |
---|
4977 | |
---|
4978 | Â Â # For each source file check that there exists three files ending with: |
---|
4979 | Â Â # WAVEHEIGHT_MUX2_LABEL, |
---|
4980 | Â Â # EAST_VELOCITY_MUX2_LABEL, and |
---|
4981 | Â Â # NORTH_VELOCITY_MUX2_LABEL |
---|
4982 |   for i in range(len(quantities)): |
---|
4983 |     for file_in in files_in[i]: |
---|
4984 |       if (os.access(file_in, os.F_OK) == 0): |
---|
4985 |         msg = 'File %s does not exist or is not accessible' %file_in |
---|
4986 |         raise IOError, msg |
---|
4987 | |
---|
4988 | Â Â #need to do this for velocity-e-mux2 and velocity-n-mux2 files as well |
---|
4989 | Â Â #for now set x_momentum and y_moentum quantities to zero |
---|
4990 |   if (verbose): print 'reading mux2 file' |
---|
4991 | Â Â mux={} |
---|
4992 |   for i,quantity in enumerate(quantities): |
---|
4993 |     times_urs, latitudes_urs, longitudes_urs, elevation, mux[quantity],starttime = read_mux2_py(files_in[i],weights) |
---|
4994 |     if quantity!=quantities[0]: |
---|
4995 |       msg='%s, %s and %s have inconsitent gauge data'%(files_in[0],files_in[1],files_in[2]) |
---|
4996 |       assert allclose(times_urs,times_urs_old),msg |
---|
4997 |       assert allclose(latitudes_urs,latitudes_urs_old),msg |
---|
4998 |       assert allclose(longitudes_urs,longitudes_urs_old),msg |
---|
4999 |       assert allclose(elevation,elevation_old),msg |
---|
5000 |       assert allclose(starttime,starttime_old) |
---|
5001 | Â Â Â Â times_urs_old=times_urs |
---|
5002 | Â Â Â Â latitudes_urs_old=latitudes_urs |
---|
5003 | Â Â Â Â longitudes_urs_old=longitudes_urs |
---|
5004 | Â Â Â Â elevation_old=elevation |
---|
5005 | Â Â Â Â starttime_old=starttime |
---|
5006 | Â Â Â Â |
---|
5007 |   if (minlat is not None) and (minlon is not None) and (maxlat is not None) and (maxlon is not None): |
---|
5008 |     if verbose: print 'Cliping urs data' |
---|
5009 | Â Â Â Â latitudes =Â compress((latitudes_urs>=minlat)&(latitudes_urs<=maxlat)&(longitudes_urs>=minlon)&(longitudes_urs<=maxlon),latitudes_urs) |
---|
5010 | Â Â Â Â longitudes =Â compress((latitudes_urs>=minlat)&(latitudes_urs<=maxlat)&(longitudes_urs>=minlon)&(longitudes_urs<=maxlon),longitudes_urs) |
---|
5011 | Â Â Â Â times =Â compress((latitudes_urs>=minlat)&(latitudes_urs<=maxlat)&(longitudes_urs>=minlon)&(longitudes_urs<=maxlon),times_urs) |
---|
5012 | Â Â else: |
---|
5013 | Â Â Â Â latitudes=latitudes_urs |
---|
5014 | Â Â Â Â longitudes=longitudes_urs |
---|
5015 | Â Â Â Â times=times_urs |
---|
5016 | |
---|
5017 | Â Â msg='File is empty and or clipped region not in file region' |
---|
5018 |   assert len(latitudes>0),msg |
---|
5019 | |
---|
5020 | Â Â number_of_points =Â latitudes.shape[0] |
---|
5021 | Â Â number_of_times =Â times.shape[0] |
---|
5022 | Â Â number_of_latitudes =Â latitudes.shape[0] |
---|
5023 | Â Â number_of_longitudes =Â longitudes.shape[0] |
---|
5024 | |
---|
5025 | Â Â # NetCDF file definition |
---|
5026 |   outfile = NetCDFFile(stsname, 'w') |
---|
5027 | |
---|
5028 | Â Â description =Â 'Converted from URS mux2 files: %s'\ |
---|
5029 | Â Â Â Â Â Â Â Â Â %(basename_in) |
---|
5030 | Â Â |
---|
5031 | Â Â # Create new file |
---|
5032 | Â Â #starttime = times[0] |
---|
5033 | Â Â sts =Â Write_sts() |
---|
5034 |   sts.store_header(outfile, times+starttime,number_of_points, description=description, |
---|
5035 | Â Â Â Â Â Â Â Â Â Â Â verbose=verbose,sts_precision=Float) |
---|
5036 | Â Â |
---|
5037 | Â Â # Store |
---|
5038 |   from anuga.coordinate_transforms.redfearn import redfearn |
---|
5039 |   x = zeros(number_of_points, Float) #Easting |
---|
5040 |   y = zeros(number_of_points, Float) #Northing |
---|
5041 | |
---|
5042 | Â Â # Check zone boundaries |
---|
5043 |   refzone, _, _ = redfearn(latitudes[0],longitudes[0]) |
---|
5044 | |
---|
5045 |   for i in range(number_of_points): |
---|
5046 |     zone, easting, northing = redfearn(latitudes[i],longitudes[i]) |
---|
5047 | Â Â Â Â x[i]Â =Â easting |
---|
5048 | Â Â Â Â y[i]Â =Â northing |
---|
5049 | Â Â Â Â msg='all sts gauges need to be in the same zone' |
---|
5050 |     assert zone==refzone,msg |
---|
5051 | |
---|
5052 |   if origin is None: |
---|
5053 | Â Â Â Â origin =Â Geo_reference(refzone,min(x),min(y)) |
---|
5054 |   geo_ref = write_NetCDF_georeference(origin, outfile) |
---|
5055 | |
---|
5056 | Â Â z =Â elevation |
---|
5057 | Â Â |
---|
5058 | Â Â #print geo_ref.get_xllcorner() |
---|
5059 | Â Â #print geo_ref.get_yllcorner() |
---|
5060 | |
---|
5061 | Â Â z =Â resize(z,outfile.variables['z'][:].shape) |
---|
5062 | Â Â outfile.variables['x'][:]Â =Â x -Â geo_ref.get_xllcorner() |
---|
5063 | Â Â outfile.variables['y'][:]Â =Â y -Â geo_ref.get_yllcorner() |
---|
5064 |   outfile.variables['z'][:] = z       #FIXME HACK for bacwards compat. |
---|
5065 | Â Â outfile.variables['elevation'][:]Â =Â z |
---|
5066 | |
---|
5067 | Â Â stage =Â outfile.variables['stage'] |
---|
5068 | Â Â xmomentum =Â outfile.variables['xmomentum'] |
---|
5069 | Â Â ymomentum =outfile.variables['ymomentum'] |
---|
5070 | |
---|
5071 |   if verbose: print 'Converting quantities' |
---|
5072 |   for j in range(len(times)): |
---|
5073 |     for i in range(number_of_points): |
---|
5074 | Â Â Â Â Â Â w =Â zscale*mux['HA'][i,j]Â +Â mean_stage |
---|
5075 | Â Â Â Â Â Â h=w-elevation[i] |
---|
5076 | Â Â Â Â Â Â stage[j,i]Â =Â w |
---|
5077 | Â Â Â Â Â Â #delete following two lines once velcotu files are read in. |
---|
5078 | Â Â Â Â Â Â xmomentum[j,i]Â =Â mux['UA'][i,j]*h |
---|
5079 | Â Â Â Â Â Â ymomentum[j,i]Â =Â mux['VA'][i,j]*h |
---|
5080 | |
---|
5081 | Â Â outfile.close() |
---|
5082 | |
---|
5083 | def create_sts_boundary(order_file,stsname,lat_long=True): |
---|
5084 | Â Â """ |
---|
5085 | Â Â Â Â Create boundary segments from .sts file. Points can be stored in |
---|
5086 | Â Â arbitrary order within the .sts file. The order in which the .sts points |
---|
5087 | Â Â make up the boundary are given in order.txt file |
---|
5088 | Â Â """ |
---|
5089 | Â Â |
---|
5090 |   if not order_file[-3:] == 'txt': |
---|
5091 | Â Â Â Â msg =Â 'Order file must be a txt file' |
---|
5092 |     raise Exception, msg |
---|
5093 | |
---|
5094 | Â Â try: |
---|
5095 | Â Â Â Â fid=open(order_file,'r') |
---|
5096 | Â Â Â Â file_header=fid.readline() |
---|
5097 | Â Â Â Â lines=fid.readlines() |
---|
5098 | Â Â Â Â fid.close() |
---|
5099 | Â Â except: |
---|
5100 | Â Â Â Â msg =Â 'Cannot open %s'%filename |
---|
5101 |     raise msg |
---|
5102 | |
---|
5103 | Â Â header="index,longitude,latitude\n" |
---|
5104 | |
---|
5105 |   if not file_header==header: |
---|
5106 | Â Â Â Â msg =Â 'File must contain header\n'+header+"\n" |
---|
5107 |     raise Exception, msg |
---|
5108 | |
---|
5109 |   if len(lines)<2: |
---|
5110 | Â Â Â Â msg =Â 'File must contain at least two points' |
---|
5111 |     raise Exception, msg |
---|
5112 | |
---|
5113 | Â Â try: |
---|
5114 |     fid = NetCDFFile(stsname+'.sts', 'r') |
---|
5115 | Â Â except: |
---|
5116 | Â Â Â Â msg =Â 'Cannot open %s'%filename+'.sts' |
---|
5117 | |
---|
5118 | |
---|
5119 | Â Â xllcorner =Â fid.xllcorner[0] |
---|
5120 | Â Â yllcorner =Â fid.yllcorner[0] |
---|
5121 | Â Â #Points stored in sts file are normailsed to [xllcorner,yllcorner] but |
---|
5122 | Â Â #we cannot assume that boundary polygon will be. At least the |
---|
5123 | Â Â #additional points specified by the user after this function is called |
---|
5124 | Â Â x =Â fid.variables['x'][:]+xllcorner |
---|
5125 | Â Â y =Â fid.variables['y'][:]+yllcorner |
---|
5126 | |
---|
5127 |   x = reshape(x, (len(x),1)) |
---|
5128 |   y = reshape(y, (len(y),1)) |
---|
5129 |   sts_points = concatenate((x,y), axis=1) |
---|
5130 | |
---|
5131 | Â Â xllcorner =Â fid.xllcorner[0] |
---|
5132 | Â Â yllcorner =Â fid.yllcorner[0] |
---|
5133 | |
---|
5134 | Â Â boundary_polygon=[] |
---|
5135 |   for line in lines: |
---|
5136 | Â Â Â Â fields =Â line.split(',') |
---|
5137 | Â Â Â Â index=int(fields[0]) |
---|
5138 |     if lat_long: |
---|
5139 | Â Â Â Â Â Â zone,easting,northing=redfearn(float(fields[1]),float(fields[2])) |
---|
5140 |       if not zone == fid.zone[0]: |
---|
5141 | Â Â Â Â Â Â Â Â msg =Â 'Inconsitent zones' |
---|
5142 |         raise Exception, msg |
---|
5143 | Â Â Â Â else: |
---|
5144 | Â Â Â Â Â Â easting =Â float(fields[1]) |
---|
5145 | Â Â Â Â Â Â northing =Â float(fields[2]) |
---|
5146 |     if not allclose(array([easting,northing]),sts_points[index]): |
---|
5147 | Â Â Â Â Â Â msg =Â "Points in sts file do not match those in the"+\ |
---|
5148 | Â Â Â Â Â Â Â Â ".txt file spcifying the order of the boundary points" |
---|
5149 |       raise Exception, msg |
---|
5150 | Â Â Â Â boundary_polygon.append(sts_points[index].tolist()) |
---|
5151 | Â Â |
---|
5152 |   return boundary_polygon |
---|
5153 | |
---|
5154 | class Write_sww: |
---|
5155 |   from anuga.shallow_water.shallow_water_domain import Domain |
---|
5156 | |
---|
5157 | Â Â # FIXME (Ole): Hardwiring the conserved quantities like |
---|
5158 | Â Â # this could be a problem. I would prefer taking them from |
---|
5159 | Â Â # the instantiation of Domain. |
---|
5160 | Â Â # |
---|
5161 | Â Â # (DSG) There is not always a Domain instance when Write_sww is used. |
---|
5162 | Â Â # Check to see if this is the same level of hardwiring as is in |
---|
5163 | Â Â # shallow water doamain. |
---|
5164 | Â Â |
---|
5165 | Â Â sww_quantities =Â Domain.conserved_quantities |
---|
5166 | |
---|
5167 | |
---|
5168 | Â Â RANGE =Â '_range' |
---|
5169 | Â Â EXTREMA =Â ':extrema' |
---|
5170 | |
---|
5171 |   def __init__(self): |
---|
5172 | Â Â Â Â pass |
---|
5173 | Â Â |
---|
5174 |   def store_header(self, |
---|
5175 | Â Â Â Â Â Â Â Â Â Â Â outfile, |
---|
5176 | Â Â Â Â Â Â Â Â Â Â Â times, |
---|
5177 | Â Â Â Â Â Â Â Â Â Â Â number_of_volumes, |
---|
5178 | Â Â Â Â Â Â Â Â Â Â Â number_of_points, |
---|
5179 | Â Â Â Â Â Â Â Â Â Â Â description='Converted from XXX', |
---|
5180 | Â Â Â Â Â Â Â Â Â Â Â smoothing=True, |
---|
5181 | Â Â Â Â Â Â Â Â Â Â Â order=1, |
---|
5182 | Â Â Â Â Â Â Â Â Â Â Â sww_precision=Float32, |
---|
5183 | Â Â Â Â Â Â Â Â Â Â Â verbose=False): |
---|
5184 | Â Â Â Â """ |
---|
5185 | Â Â Â Â outfile - the name of the file that will be written |
---|
5186 | Â Â Â Â times - A list of the time slice times OR a start time |
---|
5187 | Â Â Â Â Note, if a list is given the info will be made relative. |
---|
5188 | Â Â Â Â number_of_volumes - the number of triangles |
---|
5189 | Â Â Â Â """ |
---|
5190 | Â Â |
---|
5191 | Â Â Â Â outfile.institution =Â 'Geoscience Australia' |
---|
5192 | Â Â Â Â outfile.description =Â description |
---|
5193 | |
---|
5194 | Â Â Â Â # For sww compatibility |
---|
5195 |     if smoothing is True: |
---|
5196 | Â Â Â Â Â Â # Smoothing to be depreciated |
---|
5197 | Â Â Â Â Â Â outfile.smoothing =Â 'Yes' |
---|
5198 | Â Â Â Â Â Â outfile.vertices_are_stored_uniquely =Â 'False' |
---|
5199 | Â Â Â Â else: |
---|
5200 | Â Â Â Â Â Â # Smoothing to be depreciated |
---|
5201 | Â Â Â Â Â Â outfile.smoothing =Â 'No' |
---|
5202 | Â Â Â Â Â Â outfile.vertices_are_stored_uniquely =Â 'True' |
---|
5203 | Â Â Â Â outfile.order =Â order |
---|
5204 | |
---|
5205 | Â Â Â Â try: |
---|
5206 | Â Â Â Â Â Â revision_number =Â get_revision_number() |
---|
5207 | Â Â Â Â except: |
---|
5208 | Â Â Â Â Â Â revision_number =Â None |
---|
5209 |     # Allow None to be stored as a string        |
---|
5210 | Â Â Â Â outfile.revision_number =Â str(revision_number)Â |
---|
5211 | |
---|
5212 | |
---|
5213 | Â Â Â Â |
---|
5214 | Â Â Â Â # times - A list or array of the time slice times OR a start time |
---|
5215 | Â Â Â Â # times = ensure_numeric(times) |
---|
5216 | Â Â Â Â # Start time in seconds since the epoch (midnight 1/1/1970) |
---|
5217 | |
---|
5218 | Â Â Â Â # This is being used to seperate one number from a list. |
---|
5219 | Â Â Â Â # what it is actually doing is sorting lists from numeric arrays. |
---|
5220 |     if type(times) is list or type(times) is ArrayType: |
---|
5221 | Â Â Â Â Â Â number_of_times =Â len(times) |
---|
5222 | Â Â Â Â Â Â times =Â ensure_numeric(times)Â |
---|
5223 |       if number_of_times == 0: |
---|
5224 | Â Â Â Â Â Â Â Â starttime =Â 0 |
---|
5225 | Â Â Â Â Â Â else: |
---|
5226 | Â Â Â Â Â Â Â Â starttime =Â times[0] |
---|
5227 |         times = times - starttime #Store relative times |
---|
5228 | Â Â Â Â else: |
---|
5229 | Â Â Â Â Â Â number_of_times =Â 0 |
---|
5230 | Â Â Â Â Â Â starttime =Â times |
---|
5231 | Â Â Â Â Â Â #times = ensure_numeric([]) |
---|
5232 | Â Â Â Â outfile.starttime =Â starttime |
---|
5233 | Â Â Â Â # dimension definitions |
---|
5234 |     outfile.createDimension('number_of_volumes', number_of_volumes) |
---|
5235 |     outfile.createDimension('number_of_vertices', 3) |
---|
5236 |     outfile.createDimension('numbers_in_range', 2) |
---|
5237 | Â Â |
---|
5238 |     if smoothing is True: |
---|
5239 |       outfile.createDimension('number_of_points', number_of_points) |
---|
5240 | Â Â Â Â |
---|
5241 | Â Â Â Â Â Â # FIXME(Ole): This will cause sww files for paralle domains to |
---|
5242 | Â Â Â Â Â Â # have ghost nodes stored (but not used by triangles). |
---|
5243 | Â Â Â Â Â Â # To clean this up, we have to change get_vertex_values and |
---|
5244 | Â Â Â Â Â Â # friends in quantity.py (but I can't be bothered right now) |
---|
5245 | Â Â Â Â else: |
---|
5246 |       outfile.createDimension('number_of_points', 3*number_of_volumes) |
---|
5247 |     outfile.createDimension('number_of_timesteps', number_of_times) |
---|
5248 | |
---|
5249 | Â Â Â Â # variable definitions |
---|
5250 |     outfile.createVariable('x', sww_precision, ('number_of_points',)) |
---|
5251 |     outfile.createVariable('y', sww_precision, ('number_of_points',)) |
---|
5252 |     outfile.createVariable('elevation', sww_precision, ('number_of_points',)) |
---|
5253 | Â Â Â Â q =Â 'elevation' |
---|
5254 |     outfile.createVariable(q+Write_sww.RANGE, sww_precision, |
---|
5255 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('numbers_in_range',)) |
---|
5256 | |
---|
5257 | |
---|
5258 | Â Â Â Â # Initialise ranges with small and large sentinels. |
---|
5259 | Â Â Â Â # If this was in pure Python we could have used None sensibly |
---|
5260 |     outfile.variables[q+Write_sww.RANGE][0] = max_float # Min |
---|
5261 | Â Â Â Â outfile.variables[q+Write_sww.RANGE][1]Â =Â -max_float # Max |
---|
5262 | |
---|
5263 | Â Â Â Â # FIXME: Backwards compatibility |
---|
5264 |     outfile.createVariable('z', sww_precision, ('number_of_points',)) |
---|
5265 | Â Â Â Â ################################# |
---|
5266 | |
---|
5267 |     outfile.createVariable('volumes', Int, ('number_of_volumes', |
---|
5268 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_vertices')) |
---|
5269 | Â Â Â Â # Doing sww_precision instead of Float gives cast errors. |
---|
5270 |     outfile.createVariable('time', Float, |
---|
5271 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps',)) |
---|
5272 | Â Â Â Â |
---|
5273 |     for q in Write_sww.sww_quantities: |
---|
5274 |       outfile.createVariable(q, sww_precision, |
---|
5275 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps', |
---|
5276 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_points'))Â |
---|
5277 |       outfile.createVariable(q+Write_sww.RANGE, sww_precision, |
---|
5278 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('numbers_in_range',)) |
---|
5279 | |
---|
5280 | Â Â Â Â Â Â # Initialise ranges with small and large sentinels. |
---|
5281 | Â Â Â Â Â Â # If this was in pure Python we could have used None sensibly |
---|
5282 |       outfile.variables[q+Write_sww.RANGE][0] = max_float # Min |
---|
5283 | Â Â Â Â Â Â outfile.variables[q+Write_sww.RANGE][1]Â =Â -max_float # Max |
---|
5284 | Â Â Â Â Â Â |
---|
5285 |     if type(times) is list or type(times) is ArrayType: |
---|
5286 |       outfile.variables['time'][:] = times  #Store time relative |
---|
5287 | Â Â Â Â Â Â |
---|
5288 |     if verbose: |
---|
5289 |       print '------------------------------------------------' |
---|
5290 |       print 'Statistics:' |
---|
5291 |       print '  t in [%f, %f], len(t) == %d'\ |
---|
5292 |          %(min(times.flat), max(times.flat), len(times.flat)) |
---|
5293 | |
---|
5294 | Â Â Â Â |
---|
5295 |   def store_triangulation(self, |
---|
5296 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â outfile, |
---|
5297 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â points_utm, |
---|
5298 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â volumes, |
---|
5299 |               elevation, zone=None, new_origin=None, |
---|
5300 |               points_georeference=None, verbose=False): |
---|
5301 | Â Â Â Â """ |
---|
5302 | Â Â Â Â |
---|
5303 | Â Â Â Â new_origin - qa georeference that the points can be set to. (Maybe |
---|
5304 | Â Â Â Â do this before calling this function.) |
---|
5305 | Â Â Â Â |
---|
5306 | Â Â Â Â points_utm - currently a list or array of the points in UTM. |
---|
5307 | Â Â Â Â points_georeference - the georeference of the points_utm |
---|
5308 | Â Â Â Â |
---|
5309 | Â Â Â Â How about passing new_origin and current_origin. |
---|
5310 | Â Â Â Â If you get both, do a convertion from the old to the new. |
---|
5311 | Â Â Â Â |
---|
5312 | Â Â Â Â If you only get new_origin, the points are absolute, |
---|
5313 | Â Â Â Â convert to relative |
---|
5314 | Â Â Â Â |
---|
5315 | Â Â Â Â if you only get the current_origin the points are relative, store |
---|
5316 | Â Â Â Â as relative. |
---|
5317 | Â Â Â Â |
---|
5318 | Â Â Â Â if you get no georefs create a new georef based on the minimums of |
---|
5319 |     points_utm. (Another option would be to default to absolute) |
---|
5320 | Â Â Â Â |
---|
5321 | Â Â Â Â Yes, and this is done in another part of the code. |
---|
5322 | Â Â Â Â Probably geospatial. |
---|
5323 | Â Â Â Â |
---|
5324 | Â Â Â Â If you don't supply either geo_refs, then supply a zone. If not |
---|
5325 | Â Â Â Â the default zone will be used. |
---|
5326 | Â Â Â Â |
---|
5327 | Â Â Â Â |
---|
5328 | Â Â Â Â precon |
---|
5329 | Â Â Â Â |
---|
5330 | Â Â Â Â header has been called. |
---|
5331 | Â Â Â Â """ |
---|
5332 | Â Â Â Â |
---|
5333 | Â Â Â Â number_of_points =Â len(points_utm)Â Â |
---|
5334 | Â Â Â Â volumes =Â array(volumes)Â |
---|
5335 | Â Â Â Â points_utm =Â array(points_utm) |
---|
5336 | |
---|
5337 | Â Â Â Â # given the two geo_refs and the points, do the stuff |
---|
5338 | Â Â Â Â # described in the method header |
---|
5339 | Â Â Â Â # if this is needed else where, pull out as a function |
---|
5340 | Â Â Â Â points_georeference =Â ensure_geo_reference(points_georeference) |
---|
5341 | Â Â Â Â new_origin =Â ensure_geo_reference(new_origin) |
---|
5342 |     if new_origin is None and points_georeference is not None: |
---|
5343 | Â Â Â Â Â Â points =Â points_utm |
---|
5344 | Â Â Â Â Â Â geo_ref =Â points_georeference |
---|
5345 | Â Â Â Â else: |
---|
5346 |       if new_origin is None: |
---|
5347 | Â Â Â Â Â Â Â Â new_origin =Â Geo_reference(zone,min(points_utm[:,0]), |
---|
5348 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â min(points_utm[:,1])) |
---|
5349 | Â Â Â Â Â Â points =Â new_origin.change_points_geo_ref(points_utm, |
---|
5350 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â points_georeference) |
---|
5351 | Â Â Â Â Â Â geo_ref =Â new_origin |
---|
5352 | |
---|
5353 | Â Â Â Â # At this stage I need a georef and points |
---|
5354 | Â Â Â Â # the points are relative to the georef |
---|
5355 | Â Â Â Â geo_ref.write_NetCDF(outfile) |
---|
5356 | Â Â |
---|
5357 | Â Â Â Â # This will put the geo ref in the middle |
---|
5358 | Â Â Â Â #geo_ref=Geo_reference(refzone,(max(x)+min(x))/2.0,(max(x)+min(y))/2.) |
---|
5359 | Â Â Â Â |
---|
5360 | Â Â Â Â x =Â points[:,0] |
---|
5361 | Â Â Â Â y =Â points[:,1] |
---|
5362 | Â Â Â Â z =Â outfile.variables['z'][:] |
---|
5363 | Â Â |
---|
5364 |     if verbose: |
---|
5365 |       print '------------------------------------------------' |
---|
5366 |       print 'More Statistics:' |
---|
5367 |       print ' Extent (/lon):' |
---|
5368 |       print '  x in [%f, %f], len(lat) == %d'\ |
---|
5369 |          %(min(x), max(x), |
---|
5370 | Â Â Â Â Â Â Â Â Â Â len(x)) |
---|
5371 |       print '  y in [%f, %f], len(lon) == %d'\ |
---|
5372 |          %(min(y), max(y), |
---|
5373 | Â Â Â Â Â Â Â Â Â Â len(y)) |
---|
5374 |       print '  z in [%f, %f], len(z) == %d'\ |
---|
5375 |          %(min(elevation), max(elevation), |
---|
5376 | Â Â Â Â Â Â Â Â Â Â len(elevation)) |
---|
5377 |       print 'geo_ref: ',geo_ref |
---|
5378 |       print '------------------------------------------------' |
---|
5379 | Â Â Â Â Â Â |
---|
5380 | Â Â Â Â #z = resize(bath_grid,outfile.variables['z'][:].shape) |
---|
5381 | Â Â Â Â #print "points[:,0]", points[:,0] |
---|
5382 | Â Â Â Â outfile.variables['x'][:]Â =Â points[:,0]Â #- geo_ref.get_xllcorner() |
---|
5383 | Â Â Â Â outfile.variables['y'][:]Â =Â points[:,1]Â #- geo_ref.get_yllcorner() |
---|
5384 | Â Â Â Â outfile.variables['z'][:]Â =Â elevation |
---|
5385 |     outfile.variables['elevation'][:] = elevation #FIXME HACK |
---|
5386 | Â Â Â Â outfile.variables['volumes'][:]Â =Â volumes.astype(Int32)Â #On Opteron 64 |
---|
5387 | |
---|
5388 | Â Â Â Â q =Â 'elevation' |
---|
5389 | Â Â Â Â # This updates the _range values |
---|
5390 | Â Â Â Â outfile.variables[q+Write_sww.RANGE][0]Â =Â min(elevation) |
---|
5391 | Â Â Â Â outfile.variables[q+Write_sww.RANGE][1]Â =Â max(elevation) |
---|
5392 | |
---|
5393 | |
---|
5394 |   def store_quantities(self, outfile, sww_precision=Float32, |
---|
5395 |              slice_index=None, time=None, |
---|
5396 |              verbose=False, **quant): |
---|
5397 | Â Â Â Â """ |
---|
5398 | Â Â Â Â Write the quantity info. |
---|
5399 | |
---|
5400 | Â Â Â Â **quant is extra keyword arguments passed in. These must be |
---|
5401 | Â Â Â Â Â the sww quantities, currently; stage, xmomentum, ymomentum. |
---|
5402 | Â Â Â Â |
---|
5403 | Â Â Â Â if the time array is already been built, use the slice_index |
---|
5404 | Â Â Â Â to specify the index. |
---|
5405 | Â Â Â Â |
---|
5406 | Â Â Â Â Otherwise, use time to increase the time dimension |
---|
5407 | |
---|
5408 | Â Â Â Â Maybe make this general, but the viewer assumes these quantities, |
---|
5409 | Â Â Â Â so maybe we don't want it general - unless the viewer is general |
---|
5410 | Â Â Â Â |
---|
5411 | Â Â Â Â precon |
---|
5412 | Â Â Â Â triangulation and |
---|
5413 | Â Â Â Â header have been called. |
---|
5414 | Â Â Â Â """ |
---|
5415 | |
---|
5416 |     if time is not None: |
---|
5417 | Â Â Â Â Â Â file_time =Â outfile.variables['time'] |
---|
5418 | Â Â Â Â Â Â slice_index =Â len(file_time) |
---|
5419 |       file_time[slice_index] = time  |
---|
5420 | |
---|
5421 | Â Â Â Â # Write the conserved quantities from Domain. |
---|
5422 |     # Typically stage, xmomentum, ymomentum |
---|
5423 | Â Â Â Â # other quantities will be ignored, silently. |
---|
5424 | Â Â Â Â # Also write the ranges: stage_range, |
---|
5425 | Â Â Â Â # xmomentum_range and ymomentum_range |
---|
5426 |     for q in Write_sww.sww_quantities: |
---|
5427 |       if not quant.has_key(q): |
---|
5428 | Â Â Â Â Â Â Â Â msg =Â 'SWW file can not write quantity %s'Â %q |
---|
5429 |         raise NewQuantity, msg |
---|
5430 | Â Â Â Â Â Â else: |
---|
5431 | Â Â Â Â Â Â Â Â q_values =Â quant[q] |
---|
5432 | Â Â Â Â Â Â Â Â outfile.variables[q][slice_index]Â =Â \ |
---|
5433 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â q_values.astype(sww_precision) |
---|
5434 | |
---|
5435 | Â Â Â Â Â Â Â Â # This updates the _range values |
---|
5436 | Â Â Â Â Â Â Â Â q_range =Â outfile.variables[q+Write_sww.RANGE][:] |
---|
5437 | Â Â Â Â Â Â Â Â q_values_min =Â min(q_values) |
---|
5438 |         if q_values_min < q_range[0]: |
---|
5439 | Â Â Â Â Â Â Â Â Â Â outfile.variables[q+Write_sww.RANGE][0]Â =Â q_values_min |
---|
5440 | Â Â Â Â Â Â Â Â q_values_max =Â max(q_values) |
---|
5441 |         if q_values_max > q_range[1]: |
---|
5442 | Â Â Â Â Â Â Â Â Â Â outfile.variables[q+Write_sww.RANGE][1]Â =Â q_values_max |
---|
5443 | |
---|
5444 |   def verbose_quantities(self, outfile): |
---|
5445 |     print '------------------------------------------------' |
---|
5446 |     print 'More Statistics:' |
---|
5447 |     for q in Write_sww.sww_quantities: |
---|
5448 |       print ' %s in [%f, %f]' %(q, |
---|
5449 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â outfile.variables[q+Write_sww.RANGE][0], |
---|
5450 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â outfile.variables[q+Write_sww.RANGE][1]) |
---|
5451 |     print '------------------------------------------------' |
---|
5452 | |
---|
5453 | |
---|
5454 | Â Â Â Â |
---|
5455 | def obsolete_write_sww_time_slices(outfile, has, uas, vas, elevation, |
---|
5456 |              mean_stage=0, zscale=1, |
---|
5457 | Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=False):Â Â |
---|
5458 | Â Â #Time stepping |
---|
5459 | Â Â stage =Â outfile.variables['stage'] |
---|
5460 | Â Â xmomentum =Â outfile.variables['xmomentum'] |
---|
5461 | Â Â ymomentum =Â outfile.variables['ymomentum'] |
---|
5462 | |
---|
5463 | Â Â n =Â len(has) |
---|
5464 | Â Â j=0 |
---|
5465 |   for ha, ua, va in map(None, has, uas, vas): |
---|
5466 |     if verbose and j%((n+10)/10)==0: print ' Doing %d of %d' %(j, n) |
---|
5467 | Â Â Â Â w =Â zscale*ha +Â mean_stage |
---|
5468 | Â Â Â Â stage[j]Â =Â w |
---|
5469 | Â Â Â Â h =Â w -Â elevation |
---|
5470 | Â Â Â Â xmomentum[j]Â =Â ua*h |
---|
5471 |     ymomentum[j] = -1*va*h # -1 since in mux files south is positive. |
---|
5472 | Â Â Â Â j +=Â 1 |
---|
5473 | Â Â |
---|
5474 | def urs2txt(basename_in, location_index=None): |
---|
5475 | Â Â """ |
---|
5476 | Â Â Not finished or tested |
---|
5477 | Â Â """ |
---|
5478 | Â Â |
---|
5479 | Â Â files_in =Â [basename_in +Â WAVEHEIGHT_MUX_LABEL, |
---|
5480 | Â Â Â Â Â Â Â Â basename_in +Â EAST_VELOCITY_LABEL, |
---|
5481 | Â Â Â Â Â Â Â Â basename_in +Â NORTH_VELOCITY_LABEL] |
---|
5482 | Â Â quantities =Â ['HA','UA','VA'] |
---|
5483 | |
---|
5484 | Â Â d =Â "," |
---|
5485 | Â Â |
---|
5486 | Â Â # instanciate urs_points of the three mux files. |
---|
5487 | Â Â mux =Â {} |
---|
5488 |   for quantity, file in map(None, quantities, files_in): |
---|
5489 | Â Â Â Â mux[quantity]Â =Â Urs_points(file) |
---|
5490 | Â Â Â Â |
---|
5491 | Â Â # Could check that the depth is the same. (hashing) |
---|
5492 | |
---|
5493 | Â Â # handle to a mux file to do depth stuff |
---|
5494 | Â Â a_mux =Â mux[quantities[0]] |
---|
5495 | Â Â |
---|
5496 | Â Â # Convert to utm |
---|
5497 | Â Â latitudes =Â a_mux.lonlatdep[:,1] |
---|
5498 | Â Â longitudes =Â a_mux.lonlatdep[:,0] |
---|
5499 |   points_utm, zone = convert_from_latlon_to_utm( \ |
---|
5500 |     latitudes=latitudes, longitudes=longitudes) |
---|
5501 | Â Â #print "points_utm", points_utm |
---|
5502 | Â Â #print "zone", zone |
---|
5503 | Â Â depths =Â a_mux.lonlatdep[:,2]Â # |
---|
5504 | Â Â |
---|
5505 |   fid = open(basename_in + '.txt', 'w') |
---|
5506 | |
---|
5507 | Â Â fid.write("zone: "Â +Â str(zone)Â +Â "\n") |
---|
5508 | |
---|
5509 |   if location_index is not None: |
---|
5510 | Â Â Â Â #Title |
---|
5511 | Â Â Â Â li =Â location_index |
---|
5512 | Â Â Â Â fid.write('location_index'+d+'lat'+d+Â 'long'Â +d+Â 'Easting'Â +d+Â \ |
---|
5513 | Â Â Â Â Â Â Â Â Â 'Northing'Â +Â "\n") |
---|
5514 | Â Â Â Â fid.write(str(li)Â +d+Â str(latitudes[li])+d+Â \ |
---|
5515 | Â Â Â Â Â Â Â str(longitudes[li])Â +d+Â str(points_utm[li][0])Â +d+Â \ |
---|
5516 | Â Â Â Â Â Â Â str(points_utm[li][01])Â +Â "\n") |
---|
5517 | |
---|
5518 | Â Â # the non-time dependent stuff |
---|
5519 | Â Â #Title |
---|
5520 | Â Â fid.write('location_index'+d+'lat'+d+Â 'long'Â +d+Â 'Easting'Â +d+Â \ |
---|
5521 | Â Â Â Â Â Â Â 'Northing'Â +d+Â 'depth m'Â +Â "\n") |
---|
5522 | Â Â i =Â 0 |
---|
5523 |   for depth, point_utm, lat, long in map(None, depths, |
---|
5524 |                         points_utm, latitudes, |
---|
5525 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â longitudes): |
---|
5526 | Â Â Â Â |
---|
5527 | Â Â Â Â fid.write(str(i)Â +d+Â str(lat)+d+Â str(long)Â +d+Â str(point_utm[0])Â +d+Â \ |
---|
5528 | Â Â Â Â Â Â Â Â Â str(point_utm[01])Â +d+Â str(depth)Â +Â "\n") |
---|
5529 | Â Â Â Â i +=1 |
---|
5530 | Â Â #Time dependent |
---|
5531 |   if location_index is not None: |
---|
5532 | Â Â Â Â time_step =Â a_mux.time_step |
---|
5533 | Â Â Â Â i =Â 0 |
---|
5534 | Â Â Â Â #Title |
---|
5535 | Â Â Â Â fid.write('time'Â +d+Â 'HA depth m'+d+Â \ |
---|
5536 | Â Â Â Â Â Â Â Â Â 'UA momentum East x m/sec'Â +d+Â 'VA momentum North y m/sec'Â \ |
---|
5537 | Â Â Â Â Â Â Â Â Â Â Â +Â "\n") |
---|
5538 |     for HA, UA, VA in map(None, mux['HA'], mux['UA'], mux['VA']): |
---|
5539 | Â Â Â Â Â Â fid.write(str(i*time_step)Â +d+Â str(HA[location_index])+d+Â \ |
---|
5540 | Â Â Â Â Â Â Â Â Â Â Â str(UA[location_index])Â +d+Â str(VA[location_index])Â \ |
---|
5541 | Â Â Â Â Â Â Â Â Â Â Â +Â "\n") |
---|
5542 | Â Â Â Â Â Â |
---|
5543 | Â Â Â Â Â Â i +=1 |
---|
5544 | |
---|
5545 | class Write_sts: |
---|
5546 | |
---|
5547 | Â Â sts_quantities =Â ['stage','xmomentum','ymomentum'] |
---|
5548 | |
---|
5549 | |
---|
5550 | Â Â RANGE =Â '_range' |
---|
5551 | Â Â EXTREMA =Â ':extrema' |
---|
5552 | Â Â |
---|
5553 |   def __init__(self): |
---|
5554 | Â Â Â Â pass |
---|
5555 | |
---|
5556 |   def store_header(self, |
---|
5557 | Â Â Â Â Â Â Â Â Â Â Â outfile, |
---|
5558 | Â Â Â Â Â Â Â Â Â Â Â times, |
---|
5559 | Â Â Â Â Â Â Â Â Â Â Â number_of_points, |
---|
5560 | Â Â Â Â Â Â Â Â Â Â Â description='Converted from URS mux2 format', |
---|
5561 | Â Â Â Â Â Â Â Â Â Â Â sts_precision=Float32, |
---|
5562 | Â Â Â Â Â Â Â Â Â Â Â verbose=False): |
---|
5563 | Â Â Â Â """ |
---|
5564 | Â Â Â Â outfile - the name of the file that will be written |
---|
5565 | Â Â Â Â times - A list of the time slice times OR a start time |
---|
5566 | Â Â Â Â Note, if a list is given the info will be made relative. |
---|
5567 | Â Â Â Â number_of_points - the number of urs gauges sites |
---|
5568 | Â Â Â Â """ |
---|
5569 | |
---|
5570 | Â Â Â Â outfile.institution =Â 'Geoscience Australia' |
---|
5571 | Â Â Â Â outfile.description =Â description |
---|
5572 | Â Â Â Â |
---|
5573 | Â Â Â Â try: |
---|
5574 | Â Â Â Â Â Â revision_number =Â get_revision_number() |
---|
5575 | Â Â Â Â except: |
---|
5576 | Â Â Â Â Â Â revision_number =Â None |
---|
5577 |     # Allow None to be stored as a string        |
---|
5578 | Â Â Â Â outfile.revision_number =Â str(revision_number)Â |
---|
5579 | Â Â Â Â |
---|
5580 | Â Â Â Â # times - A list or array of the time slice times OR a start time |
---|
5581 | Â Â Â Â # Start time in seconds since the epoch (midnight 1/1/1970) |
---|
5582 | |
---|
5583 | Â Â Â Â # This is being used to seperate one number from a list. |
---|
5584 | Â Â Â Â # what it is actually doing is sorting lists from numeric arrays. |
---|
5585 |     if type(times) is list or type(times) is ArrayType: |
---|
5586 | Â Â Â Â Â Â number_of_times =Â len(times) |
---|
5587 | Â Â Â Â Â Â times =Â ensure_numeric(times)Â |
---|
5588 |       if number_of_times == 0: |
---|
5589 | Â Â Â Â Â Â Â Â starttime =Â 0 |
---|
5590 | Â Â Â Â Â Â else: |
---|
5591 | Â Â Â Â Â Â Â Â starttime =Â times[0] |
---|
5592 |         times = times - starttime #Store relative times |
---|
5593 | Â Â Â Â else: |
---|
5594 | Â Â Â Â Â Â number_of_times =Â 0 |
---|
5595 | Â Â Â Â Â Â starttime =Â times |
---|
5596 | |
---|
5597 | Â Â Â Â outfile.starttime =Â starttime |
---|
5598 | |
---|
5599 | Â Â Â Â # Dimension definitions |
---|
5600 |     outfile.createDimension('number_of_points', number_of_points) |
---|
5601 |     outfile.createDimension('number_of_timesteps', number_of_times) |
---|
5602 |     outfile.createDimension('numbers_in_range', 2) |
---|
5603 | |
---|
5604 | Â Â Â Â # Variable definitions |
---|
5605 |     outfile.createVariable('x', sts_precision, ('number_of_points',)) |
---|
5606 |     outfile.createVariable('y', sts_precision, ('number_of_points',)) |
---|
5607 |     outfile.createVariable('elevation', sts_precision,('number_of_points',)) |
---|
5608 | |
---|
5609 | Â Â Â Â q =Â 'elevation' |
---|
5610 |     outfile.createVariable(q+Write_sts.RANGE, sts_precision, |
---|
5611 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('numbers_in_range',)) |
---|
5612 | |
---|
5613 | Â Â Â Â # Initialise ranges with small and large sentinels. |
---|
5614 | Â Â Â Â # If this was in pure Python we could have used None sensibly |
---|
5615 |     outfile.variables[q+Write_sts.RANGE][0] = max_float # Min |
---|
5616 | Â Â Â Â outfile.variables[q+Write_sts.RANGE][1]Â =Â -max_float # Max |
---|
5617 | |
---|
5618 |     outfile.createVariable('z', sts_precision, ('number_of_points',)) |
---|
5619 | Â Â Â Â # Doing sts_precision instead of Float gives cast errors. |
---|
5620 |     outfile.createVariable('time', Float, ('number_of_timesteps',)) |
---|
5621 | |
---|
5622 |     for q in Write_sts.sts_quantities: |
---|
5623 |       outfile.createVariable(q, sts_precision, |
---|
5624 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('number_of_timesteps', |
---|
5625 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'number_of_points')) |
---|
5626 |       outfile.createVariable(q+Write_sts.RANGE, sts_precision, |
---|
5627 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ('numbers_in_range',)) |
---|
5628 | Â Â Â Â Â Â # Initialise ranges with small and large sentinels. |
---|
5629 | Â Â Â Â Â Â # If this was in pure Python we could have used None sensibly |
---|
5630 |       outfile.variables[q+Write_sts.RANGE][0] = max_float # Min |
---|
5631 | Â Â Â Â Â Â outfile.variables[q+Write_sts.RANGE][1]Â =Â -max_float # Max |
---|
5632 | |
---|
5633 |     if type(times) is list or type(times) is ArrayType: |
---|
5634 |       outfile.variables['time'][:] = times  #Store time relative |
---|
5635 | |
---|
5636 |     if verbose: |
---|
5637 |       print '------------------------------------------------' |
---|
5638 |       print 'Statistics:' |
---|
5639 |       print '  t in [%f, %f], len(t) == %d'\ |
---|
5640 |          %(min(times.flat), max(times.flat), len(times.flat)) |
---|
5641 | |
---|
5642 |   def store_points(self, |
---|
5643 | Â Â Â Â Â Â Â Â Â Â Â outfile, |
---|
5644 | Â Â Â Â Â Â Â Â Â Â Â points_utm, |
---|
5645 |            elevation, zone=None, new_origin=None, |
---|
5646 |            points_georeference=None, verbose=False): |
---|
5647 | |
---|
5648 | Â Â Â Â """ |
---|
5649 | Â Â Â Â points_utm - currently a list or array of the points in UTM. |
---|
5650 | Â Â Â Â points_georeference - the georeference of the points_utm |
---|
5651 | |
---|
5652 | Â Â Â Â How about passing new_origin and current_origin. |
---|
5653 | Â Â Â Â If you get both, do a convertion from the old to the new. |
---|
5654 | Â Â Â Â |
---|
5655 | Â Â Â Â If you only get new_origin, the points are absolute, |
---|
5656 | Â Â Â Â convert to relative |
---|
5657 | Â Â Â Â |
---|
5658 | Â Â Â Â if you only get the current_origin the points are relative, store |
---|
5659 | Â Â Â Â as relative. |
---|
5660 | Â Â Â Â |
---|
5661 | Â Â Â Â if you get no georefs create a new georef based on the minimums of |
---|
5662 |     points_utm. (Another option would be to default to absolute) |
---|
5663 | Â Â Â Â |
---|
5664 | Â Â Â Â Yes, and this is done in another part of the code. |
---|
5665 | Â Â Â Â Probably geospatial. |
---|
5666 | Â Â Â Â |
---|
5667 | Â Â Â Â If you don't supply either geo_refs, then supply a zone. If not |
---|
5668 | Â Â Â Â the default zone will be used. |
---|
5669 | |
---|
5670 | Â Â Â Â precondition: |
---|
5671 | Â Â Â Â Â Â Â header has been called. |
---|
5672 | Â Â Â Â """ |
---|
5673 | |
---|
5674 | Â Â Â Â number_of_points =Â len(points_utm) |
---|
5675 | Â Â Â Â points_utm =Â array(points_utm) |
---|
5676 | |
---|
5677 | Â Â Â Â # given the two geo_refs and the points, do the stuff |
---|
5678 | Â Â Â Â # described in the method header |
---|
5679 | Â Â Â Â points_georeference =Â ensure_geo_reference(points_georeference) |
---|
5680 | Â Â Â Â new_origin =Â ensure_geo_reference(new_origin) |
---|
5681 | Â Â Â Â |
---|
5682 |     if new_origin is None and points_georeference is not None: |
---|
5683 | Â Â Â Â Â Â points =Â points_utm |
---|
5684 | Â Â Â Â Â Â geo_ref =Â points_georeference |
---|
5685 | Â Â Â Â else: |
---|
5686 |       if new_origin is None: |
---|
5687 | Â Â Â Â Â Â Â Â new_origin =Â Geo_reference(zone,min(points_utm[:,0]), |
---|
5688 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â min(points_utm[:,1])) |
---|
5689 | Â Â Â Â Â Â points =Â new_origin.change_points_geo_ref(points_utm, |
---|
5690 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â points_georeference) |
---|
5691 | Â Â Â Â Â Â geo_ref =Â new_origin |
---|
5692 | |
---|
5693 | Â Â Â Â # At this stage I need a georef and points |
---|
5694 | Â Â Â Â # the points are relative to the georef |
---|
5695 | Â Â Â Â geo_ref.write_NetCDF(outfile) |
---|
5696 | |
---|
5697 | Â Â Â Â x =Â points[:,0] |
---|
5698 | Â Â Â Â y =Â points[:,1] |
---|
5699 | Â Â Â Â z =Â outfile.variables['z'][:] |
---|
5700 | Â Â |
---|
5701 |     if verbose: |
---|
5702 |       print '------------------------------------------------' |
---|
5703 |       print 'More Statistics:' |
---|
5704 |       print ' Extent (/lon):' |
---|
5705 |       print '  x in [%f, %f], len(lat) == %d'\ |
---|
5706 |          %(min(x), max(x), |
---|
5707 | Â Â Â Â Â Â Â Â Â Â len(x)) |
---|
5708 |       print '  y in [%f, %f], len(lon) == %d'\ |
---|
5709 |          %(min(y), max(y), |
---|
5710 | Â Â Â Â Â Â Â Â Â Â len(y)) |
---|
5711 |       print '  z in [%f, %f], len(z) == %d'\ |
---|
5712 |          %(min(elevation), max(elevation), |
---|
5713 | Â Â Â Â Â Â Â Â Â Â len(elevation)) |
---|
5714 |       print 'geo_ref: ',geo_ref |
---|
5715 |       print '------------------------------------------------' |
---|
5716 | Â Â Â Â Â Â |
---|
5717 | Â Â Â Â #z = resize(bath_grid,outfile.variables['z'][:].shape) |
---|
5718 | Â Â Â Â #print "points[:,0]", points[:,0] |
---|
5719 | Â Â Â Â outfile.variables['x'][:]Â =Â points[:,0]Â #- geo_ref.get_xllcorner() |
---|
5720 | Â Â Â Â outfile.variables['y'][:]Â =Â points[:,1]Â #- geo_ref.get_yllcorner() |
---|
5721 | Â Â Â Â outfile.variables['z'][:]Â =Â elevation |
---|
5722 |     outfile.variables['elevation'][:] = elevation #FIXME HACK4 |
---|
5723 | |
---|
5724 | Â Â Â Â q =Â 'elevation' |
---|
5725 | Â Â Â Â # This updates the _range values |
---|
5726 | Â Â Â Â outfile.variables[q+Write_sts.RANGE][0]Â =Â min(elevation) |
---|
5727 | Â Â Â Â outfile.variables[q+Write_sts.RANGE][1]Â =Â max(elevation) |
---|
5728 | |
---|
5729 |   def store_quantities(self, outfile, sts_precision=Float32, |
---|
5730 |              slice_index=None, time=None, |
---|
5731 |              verbose=False, **quant): |
---|
5732 | Â Â Â Â |
---|
5733 | Â Â Â Â """ |
---|
5734 | Â Â Â Â Write the quantity info. |
---|
5735 | |
---|
5736 | Â Â Â Â **quant is extra keyword arguments passed in. These must be |
---|
5737 | Â Â Â Â Â the sts quantities, currently; stage. |
---|
5738 | Â Â Â Â |
---|
5739 | Â Â Â Â if the time array is already been built, use the slice_index |
---|
5740 | Â Â Â Â to specify the index. |
---|
5741 | Â Â Â Â |
---|
5742 | Â Â Â Â Otherwise, use time to increase the time dimension |
---|
5743 | |
---|
5744 | Â Â Â Â Maybe make this general, but the viewer assumes these quantities, |
---|
5745 | Â Â Â Â so maybe we don't want it general - unless the viewer is general |
---|
5746 | Â Â Â Â |
---|
5747 | Â Â Â Â precondition: |
---|
5748 | Â Â Â Â Â Â triangulation and |
---|
5749 | Â Â Â Â Â Â header have been called. |
---|
5750 | Â Â Â Â """ |
---|
5751 |     if time is not None: |
---|
5752 | Â Â Â Â Â Â file_time =Â outfile.variables['time'] |
---|
5753 | Â Â Â Â Â Â slice_index =Â len(file_time) |
---|
5754 |       file_time[slice_index] = time  |
---|
5755 | |
---|
5756 | Â Â Â Â # Write the conserved quantities from Domain. |
---|
5757 |     # Typically stage, xmomentum, ymomentum |
---|
5758 | Â Â Â Â # other quantities will be ignored, silently. |
---|
5759 | Â Â Â Â # Also write the ranges: stage_range |
---|
5760 |     for q in Write_sts.sts_quantities: |
---|
5761 |       if not quant.has_key(q): |
---|
5762 | Â Â Â Â Â Â Â Â msg =Â 'STS file can not write quantity %s'Â %q |
---|
5763 |         raise NewQuantity, msg |
---|
5764 | Â Â Â Â Â Â else: |
---|
5765 | Â Â Â Â Â Â Â Â q_values =Â quant[q] |
---|
5766 | Â Â Â Â Â Â Â Â outfile.variables[q][slice_index]Â =Â \ |
---|
5767 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â q_values.astype(sts_precision) |
---|
5768 | |
---|
5769 | Â Â Â Â Â Â Â Â # This updates the _range values |
---|
5770 | Â Â Â Â Â Â Â Â q_range =Â outfile.variables[q+Write_sts.RANGE][:] |
---|
5771 | Â Â Â Â Â Â Â Â q_values_min =Â min(q_values) |
---|
5772 |         if q_values_min < q_range[0]: |
---|
5773 | Â Â Â Â Â Â Â Â Â Â outfile.variables[q+Write_sts.RANGE][0]Â =Â q_values_min |
---|
5774 | Â Â Â Â Â Â Â Â q_values_max =Â max(q_values) |
---|
5775 |         if q_values_max > q_range[1]: |
---|
5776 | Â Â Â Â Â Â Â Â Â Â outfile.variables[q+Write_sts.RANGE][1]Â =Â q_values_max |
---|
5777 | |
---|
5778 | |
---|
5779 | Â Â |
---|
5780 | class Urs_points: |
---|
5781 | Â Â """ |
---|
5782 | Â Â Read the info in URS mux files. |
---|
5783 | |
---|
5784 | Â Â for the quantities heres a correlation between the file names and |
---|
5785 | Â Â what they mean; |
---|
5786 | Â Â z-mux is height above sea level, m |
---|
5787 | Â Â e-mux is velocity is Eastern direction, m/s |
---|
5788 |   n-mux is velocity is Northern direction, m/s  |
---|
5789 | Â Â """ |
---|
5790 |   def __init__(self,urs_file): |
---|
5791 | Â Â Â Â self.iterated =Â False |
---|
5792 | Â Â Â Â columns =Â 3Â # long, lat , depth |
---|
5793 |     mux_file = open(urs_file, 'rb') |
---|
5794 | Â Â Â Â |
---|
5795 | Â Â Â Â # Number of points/stations |
---|
5796 | Â Â Â Â (self.points_num,)=Â unpack('i',mux_file.read(4)) |
---|
5797 | Â Â Â Â |
---|
5798 | Â Â Â Â # nt, int - Number of time steps |
---|
5799 | Â Â Â Â (self.time_step_count,)=Â unpack('i',mux_file.read(4)) |
---|
5800 | Â Â Â Â #print "self.time_step_count", self.time_step_count |
---|
5801 | Â Â Â Â #dt, float - time step, seconds |
---|
5802 |     (self.time_step,) = unpack('f', mux_file.read(4)) |
---|
5803 | Â Â Â Â #print "self.time_step", self.time_step |
---|
5804 | Â Â Â Â msg =Â "Bad data in the urs file." |
---|
5805 |     if self.points_num < 0: |
---|
5806 | Â Â Â Â Â Â mux_file.close() |
---|
5807 |       raise ANUGAError, msg |
---|
5808 |     if self.time_step_count < 0: |
---|
5809 | Â Â Â Â Â Â mux_file.close() |
---|
5810 |       raise ANUGAError, msg |
---|
5811 |     if self.time_step < 0: |
---|
5812 | Â Â Â Â Â Â mux_file.close() |
---|
5813 |       raise ANUGAError, msg |
---|
5814 | |
---|
5815 | Â Â Â Â # the depth is in meters, and it is the distance from the ocean |
---|
5816 | Â Â Â Â # to the sea bottom. |
---|
5817 | Â Â Â Â lonlatdep =Â p_array.array('f') |
---|
5818 |     lonlatdep.read(mux_file, columns * self.points_num) |
---|
5819 |     lonlatdep = array(lonlatdep, typecode=Float)  |
---|
5820 |     lonlatdep = reshape(lonlatdep, (self.points_num, columns)) |
---|
5821 | Â Â Â Â #print 'lonlatdep',lonlatdep |
---|
5822 | Â Â Â Â self.lonlatdep =Â lonlatdep |
---|
5823 | Â Â Â Â |
---|
5824 | Â Â Â Â self.mux_file =Â mux_file |
---|
5825 | Â Â Â Â # check this array |
---|
5826 | |
---|
5827 |   def __iter__(self): |
---|
5828 | Â Â Â Â """ |
---|
5829 | Â Â Â Â iterate over quantity data which is with respect to time. |
---|
5830 | |
---|
5831 | Â Â Â Â Note: You can only interate once over an object |
---|
5832 | Â Â Â Â |
---|
5833 | Â Â Â Â returns quantity infomation for each time slice |
---|
5834 | Â Â Â Â """ |
---|
5835 | Â Â Â Â msg =Â "You can only interate once over a urs file." |
---|
5836 |     assert not self.iterated, msg |
---|
5837 | Â Â Â Â self.iter_time_step =Â 0 |
---|
5838 | Â Â Â Â self.iterated =Â True |
---|
5839 |     return self |
---|
5840 | Â Â |
---|
5841 |   def next(self): |
---|
5842 |     if self.time_step_count == self.iter_time_step: |
---|
5843 | Â Â Â Â Â Â self.close() |
---|
5844 |       raise StopIteration |
---|
5845 |     #Read in a time slice from mux file |
---|
5846 | Â Â Â Â hz_p_array =Â p_array.array('f') |
---|
5847 |     hz_p_array.read(self.mux_file, self.points_num) |
---|
5848 |     hz_p = array(hz_p_array, typecode=Float) |
---|
5849 | Â Â Â Â self.iter_time_step +=Â 1 |
---|
5850 | Â Â Â Â |
---|
5851 |     return hz_p |
---|
5852 | |
---|
5853 |   def close(self): |
---|
5854 | Â Â Â Â self.mux_file.close() |
---|
5855 | Â Â Â Â |
---|
5856 | Â Â #### END URS UNGRIDDED 2 SWW ### |
---|
5857 | |
---|
5858 | Â Â Â Â |
---|
5859 | def start_screen_catcher(dir_name=None, myid='', numprocs='', extra_info='', |
---|
5860 | Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=True): |
---|
5861 | Â Â """ |
---|
5862 | Â Â Used to store screen output and errors to file, if run on multiple |
---|
5863 | Â Â processes eachprocessor will have its own output and error file. |
---|
5864 | Â Â |
---|
5865 | Â Â extra_info - is used as a string that can identify outputs with another |
---|
5866 | Â Â string eg. '_other' |
---|
5867 | Â Â |
---|
5868 | Â Â FIXME: Would be good if you could suppress all the screen output and |
---|
5869 | Â Â only save it to file... however it seems a bit tricky as this capture |
---|
5870 | Â Â techique response to sys.stdout and by this time it is already printed out. |
---|
5871 | Â Â """ |
---|
5872 | Â Â |
---|
5873 |   import sys |
---|
5874 | #Â Â dir_name = dir_name |
---|
5875 |   if dir_name == None: |
---|
5876 | Â Â Â Â dir_name=getcwd() |
---|
5877 | Â Â Â Â |
---|
5878 |   if access(dir_name,W_OK) == 0: |
---|
5879 |     if verbose: print 'Making directory %s' %dir_name |
---|
5880 | Â Â Â #Â if verbose: print "myid", myid |
---|
5881 | Â Â Â Â mkdir (dir_name,0777) |
---|
5882 | |
---|
5883 |   if myid <>'': |
---|
5884 | Â Â Â Â myid =Â '_'+str(myid) |
---|
5885 |   if numprocs <>'': |
---|
5886 | Â Â Â Â numprocs =Â '_'+str(numprocs) |
---|
5887 |   if extra_info <>'': |
---|
5888 | Â Â Â Â extra_info =Â '_'+str(extra_info) |
---|
5889 | #Â Â print 'hello1' |
---|
5890 |   screen_output_name = join(dir_name, "screen_output%s%s%s.txt" %(myid, |
---|
5891 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â numprocs, |
---|
5892 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â extra_info)) |
---|
5893 |   screen_error_name = join(dir_name, "screen_error%s%s%s.txt" %(myid, |
---|
5894 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â numprocs, |
---|
5895 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â extra_info)) |
---|
5896 | |
---|
5897 |   if verbose: print 'Starting ScreenCatcher, all output will be stored in %s' \ |
---|
5898 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â %(screen_output_name) |
---|
5899 | Â Â #used to catch screen output to file |
---|
5900 | Â Â sys.stdout =Â Screen_Catcher(screen_output_name) |
---|
5901 | Â Â sys.stderr =Â Screen_Catcher(screen_error_name) |
---|
5902 | |
---|
5903 | class Screen_Catcher: |
---|
5904 | Â Â """this simply catches the screen output and stores it to file defined by |
---|
5905 | Â Â start_screen_catcher (above) |
---|
5906 | Â Â """ |
---|
5907 | Â Â |
---|
5908 |   def __init__(self, filename): |
---|
5909 | Â Â Â Â self.filename =Â filename |
---|
5910 | #Â Â Â Â print 'init' |
---|
5911 |     if exists(self.filename)is True: |
---|
5912 | Â Â Â Â Â Â print'Old existing file "%s" has been deleted'Â %(self.filename) |
---|
5913 | Â Â Â Â Â Â remove(self.filename) |
---|
5914 | |
---|
5915 |   def write(self, stuff): |
---|
5916 |     fid = open(self.filename, 'a') |
---|
5917 | Â Â Â Â fid.write(stuff) |
---|
5918 | Â Â Â Â fid.close() |
---|
5919 | Â Â Â Â |
---|
5920 | # FIXME (DSG): Add unit test, make general, not just 2 files, |
---|
5921 | # but any number of files. |
---|
5922 | def copy_code_files(dir_name, filename1, filename2=None): |
---|
5923 | Â Â """Copies "filename1" and "filename2" to "dir_name". Very useful for |
---|
5924 | Â Â information management |
---|
5925 |   filename1 and filename2 are both absolute pathnames  |
---|
5926 | Â Â """ |
---|
5927 | |
---|
5928 |   if access(dir_name,F_OK) == 0: |
---|
5929 |     print 'Make directory %s' %dir_name |
---|
5930 | Â Â Â Â mkdir (dir_name,0777) |
---|
5931 |   shutil.copy(filename1, dir_name + sep + basename(filename1)) |
---|
5932 |   if filename2!=None: |
---|
5933 |     shutil.copy(filename2, dir_name + sep + basename(filename2)) |
---|
5934 |     print 'Files %s and %s copied' %(filename1, filename2) |
---|
5935 | Â Â else: |
---|
5936 |     print 'File %s copied' %(filename1) |
---|
5937 | |
---|
5938 | def get_data_from_file(filename,separator_value = ','): |
---|
5939 | Â Â """ |
---|
5940 | Â Â Read in data information from file and |
---|
5941 | Â Â |
---|
5942 | Â Â Returns: |
---|
5943 | Â Â Â Â header_fields, a string? of the first line separated |
---|
5944 | Â Â Â Â by the 'separator_value' |
---|
5945 | Â Â Â Â |
---|
5946 | Â Â Â Â data, a array (N data columns X M lines) in the file |
---|
5947 | Â Â Â Â excluding the header |
---|
5948 | Â Â Â Â |
---|
5949 | Â Â NOTE: wont deal with columns with different lenghts and there must be |
---|
5950 | Â Â no blank lines at the end. |
---|
5951 | Â Â """ |
---|
5952 | Â Â |
---|
5953 | Â Â fid =Â open(filename) |
---|
5954 | Â Â lines =Â fid.readlines() |
---|
5955 | Â Â |
---|
5956 | Â Â fid.close() |
---|
5957 | Â Â |
---|
5958 | Â Â header_line =Â lines[0] |
---|
5959 | Â Â header_fields =Â header_line.split(separator_value) |
---|
5960 | |
---|
5961 | Â Â #array to store data, number in there is to allow float... |
---|
5962 | Â Â #i'm sure there is a better way! |
---|
5963 | Â Â data=array([],typecode=Float) |
---|
5964 | Â Â data=resize(data,((len(lines)-1),len(header_fields))) |
---|
5965 | #Â Â print 'number of fields',range(len(header_fields)) |
---|
5966 | #Â Â print 'number of lines',len(lines), shape(data) |
---|
5967 | #Â Â print'data',data[1,1],header_line |
---|
5968 | |
---|
5969 | Â Â array_number =Â 0 |
---|
5970 | Â Â line_number =Â 1 |
---|
5971 |   while line_number < (len(lines)): |
---|
5972 |     for i in range(len(header_fields)): |
---|
5973 | Â Â Â Â Â Â #this get line below the header, explaining the +1 |
---|
5974 | Â Â Â Â Â Â #and also the line_number can be used as the array index |
---|
5975 | Â Â Â Â Â Â fields =Â lines[line_number].split(separator_value) |
---|
5976 | Â Â Â Â Â Â #assign to array |
---|
5977 | Â Â Â Â Â Â data[array_number,i]Â =Â float(fields[i]) |
---|
5978 | Â Â Â Â Â Â |
---|
5979 | Â Â Â Â line_number =Â line_number +1 |
---|
5980 | Â Â Â Â array_number =Â array_number +1 |
---|
5981 | Â Â Â Â |
---|
5982 |   return header_fields, data |
---|
5983 | |
---|
5984 | def store_parameters(verbose=False,**kwargs): |
---|
5985 | Â Â """ |
---|
5986 | Â Â Store "kwargs" into a temp csv file, if "completed" is a kwargs csv file is |
---|
5987 | Â Â kwargs[file_name] else it is kwargs[output_dir] + details_temp.csv |
---|
5988 | Â Â |
---|
5989 | Â Â Must have a file_name keyword arg, this is what is writing to. |
---|
5990 | Â Â might be a better way to do this using CSV module Writer and writeDict |
---|
5991 | Â Â |
---|
5992 | Â Â writes file to "output_dir" unless "completed" is in kwargs, then |
---|
5993 | Â Â it writes to "file_name" kwargs |
---|
5994 | |
---|
5995 | Â Â """ |
---|
5996 |   import types |
---|
5997 | #Â Â import os |
---|
5998 | Â Â |
---|
5999 | Â Â # Check that kwargs is a dictionary |
---|
6000 |   if type(kwargs) != types.DictType: |
---|
6001 |     raise TypeError |
---|
6002 | Â Â |
---|
6003 | Â Â #is completed is kwargs? |
---|
6004 | Â Â try: |
---|
6005 | Â Â Â Â kwargs['completed'] |
---|
6006 | Â Â Â Â completed=True |
---|
6007 | Â Â except: |
---|
6008 | Â Â Â Â completed=False |
---|
6009 | Â |
---|
6010 | Â Â #get file name and removes from dict and assert that a file_name exists |
---|
6011 |   if completed: |
---|
6012 | Â Â Â Â try: |
---|
6013 |       file = str(kwargs['file_name']) |
---|
6014 | Â Â Â Â except: |
---|
6015 |       raise 'kwargs must have file_name' |
---|
6016 | Â Â else: |
---|
6017 | Â Â Â Â #write temp file in output directory |
---|
6018 | Â Â Â Â try: |
---|
6019 |       file = str(kwargs['output_dir'])+'detail_temp.csv' |
---|
6020 | Â Â Â Â except: |
---|
6021 |       raise 'kwargs must have output_dir' |
---|
6022 | Â Â Â Â |
---|
6023 | Â Â #extracts the header info and the new line info |
---|
6024 | Â Â line='' |
---|
6025 | Â Â header='' |
---|
6026 | Â Â count=0 |
---|
6027 | Â Â keys =Â kwargs.keys() |
---|
6028 | Â Â keys.sort() |
---|
6029 | Â Â |
---|
6030 | Â Â #used the sorted keys to create the header and line data |
---|
6031 |   for k in keys: |
---|
6032 | #Â Â Â Â print "%s = %s" %(k, kwargs[k]) |
---|
6033 | Â Â Â Â header =Â header+str(k) |
---|
6034 | Â Â Â Â line =Â line+str(kwargs[k]) |
---|
6035 | Â Â Â Â count+=1 |
---|
6036 |     if count <len(kwargs): |
---|
6037 | Â Â Â Â Â Â header =Â header+',' |
---|
6038 | Â Â Â Â Â Â line =Â line+',' |
---|
6039 | Â Â header+='\n' |
---|
6040 | Â Â line+='\n' |
---|
6041 | |
---|
6042 | Â Â # checks the header info, if the same, then write, if not create a new file |
---|
6043 | Â Â #try to open! |
---|
6044 | Â Â try: |
---|
6045 | Â Â Â Â fid =Â open(file,"r") |
---|
6046 | Â Â Â Â file_header=fid.readline() |
---|
6047 | Â Â Â Â fid.close() |
---|
6048 |     if verbose: print 'read file header %s' %file_header |
---|
6049 | Â Â Â Â |
---|
6050 | Â Â except: |
---|
6051 | Â Â Â Â msg =Â 'try to create new file',file |
---|
6052 |     if verbose: print msg |
---|
6053 | Â Â Â Â #tries to open file, maybe directory is bad |
---|
6054 | Â Â Â Â try: |
---|
6055 | Â Â Â Â Â Â fid =Â open(file,"w") |
---|
6056 | Â Â Â Â Â Â fid.write(header) |
---|
6057 | Â Â Â Â Â Â fid.close() |
---|
6058 | Â Â Â Â Â Â file_header=header |
---|
6059 | Â Â Â Â except: |
---|
6060 | Â Â Â Â Â Â msg =Â 'cannot create new file',file |
---|
6061 |       raise msg |
---|
6062 | Â Â Â Â Â Â |
---|
6063 | Â Â #if header is same or this is a new file |
---|
6064 |   if file_header==str(header): |
---|
6065 | Â Â Â Â fid=open(file,"a") |
---|
6066 | Â Â Â Â #write new line |
---|
6067 | Â Â Â Â fid.write(line) |
---|
6068 | Â Â Â Â fid.close() |
---|
6069 | Â Â else: |
---|
6070 | Â Â Â Â #backup plan, |
---|
6071 | Â Â Â Â # if header is different and has completed will append info to |
---|
6072 | Â Â Â Â #end of details_temp.cvs file in output directory |
---|
6073 |     file = str(kwargs['output_dir'])+'detail_temp.csv' |
---|
6074 | Â Â Â Â fid=open(file,"a") |
---|
6075 | Â Â Â Â fid.write(header) |
---|
6076 | Â Â Â Â fid.write(line) |
---|
6077 | Â Â Â Â fid.close() |
---|
6078 |     if verbose: print 'file',file_header.strip('\n') |
---|
6079 |     if verbose: print 'head',header.strip('\n') |
---|
6080 |     if file_header.strip('\n')==str(header): print 'they equal' |
---|
6081 | Â Â Â Â msg =Â 'WARNING: File header does not match input info, the input variables have changed, suggest to change file name' |
---|
6082 |     print msg |
---|
6083 | |
---|
6084 | |
---|
6085 | |
---|
6086 | # ---------------------------------------------- |
---|
6087 | # Functions to obtain diagnostics from sww files |
---|
6088 | #----------------------------------------------- |
---|
6089 | |
---|
6090 | def get_mesh_and_quantities_from_file(filename, |
---|
6091 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â quantities=None, |
---|
6092 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=False): |
---|
6093 | Â Â """Get and rebuild mesh structure and the associated quantities from sww file |
---|
6094 | |
---|
6095 | Â Â Input: |
---|
6096 | Â Â Â Â filename - Name os sww file |
---|
6097 | Â Â Â Â quantities - Names of quantities to load |
---|
6098 | |
---|
6099 | Â Â Output: |
---|
6100 | Â Â Â Â mesh - instance of class Interpolate |
---|
6101 | Â Â Â Â Â Â Â Â (including mesh and interpolation functionality) |
---|
6102 | Â Â Â Â quantities - arrays with quantity values at each mesh node |
---|
6103 | Â Â Â Â time - vector of stored timesteps |
---|
6104 | Â Â """ |
---|
6105 | Â |
---|
6106 | Â Â # FIXME (Ole): Maybe refactor filefunction using this more fundamental code. |
---|
6107 | Â Â |
---|
6108 |   import types |
---|
6109 |   from Scientific.IO.NetCDF import NetCDFFile |
---|
6110 |   from shallow_water import Domain |
---|
6111 |   from Numeric import asarray, transpose, resize |
---|
6112 |   from anuga.abstract_2d_finite_volumes.neighbour_mesh import Mesh |
---|
6113 | |
---|
6114 |   if verbose: print 'Reading from ', filename |
---|
6115 |   fid = NetCDFFile(filename, 'r')  # Open existing file for read |
---|
6116 | Â Â time =Â fid.variables['time'][:]Â Â # Time vector |
---|
6117 | Â Â time +=Â fid.starttime[0] |
---|
6118 | Â Â |
---|
6119 | Â Â # Get the variables as Numeric arrays |
---|
6120 | Â Â x =Â fid.variables['x'][:]Â Â Â Â Â Â Â Â Â Â # x-coordinates of nodes |
---|
6121 | Â Â y =Â fid.variables['y'][:]Â Â Â Â Â Â Â Â Â Â # y-coordinates of nodes |
---|
6122 | Â Â elevation =Â fid.variables['elevation'][:]Â Â # Elevation |
---|
6123 | Â Â stage =Â fid.variables['stage'][:]Â Â Â Â Â Â # Water level |
---|
6124 | Â Â xmomentum =Â fid.variables['xmomentum'][:]Â Â # Momentum in the x-direction |
---|
6125 | Â Â ymomentum =Â fid.variables['ymomentum'][:]Â Â # Momentum in the y-direction |
---|
6126 | |
---|
6127 | |
---|
6128 | Â Â # Mesh (nodes (Mx2), triangles (Nx3)) |
---|
6129 |   nodes = concatenate( (x[:, NewAxis], y[:, NewAxis]), axis=1 ) |
---|
6130 | Â Â triangles =Â fid.variables['volumes'][:] |
---|
6131 | Â Â |
---|
6132 | Â Â # Get geo_reference |
---|
6133 | Â Â try: |
---|
6134 | Â Â Â Â geo_reference =Â Geo_reference(NetCDFObject=fid) |
---|
6135 | Â Â except:Â #AttributeError, e: |
---|
6136 | Â Â Â Â # Sww files don't have to have a geo_ref |
---|
6137 | Â Â Â Â geo_reference =Â None |
---|
6138 | |
---|
6139 |   if verbose: print '  building mesh from sww file %s' %filename |
---|
6140 | Â Â boundary =Â None |
---|
6141 | |
---|
6142 | Â Â #FIXME (Peter Row): Should this be in mesh? |
---|
6143 |   if fid.smoothing != 'Yes': |
---|
6144 | Â Â Â Â nodes =Â nodes.tolist() |
---|
6145 | Â Â Â Â triangles =Â triangles.tolist() |
---|
6146 |     nodes, triangles, boundary=weed(nodes, triangles, boundary) |
---|
6147 | |
---|
6148 | |
---|
6149 | Â Â try: |
---|
6150 |     mesh = Mesh(nodes, triangles, boundary, |
---|
6151 | Â Â Â Â Â Â Â Â Â Â geo_reference=geo_reference) |
---|
6152 |   except AssertionError, e: |
---|
6153 | Â Â Â Â fid.close() |
---|
6154 | Â Â Â Â msg =Â 'Domain could not be created: %s. "'Â %e |
---|
6155 |     raise DataDomainError, msg |
---|
6156 | |
---|
6157 | |
---|
6158 | Â Â quantities =Â {} |
---|
6159 | Â Â quantities['elevation']Â =Â elevation |
---|
6160 |   quantities['stage'] = stage  |
---|
6161 | Â Â quantities['xmomentum']Â =Â xmomentum |
---|
6162 |   quantities['ymomentum'] = ymomentum  |
---|
6163 | |
---|
6164 | Â Â fid.close() |
---|
6165 |   return mesh, quantities, time |
---|
6166 | |
---|
6167 | |
---|
6168 | |
---|
6169 | def get_flow_through_cross_section(filename, |
---|
6170 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â polyline, |
---|
6171 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=False): |
---|
6172 | Â Â """Obtain flow (m^3/s) perpendicular to specified cross section. |
---|
6173 | |
---|
6174 | Â Â Inputs: |
---|
6175 | Â Â Â Â filename: Name of sww file |
---|
6176 | Â Â Â Â polyline: Representation of desired cross section - it may contain multiple |
---|
6177 | Â Â Â Â Â Â Â Â Â sections allowing for complex shapes. Assume absolute UTM coordinates. |
---|
6178 | Â Â Â Â Â Â Â Â Â Format [[x0, y0], [x1, y1], ...] |
---|
6179 | |
---|
6180 | Â Â Output: |
---|
6181 | Â Â Â Â time: All stored times in sww file |
---|
6182 | Â Â Â Â Q: Hydrograph of total flow across given segments for all stored times. |
---|
6183 | |
---|
6184 | Â Â The normal flow is computed for each triangle intersected by the polyline and |
---|
6185 |   added up. Multiple segments at different angles are specified the normal flows |
---|
6186 | Â Â may partially cancel each other. |
---|
6187 | |
---|
6188 | Â Â The typical usage of this function would be to get flow through a channel, |
---|
6189 | Â Â and the polyline would then be a cross section perpendicular to the flow. |
---|
6190 | |
---|
6191 | Â Â """ |
---|
6192 | |
---|
6193 |   from anuga.fit_interpolate.interpolate import Interpolation_function |
---|
6194 | |
---|
6195 | Â Â quantity_names =['elevation', |
---|
6196 | Â Â Â Â Â Â Â Â Â Â Â 'stage', |
---|
6197 | Â Â Â Â Â Â Â Â Â Â Â 'xmomentum', |
---|
6198 | Â Â Â Â Â Â Â Â Â Â Â 'ymomentum'] |
---|
6199 | |
---|
6200 | Â Â # Get mesh and quantities from sww file |
---|
6201 | Â Â X =Â get_mesh_and_quantities_from_file(filename, |
---|
6202 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â quantities=quantity_names, |
---|
6203 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=verbose) |
---|
6204 |   mesh, quantities, time = X |
---|
6205 | |
---|
6206 | |
---|
6207 | Â Â # Adjust polyline to mesh spatial origin |
---|
6208 | Â Â polyline =Â mesh.geo_reference.get_relative(polyline) |
---|
6209 | Â Â |
---|
6210 | Â Â # Find all intersections and associated triangles. |
---|
6211 |   segments = mesh.get_intersecting_segments(polyline, verbose=verbose) |
---|
6212 | Â Â #print |
---|
6213 | Â Â #for x in segments: |
---|
6214 | Â Â #Â Â print x |
---|
6215 | |
---|
6216 | Â Â |
---|
6217 | Â Â # Then store for each triangle the length of the intersecting segment(s), |
---|
6218 | Â Â # right hand normal(s) and midpoints as interpolation_points. |
---|
6219 | Â Â interpolation_points =Â [] |
---|
6220 |   for segment in segments: |
---|
6221 | Â Â Â Â midpoint =Â sum(array(segment.segment))/2 |
---|
6222 | Â Â Â Â interpolation_points.append(midpoint) |
---|
6223 | |
---|
6224 | |
---|
6225 |   if verbose: |
---|
6226 |     print 'Interpolating - ',    |
---|
6227 |     print 'total number of interpolation points = %d'\ |
---|
6228 | Â Â Â Â Â Â Â %len(interpolation_points) |
---|
6229 | |
---|
6230 | Â Â I =Â Interpolation_function(time, |
---|
6231 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â quantities, |
---|
6232 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â quantity_names=quantity_names, |
---|
6233 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â vertex_coordinates=mesh.nodes, |
---|
6234 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â triangles=mesh.triangles, |
---|
6235 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â interpolation_points=interpolation_points, |
---|
6236 | Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â verbose=verbose) |
---|
6237 | |
---|
6238 |   if verbose: print 'Computing hydrograph' |
---|
6239 | Â Â # Compute hydrograph |
---|
6240 | Â Â Q =Â [] |
---|
6241 |   for t in time: |
---|
6242 | Â Â Â Â total_flow=0 |
---|
6243 |     for i, p in enumerate(interpolation_points): |
---|
6244 |       elevation, stage, uh, vh = I(t, point_id=i) |
---|
6245 | Â Â Â Â Â Â normal =Â segments[i].normal |
---|
6246 | |
---|
6247 | Â |
---|