Changeset 8978


Ignore:
Timestamp:
Sep 17, 2013, 7:08:50 PM (12 years ago)
Author:
steve
Message:

Changing anuga init to allow simple interface

Location:
trunk/anuga_core/source
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • trunk/anuga_core/source/anuga/__init__.py

    r8977 r8978  
    387387from anuga.utilities.model_tools import Create_culvert_bridge_Operator
    388388
     389from anuga_parallel.parallel_api import distribute
     390from anuga_parallel.parallel_api import myid, numprocs, get_processor_name
     391from anuga_parallel.parallel_api import send, receive
     392from anuga_parallel.parallel_api import pypar_available, barrier, finalize
     393
     394if pypar_available:
     395    #from anuga_parallel.parallel_meshes import parallel_rectangle
     396    #from anuga_parallel.parallel_shallow_water import Parallel_domain as Parallel_shallow_water_domain
     397    #from anuga_parallel.parallel_advection     import Parallel_domain as Parallel_advection_domain
     398    from anuga_parallel.parallel_operator_factory import Inlet_operator, Boyd_box_operator
     399
     400
     401
     402
  • trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/quantity.py

    r8974 r8978  
    10911091       
    10921092       
    1093     def set_values_from_asc_file(self,
     1093       
     1094       
     1095    def set_values_from_utm_grid_file(self,
    10941096                             filename,
    10951097                             location='vertices',
     
    11431145   
    11441146        root = filename[:-4]
    1145    
    1146 #         # Read Meta data
    1147 #         if verbose: log.critical('Reading METADATA from %s' % (root + '.prj'))
    1148 #     
    1149 #         metadatafile = open(root + '.prj')
    1150 #         metalines = metadatafile.readlines()
    1151 #         metadatafile.close()
    1152 #     
    1153 #         L = metalines[0].strip().split()
    1154 #         assert L[0].strip().lower() == 'projection'
    1155 #         projection = L[1].strip()                   #TEXT
    1156 #     
    1157 #         L = metalines[1].strip().split()
    1158 #         assert L[0].strip().lower() == 'zone'
    1159 #         zone = int(L[1].strip())
    1160 #     
    1161 #         L = metalines[2].strip().split()
    1162 #         assert L[0].strip().lower() == 'datum'
    1163 #         datum = L[1].strip()                        #TEXT
    1164 #     
    1165 #         L = metalines[3].strip().split()
    1166 #         assert L[0].strip().lower() == 'zunits'     #IGNORE
    1167 #         zunits = L[1].strip()                       #TEXT
    1168 #     
    1169 #         L = metalines[4].strip().split()
    1170 #         assert L[0].strip().lower() == 'units'
    1171 #         units = L[1].strip()                        #TEXT
    1172 #     
    1173 #         L = metalines[5].strip().split()
    1174 #         assert L[0].strip().lower() == 'spheroid'   #IGNORE
    1175 #         spheroid = L[1].strip()                     #TEXT
    1176 #     
    1177 #         L = metalines[6].strip().split()
    1178 #         assert L[0].strip().lower() == 'xshift'
    1179 #         false_easting = float(L[1].strip())
    1180 #     
    1181 #         L = metalines[7].strip().split()
    1182 #         assert L[0].strip().lower() == 'yshift'
    1183 #         false_northing = float(L[1].strip())
    11841147   
    11851148   
     
    13091272                # Brute force
    13101273                self.vertex_values[indices] = values.reshape((-1,3))
    1311                
     1274            # Cleanup centroid values
     1275            self.interpolate()
     1276           
     1277    def set_values_from_lat_long_grid_file(self,
     1278                             filename,
     1279                             location='vertices',
     1280                             indices=None,
     1281                             verbose=False):
     1282       
     1283        """Read Digital Elevation model from the following ASCII format (.asc or .grd)
     1284   
     1285        Example:
     1286        ncols         3121
     1287        nrows         1800
     1288        xllcorner     722000
     1289        yllcorner     5893000
     1290        cellsize      25
     1291        NODATA_value  -9999
     1292        138.3698 137.4194 136.5062 135.5558 ..........
     1293   
     1294   
     1295        An accompanying file with same basename but extension .prj must exist
     1296        and is used to fix the UTM zone, datum, false northings and eastings.
     1297   
     1298        The prj format is assumed to be as
     1299   
     1300        Projection    UTM
     1301        Zone          56
     1302        Datum         WGS84
     1303        Zunits        NO
     1304        Units         METERS
     1305        Spheroid      WGS84
     1306        Xshift        0.0000000000
     1307        Yshift        10000000.0000000000
     1308        Parameters
     1309        """
     1310
     1311
     1312
     1313
     1314        msg = 'Filename must be a text string'
     1315        assert isinstance(filename, basestring), msg
     1316       
     1317        msg = 'Extension should be .grd or asc'
     1318        assert os.path.splitext(filename)[1] in ['.grd', '.asc'], msg
     1319       
     1320
     1321        msg = "set_values_from_grd_file is only defined for location='vertices' or 'centroids'"
     1322        assert location in ['vertices', 'centroids'], msg
     1323
     1324   
     1325        root = filename[:-4]
     1326   
     1327   
     1328        #Read DEM data
     1329        datafile = open(filename)
     1330   
     1331        if verbose: log.critical('Reading data from %s' % (filename))
     1332       
     1333        lines = datafile.readlines()
     1334        datafile.close()
     1335   
     1336   
     1337        if verbose: log.critical('Got %d lines' % len(lines))
     1338   
     1339        # Parse the line data
     1340        ncols = int(lines[0].split()[1].strip())
     1341        nrows = int(lines[1].split()[1].strip())
     1342
     1343   
     1344        # Do cellsize (line 4) before line 2 and 3
     1345        cellsize = float(lines[4].split()[1].strip())
     1346   
     1347        # Checks suggested by Joaquim Luis
     1348        # Our internal representation of xllcorner
     1349        # and yllcorner is non-standard.
     1350        xref = lines[2].split()
     1351        if xref[0].strip() == 'xllcorner':
     1352            xllcorner = float(xref[1].strip()) # + 0.5*cellsize # Correct offset
     1353        elif xref[0].strip() == 'xllcenter':
     1354            xllcorner = float(xref[1].strip())
     1355        else:
     1356            msg = 'Unknown keyword: %s' % xref[0].strip()
     1357            raise Exception, msg
     1358   
     1359        yref = lines[3].split()
     1360        if yref[0].strip() == 'yllcorner':
     1361            yllcorner = float(yref[1].strip()) # + 0.5*cellsize # Correct offset
     1362        elif yref[0].strip() == 'yllcenter':
     1363            yllcorner = float(yref[1].strip())
     1364        else:
     1365            msg = 'Unknown keyword: %s' % yref[0].strip()
     1366            raise Exception, msg
     1367   
     1368        NODATA_value = int(float(lines[5].split()[1].strip()))
     1369   
     1370        assert len(lines) == nrows + 6
     1371   
     1372 
     1373        #Store data
     1374        import numpy
     1375   
     1376        datafile = open(filename)
     1377        Z = numpy.loadtxt(datafile, skiprows=6)
     1378        datafile.close()
     1379       
     1380        #print Z.shape
     1381        #print Z
     1382       
     1383        # For raster data we need to a flip and transpose
     1384        Z = numpy.flipud(Z)
     1385
     1386        # Transpose z to have y coordinates along the first axis and x coordinates
     1387        # along the second axis
     1388        Z = Z.transpose()
     1389   
     1390        x = num.linspace(xllcorner, xllcorner+cellsize*(ncols-1), ncols)
     1391        y = num.linspace(yllcorner, yllcorner+cellsize*(nrows-1), nrows)
     1392       
     1393       
     1394        if location == 'centroids':
     1395            points = self.domain.centroid_coordinates
     1396        else:
     1397            points = self.domain.vertex_coordinates
     1398           
     1399        from anuga.geospatial_data.geospatial_data import Geospatial_data,  ensure_absolute
     1400        points = ensure_absolute(points, geo_reference=self.domain.geo_reference)
     1401           
     1402#         print numpy.max(points[:,0])
     1403#         print numpy.min(points[:,0])
     1404#         print numpy.max(points[:,1])
     1405#         print numpy.min(points[:,1])
     1406#         
     1407#         print numpy.max(x)
     1408#         print numpy.min(x)
     1409#         print numpy.max(y)
     1410#         print numpy.min(y)
     1411       
     1412       
     1413        #print x.shape, x
     1414        #print y.shape, y
     1415       
     1416       
     1417       
     1418        from  anuga.fit_interpolate.interpolate2d import interpolate2d
     1419       
     1420        #print points
     1421        values = interpolate2d(x, y, Z, points, mode='linear', bounds_error=False)
     1422       
     1423        #print values
     1424
     1425        # Call underlying method using array values
     1426        if verbose:
     1427            log.critical('Applying fitted data to quantity')
     1428           
     1429       
     1430        if location == 'centroids':
     1431            if indices is None:
     1432                msg = 'Number of values must match number of elements'
     1433                #assert values.shape[0] == N, msg
     1434
     1435                self.centroid_values[:] = values
     1436            else:
     1437                msg = 'Number of values must match number of indices'
     1438                assert values.shape[0] == indices.shape[0], msg
     1439
     1440                # Brute force
     1441                self.centroid_values[indices] = values
     1442        else:
     1443            if indices is None:
     1444                msg = 'Number of values must match number of elements'
     1445                #assert values.shape[0] == N, msg
     1446
     1447                #print values.shape
     1448                #print self.vertex_values.shape
     1449                self.vertex_values[:] = values.reshape((-1,3))
     1450            else:
     1451                msg = 'Number of values must match number of indices'
     1452                assert values.shape[0] == indices.shape[0], msg
     1453
     1454                # Brute force
     1455                self.vertex_values[indices] = values.reshape((-1,3))
     1456            # Cleanup centroid values
     1457            self.interpolate()
     1458                           
    13121459    def get_extremum_index(self, mode=None, indices=None):
    13131460        """Return index for maximum or minimum value of quantity (on centroids)
  • trunk/anuga_core/source/anuga/abstract_2d_finite_volumes/test_quantity.py

    r8974 r8978  
    13871387
    13881388
    1389     def test_set_values_from_asc_vertices(self):
    1390        
    1391        
    1392        
    1393 
     1389    def test_set_values_from_utm_grid_file(self):
     1390       
     1391       
    13941392
    13951393        x0 = 0.0
     
    14671465        #print quantity.centroid_values
    14681466
    1469         quantity.set_values_from_asc_file(txt_file,
     1467        quantity.set_values_from_utm_grid_file(txt_file,
    14701468                             location='vertices',
    14711469                             indices=None,
     
    14891487        #print quantity.vertex_values
    14901488        #print quantity.centroid_values
    1491         quantity.set_values_from_asc_file(txt_file,
     1489        quantity.set_values_from_utm_grid_file(txt_file,
    14921490                             location='centroids',
    14931491                             indices=None,
  • trunk/anuga_core/source/anuga/operators/rate_operators.py

    r8974 r8978  
    1717
    1818
     19from anuga import Quantity
    1920from anuga.operators.base_operator import Operator
    2021from anuga.operators.region import Region
     
    103104
    104105            rate = self.get_spatial_rate(x,y,t)
     106        elif self.rate_type == 'quantity':
     107            if indices is None:
     108                rate  = self.rate.centroid_values
     109            else:
     110                rate = self.rate.centroid_values[indices]
    105111        else:
    106112            rate = self.get_non_spatial_rate(t)
     
    184190
    185191    def set_rate(self, rate):
    186         """Set rate (function)
     192        """Set rate
    187193        Can change rate while running
    188         """
    189 
    190         from anuga.utilities.function_utils import determine_function_type
    191 
    192         # Possible types are 'scalar', 't', 'x,y' and 'x,y,t'
    193         self.rate_type = determine_function_type(rate)
     194        Can be a scalar, or a function of t or x,y or x,y,t or a quantity
     195        """
     196
     197        # Test if rate is a quantity
     198        if isinstance(rate, Quantity):
     199            self.rate_type = 'quantity'
     200        else:
     201            # Possible types are 'scalar', 't', 'x,y' and 'x,y,t'
     202            from anuga.utilities.function_utils import determine_function_type
     203            self.rate_type = determine_function_type(rate)
     204
    194205
    195206        self.rate = rate
     207       
    196208
    197209        if self.rate_type == 'scalar':
     210            self.rate_callable = False
     211            self.rate_spatial = False
     212        elif self.rate_type == 'quantity':
    198213            self.rate_callable = False
    199214            self.rate_spatial = False
     
    243258                fid = self.full_indices
    244259                return num.sum(self.areas[fid]*rate[fid])*self.factor
     260            elif self.rate_type == 'quantity':
     261                rate = self.rate.centroid_values # rate is a quantity
     262                fid = self.full_indices
     263                return num.sum(self.areas[fid]*rate[fid])*self.factor
    245264            else:
    246265                rate = self.get_non_spatial_rate() # rate is a scalar
     
    251270                rate = self.get_spatial_rate() # rate is an array
    252271                return num.sum(self.areas*rate)*self.factor
     272            elif self.rate_type == 'quantity':
     273                rate = self.rate.centroid_values # rate is a quantity
     274                return num.sum(self.areas*rate)*self.factor               
    253275            else:
    254276                rate = self.get_non_spatial_rate() # rate is a scalar
  • trunk/anuga_core/source/anuga/operators/test_rate_operators.py

    r8945 r8978  
    635635        assert num.allclose(Q_ex, Q)
    636636
     637
     638    def test_rate_operator_rate_quantity(self):
     639        from anuga.config import rho_a, rho_w, eta_w
     640        from math import pi, cos, sin
     641
     642        a = [0.0, 0.0]
     643        b = [0.0, 2.0]
     644        c = [2.0, 0.0]
     645        d = [0.0, 4.0]
     646        e = [2.0, 2.0]
     647        f = [4.0, 0.0]
     648
     649        points = [a, b, c, d, e, f]
     650        #             bac,     bce,     ecf,     dbe
     651        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]
     652
     653        domain = Domain(points, vertices)
     654
     655        #Flat surface with 1m of water
     656        domain.set_quantity('elevation', 0.0)
     657        domain.set_quantity('stage', 1.0)
     658        domain.set_quantity('friction', 0.0)
     659
     660        Br = Reflective_boundary(domain)
     661        domain.set_boundary({'exterior': Br})
     662
     663        verbose = False
     664
     665        if verbose:
     666            print domain.quantities['elevation'].centroid_values
     667            print domain.quantities['stage'].centroid_values
     668            print domain.quantities['xmomentum'].centroid_values
     669            print domain.quantities['ymomentum'].centroid_values
     670
     671        # Apply operator to these triangles
     672        indices = [0,1,3]
     673        factor = 10.0
     674
     675
     676        from anuga import Quantity
     677        rate_Q = Quantity(domain)
     678        rate_Q.set_values(1.0)
     679
     680        operator = Rate_operator(domain, rate=rate_Q, factor=factor, \
     681                                 indices=indices)
     682
     683
     684        # Apply Operator
     685        domain.timestep = 2.0
     686        operator()
     687        rate = rate_Q.centroid_values[indices]
     688        t = operator.get_time()
     689        Q = operator.get_Q()
     690
     691        rate = rate*factor
     692        Q_ex = num.sum(domain.areas[indices]*rate)
     693        d = operator.get_timestep()*rate + 1
     694
     695
     696        #print "d"
     697        #print d
     698        #print Q_ex
     699        #print Q
     700        stage_ex = num.array([ 1.0,  1.0,   1.0,  1.0])
     701        stage_ex[indices] = d
     702       
     703        verbose = False
     704       
     705        if verbose:
     706            print domain.quantities['elevation'].centroid_values
     707            print domain.quantities['stage'].centroid_values
     708            print domain.quantities['xmomentum'].centroid_values
     709            print domain.quantities['ymomentum'].centroid_values
     710
     711        assert num.allclose(domain.quantities['stage'].centroid_values, stage_ex)
     712        assert num.allclose(domain.quantities['xmomentum'].centroid_values, 0.0)
     713        assert num.allclose(domain.quantities['ymomentum'].centroid_values, 0.0)
     714        assert num.allclose(Q_ex, Q)
     715
     716
    637717    def test_rate_operator_functions_empty_indices(self):
    638718        from anuga.config import rho_a, rho_w, eta_w
  • trunk/anuga_core/source/anuga_parallel/__init__.py

    r8972 r8978  
    55imported from this module
    66"""
     7
     8# Lets import the standard anuga interface
     9#from anuga import *
     10
    711
    812from parallel_api import distribute
     
    1519    from parallel_shallow_water import Parallel_domain as Parallel_shallow_water_domain
    1620    from parallel_advection     import Parallel_domain as Parallel_advection_domain
     21    from parallel_operator_factory import Inlet_operator, Boyd_box_operator
    1722else:
    1823    from anuga import rectangular_cross as parallel_rectangle
     
    2429
    2530
    26 #Added by Petar Milevski 10/09/2013
    27 from anuga_parallel import distribute, myid, numprocs, finalize
    28 from anuga_parallel.parallel_operator_factory import Inlet_operator, Boyd_box_operator
Note: See TracChangeset for help on using the changeset viewer.