# ******************************************************
## Revision "$LastChangedDate: 2015-05-21 09:31:08 +0200 (Thu, 21 May 2015) $"
## Date "$LastChangedRevision: 507 $"
## Author "$LastChangedBy: arthurbeusen $"
## URL "$HeadURL: https://pbl.sliksvn.com/globalnutrients/N_model/trunk/tools/n_nowater.py $"
# ******************************************************

import os
import ascraster
import aggregate
    
def calculate(params,mask,N_bal_grass,\
              N_bal_arable,N_bal_natural,pnet,\
              mouth_dict,basin):
    '''
    Calculates the Nitrogen load which is not transported, because there is no water.
    It returns the ascraster object with the nitrogen load which is inactive.
    The balances (grass,arable and natural) are changed by setting the balance on zero when there is no water.
    This function only corrects grass and natural land. For arable land it is assumed that there is always enough water.
    '''

    if params.ldebug: print "Start with calculation of N balance which is inactive."
      
    # Make a copy (alias not a deepcopy) of the return values
    N_nowater = ascraster.duplicategrid(N_bal_grass)
    if (N_nowater.nodata_value == None):
        N_nowater.nodata_value = -1
    N_nowater_grs = ascraster.duplicategrid(N_nowater)
    N_nowater_nat = ascraster.duplicategrid(N_nowater)  
    
    for icell in xrange(N_bal_grass.length):
        pnet_cell = pnet.get_data(icell,0.0)
        if (pnet_cell < params.minimal_soil_infiltration):
            # There is not enough water to transport N
            N_nowater_cell = 0.0
            N_bal_grass_cell = N_bal_grass.get_data(icell,0.0)
            N_nowater_cell += N_bal_grass_cell
            N_bal_grass.set_data(icell,0.0)  
            N_nowater_grs.set_data(icell,N_bal_grass_cell)
            
            N_bal_nat_cell = N_bal_natural.get_data(icell,0.0)
            N_nowater_cell += N_bal_nat_cell
            N_bal_natural.set_data(icell,0.0)  
            # Put inactive N into grid.
            N_nowater.set_data(icell,N_nowater_cell)
            N_nowater_nat.set_data(icell,N_bal_nat_cell)         
        else:
            N_nowater.set_data(icell,0.0)
            N_nowater_grs.set_data(icell,0.0)
            N_nowater_nat.set_data(icell,0.0)
   
    # Write N inactive N load to output file
    N_nowater.write_ascii_file(os.path.join(params.outputdir,"N_nowater.asc")) 
    N_nowater_grs.write_ascii_file(os.path.join(params.outputdir,"N_nowater_grs.asc")) 
    N_nowater_nat.write_ascii_file(os.path.join(params.outputdir,"N_nowater_nat.asc")) 

    # Aggregate the inactive N
    aggregate.aggregate_grid(basin,N_nowater,mouth_dict,item="n_inactive")
    aggregate.aggregate_grid(basin,N_nowater_grs,mouth_dict,item="n_inactive_grs")
    aggregate.aggregate_grid(basin,N_nowater_nat,mouth_dict,item="n_inactive_nat") 
    
    return N_nowater
        
    
