# ******************************************************
## Revision "$LastChangedDate: 2012-11-04 17:52:55 +0100 (Sun, 04 Nov 2012) $"
## Date "$LastChangedRevision: 282 $"
## Author "$LastChangedBy: arthurbeusen $"
## URL "$HeadURL: https://pbl.sliksvn.com/globalnutrients/generalcode/trunk/travel_load.py $"
# ******************************************************

import ascraster
import aggregate

def calculate(mouth_dict,basin,load,traveltime,sumtime,avgtime,sumload):
    '''
    This function calculates the the sum and the average of the product of residence_time and load.
    This must be an index for the travel time of the load in a river basin.
    sumtime,avgtime and sumload are attributes which are in mouth_dict. They must be given as text.
    '''

    loadtime = ascraster.duplicategrid(traveltime)

    # Calculate the travel time for the N load
    loadtime.multiply(load,default_nodata_value = 0.0)
    # Check whether sumtime is a valid attribute of the mouth_dict dictionairy.
    for key in mouth_dict.keys():
        try:
            sumtime_riv = getattr(mouth_dict[key],sumtime)
        except AttributeError:
            # Make attribute in the mouth_dict dictionary
            setattr(mouth_dict[key],sumtime, 0.0)

    # Aggregate traveltime over the river basin.
    aggregate.aggregate_grid(basin,loadtime,mouth_dict,item=sumtime)

    # Calculate the average traveltime for each river basin
    for key in mouth_dict.keys():
        try:
            sumtime_riv = getattr(mouth_dict[key],sumtime)
            sumload_riv = getattr(mouth_dict[key],sumload)
            setattr(mouth_dict[key],avgtime, sumtime_riv/sumload_riv)
        except ZeroDivisionError:
            setattr(mouth_dict[key],avgtime, 0.0)


