source: anuga_core/source/anuga/shallow_water/shallow_water_domain.py @ 6045

Last change on this file since 6045 was 6045, checked in by ole, 15 years ago

Implemented, tested and documunted new boundary condition:

Transmissive_stage_zero_momentum_boundary

Renamed two others according to style guide but retained backward compatibility

  • Property svn:keywords set to LastChangedDate LastChangedRevision LastChangedBy HeadURL Id
File size: 70.8 KB
Line 
1"""Finite-volume computations of the shallow water wave equation.
2
3Title: ANGUA shallow_water_domain - 2D triangular domains for finite-volume
4       computations of the shallow water wave equation.
5
6
7Author: Ole Nielsen, Ole.Nielsen@ga.gov.au
8        Stephen Roberts, Stephen.Roberts@anu.edu.au
9        Duncan Gray, Duncan.Gray@ga.gov.au
10
11CreationDate: 2004
12
13Description:
14    This module contains a specialisation of class Domain from
15    module domain.py consisting of methods specific to the
16    Shallow Water Wave Equation
17
18    U_t + E_x + G_y = S
19
20    where
21
22    U = [w, uh, vh]
23    E = [uh, u^2h + gh^2/2, uvh]
24    G = [vh, uvh, v^2h + gh^2/2]
25    S represents source terms forcing the system
26    (e.g. gravity, friction, wind stress, ...)
27
28    and _t, _x, _y denote the derivative with respect to t, x and y
29    respectively.
30
31
32    The quantities are
33
34    symbol    variable name    explanation
35    x         x                horizontal distance from origin [m]
36    y         y                vertical distance from origin [m]
37    z         elevation        elevation of bed on which flow is modelled [m]
38    h         height           water height above z [m]
39    w         stage            absolute water level, w = z+h [m]
40    u                          speed in the x direction [m/s]
41    v                          speed in the y direction [m/s]
42    uh        xmomentum        momentum in the x direction [m^2/s]
43    vh        ymomentum        momentum in the y direction [m^2/s]
44
45    eta                        mannings friction coefficient [to appear]
46    nu                         wind stress coefficient [to appear]
47
48    The conserved quantities are w, uh, vh
49
50Reference:
51    Catastrophic Collapse of Water Supply Reservoirs in Urban Areas,
52    Christopher Zoppou and Stephen Roberts,
53    Journal of Hydraulic Engineering, vol. 127, No. 7 July 1999
54
55    Hydrodynamic modelling of coastal inundation.
56    Nielsen, O., S. Roberts, D. Gray, A. McPherson and A. Hitchman
57    In Zerger, A. and Argent, R.M. (eds) MODSIM 2005 International Congress on
58    Modelling and Simulation. Modelling and Simulation Society of Australia and
59    New Zealand, December 2005, pp. 518-523. ISBN: 0-9758400-2-9.
60    http://www.mssanz.org.au/modsim05/papers/nielsen.pdf
61
62
63SeeAlso:
64    TRAC administration of ANUGA (User Manuals etc) at
65    https://datamining.anu.edu.au/anuga and Subversion repository at
66    $HeadURL: anuga_core/source/anuga/shallow_water/shallow_water_domain.py $
67
68Constraints: See GPL license in the user guide
69Version: 1.0 ($Revision: 6045 $)
70ModifiedBy:
71    $Author: ole $
72    $Date: 2008-12-05 00:35:49 +0000 (Fri, 05 Dec 2008) $
73
74"""
75
76# Subversion keywords:
77#
78# $LastChangedDate: 2008-12-05 00:35:49 +0000 (Fri, 05 Dec 2008) $
79# $LastChangedRevision: 6045 $
80# $LastChangedBy: ole $
81
82from Numeric import zeros, ones, Float, array, sum, size
83from Numeric import compress, arange
84
85from anuga.abstract_2d_finite_volumes.neighbour_mesh import segment_midpoints
86from anuga.abstract_2d_finite_volumes.domain import Domain as Generic_Domain
87from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\
88     import Boundary
89from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\
90     import File_boundary
91from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\
92     import Dirichlet_boundary
93from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\
94     import Time_boundary
95from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\
96     import Transmissive_boundary
97
98from anuga.utilities.numerical_tools import gradient, mean, ensure_numeric
99from anuga.geospatial_data.geospatial_data import ensure_geospatial
100
101from anuga.config import minimum_storable_height
102from anuga.config import minimum_allowed_height, maximum_allowed_speed
103from anuga.config import g, epsilon, beta_w, beta_w_dry,\
104     beta_uh, beta_uh_dry, beta_vh, beta_vh_dry, tight_slope_limiters
105from anuga.config import alpha_balance
106from anuga.config import optimise_dry_cells
107from anuga.config import optimised_gradient_limiter
108from anuga.config import use_edge_limiter
109from anuga.config import use_centroid_velocities
110
111from anuga.fit_interpolate.interpolate import Modeltime_too_late, Modeltime_too_early
112
113from anuga.utilities.polygon import inside_polygon, polygon_area, is_inside_polygon
114
115from types import IntType, FloatType
116from warnings import warn
117
118
119#---------------------
120# Shallow water domain
121#---------------------
122class Domain(Generic_Domain):
123
124    conserved_quantities = ['stage', 'xmomentum', 'ymomentum']
125    other_quantities = ['elevation', 'friction']
126   
127    def __init__(self,
128                 coordinates=None,
129                 vertices=None,
130                 boundary=None,
131                 tagged_elements=None,
132                 geo_reference=None,
133                 use_inscribed_circle=False,
134                 mesh_filename=None,
135                 use_cache=False,
136                 verbose=False,
137                 full_send_dict=None,
138                 ghost_recv_dict=None,
139                 processor=0,
140                 numproc=1,
141                 number_of_full_nodes=None,
142                 number_of_full_triangles=None):
143
144
145        other_quantities = ['elevation', 'friction']
146        Generic_Domain.__init__(self,
147                                coordinates,
148                                vertices,
149                                boundary,
150                                Domain.conserved_quantities,
151                                Domain.other_quantities,
152                                tagged_elements,
153                                geo_reference,
154                                use_inscribed_circle,
155                                mesh_filename,
156                                use_cache,
157                                verbose,
158                                full_send_dict,
159                                ghost_recv_dict,
160                                processor,
161                                numproc,
162                                number_of_full_nodes=number_of_full_nodes,
163                                number_of_full_triangles=number_of_full_triangles) 
164
165
166        self.set_minimum_allowed_height(minimum_allowed_height)
167       
168        self.maximum_allowed_speed = maximum_allowed_speed
169        self.g = g
170        self.beta_w      = beta_w
171        self.beta_w_dry  = beta_w_dry
172        self.beta_uh     = beta_uh
173        self.beta_uh_dry = beta_uh_dry
174        self.beta_vh     = beta_vh
175        self.beta_vh_dry = beta_vh_dry
176        self.alpha_balance = alpha_balance
177
178        self.tight_slope_limiters = tight_slope_limiters
179        self.optimise_dry_cells = optimise_dry_cells
180
181        self.forcing_terms.append(manning_friction_implicit)
182        self.forcing_terms.append(gravity)
183
184        # Stored output
185        self.store = True
186        self.format = 'sww'
187        self.set_store_vertices_uniquely(False)
188        self.minimum_storable_height = minimum_storable_height
189        self.quantities_to_be_stored = ['stage','xmomentum','ymomentum']
190
191        # Limiters
192        self.use_edge_limiter = use_edge_limiter
193        self.optimised_gradient_limiter = optimised_gradient_limiter
194        self.use_centroid_velocities = use_centroid_velocities
195
196
197    def set_all_limiters(self, beta):
198        """Shorthand to assign one constant value [0,1[ to all limiters.
199        0 Corresponds to first order, where as larger values make use of
200        the second order scheme.
201        """
202
203        self.beta_w      = beta
204        self.beta_w_dry  = beta
205        self.quantities['stage'].beta = beta
206       
207        self.beta_uh     = beta
208        self.beta_uh_dry = beta
209        self.quantities['xmomentum'].beta = beta
210       
211        self.beta_vh     = beta
212        self.beta_vh_dry = beta
213        self.quantities['ymomentum'].beta = beta
214       
215       
216
217    def set_store_vertices_uniquely(self, flag, reduction=None):
218        """Decide whether vertex values should be stored uniquely as
219        computed in the model or whether they should be reduced to one
220        value per vertex using self.reduction.
221        """
222
223        # FIXME (Ole): how about using the word continuous vertex values?
224        self.smooth = not flag
225
226        # Reduction operation for get_vertex_values
227        if reduction is None:
228            self.reduction = mean
229            #self.reduction = min  #Looks better near steep slopes
230
231
232    def set_minimum_storable_height(self, minimum_storable_height):
233        """
234        Set the minimum depth that will be recognised when writing
235        to an sww file. This is useful for removing thin water layers
236        that seems to be caused by friction creep.
237
238        The minimum allowed sww depth is in meters.
239        """
240        self.minimum_storable_height = minimum_storable_height
241
242
243    def set_minimum_allowed_height(self, minimum_allowed_height):
244        """
245        Set the minimum depth that will be recognised in the numerical
246        scheme
247
248        The minimum allowed depth is in meters.
249
250        The parameter H0 (Minimal height for flux computation)
251        is also set by this function
252        """
253
254        #FIXME (Ole): rename H0 to minimum_allowed_height_in_flux_computation
255
256        #FIXME (Ole): Maybe use histogram to identify isolated extreme speeds
257        #and deal with them adaptively similarly to how we used to use 1 order
258        #steps to recover.
259        self.minimum_allowed_height = minimum_allowed_height
260        self.H0 = minimum_allowed_height   
261       
262
263    def set_maximum_allowed_speed(self, maximum_allowed_speed):
264        """
265        Set the maximum particle speed that is allowed in water
266        shallower than minimum_allowed_height. This is useful for
267        controlling speeds in very thin layers of water and at the same time
268        allow some movement avoiding pooling of water.
269
270        """
271        self.maximum_allowed_speed = maximum_allowed_speed
272
273
274    def set_points_file_block_line_size(self,points_file_block_line_size):
275        """
276        Set the minimum depth that will be recognised when writing
277        to an sww file. This is useful for removing thin water layers
278        that seems to be caused by friction creep.
279
280        The minimum allowed sww depth is in meters.
281        """
282        self.points_file_block_line_size = points_file_block_line_size
283       
284       
285    def set_quantities_to_be_stored(self, q):
286        """Specify which quantities will be stored in the sww file.
287
288        q must be either:
289          - the name of a quantity
290          - a list of quantity names
291          - None
292
293        In the two first cases, the named quantities will be stored at
294        each yieldstep (This is in addition to the quantities elevation
295        and friction)
296       
297        If q is None, storage will be switched off altogether.
298        """
299
300
301        if q is None:
302            self.quantities_to_be_stored = []
303            self.store = False
304            return
305
306        if isinstance(q, basestring):
307            q = [q] # Turn argument into a list
308
309        # Check correcness
310        for quantity_name in q:
311            msg = 'Quantity %s is not a valid conserved quantity'\
312                  %quantity_name
313           
314            assert quantity_name in self.conserved_quantities, msg
315
316        self.quantities_to_be_stored = q
317
318
319
320    def get_wet_elements(self, indices=None):
321        """Return indices for elements where h > minimum_allowed_height
322
323        Optional argument:
324            indices is the set of element ids that the operation applies to.
325
326        Usage:
327            indices = get_wet_elements()
328
329        Note, centroid values are used for this operation           
330        """
331
332        # Water depth below which it is considered to be 0 in the model
333        # FIXME (Ole): Allow this to be specified as a keyword argument as well
334        from anuga.config import minimum_allowed_height
335
336       
337        elevation = self.get_quantity('elevation').\
338                    get_values(location='centroids', indices=indices)
339        stage = self.get_quantity('stage').\
340                get_values(location='centroids', indices=indices)       
341        depth = stage - elevation
342
343        # Select indices for which depth > 0
344        wet_indices = compress(depth > minimum_allowed_height,
345                               arange(len(depth)))
346        return wet_indices
347
348
349    def get_maximum_inundation_elevation(self, indices=None):
350        """Return highest elevation where h > 0
351
352        Optional argument:
353            indices is the set of element ids that the operation applies to.
354
355        Usage:
356            q = get_maximum_inundation_elevation()
357
358        Note, centroid values are used for this operation           
359        """
360
361        wet_elements = self.get_wet_elements(indices)
362        return self.get_quantity('elevation').\
363               get_maximum_value(indices=wet_elements)
364
365
366    def get_maximum_inundation_location(self, indices=None):
367        """Return location of highest elevation where h > 0
368
369        Optional argument:
370            indices is the set of element ids that the operation applies to.
371
372        Usage:
373            q = get_maximum_inundation_location()
374
375        Note, centroid values are used for this operation           
376        """
377
378        wet_elements = self.get_wet_elements(indices)
379        return self.get_quantity('elevation').\
380               get_maximum_location(indices=wet_elements)   
381               
382               
383               
384               
385    def get_flow_through_cross_section(self, polyline,
386                                       verbose=False):               
387        """Get the total flow through an arbitrary poly line.       
388       
389        This is a run-time equivalent of the function with same name
390        in data_manager.py
391       
392        Input:
393            polyline: Representation of desired cross section - it may contain
394                      multiple sections allowing for complex shapes. Assume
395                      absolute UTM coordinates.
396                      Format [[x0, y0], [x1, y1], ...]       
397                 
398        Output:       
399            Q: Total flow [m^3/s] across given segments.
400       
401         
402        """       
403       
404        # Find all intersections and associated triangles.
405        segments = self.get_intersecting_segments(polyline, 
406                                                  use_cache=True,
407                                                  verbose=verbose)
408
409        # Get midpoints
410        midpoints = segment_midpoints(segments)       
411       
412        # Make midpoints Geospatial instances
413        midpoints = ensure_geospatial(midpoints, self.geo_reference)       
414       
415        # Compute flow       
416        if verbose: print 'Computing flow through specified cross section'
417       
418        # Get interpolated values
419        xmomentum = self.get_quantity('xmomentum')
420        ymomentum = self.get_quantity('ymomentum')       
421       
422        uh = xmomentum.get_values(interpolation_points=midpoints, use_cache=True)
423        vh = ymomentum.get_values(interpolation_points=midpoints, use_cache=True)
424       
425        # Compute and sum flows across each segment
426        total_flow=0
427        for i in range(len(uh)):
428           
429            # Inner product of momentum vector with segment normal [m^2/s]
430            normal = segments[i].normal
431            normal_momentum = uh[i]*normal[0] + vh[i]*normal[1] 
432               
433            # Flow across this segment [m^3/s]
434            segment_flow = normal_momentum*segments[i].length
435
436            # Accumulate
437            total_flow += segment_flow
438           
439        return total_flow
440
441       
442               
443    def get_energy_through_cross_section(self, polyline,
444                                         kind='total',
445                                         verbose=False):               
446        """Obtain average energy head [m] across specified cross section.
447
448        Inputs:
449            polyline: Representation of desired cross section - it may contain
450                      multiple sections allowing for complex shapes. Assume
451                      absolute UTM coordinates.
452                      Format [[x0, y0], [x1, y1], ...]
453            kind:     Select which energy to compute.
454                      Options are 'specific' and 'total' (default)
455
456        Output:
457            E: Average energy [m] across given segments for all stored times.
458
459        The average velocity is computed for each triangle intersected by
460        the polyline and averaged weighted by segment lengths.
461
462        The typical usage of this function would be to get average energy of
463        flow in a channel, and the polyline would then be a cross section
464        perpendicular to the flow.
465
466        #FIXME (Ole) - need name for this energy reflecting that its dimension
467        is [m].
468        """
469
470        from anuga.config import g, epsilon, velocity_protection as h0       
471                                         
472       
473        # Find all intersections and associated triangles.
474        segments = self.get_intersecting_segments(polyline, 
475                                                  use_cache=True,
476                                                  verbose=verbose)
477
478        # Get midpoints
479        midpoints = segment_midpoints(segments)       
480       
481        # Make midpoints Geospatial instances
482        midpoints = ensure_geospatial(midpoints, self.geo_reference)       
483       
484        # Compute energy       
485        if verbose: print 'Computing %s energy' %kind       
486       
487        # Get interpolated values
488        stage = self.get_quantity('stage')       
489        elevation = self.get_quantity('elevation')               
490        xmomentum = self.get_quantity('xmomentum')
491        ymomentum = self.get_quantity('ymomentum')       
492
493        w = stage.get_values(interpolation_points=midpoints, use_cache=True)
494        z = elevation.get_values(interpolation_points=midpoints, use_cache=True)       
495        uh = xmomentum.get_values(interpolation_points=midpoints, use_cache=True)
496        vh = ymomentum.get_values(interpolation_points=midpoints, use_cache=True)
497        h = w-z # Depth
498       
499        # Compute total length of polyline for use with weighted averages
500        total_line_length = 0.0
501        for segment in segments:
502            total_line_length += segment.length
503       
504        # Compute and sum flows across each segment
505        average_energy=0.0
506        for i in range(len(w)):
507           
508            # Average velocity across this segment
509            if h[i] > epsilon:
510                # Use protection against degenerate velocities
511                u = uh[i]/(h[i] + h0/h[i])
512                v = vh[i]/(h[i] + h0/h[i])
513            else:
514                u = v = 0.0
515               
516            speed_squared = u*u + v*v   
517            kinetic_energy = 0.5*speed_squared/g
518           
519            if kind == 'specific':
520                segment_energy = h[i] + kinetic_energy
521            elif kind == 'total':
522                segment_energy = w[i] + kinetic_energy               
523            else:
524                msg = 'Energy kind must be either "specific" or "total".'
525                msg += ' I got %s' %kind
526               
527
528            # Add to weighted average
529            weigth = segments[i].length/total_line_length
530            average_energy += segment_energy*weigth
531             
532           
533        return average_energy
534       
535
536                       
537
538    def check_integrity(self):
539        Generic_Domain.check_integrity(self)
540
541        #Check that we are solving the shallow water wave equation
542
543        msg = 'First conserved quantity must be "stage"'
544        assert self.conserved_quantities[0] == 'stage', msg
545        msg = 'Second conserved quantity must be "xmomentum"'
546        assert self.conserved_quantities[1] == 'xmomentum', msg
547        msg = 'Third conserved quantity must be "ymomentum"'
548        assert self.conserved_quantities[2] == 'ymomentum', msg
549
550    def extrapolate_second_order_sw(self):
551        #Call correct module function
552        #(either from this module or C-extension)
553        extrapolate_second_order_sw(self)
554
555    def compute_fluxes(self):
556        #Call correct module function
557        #(either from this module or C-extension)
558        compute_fluxes(self)
559
560    def distribute_to_vertices_and_edges(self):
561        # Call correct module function
562        if self.use_edge_limiter:
563            distribute_using_edge_limiter(self)           
564        else:
565            distribute_using_vertex_limiter(self)
566
567
568
569
570    def evolve(self,
571               yieldstep = None,
572               finaltime = None,
573               duration = None,
574               skip_initial_step = False):
575        """Specialisation of basic evolve method from parent class
576        """
577
578        # Call check integrity here rather than from user scripts
579        # self.check_integrity()
580
581        msg = 'Parameter beta_w must be in the interval [0, 2['
582        assert 0 <= self.beta_w <= 2.0, msg
583
584
585        # Initial update of vertex and edge values before any STORAGE
586        # and or visualisation
587        # This is done again in the initialisation of the Generic_Domain
588        # evolve loop but we do it here to ensure the values are ok for storage
589        self.distribute_to_vertices_and_edges()
590
591        if self.store is True and self.time == 0.0:
592            self.initialise_storage()
593            # print 'Storing results in ' + self.writer.filename
594        else:
595            pass
596            # print 'Results will not be stored.'
597            # print 'To store results set domain.store = True'
598            # FIXME: Diagnostic output should be controlled by
599            # a 'verbose' flag living in domain (or in a parent class)
600
601        # Call basic machinery from parent class
602        for t in Generic_Domain.evolve(self,
603                                       yieldstep=yieldstep,
604                                       finaltime=finaltime,
605                                       duration=duration,
606                                       skip_initial_step=skip_initial_step):
607
608            # Store model data, e.g. for subsequent visualisation
609            if self.store is True:
610                self.store_timestep(self.quantities_to_be_stored)
611
612            # FIXME: Could maybe be taken from specified list
613            # of 'store every step' quantities
614
615            # Pass control on to outer loop for more specific actions
616            yield(t)
617
618
619    def initialise_storage(self):
620        """Create and initialise self.writer object for storing data.
621        Also, save x,y and bed elevation
622        """
623
624        from anuga.shallow_water.data_manager import get_dataobject
625
626        # Initialise writer
627        self.writer = get_dataobject(self, mode = 'w')
628
629        # Store vertices and connectivity
630        self.writer.store_connectivity()
631
632
633    def store_timestep(self, name):
634        """Store named quantity and time.
635
636        Precondition:
637           self.write has been initialised
638        """
639        self.writer.store_timestep(name)
640
641       
642    def timestepping_statistics(self,
643                                track_speeds=False,
644                                triangle_id=None):       
645        """Return string with time stepping statistics for printing or logging
646
647        Optional boolean keyword track_speeds decides whether to report
648        location of smallest timestep as well as a histogram and percentile
649        report.
650        """
651
652        from Numeric import sqrt
653        from anuga.config import epsilon, g               
654
655
656        # Call basic machinery from parent class
657        msg = Generic_Domain.timestepping_statistics(self,
658                                                     track_speeds,
659                                                     triangle_id)
660
661        if track_speeds is True:
662
663            # qwidth determines the text field used for quantities
664            qwidth = self.qwidth
665       
666            # Selected triangle
667            k = self.k
668
669            # Report some derived quantities at vertices, edges and centroid
670            # specific to the shallow water wave equation
671
672            z = self.quantities['elevation']
673            w = self.quantities['stage']           
674
675            Vw = w.get_values(location='vertices', indices=[k])[0]
676            Ew = w.get_values(location='edges', indices=[k])[0]
677            Cw = w.get_values(location='centroids', indices=[k])
678
679            Vz = z.get_values(location='vertices', indices=[k])[0]
680            Ez = z.get_values(location='edges', indices=[k])[0]
681            Cz = z.get_values(location='centroids', indices=[k])                             
682               
683
684            name = 'depth'
685            Vh = Vw-Vz
686            Eh = Ew-Ez
687            Ch = Cw-Cz
688           
689            s  = '    %s: vertex_values =  %.4f,\t %.4f,\t %.4f\n'\
690                 %(name.ljust(qwidth), Vh[0], Vh[1], Vh[2])
691           
692            s += '    %s: edge_values =    %.4f,\t %.4f,\t %.4f\n'\
693                 %(name.ljust(qwidth), Eh[0], Eh[1], Eh[2])
694           
695            s += '    %s: centroid_value = %.4f\n'\
696                 %(name.ljust(qwidth), Ch[0])                               
697           
698            msg += s
699
700            uh = self.quantities['xmomentum']
701            vh = self.quantities['ymomentum']
702
703            Vuh = uh.get_values(location='vertices', indices=[k])[0]
704            Euh = uh.get_values(location='edges', indices=[k])[0]
705            Cuh = uh.get_values(location='centroids', indices=[k])
706           
707            Vvh = vh.get_values(location='vertices', indices=[k])[0]
708            Evh = vh.get_values(location='edges', indices=[k])[0]
709            Cvh = vh.get_values(location='centroids', indices=[k])
710
711            # Speeds in each direction
712            Vu = Vuh/(Vh + epsilon)
713            Eu = Euh/(Eh + epsilon)
714            Cu = Cuh/(Ch + epsilon)           
715            name = 'U'
716            s  = '    %s: vertex_values =  %.4f,\t %.4f,\t %.4f\n'\
717                 %(name.ljust(qwidth), Vu[0], Vu[1], Vu[2])
718           
719            s += '    %s: edge_values =    %.4f,\t %.4f,\t %.4f\n'\
720                 %(name.ljust(qwidth), Eu[0], Eu[1], Eu[2])
721           
722            s += '    %s: centroid_value = %.4f\n'\
723                 %(name.ljust(qwidth), Cu[0])                               
724           
725            msg += s
726
727            Vv = Vvh/(Vh + epsilon)
728            Ev = Evh/(Eh + epsilon)
729            Cv = Cvh/(Ch + epsilon)           
730            name = 'V'
731            s  = '    %s: vertex_values =  %.4f,\t %.4f,\t %.4f\n'\
732                 %(name.ljust(qwidth), Vv[0], Vv[1], Vv[2])
733           
734            s += '    %s: edge_values =    %.4f,\t %.4f,\t %.4f\n'\
735                 %(name.ljust(qwidth), Ev[0], Ev[1], Ev[2])
736           
737            s += '    %s: centroid_value = %.4f\n'\
738                 %(name.ljust(qwidth), Cv[0])                               
739           
740            msg += s
741
742
743            # Froude number in each direction
744            name = 'Froude (x)'
745            Vfx = Vu/(sqrt(g*Vh) + epsilon)
746            Efx = Eu/(sqrt(g*Eh) + epsilon)
747            Cfx = Cu/(sqrt(g*Ch) + epsilon)
748           
749            s  = '    %s: vertex_values =  %.4f,\t %.4f,\t %.4f\n'\
750                 %(name.ljust(qwidth), Vfx[0], Vfx[1], Vfx[2])
751           
752            s += '    %s: edge_values =    %.4f,\t %.4f,\t %.4f\n'\
753                 %(name.ljust(qwidth), Efx[0], Efx[1], Efx[2])
754           
755            s += '    %s: centroid_value = %.4f\n'\
756                 %(name.ljust(qwidth), Cfx[0])                               
757           
758            msg += s
759
760
761            name = 'Froude (y)'
762            Vfy = Vv/(sqrt(g*Vh) + epsilon)
763            Efy = Ev/(sqrt(g*Eh) + epsilon)
764            Cfy = Cv/(sqrt(g*Ch) + epsilon)
765           
766            s  = '    %s: vertex_values =  %.4f,\t %.4f,\t %.4f\n'\
767                 %(name.ljust(qwidth), Vfy[0], Vfy[1], Vfy[2])
768           
769            s += '    %s: edge_values =    %.4f,\t %.4f,\t %.4f\n'\
770                 %(name.ljust(qwidth), Efy[0], Efy[1], Efy[2])
771           
772            s += '    %s: centroid_value = %.4f\n'\
773                 %(name.ljust(qwidth), Cfy[0])                               
774           
775            msg += s           
776
777               
778
779        return msg
780       
781       
782
783#=============== End of class Shallow Water Domain ===============================
784
785
786#-----------------
787# Flux computation
788#-----------------
789
790def compute_fluxes(domain):
791    """Compute all fluxes and the timestep suitable for all volumes
792    in domain.
793
794    Compute total flux for each conserved quantity using "flux_function"
795
796    Fluxes across each edge are scaled by edgelengths and summed up
797    Resulting flux is then scaled by area and stored in
798    explicit_update for each of the three conserved quantities
799    stage, xmomentum and ymomentum
800
801    The maximal allowable speed computed by the flux_function for each volume
802    is converted to a timestep that must not be exceeded. The minimum of
803    those is computed as the next overall timestep.
804
805    Post conditions:
806      domain.explicit_update is reset to computed flux values
807      domain.timestep is set to the largest step satisfying all volumes.
808   
809
810    This wrapper calls the underlying C version of compute fluxes
811    """
812
813    import sys
814
815    N = len(domain) # number_of_triangles
816
817    # Shortcuts
818    Stage = domain.quantities['stage']
819    Xmom = domain.quantities['xmomentum']
820    Ymom = domain.quantities['ymomentum']
821    Bed = domain.quantities['elevation']
822
823    timestep = float(sys.maxint)
824    from shallow_water_ext import\
825         compute_fluxes_ext_central as compute_fluxes_ext
826
827
828    flux_timestep = compute_fluxes_ext(timestep,
829                                       domain.epsilon,
830                                       domain.H0,
831                                       domain.g,
832                                       domain.neighbours,
833                                       domain.neighbour_edges,
834                                       domain.normals,
835                                       domain.edgelengths,
836                                       domain.radii,
837                                       domain.areas,
838                                       domain.tri_full_flag,
839                                       Stage.edge_values,
840                                       Xmom.edge_values,
841                                       Ymom.edge_values,
842                                       Bed.edge_values,
843                                       Stage.boundary_values,
844                                       Xmom.boundary_values,
845                                       Ymom.boundary_values,
846                                       Stage.explicit_update,
847                                       Xmom.explicit_update,
848                                       Ymom.explicit_update,
849                                       domain.already_computed_flux,
850                                       domain.max_speed,
851                                       int(domain.optimise_dry_cells))
852
853    domain.flux_timestep = flux_timestep
854
855
856
857#---------------------------------------
858# Module functions for gradient limiting
859#---------------------------------------
860
861
862# MH090605 The following method belongs to the shallow_water domain class
863# see comments in the corresponding method in shallow_water_ext.c
864def extrapolate_second_order_sw(domain):
865    """Wrapper calling C version of extrapolate_second_order_sw
866    """
867    import sys
868
869    N = len(domain) # number_of_triangles
870
871    # Shortcuts
872    Stage = domain.quantities['stage']
873    Xmom = domain.quantities['xmomentum']
874    Ymom = domain.quantities['ymomentum']
875    Elevation = domain.quantities['elevation']
876
877    from shallow_water_ext import extrapolate_second_order_sw as extrapol2
878    extrapol2(domain,
879              domain.surrogate_neighbours,
880              domain.number_of_boundaries,
881              domain.centroid_coordinates,
882              Stage.centroid_values,
883              Xmom.centroid_values,
884              Ymom.centroid_values,
885              Elevation.centroid_values,
886              domain.vertex_coordinates,
887              Stage.vertex_values,
888              Xmom.vertex_values,
889              Ymom.vertex_values,
890              Elevation.vertex_values,
891              int(domain.optimise_dry_cells))
892
893
894def distribute_using_vertex_limiter(domain):
895    """Distribution from centroids to vertices specific to the
896    shallow water wave
897    equation.
898
899    It will ensure that h (w-z) is always non-negative even in the
900    presence of steep bed-slopes by taking a weighted average between shallow
901    and deep cases.
902
903    In addition, all conserved quantities get distributed as per either a
904    constant (order==1) or a piecewise linear function (order==2).
905
906    FIXME: more explanation about removal of artificial variability etc
907
908    Precondition:
909      All quantities defined at centroids and bed elevation defined at
910      vertices.
911
912    Postcondition
913      Conserved quantities defined at vertices
914
915    """
916
917   
918
919    # Remove very thin layers of water
920    protect_against_infinitesimal_and_negative_heights(domain)
921
922    # Extrapolate all conserved quantities
923    if domain.optimised_gradient_limiter:
924        # MH090605 if second order,
925        # perform the extrapolation and limiting on
926        # all of the conserved quantities
927
928        if (domain._order_ == 1):
929            for name in domain.conserved_quantities:
930                Q = domain.quantities[name]
931                Q.extrapolate_first_order()
932        elif domain._order_ == 2:
933            domain.extrapolate_second_order_sw()
934        else:
935            raise 'Unknown order'
936    else:
937        # Old code:
938        for name in domain.conserved_quantities:
939            Q = domain.quantities[name]
940
941            if domain._order_ == 1:
942                Q.extrapolate_first_order()
943            elif domain._order_ == 2:
944                Q.extrapolate_second_order_and_limit_by_vertex()
945            else:
946                raise 'Unknown order'
947
948
949    # Take bed elevation into account when water heights are small
950    balance_deep_and_shallow(domain)
951
952    # Compute edge values by interpolation
953    for name in domain.conserved_quantities:
954        Q = domain.quantities[name]
955        Q.interpolate_from_vertices_to_edges()
956
957
958
959def distribute_using_edge_limiter(domain):
960    """Distribution from centroids to edges specific to the
961    shallow water wave
962    equation.
963
964    It will ensure that h (w-z) is always non-negative even in the
965    presence of steep bed-slopes by taking a weighted average between shallow
966    and deep cases.
967
968    In addition, all conserved quantities get distributed as per either a
969    constant (order==1) or a piecewise linear function (order==2).
970
971
972    Precondition:
973      All quantities defined at centroids and bed elevation defined at
974      vertices.
975
976    Postcondition
977      Conserved quantities defined at vertices
978
979    """
980
981    # Remove very thin layers of water
982    protect_against_infinitesimal_and_negative_heights(domain)
983
984
985    for name in domain.conserved_quantities:
986        Q = domain.quantities[name]
987        if domain._order_ == 1:
988            Q.extrapolate_first_order()
989        elif domain._order_ == 2:
990            Q.extrapolate_second_order_and_limit_by_edge()
991        else:
992            raise 'Unknown order'
993
994    balance_deep_and_shallow(domain)
995
996    # Compute edge values by interpolation
997    for name in domain.conserved_quantities:
998        Q = domain.quantities[name]
999        Q.interpolate_from_vertices_to_edges()
1000
1001
1002def protect_against_infinitesimal_and_negative_heights(domain):
1003    """Protect against infinitesimal heights and associated high velocities
1004    """
1005
1006    # Shortcuts
1007    wc = domain.quantities['stage'].centroid_values
1008    zc = domain.quantities['elevation'].centroid_values
1009    xmomc = domain.quantities['xmomentum'].centroid_values
1010    ymomc = domain.quantities['ymomentum'].centroid_values
1011
1012    from shallow_water_ext import protect
1013
1014    protect(domain.minimum_allowed_height, domain.maximum_allowed_speed,
1015            domain.epsilon, wc, zc, xmomc, ymomc)
1016
1017
1018
1019def balance_deep_and_shallow(domain):
1020    """Compute linear combination between stage as computed by
1021    gradient-limiters limiting using w, and stage computed by
1022    gradient-limiters limiting using h (h-limiter).
1023    The former takes precedence when heights are large compared to the
1024    bed slope while the latter takes precedence when heights are
1025    relatively small.  Anything in between is computed as a balanced
1026    linear combination in order to avoid numerical disturbances which
1027    would otherwise appear as a result of hard switching between
1028    modes.
1029
1030    Wrapper for C implementation
1031    """
1032
1033    from shallow_water_ext import balance_deep_and_shallow as balance_deep_and_shallow_c
1034
1035
1036    # Shortcuts
1037    wc = domain.quantities['stage'].centroid_values
1038    zc = domain.quantities['elevation'].centroid_values
1039
1040    wv = domain.quantities['stage'].vertex_values
1041    zv = domain.quantities['elevation'].vertex_values
1042
1043    # Momentums at centroids
1044    xmomc = domain.quantities['xmomentum'].centroid_values
1045    ymomc = domain.quantities['ymomentum'].centroid_values
1046
1047    # Momentums at vertices
1048    xmomv = domain.quantities['xmomentum'].vertex_values
1049    ymomv = domain.quantities['ymomentum'].vertex_values
1050
1051    balance_deep_and_shallow_c(domain,
1052                               wc, zc, wv, zv, wc, 
1053                               xmomc, ymomc, xmomv, ymomv)
1054
1055
1056
1057
1058#------------------------------------------------------------------
1059# Boundary conditions - specific to the shallow water wave equation
1060#------------------------------------------------------------------
1061class Reflective_boundary(Boundary):
1062    """Reflective boundary returns same conserved quantities as
1063    those present in its neighbour volume but reflected.
1064
1065    This class is specific to the shallow water equation as it
1066    works with the momentum quantities assumed to be the second
1067    and third conserved quantities.
1068    """
1069
1070    def __init__(self, domain = None):
1071        Boundary.__init__(self)
1072
1073        if domain is None:
1074            msg = 'Domain must be specified for reflective boundary'
1075            raise msg
1076
1077        # Handy shorthands
1078        self.stage   = domain.quantities['stage'].edge_values
1079        self.xmom    = domain.quantities['xmomentum'].edge_values
1080        self.ymom    = domain.quantities['ymomentum'].edge_values
1081        self.normals = domain.normals
1082
1083        self.conserved_quantities = zeros(3, Float)
1084
1085    def __repr__(self):
1086        return 'Reflective_boundary'
1087
1088
1089    def evaluate(self, vol_id, edge_id):
1090        """Reflective boundaries reverses the outward momentum
1091        of the volume they serve.
1092        """
1093
1094        q = self.conserved_quantities
1095        q[0] = self.stage[vol_id, edge_id]
1096        q[1] = self.xmom[vol_id, edge_id]
1097        q[2] = self.ymom[vol_id, edge_id]
1098
1099        normal = self.normals[vol_id, 2*edge_id:2*edge_id+2]
1100
1101
1102        r = rotate(q, normal, direction = 1)
1103        r[1] = -r[1]
1104        q = rotate(r, normal, direction = -1)
1105
1106        return q
1107
1108
1109
1110
1111class Transmissive_momentum_set_stage_boundary(Boundary):
1112    """Returns same momentum conserved quantities as
1113    those present in its neighbour volume.
1114    Sets stage by specifying a function f of time which may either be a
1115    vector function or a scalar function
1116
1117    Example:
1118
1119    def waveform(t):
1120        return sea_level + normalized_amplitude/cosh(t-25)**2
1121
1122    Bts = Transmissive_momentum_set_stage_boundary(domain, waveform)
1123   
1124
1125    Underlying domain must be specified when boundary is instantiated
1126    """
1127
1128    def __init__(self, domain = None, function=None):
1129        Boundary.__init__(self)
1130
1131        if domain is None:
1132            msg = 'Domain must be specified for this type boundary'
1133            raise msg
1134
1135        if function is None:
1136            msg = 'Function must be specified for this type boundary'
1137            raise msg
1138
1139        self.domain   = domain
1140        self.function = function
1141
1142    def __repr__(self):
1143        return 'Transmissive_momentum_set_stage_boundary(%s)' %self.domain
1144
1145    def evaluate(self, vol_id, edge_id):
1146        """Transmissive momentum set stage boundaries return the edge momentum
1147        values of the volume they serve.
1148        """
1149
1150        q = self.domain.get_conserved_quantities(vol_id, edge = edge_id)
1151
1152
1153        t = self.domain.get_time()
1154
1155        if hasattr(self.function, 'time'):
1156            # Roll boundary over if time exceeds           
1157            while t > self.function.time[-1]:
1158                msg = 'WARNING: domain time %.2f has exceeded' %t
1159                msg += 'time provided in '
1160                msg += 'transmissive_momentum_set_stage boundary object.\n'
1161                msg += 'I will continue, reusing the object from t==0'
1162                print msg
1163                t -= self.function.time[-1]
1164
1165
1166        value = self.function(t)
1167        try:
1168            x = float(value)
1169        except:
1170            x = float(value[0])
1171           
1172        q[0] = x
1173        return q
1174
1175
1176        # FIXME: Consider this (taken from File_boundary) to allow
1177        # spatial variation
1178        # if vol_id is not None and edge_id is not None:
1179        #     i = self.boundary_indices[ vol_id, edge_id ]
1180        #     return self.F(t, point_id = i)
1181        # else:
1182        #     return self.F(t)
1183
1184
1185# Backward compatibility       
1186# FIXME(Ole): Deprecate
1187class Transmissive_Momentum_Set_Stage_boundary(Transmissive_momentum_set_stage_boundary):
1188    pass
1189
1190     
1191
1192class Transmissive_stage_zero_momentum_boundary(Boundary):
1193    """Return same stage as those present in its neighbour volume. Set momentum to zero.
1194
1195    Underlying domain must be specified when boundary is instantiated
1196    """
1197
1198    def __init__(self, domain=None):
1199        Boundary.__init__(self)
1200
1201        if domain is None:
1202            msg = 'Domain must be specified for '
1203            msg += 'Transmissive_stage_zero_momentum boundary'
1204            raise Exception, msg
1205
1206        self.domain = domain
1207
1208    def __repr__(self):
1209        return 'Transmissive_stage_zero_momentum_boundary(%s)' %self.domain
1210
1211    def evaluate(self, vol_id, edge_id):
1212        """Transmissive boundaries return the edge values
1213        of the volume they serve.
1214        """
1215
1216        q = self.domain.get_conserved_quantities(vol_id, edge=edge_id)
1217       
1218        q[1] = q[2] = 0.0
1219        return q
1220
1221
1222       
1223class Dirichlet_discharge_boundary(Boundary):
1224    """
1225    Sets stage (stage0)
1226    Sets momentum (wh0) in the inward normal direction.
1227
1228    Underlying domain must be specified when boundary is instantiated
1229    """
1230
1231    def __init__(self, domain=None, stage0=None, wh0=None):
1232        Boundary.__init__(self)
1233
1234        if domain is None:
1235            msg = 'Domain must be specified for this type boundary'
1236            raise msg
1237
1238        if stage0 is None:
1239            raise 'set stage'
1240
1241        if wh0 is None:
1242            wh0 = 0.0
1243
1244        self.domain   = domain
1245        self.stage0  = stage0
1246        self.wh0 = wh0
1247
1248    def __repr__(self):
1249        return 'Dirichlet_Discharge_boundary(%s)' %self.domain
1250
1251    def evaluate(self, vol_id, edge_id):
1252        """Set discharge in the (inward) normal direction
1253        """
1254
1255        normal = self.domain.get_normal(vol_id,edge_id)
1256        q = [self.stage0, -self.wh0*normal[0], -self.wh0*normal[1]]
1257        return q
1258
1259
1260        # FIXME: Consider this (taken from File_boundary) to allow
1261        # spatial variation
1262        # if vol_id is not None and edge_id is not None:
1263        #     i = self.boundary_indices[ vol_id, edge_id ]
1264        #     return self.F(t, point_id = i)
1265        # else:
1266        #     return self.F(t)
1267
1268
1269       
1270# Backward compatibility       
1271# FIXME(Ole): Deprecate
1272class Dirichlet_Discharge_boundary(Dirichlet_discharge_boundary):
1273    pass
1274                                                   
1275   
1276
1277       
1278       
1279class Field_boundary(Boundary):
1280    """Set boundary from given field represented in an sww file containing values
1281    for stage, xmomentum and ymomentum.
1282    Optionally, the user can specify mean_stage to offset the stage provided in the
1283    sww file.
1284
1285    This function is a thin wrapper around the generic File_boundary. The
1286    difference between the file_boundary and field_boundary is only that the
1287    field_boundary will allow you to change the level of the stage height when
1288    you read in the boundary condition. This is very useful when running
1289    different tide heights in the same area as you need only to convert one
1290    boundary condition to a SWW file, ideally for tide height of 0 m
1291    (saving disk space). Then you can use field_boundary to read this SWW file
1292    and change the stage height (tide) on the fly depending on the scenario.
1293   
1294    """
1295
1296
1297    def __init__(self, filename, domain,
1298                 mean_stage=0.0,
1299                 time_thinning=1,
1300                 boundary_polygon=None,   
1301                 default_boundary=None,                 
1302                 use_cache=False,
1303                 verbose=False):
1304        """Constructor
1305
1306        filename: Name of sww file
1307        domain: pointer to shallow water domain for which the boundary applies
1308        mean_stage: The mean water level which will be added to stage derived
1309                    from the sww file
1310        time_thinning: Will set how many time steps from the sww file read in
1311                       will be interpolated to the boundary. For example if
1312                       the sww file has 1 second time steps and is 24 hours
1313                       in length it has 86400 time steps. If you set
1314                       time_thinning to 1 it will read all these steps.
1315                       If you set it to 100 it will read every 100th step eg
1316                       only 864 step. This parameter is very useful to increase
1317                       the speed of a model run that you are setting up
1318                       and testing.
1319                       
1320        default_boundary: Must be either None or an instance of a
1321                          class descending from class Boundary.
1322                          This will be used in case model time exceeds
1323                          that available in the underlying data.
1324                                               
1325        use_cache:
1326        verbose:
1327       
1328        """
1329
1330        # Create generic file_boundary object
1331        self.file_boundary = File_boundary(filename, domain,
1332                                           time_thinning=time_thinning,
1333                                           boundary_polygon=boundary_polygon,
1334                                           default_boundary=default_boundary,
1335                                           use_cache=use_cache,
1336                                           verbose=verbose)
1337
1338       
1339        # Record information from File_boundary
1340        self.F = self.file_boundary.F
1341        self.domain = self.file_boundary.domain
1342       
1343        # Record mean stage
1344        self.mean_stage = mean_stage
1345
1346
1347    def __repr__(self):
1348        return 'Field boundary'
1349
1350
1351    def evaluate(self, vol_id=None, edge_id=None):
1352        """Return linearly interpolated values based on domain.time
1353
1354        vol_id and edge_id are ignored
1355        """
1356       
1357        # Evaluate file boundary
1358        q = self.file_boundary.evaluate(vol_id, edge_id)
1359
1360        # Adjust stage
1361        for j, name in enumerate(self.domain.conserved_quantities):
1362            if name == 'stage':
1363                q[j] += self.mean_stage
1364        return q
1365
1366   
1367
1368#-----------------------
1369# Standard forcing terms
1370#-----------------------
1371
1372def gravity(domain):
1373    """Apply gravitational pull in the presence of bed slope
1374    Wrapper calls underlying C implementation
1375    """
1376
1377    xmom = domain.quantities['xmomentum'].explicit_update
1378    ymom = domain.quantities['ymomentum'].explicit_update
1379
1380    stage = domain.quantities['stage']
1381    elevation = domain.quantities['elevation']
1382
1383    h = stage.centroid_values - elevation.centroid_values
1384    z = elevation.vertex_values
1385
1386    x = domain.get_vertex_coordinates()
1387    g = domain.g
1388   
1389
1390    from shallow_water_ext import gravity as gravity_c
1391    gravity_c(g, h, z, x, xmom, ymom) #, 1.0e-6)
1392
1393
1394
1395def manning_friction_implicit(domain):
1396    """Apply (Manning) friction to water momentum   
1397    Wrapper for c version
1398    """
1399
1400
1401    #print 'Implicit friction'
1402
1403    xmom = domain.quantities['xmomentum']
1404    ymom = domain.quantities['ymomentum']
1405
1406    w = domain.quantities['stage'].centroid_values
1407    z = domain.quantities['elevation'].centroid_values
1408
1409    uh = xmom.centroid_values
1410    vh = ymom.centroid_values
1411    eta = domain.quantities['friction'].centroid_values
1412
1413    xmom_update = xmom.semi_implicit_update
1414    ymom_update = ymom.semi_implicit_update
1415
1416    N = len(domain)
1417    eps = domain.minimum_allowed_height
1418    g = domain.g
1419
1420    from shallow_water_ext import manning_friction as manning_friction_c
1421    manning_friction_c(g, eps, w, z, uh, vh, eta, xmom_update, ymom_update)
1422
1423
1424def manning_friction_explicit(domain):
1425    """Apply (Manning) friction to water momentum   
1426    Wrapper for c version
1427    """
1428
1429    # print 'Explicit friction'
1430
1431    xmom = domain.quantities['xmomentum']
1432    ymom = domain.quantities['ymomentum']
1433
1434    w = domain.quantities['stage'].centroid_values
1435    z = domain.quantities['elevation'].centroid_values
1436
1437    uh = xmom.centroid_values
1438    vh = ymom.centroid_values
1439    eta = domain.quantities['friction'].centroid_values
1440
1441    xmom_update = xmom.explicit_update
1442    ymom_update = ymom.explicit_update
1443
1444    N = len(domain)
1445    eps = domain.minimum_allowed_height
1446    g = domain.g
1447
1448    from shallow_water_ext import manning_friction as manning_friction_c
1449    manning_friction_c(g, eps, w, z, uh, vh, eta, xmom_update, ymom_update)
1450
1451
1452# FIXME (Ole): This was implemented for use with one of the analytical solutions (Sampson?)
1453# Is it still needed (30 Oct 2007)?
1454def linear_friction(domain):
1455    """Apply linear friction to water momentum
1456
1457    Assumes quantity: 'linear_friction' to be present
1458    """
1459
1460    from math import sqrt
1461
1462    w = domain.quantities['stage'].centroid_values
1463    z = domain.quantities['elevation'].centroid_values
1464    h = w-z
1465
1466    uh = domain.quantities['xmomentum'].centroid_values
1467    vh = domain.quantities['ymomentum'].centroid_values
1468    tau = domain.quantities['linear_friction'].centroid_values
1469
1470    xmom_update = domain.quantities['xmomentum'].semi_implicit_update
1471    ymom_update = domain.quantities['ymomentum'].semi_implicit_update
1472
1473    N = len(domain) # number_of_triangles
1474    eps = domain.minimum_allowed_height
1475    g = domain.g #Not necessary? Why was this added?
1476
1477    for k in range(N):
1478        if tau[k] >= eps:
1479            if h[k] >= eps:
1480                S = -tau[k]/h[k]
1481
1482                #Update momentum
1483                xmom_update[k] += S*uh[k]
1484                ymom_update[k] += S*vh[k]
1485
1486
1487
1488#---------------------------------
1489# Experimental auxiliary functions
1490#---------------------------------
1491def check_forcefield(f):
1492    """Check that f is either
1493    1: a callable object f(t,x,y), where x and y are vectors
1494       and that it returns an array or a list of same length
1495       as x and y
1496    2: a scalar
1497    """
1498
1499    if callable(f):
1500        N = 3
1501        x = ones(3, Float)
1502        y = ones(3, Float)
1503        try:
1504            q = f(1.0, x=x, y=y)
1505        except Exception, e:
1506            msg = 'Function %s could not be executed:\n%s' %(f, e)
1507            # FIXME: Reconsider this semantics
1508            raise msg
1509
1510        try:
1511            q = array(q).astype(Float)
1512        except:
1513            msg = 'Return value from vector function %s could ' %f
1514            msg += 'not be converted into a Numeric array of floats.\n'
1515            msg += 'Specified function should return either list or array.'
1516            raise msg
1517
1518        # Is this really what we want?
1519        msg = 'Return vector from function %s ' %f
1520        msg += 'must have same lenght as input vectors'
1521        assert len(q) == N, msg
1522
1523    else:
1524        try:
1525            f = float(f)
1526        except:
1527            msg = 'Force field %s must be either a scalar' %f
1528            msg += ' or a vector function'
1529            raise Exception(msg)
1530    return f
1531
1532
1533class Wind_stress:
1534    """Apply wind stress to water momentum in terms of
1535    wind speed [m/s] and wind direction [degrees]
1536    """
1537
1538    def __init__(self, *args, **kwargs):
1539        """Initialise windfield from wind speed s [m/s]
1540        and wind direction phi [degrees]
1541
1542        Inputs v and phi can be either scalars or Python functions, e.g.
1543
1544        W = Wind_stress(10, 178)
1545
1546        #FIXME - 'normal' degrees are assumed for now, i.e. the
1547        vector (1,0) has zero degrees.
1548        We may need to convert from 'compass' degrees later on and also
1549        map from True north to grid north.
1550
1551        Arguments can also be Python functions of t,x,y as in
1552
1553        def speed(t,x,y):
1554            ...
1555            return s
1556
1557        def angle(t,x,y):
1558            ...
1559            return phi
1560
1561        where x and y are vectors.
1562
1563        and then pass the functions in
1564
1565        W = Wind_stress(speed, angle)
1566
1567        The instantiated object W can be appended to the list of
1568        forcing_terms as in
1569
1570        Alternatively, one vector valued function for (speed, angle)
1571        can be applied, providing both quantities simultaneously.
1572        As in
1573        W = Wind_stress(F), where returns (speed, angle) for each t.
1574
1575        domain.forcing_terms.append(W)
1576        """
1577
1578        from anuga.config import rho_a, rho_w, eta_w
1579        from Numeric import array, Float
1580
1581        if len(args) == 2:
1582            s = args[0]
1583            phi = args[1]
1584        elif len(args) == 1:
1585            # Assume vector function returning (s, phi)(t,x,y)
1586            vector_function = args[0]
1587            s = lambda t,x,y: vector_function(t,x=x,y=y)[0]
1588            phi = lambda t,x,y: vector_function(t,x=x,y=y)[1]
1589        else:
1590           # Assume info is in 2 keyword arguments
1591
1592           if len(kwargs) == 2:
1593               s = kwargs['s']
1594               phi = kwargs['phi']
1595           else:
1596               raise 'Assumes two keyword arguments: s=..., phi=....'
1597
1598        self.speed = check_forcefield(s)
1599        self.phi = check_forcefield(phi)
1600
1601        self.const = eta_w*rho_a/rho_w
1602
1603
1604    def __call__(self, domain):
1605        """Evaluate windfield based on values found in domain
1606        """
1607
1608        from math import pi, cos, sin, sqrt
1609        from Numeric import Float, ones, ArrayType
1610
1611        xmom_update = domain.quantities['xmomentum'].explicit_update
1612        ymom_update = domain.quantities['ymomentum'].explicit_update
1613
1614        N = len(domain) # number_of_triangles
1615        t = domain.time
1616
1617        if callable(self.speed):
1618            xc = domain.get_centroid_coordinates()
1619            s_vec = self.speed(t, xc[:,0], xc[:,1])
1620        else:
1621            # Assume s is a scalar
1622
1623            try:
1624                s_vec = self.speed * ones(N, Float)
1625            except:
1626                msg = 'Speed must be either callable or a scalar: %s' %self.s
1627                raise msg
1628
1629
1630        if callable(self.phi):
1631            xc = domain.get_centroid_coordinates()
1632            phi_vec = self.phi(t, xc[:,0], xc[:,1])
1633        else:
1634            # Assume phi is a scalar
1635
1636            try:
1637                phi_vec = self.phi * ones(N, Float)
1638            except:
1639                msg = 'Angle must be either callable or a scalar: %s' %self.phi
1640                raise msg
1641
1642        assign_windfield_values(xmom_update, ymom_update,
1643                                s_vec, phi_vec, self.const)
1644
1645
1646def assign_windfield_values(xmom_update, ymom_update,
1647                            s_vec, phi_vec, const):
1648    """Python version of assigning wind field to update vectors.
1649    A c version also exists (for speed)
1650    """
1651    from math import pi, cos, sin, sqrt
1652
1653    N = len(s_vec)
1654    for k in range(N):
1655        s = s_vec[k]
1656        phi = phi_vec[k]
1657
1658        # Convert to radians
1659        phi = phi*pi/180
1660
1661        # Compute velocity vector (u, v)
1662        u = s*cos(phi)
1663        v = s*sin(phi)
1664
1665        # Compute wind stress
1666        S = const * sqrt(u**2 + v**2)
1667        xmom_update[k] += S*u
1668        ymom_update[k] += S*v
1669
1670
1671
1672
1673
1674class General_forcing:
1675    """General explicit forcing term for update of quantity
1676   
1677    This is used by Inflow and Rainfall for instance
1678   
1679
1680    General_forcing(quantity_name, rate, center, radius, polygon)
1681
1682    domain:     ANUGA computational domain
1683    quantity_name: Name of quantity to update.
1684                   It must be a known conserved quantity.
1685                   
1686    rate [?/s]: Total rate of change over the specified area. 
1687                This parameter can be either a constant or a
1688                function of time. Positive values indicate increases,
1689                negative values indicate decreases.
1690                Rate can be None at initialisation but must be specified
1691                before forcing term is applied (i.e. simulation has started).
1692
1693    center [m]: Coordinates at center of flow point
1694    radius [m]: Size of circular area
1695    polygon:    Arbitrary polygon
1696    default_rate: Rate to be used if rate fails (e.g. if model time exceeds its data)
1697                  Admissible types: None, constant number or function of t
1698
1699
1700    Either center, radius or polygon can be specified but not both.
1701    If neither are specified the entire domain gets updated.
1702    All coordinates to be specified in absolute UTM coordinates (x, y) assuming the zone of domain.   
1703   
1704    Inflow or Rainfall for examples of use
1705    """
1706
1707
1708    # FIXME (AnyOne) : Add various methods to allow spatial variations
1709
1710    def __init__(self,
1711                 domain,
1712                 quantity_name,
1713                 rate=0.0,
1714                 center=None, radius=None,
1715                 polygon=None,
1716                 default_rate=None,
1717                 verbose=False):
1718                     
1719        if center is None:
1720            msg = 'I got radius but no center.'       
1721            assert radius is None, msg
1722           
1723        if radius is None:
1724            msg += 'I got center but no radius.'       
1725            assert center is None, msg
1726           
1727           
1728                     
1729        from math import pi, cos, sin
1730
1731        self.domain = domain
1732        self.quantity_name = quantity_name
1733        self.rate = rate
1734        self.center = ensure_numeric(center)
1735        self.radius = radius
1736        self.polygon = polygon       
1737        self.verbose = verbose
1738        self.value = 0.0 # Can be used to remember value at
1739                         # previous timestep in order to obtain rate
1740
1741        # Get boundary (in absolute coordinates)
1742        bounding_polygon = domain.get_boundary_polygon()
1743
1744
1745        # Update area if applicable
1746        self.exchange_area = None       
1747        if center is not None and radius is not None:
1748            assert len(center) == 2
1749            msg = 'Polygon cannot be specified when center and radius are'
1750            assert polygon is None, msg
1751
1752            self.exchange_area = radius**2*pi
1753
1754            # Check that circle center lies within the mesh.
1755            msg = 'Center %s specified for forcing term did not' %(str(center))
1756            msg += 'fall within the domain boundary.'
1757            assert is_inside_polygon(center, bounding_polygon), msg
1758
1759            # Check that circle periphery lies within the mesh.
1760            N = 100
1761            periphery_points = []
1762            for i in range(N):
1763
1764                theta = 2*pi*i/100
1765               
1766                x = center[0] + radius*cos(theta)
1767                y = center[1] + radius*sin(theta)
1768
1769                periphery_points.append([x,y])
1770
1771
1772            for point in periphery_points:
1773                msg = 'Point %s on periphery for forcing term' %(str(point))
1774                msg += ' did not fall within the domain boundary.'
1775                assert is_inside_polygon(point, bounding_polygon), msg
1776
1777       
1778        if polygon is not None:
1779
1780            # Check that polygon lies within the mesh.
1781            for point in self.polygon:
1782                msg = 'Point %s in polygon for forcing term' %(point)
1783                msg += ' did not fall within the domain boundary.'
1784                assert is_inside_polygon(point, bounding_polygon), msg
1785               
1786            # Compute area and check that it is greater than 0   
1787            self.exchange_area = polygon_area(self.polygon)
1788           
1789            msg = 'Polygon %s in forcing term' %(self.polygon)
1790            msg += ' has area = %f' %self.exchange_area
1791            assert self.exchange_area > 0.0           
1792           
1793               
1794               
1795
1796        # Pointer to update vector
1797        self.update = domain.quantities[self.quantity_name].explicit_update
1798
1799        # Determine indices in flow area
1800        N = len(domain)   
1801        points = domain.get_centroid_coordinates(absolute=True)
1802
1803        # Calculate indices in exchange area for this forcing term
1804        self.exchange_indices = None
1805        if self.center is not None and self.radius is not None:
1806            # Inlet is circular
1807           
1808            inlet_region = 'center=%s, radius=%s' %(self.center, self.radius) 
1809           
1810            self.exchange_indices = []
1811            for k in range(N):
1812                x, y = points[k,:] # Centroid
1813               
1814                c = self.center
1815                if ((x-c[0])**2+(y-c[1])**2) < self.radius**2:
1816                    self.exchange_indices.append(k)
1817                   
1818        if self.polygon is not None:                   
1819            # Inlet is polygon
1820           
1821            inlet_region = 'polygon=%s, area=%f m^2' %(self.polygon, 
1822                                                       self.exchange_area) 
1823                       
1824            self.exchange_indices = inside_polygon(points, self.polygon)
1825           
1826           
1827           
1828        if self.exchange_indices is not None:
1829            #print inlet_region
1830       
1831            if len(self.exchange_indices) == 0:
1832                msg = 'No triangles have been identified in '
1833                msg += 'specified region: %s' %inlet_region
1834                raise Exception, msg
1835           
1836        # Check and store default_rate
1837        msg = 'Keyword argument default_rate must be either None ' 
1838        msg += 'or a function of time.\n I got %s' %(str(default_rate)) 
1839        assert default_rate is None or \
1840               type(default_rate) in [IntType, FloatType] or \
1841               callable(default_rate), msg
1842       
1843        if default_rate is not None:
1844
1845            # If it is a constant, make it a function
1846            if not callable(default_rate):
1847                tmp = default_rate
1848                default_rate = lambda t: tmp
1849
1850           
1851            # Check that default_rate is a function of one argument
1852            try:
1853                default_rate(0.0)
1854            except:
1855                raise Exception, msg
1856
1857        self.default_rate = default_rate
1858        self.default_rate_invoked = False    # Flag       
1859       
1860
1861    def __call__(self, domain):
1862        """Apply inflow function at time specified in domain and update stage
1863        """
1864
1865        # Call virtual method allowing local modifications
1866
1867        t = domain.get_time()
1868        try:
1869            rate = self.update_rate(t)
1870        except Modeltime_too_early, e:
1871            raise Modeltime_too_early, e
1872        except Modeltime_too_late, e:
1873            if self.default_rate is None:
1874                raise Exception, e # Reraise exception
1875            else:
1876                # Pass control to default rate function
1877                rate = self.default_rate(t)
1878               
1879                if self.default_rate_invoked is False:
1880                    # Issue warning the first time
1881                    msg = '%s' %str(e)
1882                    msg += 'Instead I will use the default rate: %s\n'\
1883                        %str(self.default_rate) 
1884                    msg += 'Note: Further warnings will be supressed'
1885                    warn(msg)
1886                   
1887                    # FIXME (Ole): Replace this crude flag with
1888                    # Python's ability to print warnings only once.
1889                    # See http://docs.python.org/lib/warning-filter.html
1890                    self.default_rate_invoked = True
1891                   
1892
1893           
1894               
1895
1896        if rate is None:
1897            msg = 'Attribute rate must be specified in General_forcing'
1898            msg += ' or its descendants before attempting to call it'
1899            raise Exception, msg
1900       
1901
1902        # Now rate is a number
1903        if self.verbose is True:
1904            print 'Rate of %s at time = %.2f = %f' %(self.quantity_name,
1905                                                     domain.get_time(),
1906                                                     rate)
1907
1908
1909        if self.exchange_indices is None:
1910            self.update[:] += rate
1911        else:
1912            # Brute force assignment of restricted rate
1913            for k in self.exchange_indices:
1914                self.update[k] += rate
1915
1916
1917    def update_rate(self, t):
1918        """Virtual method allowing local modifications by writing an
1919        overriding version in descendant
1920       
1921        """
1922        if callable(self.rate):
1923            rate = self.rate(t)
1924        else:
1925            rate = self.rate
1926
1927        return rate
1928
1929
1930    def get_quantity_values(self):
1931        """Return values for specified quantity restricted to opening
1932        """
1933       
1934        q = self.domain.quantities[self.quantity_name]
1935        return q.get_values(indices=self.exchange_indices)
1936   
1937
1938    def set_quantity_values(self, val):
1939        """Set values for specified quantity restricted to opening
1940        """
1941
1942        q = self.domain.quantities[self.quantity_name]               
1943        q.set_values(val, indices=self.exchange_indices)   
1944
1945
1946
1947class Rainfall(General_forcing):
1948    """Class Rainfall - general 'rain over entire domain' forcing term.
1949   
1950    Used for implementing Rainfall over the entire domain.
1951       
1952        Current Limited to only One Gauge..
1953       
1954        Need to add Spatial Varying Capability
1955        (This module came from copying and amending the Inflow Code)
1956   
1957    Rainfall(rain)
1958
1959    domain   
1960    rain [mm/s]:  Total rain rate over the specified domain. 
1961                  NOTE: Raingauge Data needs to reflect the time step.
1962                  IE: if Gauge is mm read at a time step, then the input
1963                  here is as mm/(timeStep) so 10mm in 5minutes becomes
1964                  10/(5x60) = 0.0333mm/s.
1965       
1966       
1967                  This parameter can be either a constant or a
1968                  function of time. Positive values indicate inflow,
1969                  negative values indicate outflow.
1970                  (and be used for Infiltration - Write Seperate Module)
1971                  The specified flow will be divided by the area of
1972                  the inflow region and then applied to update the
1973                  stage quantity.
1974
1975    polygon: Specifies a polygon to restrict the rainfall.
1976   
1977    Examples
1978    How to put them in a run File...
1979       
1980    #------------------------------------------------------------------------
1981    # Setup specialised forcing terms
1982    #------------------------------------------------------------------------
1983    # This is the new element implemented by Ole and Rudy to allow direct
1984    # input of Inflow in mm/s
1985
1986    catchmentrainfall = Rainfall(rain=file_function('Q100_2hr_Rain.tms')) 
1987                        # Note need path to File in String.
1988                        # Else assumed in same directory
1989
1990    domain.forcing_terms.append(catchmentrainfall)
1991    """
1992
1993   
1994    def __init__(self,
1995                 domain,
1996                 rate=0.0,
1997                 center=None, radius=None,
1998                 polygon=None,
1999                 default_rate=None,                 
2000                 verbose=False):
2001
2002        # Converting mm/s to m/s to apply in ANUGA)
2003        if callable(rate):
2004            rain = lambda t: rate(t)/1000.0
2005        else:
2006            rain = rate/1000.0
2007
2008        if default_rate is not None:   
2009            if callable(default_rate):
2010                default_rain = lambda t: default_rate(t)/1000.0
2011            else:
2012                default_rain = default_rate/1000.0
2013        else:
2014            default_rain = None
2015
2016
2017           
2018           
2019        General_forcing.__init__(self,
2020                                 domain,
2021                                 'stage',
2022                                 rate=rain,
2023                                 center=center, radius=radius,
2024                                 polygon=polygon,
2025                                 default_rate=default_rain,
2026                                 verbose=verbose)
2027
2028       
2029
2030
2031
2032
2033class Inflow(General_forcing):
2034    """Class Inflow - general 'rain and drain' forcing term.
2035   
2036    Useful for implementing flows in and out of the domain.
2037   
2038    Inflow(flow, center, radius, polygon)
2039
2040    domain
2041    rate [m^3/s]: Total flow rate over the specified area. 
2042                  This parameter can be either a constant or a
2043                  function of time. Positive values indicate inflow,
2044                  negative values indicate outflow.
2045                  The specified flow will be divided by the area of
2046                  the inflow region and then applied to update stage.     
2047    center [m]: Coordinates at center of flow point
2048    radius [m]: Size of circular area
2049    polygon:    Arbitrary polygon.
2050
2051    Either center, radius or polygon must be specified
2052   
2053    Examples
2054
2055    # Constant drain at 0.003 m^3/s.
2056    # The outflow area is 0.07**2*pi=0.0154 m^2
2057    # This corresponds to a rate of change of 0.003/0.0154 = 0.2 m/s
2058    #                                     
2059    Inflow((0.7, 0.4), 0.07, -0.003)
2060
2061
2062    # Tap turning up to a maximum inflow of 0.0142 m^3/s.
2063    # The inflow area is 0.03**2*pi = 0.00283 m^2
2064    # This corresponds to a rate of change of 0.0142/0.00283 = 5 m/s     
2065    # over the specified area
2066    Inflow((0.5, 0.5), 0.03, lambda t: min(0.01*t, 0.0142))
2067
2068
2069    #------------------------------------------------------------------------
2070    # Setup specialised forcing terms
2071    #------------------------------------------------------------------------
2072    # This is the new element implemented by Ole to allow direct input
2073    # of Inflow in m^3/s
2074
2075    hydrograph = Inflow(center=(320, 300), radius=10,
2076                        rate=file_function('Q/QPMF_Rot_Sub13.tms'))
2077
2078    domain.forcing_terms.append(hydrograph)
2079   
2080    """
2081
2082
2083    def __init__(self,
2084                 domain,
2085                 rate=0.0,
2086                 center=None, radius=None,
2087                 polygon=None,
2088                 default_rate=None,
2089                 verbose=False):                 
2090
2091
2092        # Create object first to make area is available
2093        General_forcing.__init__(self,
2094                                 domain,
2095                                 'stage',
2096                                 rate=rate,
2097                                 center=center, radius=radius,
2098                                 polygon=polygon,
2099                                 default_rate=default_rate,
2100                                 verbose=verbose)
2101
2102    def update_rate(self, t):
2103        """Virtual method allowing local modifications by writing an
2104        overriding version in descendant
2105
2106        This one converts m^3/s to m/s which can be added directly
2107        to 'stage' in ANUGA
2108        """
2109
2110        if callable(self.rate):
2111            _rate = self.rate(t)/self.exchange_area
2112        else:
2113            _rate = self.rate/self.exchange_area
2114
2115        return _rate
2116
2117
2118
2119
2120#------------------
2121# Initialise module
2122#------------------
2123
2124
2125from anuga.utilities import compile
2126if compile.can_use_C_extension('shallow_water_ext.c'):
2127    # Underlying C implementations can be accessed
2128
2129    from shallow_water_ext import rotate, assign_windfield_values
2130else:
2131    msg = 'C implementations could not be accessed by %s.\n ' %__file__
2132    msg += 'Make sure compile_all.py has been run as described in '
2133    msg += 'the ANUGA installation guide.'
2134    raise Exception, msg
2135
2136
2137# Optimisation with psyco
2138from anuga.config import use_psyco
2139if use_psyco:
2140    try:
2141        import psyco
2142    except:
2143        import os
2144        if os.name == 'posix' and os.uname()[4] in ['x86_64', 'ia64']:
2145            pass
2146            #Psyco isn't supported on 64 bit systems, but it doesn't matter
2147        else:
2148            msg = 'WARNING: psyco (speedup) could not import'+\
2149                  ', you may want to consider installing it'
2150            print msg
2151    else:
2152        psyco.bind(Domain.distribute_to_vertices_and_edges)
2153        psyco.bind(Domain.compute_fluxes)
2154
2155if __name__ == "__main__":
2156    pass
2157
2158
Note: See TracBrowser for help on using the repository browser.