Changeset 4103


Ignore:
Timestamp:
Dec 20, 2006, 1:22:23 PM (17 years ago)
Author:
duncan
Message:

added blocking for file reading in geospatial_data.py

Location:
anuga_core/source/anuga/geospatial_data
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • anuga_core/source/anuga/geospatial_data/geospatial_data.py

    r4102 r4103  
    1616from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
    1717
    18        
     18MAX_READ_LINES = 500       
    1919class Geospatial_data:
    2020
    2121    def __init__(self,
    22                  data_points=None,
     22                 data_points=None, # this can also be a points file name
    2323                 attributes=None,
    2424                 geo_reference=None,
     
    2929                 longitudes=None,
    3030                 points_are_lats_longs=False,
     31                 max_read_lines=None,                 
    3132                 verbose=False):
    3233
     
    110111        self.set_verbose(verbose)
    111112        self.geo_reference=None #create the attribute
     113        self.file_name = file_name
     114        self.max_read_lines = max_read_lines
    112115        if file_name is None:
    113116            if delimiter is not None:
     
    656659        return G1, G2
    657660
    658 
    659 def _read_pts_file(file_name, verbose=False):
     661    def __iter__(self):
     662        # read in the header and save the file pointer position
     663
     664        #FIXME - what to do if the file isn't there
     665        file_pointer = open(self.file_name)
     666        self.header, self.file_pointer = _read_csv_file_header(file_pointer)
     667
     668        if self.max_read_lines is None:
     669            self.max_read_lines = MAX_READ_LINES
     670        return self
     671   
     672    def next(self):
     673        # read a block, instanciate a new geospatial and return it
     674        try:
     675            pointlist, att_dict, self.file_pointer = _read_csv_file_blocking( \
     676                self.file_pointer,
     677                self.header[:],
     678                max_read_lines=self.max_read_lines)
     679        except StopIteration:
     680            self.file_pointer.close()
     681            raise StopIteration
     682        return Geospatial_data(pointlist, att_dict)
     683
     684def _read_pts_file(file_name, verbose = False):
    660685    """Read .pts NetCDF file
    661686   
     
    721746    """
    722747   
    723     from anuga.shallow_water.data_manager import Exposure_csv
    724     csv =Exposure_csv(file_name)
    725    
    726     return pointlist, attributes, geo_reference
     748    #from anuga.shallow_water.data_manager import Exposure_csv
     749    #csv =Exposure_csv(file_name)
     750   
     751    file_pointer = open(file_name)
     752    header, file_pointer = _read_csv_file_header(file_pointer)
     753
     754    while True:
     755        try:
     756            pointlist, att_dict,file_pointer  = _read_csv_file_blocking( \
     757                file_pointer,
     758                header,
     759                max_read_lines=5000) #FIXME: how hacky is that!
     760        except StopIteration:
     761            break
     762       
     763    file_pointer.close()
     764    return pointlist, att_dict, None   
     765
     766CSV_DELIMITER = ','
     767def _read_csv_file_header(file_pointer, delimiter=CSV_DELIMITER,
     768                          verbose=False):
     769
     770    """Read the header of a .csv file
     771    Return a list of the header names
     772    """
     773    line = file_pointer.readline()
     774    header = clean_line(line, delimiter)
     775    return header, file_pointer
     776
     777def _read_csv_file_blocking(file_pointer, header,
     778                            delimiter=CSV_DELIMITER,
     779                            max_read_lines = 500,
     780                            verbose = False):
     781   
     782
     783    """
     784    Read the body of a .csv file.
     785    header: The list header of the csv file, with the x and y labels.
     786    """
     787    points = []
     788    pointattributes = []
     789    att_dict = {}
     790
     791    #This is to remove the x and y headers.
     792    header.pop(0)
     793    header.pop(0)
     794   
     795    read_lines = 0
     796    while read_lines<max_read_lines:
     797        line = file_pointer.readline()
     798        #print "line",line
     799        numbers = clean_line(line,delimiter)
     800        if len(numbers) <= 1:
     801            break
     802        if line[0] == '#':
     803            continue
     804        read_lines += 1
     805        if True: # remove.. #if numbers != []:
     806            try:
     807                x = float(numbers[0])
     808                y = float(numbers[1])
     809                points.append([x,y])
     810                numbers.pop(0)
     811                numbers.pop(0)
     812                if len(header) != len(numbers):
     813                   
     814                    file_pointer.close()
     815                    # It might not be a problem with the header
     816                    #raise TitleAmountError
     817                    raise IOError
     818                for i,num in enumerate(numbers):
     819                    num.strip()
     820                    if num != '\n' and num != '':
     821                        #attributes.append(float(num))
     822                        att_dict.setdefault(header[i],[]).append(float(num))
     823            except ValueError:
     824                raise SyntaxError
     825    if points == []:
     826        raise StopIteration
     827       
     828   
     829    pointlist = array(points).astype(Float)
     830    for key in att_dict.keys():
     831        att_dict[key] = array(att_dict[key]).astype(Float)
     832       
     833    return pointlist, att_dict,file_pointer
    727834
    728835def _read_xya_file(fd, delimiter):
     
    10101117
    10111118             
     1119
     1120         
     1121if __name__ == "__main__":
     1122    g = Geospatial_data("t.xxx")
     1123    print "g.get_data_points()", g.get_data_points()
     1124    for i,a in enumerate(g):
     1125        if i >3: break
     1126        print a
     1127   
  • anuga_core/source/anuga/geospatial_data/test_geospatial_data.py

    r4061 r4103  
    903903#                        'imaginary file did not raise error!')
    904904
    905                        
    906   ###################### .XYA ##############################
     905
     906  ###################### .CSV ##############################
     907
     908    def test_load_csv(self):
     909        """
     910        space delimited
     911        """
     912        import os
     913       
     914        fileName = tempfile.mktemp(".xxx")
     915        file = open(fileName,"w")
     916        file.write(" x,y, elevation ,  speed \n\
     9171.0, 0.0, 10.0, 0.0\n\
     9180.0, 1.0, 0.0, 10.0\n\
     9191.0, 0.0 ,10.4, 40.0\n")
     920        file.close()
     921
     922        results = Geospatial_data(fileName, max_read_lines=2)
     923
     924
     925        assert allclose(results.get_data_points(), [[1.0, 0.0],[0.0, 1.0],[1.0, 0.0]])
     926        assert allclose(results.get_attributes(attribute_name='elevation'), [10.0, 0.0, 10.4])
     927        assert allclose(results.get_attributes(attribute_name='speed'), [0.0, 10.0, 40.0])
     928
     929        # Blocking
     930        geo_list = []
     931        for i in results:
     932            geo_list.append(i)
     933           
     934        assert allclose(geo_list[0].get_data_points(),
     935                        [[1.0, 0.0],[0.0, 1.0]])
     936
     937        assert allclose(geo_list[0].get_attributes(attribute_name='elevation'),
     938                        [10.0, 0.0])
     939        assert allclose(geo_list[1].get_data_points(),
     940                        [[1.0, 0.0]])       
     941        assert allclose(geo_list[1].get_attributes(attribute_name='elevation'),
     942                        [10.4])
     943           
     944        os.remove(fileName)             
    907945       
    908946    def test_export_xya_file(self):
Note: See TracChangeset for help on using the changeset viewer.