Changeset 3292


Ignore:
Timestamp:
Jul 7, 2006, 4:09:39 PM (18 years ago)
Author:
duncan
Message:

Adding class Exposure_csv, to interact with exposure csv files.

Location:
inundation
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • inundation/coordinate_transforms/redfearn.py

    r3280 r3292  
    178178   
    179179    for lat, long in map(None, latitudes, longitudes,):
    180         zone, easting, northing = redfearn(lat,
    181                                            long,
     180        zone, easting, northing = redfearn(float(lat),
     181                                           float(long),
    182182                                           false_easting=false_easting,
    183183                                           false_northing=false_northing)
  • inundation/coordinate_transforms/test_redfearn.py

    r3280 r3292  
    187187            self.failUnless(0 ==1,
    188188                        'Error not thrown error!')
    189 
     189           
     190    def test_convert_lats_longs3(self):
     191
     192        #Site Name:    GDA-MGA: (UTM with GRS80 ellipsoid)
     193        #Zone:   56   
     194        #Easting:  222908.705  Northing: 6233785.284
     195        #Latitude:   -34  0 ' 0.00000 ''  Longitude: 150  0 ' 0.00000 ''
     196        #Grid Convergence:  -1  40 ' 43.13 ''  Point Scale: 1.00054660
     197
     198        lat_gong = "-34.5"
     199        lon_gong = "150.916666667"
     200        lat_2 = degminsec2decimal_degrees(34,00,0.)
     201        lon_2 = degminsec2decimal_degrees(100,00,0.)
     202       
     203        lats = [lat_gong, lat_2]
     204        longs = [lon_gong, lon_2]
     205        try:
     206            zone, points = convert_lats_longs(lats, longs)
     207        except ANUGAError:
     208            pass
     209        else:
     210            self.failUnless(0 ==1,
     211                        'Error not thrown error!')
    190212#-------------------------------------------------------------
    191213if __name__ == "__main__":
  • inundation/geospatial_data/test_geospatial_data.py

    r3280 r3292  
    12741274            pass
    12751275        else:
    1276             self.failUnless(0 ==1,
    1277                         'Error not thrown error!')
     1276            self.failUnless(0 ==1,  'Error not thrown error!')
    12781277        try:
    12791278            results = Geospatial_data(latitudes=lats)
     
    12811280            pass
    12821281        else:
    1283             self.failUnless(0 ==1,
    1284                         'Error not thrown error!')
     1282            self.failUnless(0 ==1,  'Error not thrown error!')
    12851283        try:
    12861284            results = Geospatial_data(longitudes=lats)
     
    12881286            pass
    12891287        else:
    1290             self.failUnless(0 ==1,
    1291                         'Error not thrown error!')
     1288            self.failUnless(0 ==1, 'Error not thrown error!')
    12921289        try:
    12931290            results = Geospatial_data(latitudes=lats, longitudes=longs,
     
    12961293            pass
    12971294        else:
    1298             self.failUnless(0 ==1,
    1299                         'Error not thrown error!')
     1295            self.failUnless(0 ==1,  'Error not thrown error!')
    13001296           
    13011297        try:
     
    13051301            pass
    13061302        else:
    1307             self.failUnless(0 ==1,
    1308                         'Error not thrown error!')
     1303            self.failUnless(0 ==1,  'Error not thrown error!')
    13091304           
    13101305if __name__ == "__main__":
  • inundation/pyvolution/data_manager.py

    r2931 r3292  
    5050
    5151import exceptions
     52class TitleValueError(exceptions.Exception): pass
    5253class DataMissingValuesError(exceptions.Exception): pass
    5354class DataFileNotOpenError(exceptions.Exception): pass
     
    5758
    5859
     60import csv
    5961import os
    6062
     
    6466
    6567from coordinate_transforms.geo_reference import Geo_reference
     68from geospatial_data.geospatial_data import Geospatial_data
    6669
    6770
     
    646649#Function for storing xya output
    647650#FIXME Not done yet for this version
     651#This is obsolete.  Use geo_spatial_data instead
    648652class Data_format_xya(Data_format):
    649653    """Generic interface to data formats
     
    715719        """
    716720        pass
     721
     722
     723#### NBED national exposure database
     724   
     725LAT_TITLE = 'LATITUDE'
     726LONG_TITLE = 'LONGITUDE'
     727class Exposure_csv:
     728    def __init__(self,file_name, latitude_title=LAT_TITLE,
     729                 longitude_title=LONG_TITLE, refine_polygon=None):
     730        """
     731        Not for adding and deleting rows
     732        Can geospatial handle string attributes? It's not made for them.
     733        Currently it can't load and save string att's.
     734
     735        So just use geospatial to hold the x, y and georef? Bad, since
     736        different att's are in diferent structures.  Not so bad, the info
     737        to write if the .csv file is saved is in attribute_dic
     738
     739        The location info is in the geospatial attribute.
     740       
     741       
     742        """
     743        self._file_name = file_name
     744        self._geospatial = None #
     745
     746        # self._attribute_dic is a dictionary.
     747        #The keys are the column titles.
     748        #The values are lists of column data
     749       
     750        # self._title_index_dic is a dictionary.
     751        #The keys are the column titles.
     752        #The values are the index positions of file columns.
     753        self._attribute_dic, self._title_index_dic = \
     754        self._load_exposure_csv(self._file_name)
     755        try:
     756            lats = self._attribute_dic[latitude_title]
     757            longs = self._attribute_dic[longitude_title]
     758           
     759        except KeyError:
     760            # maybe a warning..
     761            pass
     762        else:
     763            self._geospatial = Geospatial_data(latitudes = lats,
     764                 longitudes = longs)
     765           
     766        # create a list of points that are in the refining_polygon
     767        # described by a list of indexes representing the points
     768
     769    def __cmp__(self, other):
     770        #print "self._attribute_dic",self._attribute_dic
     771        #print "other._attribute_dic",other._attribute_dic
     772        #print "self._title_index_dic", self._title_index_dic
     773        #print "other._title_index_dic", other._title_index_dic
     774       
     775        #check that a is an instance of this class
     776        if isinstance(self, type(other)):
     777            result = cmp(self._attribute_dic, other._attribute_dic)
     778            if result <>0:
     779                return result
     780            # The order of the columns is important. Therefore..
     781            result = cmp(self._title_index_dic, other._title_index_dic)
     782            if result <>0:
     783                return result
     784            for self_ls, other_ls in map(None,self._attribute_dic, \
     785                    other._attribute_dic):
     786                result = cmp(self._attribute_dic[self_ls],
     787                             other._attribute_dic[other_ls])
     788                if result <>0:
     789                    return result
     790            return 0
     791        else:
     792            return 1
     793   
     794    def _load_exposure_csv(self, file_name):
     795        """
     796        Load in the csv as a dic, title as key and column info as value, .
     797        Also, create a dic, title as key and column index as value.
     798        """
     799        #
     800        attribute_dic = {}
     801        title_index_dic = {}
     802        titles_stripped = [] # list of titles
     803       
     804        reader = csv.reader(file(file_name))
     805
     806        # Read in and manipulate the title info
     807        titles = reader.next()
     808        for i,title in enumerate(titles):
     809            titles_stripped.append(title.strip())
     810            title_index_dic[title.strip()] = i
     811        title_count = len(titles_stripped)       
     812        #print "title_index_dic",title_index_dic
     813
     814       
     815        #create a dic of colum values, indexed by column title
     816        for line in reader:
     817            if len(line) <> title_count:
     818                raise IOError #FIXME make this nicer
     819            for i, value in enumerate(line):
     820                attribute_dic.setdefault(titles_stripped[i],[]).append(value)
     821           
     822        return attribute_dic, title_index_dic
     823
     824    def get_column(self, column_name, use_refind_polygon=False):
     825        """
     826        Given a column name return a list of the column values
     827
     828        Note, the type of the values will be String!
     829        Thinking of semi-hard coding this to not be so..
     830       
     831        Not implemented:
     832        if use_refind_polygon is True, only return values in the
     833        refined polygon
     834        """
     835        if not self._attribute_dic.has_key(column_name):
     836            msg = 'Therer is  no column called %s!' %column_name
     837            raise TitleValueError, msg
     838        return self._attribute_dic[column_name]
     839
     840    def get_location(self, use_refind_polygon=False):
     841        """
     842        Return a geospatial object which describes the
     843        locations of the location file.
     844
     845        Note, if there is not location info, this returns None.
     846       
     847        Not implemented:
     848        if use_refind_polygon is True, only return values in the
     849        refined polygon
     850        """
     851        return self._geospatial
     852
     853    def set_column(self, column_name, column_values, overwrite=False):
     854        """
     855        Add a column to the 'end' (with the right most column being the end)
     856        of the csv file.
     857
     858        Set overwrite to True if you want to overwrite a column.
     859       
     860        Note, in column_name white space is removed and case is not checked.
     861        Precondition
     862        The column_name and column_values cannot have comma's in it.
     863        """
     864       
     865        value_row_count = \
     866            len(self._attribute_dic[self._title_index_dic.keys()[0]])
     867        if len(column_values) <> value_row_count:
     868            msg = 'The number of column values must equal the number of rows.'
     869            raise DataMissingValuesError, msg
     870       
     871        if self._attribute_dic.has_key(column_name):
     872            if not overwrite:
     873                msg = 'Column name %s already in use!' %column_name
     874                raise TitleValueError, msg
     875        else:
     876            # New title.  Add it to the title index.
     877            self._title_index_dic[column_name] = len(self._title_index_dic)
     878        self._attribute_dic[column_name] = column_values
     879        #print "self._title_index_dic[column_name]",self._title_index_dic
     880
     881    def save(self, file_name=None):
     882        """
     883        Save the exposure csv file
     884        """
     885        if file_name is None:
     886            file_name = self._file_name
     887       
     888        fd = open(file_name,'wb')
     889        writer = csv.writer(fd)
     890       
     891        #Write the title to a cvs file
     892        line = [None]* len(self._title_index_dic)
     893        for title in self._title_index_dic.iterkeys():
     894            line[self._title_index_dic[title]]= title
     895        writer.writerow(line)
     896       
     897        # Write the values to a cvs file
     898        value_row_count = \
     899            len(self._attribute_dic[self._title_index_dic.keys()[0]])
     900        for row_i in range(value_row_count):
     901            line = [None]* len(self._title_index_dic)
     902            for title in self._title_index_dic.iterkeys():
     903                line[self._title_index_dic[title]]= \
     904                     self._attribute_dic[title][row_i]
     905            writer.writerow(line)
    717906
    718907
     
    9511140    return cls(domain, mode)
    9521141
     1142#FIXME move into geospatial.  There should only be one method that
     1143# reads xya, and writes pts.
    9531144def xya2pts(basename_in, basename_out=None, verbose=False,
    9541145            #easting_min=None, easting_max=None,
     
    33013492    """
    33023493
    3303     #FIXME Move to data_manager
    33043494    from shallow_water import Domain
    33053495    from pmesh2domain import pmesh_to_domain_instance
     
    38023992
    38033993    return
     3994
     3995#-------------------------------------------------------------
     3996if __name__ == "__main__":
     3997    import csv
     3998    reader = csv.reader(file("some.csv"))
     3999    heading = reader.next()
     4000    clean_heading = heading.strip()
     4001    print "heading",heading
     4002
     4003    #a = csv.DictReader("some.csv")
     4004   
     4005
     4006
     4007
  • inundation/pyvolution/test_data_manager.py

    r3279 r3292  
    46594659
    46604660
    4661 
     4661    def test_exposure_csv_loading(self):
     4662       
     4663
     4664        file_name = tempfile.mktemp(".xya")
     4665        file = open(file_name,"w")
     4666        file.write("LATITUDE, LONGITUDE ,sound  , speed \n\
     4667115.0, -21.0, splat, 0.0\n\
     4668114.0, -21.7, pow, 10.0\n\
     4669114.5, -21.4, bang, 40.0\n")
     4670        file.close()
     4671        exposure = Exposure_csv(file_name)
     4672        exposure.get_column("sound")
     4673       
     4674        self.failUnless(exposure._attribute_dic['sound'][2]==' bang',
     4675                        'FAILED!')
     4676        self.failUnless(exposure._attribute_dic['speed'][2]==' 40.0',
     4677                        'FAILED!')
     4678       
     4679        os.remove(file_name)
     4680       
     4681    def test_exposure_csv_loading(self):
     4682       
     4683
     4684        file_name = tempfile.mktemp(".xya")
     4685        file = open(file_name,"w")
     4686        file.write("LATITUDE, LONGITUDE ,sound  , speed \n\
     4687115.0, -21.0, splat, 0.0\n\
     4688114.0, -21.7, pow, 10.0\n\
     4689114.5, -21.4, bang, 40.0\n")
     4690        file.close()
     4691        exposure = Exposure_csv(file_name)
     4692        exposure.get_column("sound")
     4693       
     4694        self.failUnless(exposure._attribute_dic['sound'][2]==' bang',
     4695                        'FAILED!')
     4696        self.failUnless(exposure._attribute_dic['speed'][2]==' 40.0',
     4697                        'FAILED!')
     4698       
     4699        os.remove(file_name)
     4700
     4701    def test_exposure_csv_cmp(self):
     4702        file_name = tempfile.mktemp(".xya")
     4703        file = open(file_name,"w")
     4704        file.write("LATITUDE, LONGITUDE ,sound  , speed \n\
     4705115.0, -21.0, splat, 0.0\n\
     4706114.0, -21.7, pow, 10.0\n\
     4707114.5, -21.4, bang, 40.0\n")
     4708        file.close()
     4709       
     4710        e1 = Exposure_csv(file_name)
     4711        e2 = Exposure_csv(file_name)
     4712        os.remove(file_name)
     4713
     4714        self.failUnless(cmp(e1,e2)==0,
     4715                        'FAILED!')
     4716       
     4717        self.failUnless(cmp(e1,"hey")==1,
     4718                        'FAILED!')
     4719       
     4720        file_name = tempfile.mktemp(".xya")
     4721        file = open(file_name,"w")
     4722        # Note, this has less spaces in the title,
     4723        # the instances will be the same.
     4724        file.write("LATITUDE,LONGITUDE ,sound, speed \n\
     4725115.0, -21.0, splat, 0.0\n\
     4726114.0, -21.7, pow, 10.0\n\
     4727114.5, -21.4, bang, 40.0\n")
     4728        file.close()
     4729        e3 = Exposure_csv(file_name)
     4730        os.remove(file_name)
     4731
     4732        self.failUnless(cmp(e3,e2)==0,
     4733                        'FAILED!')
     4734       
     4735        file_name = tempfile.mktemp(".xya")
     4736        file = open(file_name,"w")
     4737        # Note, 40 changed to 44 .
     4738        file.write("LATITUDE,LONGITUDE ,sound, speed \n\
     4739115.0, -21.0, splat, 0.0\n\
     4740114.0, -21.7, pow, 10.0\n\
     4741114.5, -21.4, bang, 44.0\n")
     4742        file.close()
     4743        e4 = Exposure_csv(file_name)
     4744        os.remove(file_name)
     4745        #print "e4",e4._attribute_dic
     4746        #print "e2",e2._attribute_dic
     4747        self.failUnless(cmp(e4,e2)<>0,
     4748                        'FAILED!')
     4749       
     4750        file_name = tempfile.mktemp(".xya")
     4751        file = open(file_name,"w")
     4752        # Note, the first two columns are swapped.
     4753        file.write("LONGITUDE,LATITUDE ,sound, speed \n\
     4754 -21.0,115.0, splat, 0.0\n\
     4755 -21.7,114.0, pow, 10.0\n\
     4756 -21.4,114.5, bang, 40.0\n")
     4757        file.close()
     4758        e5 = Exposure_csv(file_name)
     4759        os.remove(file_name)
     4760
     4761        self.failUnless(cmp(e3,e5)<>0,
     4762                        'FAILED!')
     4763       
     4764    def test_exposure_csv_saving(self):
     4765       
     4766
     4767        file_name = tempfile.mktemp(".xya")
     4768        file = open(file_name,"w")
     4769        file.write("LATITUDE, LONGITUDE ,sound  , speed \n\
     4770115.0, -21.0, splat, 0.0\n\
     4771114.0, -21.7, pow, 10.0\n\
     4772114.5, -21.4, bang, 40.0\n")
     4773        file.close()
     4774        e1 = Exposure_csv(file_name)
     4775       
     4776        file_name2 = tempfile.mktemp(".xya")
     4777        e1.save(file_name = file_name2)
     4778        e2 = Exposure_csv(file_name2)
     4779       
     4780        self.failUnless(cmp(e1,e2)==0,
     4781                        'FAILED!')
     4782        os.remove(file_name)
     4783        os.remove(file_name2)
     4784
     4785    def test_exposure_csv_get_location(self):
     4786        file_name = tempfile.mktemp(".xya")
     4787        file = open(file_name,"w")
     4788        file.write("LONGITUDE , LATITUDE, sound  , speed \n\
     4789150.916666667, -34.5, splat, 0.0\n\
     4790150.0, -34.0, pow, 10.0\n")
     4791        file.close()
     4792        e1 = Exposure_csv(file_name)
     4793
     4794        gsd = e1.get_location()
     4795       
     4796        points = gsd.get_data_points(absolute=True)
     4797       
     4798        assert allclose(points[0][0], 308728.009)
     4799        assert allclose(points[0][1], 6180432.601)
     4800        assert allclose(points[1][0],  222908.705)
     4801        assert allclose(points[1][1], 6233785.284)
     4802        self.failUnless(gsd.get_geo_reference().get_zone() == 56,
     4803                        'Bad zone error!')
     4804
     4805        os.remove(file_name)
     4806       
     4807    def test_exposure_csv_set_column_get_column(self):
     4808        file_name = tempfile.mktemp(".xya")
     4809        file = open(file_name,"w")
     4810        file.write("LONGITUDE , LATITUDE, sound  , speed \n\
     4811150.916666667, -34.5, splat, 0.0\n\
     4812150.0, -34.0, pow, 10.0\n")
     4813        file.close()
     4814        e1 = Exposure_csv(file_name)     
     4815        os.remove(file_name)
     4816
     4817        new_title = "feast"
     4818        new_values = ["chicken","soup"]
     4819        e1.set_column(new_title, new_values)
     4820        returned_values = e1.get_column(new_title)
     4821        self.failUnless(returned_values == new_values,
     4822                        ' Error!')
     4823       
     4824        file_name2 = tempfile.mktemp(".xya")
     4825        e1.save(file_name = file_name2)
     4826        e2 = Exposure_csv(file_name2)
     4827        returned_values = e2.get_column(new_title)
     4828        self.failUnless(returned_values == new_values,
     4829                        ' Error!')       
     4830        os.remove(file_name2)
     4831
     4832    def test_exposure_csv_set_column_get_column_error_checking(self):
     4833        file_name = tempfile.mktemp(".xya")
     4834        file = open(file_name,"w")
     4835        file.write("LONGITUDE , LATITUDE, sound  , speed \n\
     4836150.916666667, -34.5, splat, 0.0\n\
     4837150.0, -34.0, pow, 10.0\n")
     4838        file.close()
     4839        e1 = Exposure_csv(file_name)     
     4840        os.remove(file_name)
     4841
     4842        new_title = "sound"
     4843        new_values = [12.5,7.6]
     4844        try:
     4845            e1.set_column(new_title, new_values)
     4846        except TitleValueError:
     4847            pass
     4848        else:
     4849            self.failUnless(0 ==1,  'Error not thrown error!')
     4850           
     4851        e1.set_column(new_title, new_values, overwrite=True)
     4852        returned_values = e1.get_column(new_title)
     4853        self.failUnless(returned_values == new_values,
     4854                        ' Error!')       
     4855       
     4856        new2_title = "short list"
     4857        new2_values = [12.5]
     4858        try:
     4859            e1.set_column(new2_title, new2_values)
     4860        except DataMissingValuesError:
     4861            pass
     4862        else:
     4863            self.failUnless(0 ==1,  'Error not thrown error!')
     4864           
     4865        new2_title = "long list"
     4866        new2_values = [12.5, 7,8]
     4867        try:
     4868            e1.set_column(new2_title, new2_values)
     4869        except DataMissingValuesError:
     4870            pass
     4871        else:
     4872            self.failUnless(0 ==1,  'Error not thrown error!')
     4873        file_name2 = tempfile.mktemp(".xya")
     4874        e1.save(file_name = file_name2)
     4875        e2 = Exposure_csv(file_name2)
     4876        returned_values = e2.get_column(new_title)
     4877        for returned, new in map(None, returned_values, new_values):
     4878            self.failUnless(returned == str(new), ' Error!')
     4879        #self.failUnless(returned_values == new_values, ' Error!')       
     4880        os.remove(file_name2)
     4881       
     4882        try:
     4883            e1.get_column("toe jam")
     4884        except TitleValueError:
     4885            pass
     4886        else:
     4887            self.failUnless(0 ==1,  'Error not thrown error!')
     4888       
     4889       
    46624890#-------------------------------------------------------------
    46634891if __name__ == "__main__":
     4892    #suite = unittest.makeSuite(Test_Data_Manager,'test_exposure_csv')
    46644893    suite = unittest.makeSuite(Test_Data_Manager,'test')
    46654894    runner = unittest.TextTestRunner()
Note: See TracChangeset for help on using the changeset viewer.