Ignore:
Timestamp:
Jun 15, 2010, 12:06:46 PM (13 years ago)
Author:
hudson
Message:

Refactorings to allow tests to pass.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/anuga_core/source/anuga/file/sww.py

    r7796 r7841  
    4747
    4848        #FIXME: Should we have a general set_precision function?
    49 
    50 
    51 ##
    52 # @brief Class for handling checkpoints data
    53 # @note This is not operational at the moment
    54 class CPT_file(Data_format):
    55     """Interface to native NetCDF format (.cpt) to be
    56     used for checkpointing (one day)
    57     """
    58 
    59     ##
    60     # @brief Initialize this instantiation.
    61     # @param domain ??
    62     # @param mode Mode of underlying data file (default WRITE).
    63     def __init__(self, domain, mode=netcdf_mode_w):
    64         from Scientific.IO.NetCDF import NetCDFFile
    65 
    66         self.precision = netcdf_float #Use full precision
    67 
    68         Data_format.__init__(self, domain, 'sww', mode)
    69 
    70         # NetCDF file definition
    71         fid = NetCDFFile(self.filename, mode)
    72         if mode[0] == 'w':
    73             # Create new file
    74             fid.institution = 'Geoscience Australia'
    75             fid.description = 'Checkpoint data'
    76             #fid.smooth = domain.smooth
    77             fid.order = domain.default_order
    78 
    79             # Dimension definitions
    80             fid.createDimension('number_of_volumes', self.number_of_volumes)
    81             fid.createDimension('number_of_vertices', 3)
    82 
    83             # Store info at all vertices (no smoothing)
    84             fid.createDimension('number_of_points', 3*self.number_of_volumes)
    85             fid.createDimension('number_of_timesteps', None) #extensible
    86 
    87             # Variable definitions
    88 
    89             # Mesh
    90             fid.createVariable('x', self.precision, ('number_of_points',))
    91             fid.createVariable('y', self.precision, ('number_of_points',))
    92 
    93 
    94             fid.createVariable('volumes', netcdf_int, ('number_of_volumes',
    95                                                        'number_of_vertices'))
    96 
    97             fid.createVariable('time', self.precision, ('number_of_timesteps',))
    98 
    99             #Allocate space for all quantities
    100             for name in domain.quantities.keys():
    101                 fid.createVariable(name, self.precision,
    102                                    ('number_of_timesteps',
    103                                     'number_of_points'))
    104 
    105         fid.close()
    106 
    107     ##
    108     # @brief Store connectivity data to underlying data file.
    109     def store_checkpoint(self):
    110         """Write x,y coordinates of triangles.
    111         Write connectivity (
    112         constituting
    113         the bed elevation.
    114         """
    115 
    116         from Scientific.IO.NetCDF import NetCDFFile
    117 
    118         domain = self.domain
    119 
    120         #Get NetCDF
    121         fid = NetCDFFile(self.filename, netcdf_mode_a)
    122 
    123         # Get the variables
    124         x = fid.variables['x']
    125         y = fid.variables['y']
    126 
    127         volumes = fid.variables['volumes']
    128 
    129         # Get X, Y and bed elevation Z
    130         Q = domain.quantities['elevation']
    131         X,Y,Z,V = Q.get_vertex_values(xy=True, precision=self.precision)
    132 
    133         x[:] = X.astype(self.precision)
    134         y[:] = Y.astype(self.precision)
    135         z[:] = Z.astype(self.precision)
    136 
    137         volumes[:] = V
    138 
    139         fid.close()
    140 
    141     ##
    142     # @brief Store time and named quantities to underlying data file.
    143     # @param name
    144     def store_timestep(self, name):
    145         """Store time and named quantity to file
    146         """
    147 
    148         from Scientific.IO.NetCDF import NetCDFFile
    149         from time import sleep
    150 
    151         #Get NetCDF
    152         retries = 0
    153         file_open = False
    154         while not file_open and retries < 10:
    155             try:
    156                 fid = NetCDFFile(self.filename, netcdf_mode_a)
    157             except IOError:
    158                 #This could happen if someone was reading the file.
    159                 #In that case, wait a while and try again
    160                 msg = 'Warning (store_timestep): File %s could not be opened' \
    161                       ' - trying again' % self.filename
    162                 log.critical(msg)
    163                 retries += 1
    164                 sleep(1)
    165             else:
    166                 file_open = True
    167 
    168         if not file_open:
    169             msg = 'File %s could not be opened for append' % self.filename
    170             raise DataFileNotOpenError, msg
    171 
    172         domain = self.domain
    173 
    174         # Get the variables
    175         time = fid.variables['time']
    176         stage = fid.variables['stage']
    177         i = len(time)
    178 
    179         #Store stage
    180         time[i] = self.domain.time
    181 
    182         # Get quantity
    183         Q = domain.quantities[name]
    184         A,V = Q.get_vertex_values(xy=False, precision=self.precision)
    185 
    186         stage[i,:] = A.astype(self.precision)
    187 
    188         #Flush and close
    189         fid.sync()
    190         fid.close()
    19149
    19250
     
    536394
    537395    def read_mesh(self):
     396        """ Read and store the mesh data contained within this sww file.
     397        """
    538398        fin = NetCDFFile(self.source, 'r')
    539399
     
    551411
    552412
    553 
    554413        fin.close()
    555414       
    556415    def read_quantities(self, frame_number=0):
    557 
     416        """
     417        Read the quantities contained in this file.
     418        frame_number is the time index to load.
     419        """
    558420        assert frame_number >= 0 and frame_number <= self.last_frame_number
    559421
     
    575437
    576438    def get_bounds(self):
     439        """
     440            Get the bounding rect around the mesh.
     441        """
    577442        return [self.xmin, self.xmax, self.ymin, self.ymax]
    578443
    579444    def get_last_frame_number(self):
     445        """
     446            Return the last loaded frame index.
     447        """
    580448        return self.last_frame_number
    581449
    582450    def get_time(self):
     451        """
     452            Get time at the current frame num, in secs.
     453        """
    583454        return self.time[self.frame_number]
    584455
    585456
    586 # @brief A class to write an SWW file.
    587457class Write_sww:
    588    
     458    """
     459        A class to write an SWW file.
     460       
     461        It is domain agnostic, and requires all the data to be fed in
     462        manually.
     463    """
    589464    RANGE = '_range'
    590465    EXTREMA = ':extrema'
    591466
    592     ##
    593     # brief Instantiate the SWW writer class.
    594467    def __init__(self, static_quantities, dynamic_quantities):
    595468        """Initialise Write_sww with two list af quantity names:
     
    607480
    608481
    609     ##
    610     # @brief Store a header in the SWW file.
    611     # @param outfile Open handle to the file that will be written.
    612     # @param times A list of time slices *or* a start time.
    613     # @param number_of_volumes The number of triangles.
    614     # @param number_of_points The number of points.
    615     # @param description The internal file description string.
    616     # @param smoothing True if smoothing is to be used.
    617     # @param order
    618     # @param sww_precision Data type of the quantity written (netcdf constant)
    619     # @param verbose True if this function is to be verbose.
    620     # @note If 'times' is a list, the info will be made relative.
    621482    def store_header(self,
    622483                     outfile,
     
    631492        """Write an SWW file header.
    632493
     494        Writes the first section of the .sww file.
     495
    633496        outfile - the open file that will be written
    634497        times - A list of the time slice times OR a start time
    635498        Note, if a list is given the info will be made relative.
    636499        number_of_volumes - the number of triangles
     500        number_of_points - the number of vertices in the mesh
    637501        """
    638502
     
    746610                         % (num.min(times), num.max(times), len(times.flat)))
    747611
    748     ##
    749     # @brief Store triangulation data in the underlying file.
    750     # @param outfile Open handle to underlying file.
    751     # @param points_utm List or array of points in UTM.
    752     # @param volumes
    753     # @param zone
    754     # @param new_origin georeference that the points can be set to.
    755     # @param points_georeference The georeference of the points_utm.
    756     # @param verbose True if this function is to be verbose.
     612
    757613    def store_triangulation(self,
    758614                            outfile,
     
    764620                            verbose=False):
    765621        """
     622        Store triangulation data in the underlying file.
     623       
     624        Stores the points and triangle indices in the sww file
     625       
     626        outfile Open handle to underlying file.
     627
     628        new_origin georeference that the points can be set to.
     629
     630        points_georeference The georeference of the points_utm.
     631
     632        verbose True if this function is to be verbose.
     633
    766634        new_origin - qa georeference that the points can be set to. (Maybe
    767635        do this before calling this function.)
     
    840708
    841709
    842 
    843     # @brief Write the static quantity data to the underlying file.
    844     # @param outfile Handle to open underlying file.
    845     # @param sww_precision Format of quantity data to write (default Float32).
    846     # @param verbose True if this function is to be verbose.
    847     # @param **quant
    848710    def store_static_quantities(self,
    849711                                outfile,
     
    896758       
    897759       
    898     ##
    899     # @brief Write the quantity data to the underlying file.
    900     # @param outfile Handle to open underlying file.
    901     # @param sww_precision Format of quantity data to write (default Float32).
    902     # @param slice_index
    903     # @param time
    904     # @param verbose True if this function is to be verbose.
    905     # @param **quant
    906760    def store_quantities(self,
    907761                         outfile,
     
    986840
    987841
    988 ##
    989 # @brief Get the extents of a NetCDF data file.
    990 # @param file_name The path to the SWW file.
    991 # @return A list of x, y, z and stage limits (min, max).
    992842def extent_sww(file_name):
    993     """Read in an sww file.
     843    """Read in an sww file, then get its extents
    994844
    995845    Input:
     
    1015865
    1016866
    1017 ##
    1018 # @brief
    1019 # @param filename
    1020 # @param boundary
    1021 # @param t
    1022 # @param fail_if_NaN
    1023 # @param NaN_filler
    1024 # @param verbose
    1025 # @param very_verbose
    1026 # @return
    1027867def load_sww_as_domain(filename, boundary=None, t=None,
    1028868               fail_if_NaN=True, NaN_filler=0,
    1029869               verbose=False, very_verbose=False):
    1030870    """
     871    Load an sww file into a domain.
     872
    1031873    Usage: domain = load_sww_as_domain('file.sww',
    1032874                        t=time (default = last time in file))
     
    11941036
    11951037
    1196 ##
    1197 # @brief Get mesh and quantity data from an SWW file.
    1198 # @param filename Path to data file to read.
    1199 # @param quantities UNUSED!
    1200 # @param verbose True if this function is to be verbose.
    1201 # @return (mesh, quantities, time) where mesh is the mesh data, quantities is
    1202 #         a dictionary of {name: value}, and time is the time vector.
    1203 # @note Quantities extracted: 'elevation', 'stage', 'xmomentum' and 'ymomentum'
    12041038def get_mesh_and_quantities_from_file(filename,
    12051039                                      quantities=None,
     
    12801114
    12811115
    1282 
    1283 ##
    1284 # @brief
    1285 # @parm time
    1286 # @param t
    1287 # @return An (index, ration) tuple.
    12881116def get_time_interp(time, t=None):
    1289     #Finds the ratio and index for time interpolation.
    1290     #It is borrowed from previous abstract_2d_finite_volumes code.
     1117    """Finds the ratio and index for time interpolation.
     1118        time is an array of time steps
     1119        t is the sample time.
     1120        returns a tuple containing index into time, and ratio
     1121    """
    12911122    if t is None:
    12921123        t=time[-1]
     
    13371168
    13381169
    1339 ##
    1340 # @brief
    1341 # @param coordinates
    1342 # @param volumes
    1343 # @param boundary
    13441170def weed(coordinates, volumes, boundary=None):
     1171    """ Excise all duplicate points.
     1172    """
    13451173    if isinstance(coordinates, num.ndarray):
    13461174        coordinates = coordinates.tolist()
Note: See TracChangeset for help on using the changeset viewer.