# ******************************************************
## Revision "$LastChangedDate: 2014-01-03 14:08:37 +0100 (Fri, 03 Jan 2014) $"
## Date "$LastChangedRevision: 439 $"
## Author "$LastChangedBy: arthurbeusen $"
## URL "$HeadURL: https://pbl.sliksvn.com/globalnutrients/N_model/trunk/tools/sgd.py $"
# ******************************************************

import os
import ascraster
import aggregate
 
def calculate(params,mask,mouth_dict,basin,nsgrw,ndgrw):
    '''
    The SGD is calculated and subtracted from the groundwater flow.
    The distance which determines whether it is an coastal cell is read from file, and the min and max is
    given in the parameters file.
    The fraction of the cell that flows directly to the coast is also read from the parameters file. 
    '''

    if params.ldebug: print "Start with calculation of submarine groundwater."

    # Read the distance to the coast from file in km
    distance = ascraster.Asciigrid(ascii_file=params.coast_distance,\
                                            mask=mask,numtype=float)

    # Make an output file
    sgd = ascraster.duplicategrid(nsgrw)
    sgd.add_values(sgd.length*[0.0])

    # Loads at the coast. Only the cells which are at the coastline (between distance_min and distance_max) are taken into account.
    for icell in range(nsgrw.length):
        dist = distance.get_data(icell,0.0)
        if (dist > params.distance_min and dist < params.distance_max):
            # This cell is an SGD cell
            nsgrw_cell = nsgrw.get_data(icell,0.0)
            ndgrw_cell = ndgrw.get_data(icell,0.0)
            sgd_shallow = params.sgdfraction_shallow * nsgrw_cell
            sgd_deep    = params.sgdfraction_deep    * ndgrw_cell
            # Reduce the groundwater flow to river with SGD
            # Here the max is taken to avoid small negative errors.
            nsgrw.set_data(icell,max(0.0,nsgrw_cell-sgd_shallow))
            ndgrw.set_data(icell,max(0.0,ndgrw_cell-sgd_deep))
            sgd.set_data(icell,sgd_shallow+sgd_deep)

    # Aggregate rasters
    aggregate.aggregate_grid(basin,sgd,mouth_dict,item="sgd")

    # Write total N coastal SGD load to output files.
    sgd.write_ascii_file(os.path.join(params.outputdir,"sgd.asc"))

