# ******************************************************
## Revision "$LastChangedDate: 2014-11-09 23:19:57 +0100 (Sun, 09 Nov 2014) $"
## Date "$LastChangedRevision: 472 $"
## Author "$LastChangedBy: arthurbeusen $"
## URL "$HeadURL: https://pbl.sliksvn.com/globalnutrients/P_model/trunk/tools/p_gnpp.py $"
# ******************************************************

import os
import ascraster
import aggregate
 
def calculate(params,mask,mouth_dict,basin):

    flooding_fraction = ascraster.Asciigrid(ascii_file=params.flooding_fraction,\
                                            mask=mask,numtype=float)
    gnpp = ascraster.Asciigrid(ascii_file=params.gnpp,\
                               mask=mask,numtype=float)
    cellarea = ascraster.Asciigrid(ascii_file=params.cellarea,\
                                   mask=mask,numtype=float)
    
    # Create new P grid with P load of gnpp in the water
    P_gnpp = ascraster.duplicategrid(flooding_fraction)

    # Make all cells zero.
    P_gnpp.add_values(P_gnpp.length*[0.0])

    for icell in xrange(flooding_fraction.length):
        flooding_fraction_cell = flooding_fraction.get_data(icell,0.0)
        if (flooding_fraction_cell > 0.0):
            gnpp_cell = gnpp.get_data(icell,0.0)
            area_cell = cellarea.get_data(icell,0.0)
            # Calculate the amount of C in the cell (NPP = gC /m2)
            # Area_cell is in m2. So 0.001 is from gr to kg.
            totC_cell = gnpp_cell * area_cell * 0.001
            # Calculate the amount of P in the part that is flooded.
            totP_cell = params.fr_gnpp_to_surface_water * totC_cell * min(flooding_fraction_cell,1.0) / params.CP_ratio_gnpp
            P_gnpp.set_data(icell,totP_cell)

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

    # Write to output file
    P_gnpp.write_ascii_file(os.path.join(params.outputdir,"p_gnpp.asc"))

    return P_gnpp         
        
