def make_balance_total( params, N_bal_grass, N_bal_arable, N_bal_natural, grassarea, croparea, natarea, mouth_dict, basin, check=1 ): """ Adds all positive balances to one total balance. Balances are changed when balance term is smaller than params.epsilon_load. When area does not match with the balances, than the balances are made zero. Input argument check determines whether the negative mass is counted for. """ errorlevel = 1.0e-15 if params.ldebug: print "Start with calculation of make_balance_total." balance_total = ascraster.duplicategrid(N_bal_grass) if check: N_bal_grass, N_bal_arable, N_bal_natural, removed_balance_arable, removed_balance_grs, removed_balance_nat = clean_balance( params, N_bal_grass, N_bal_arable, N_bal_natural, grassarea, croparea, natarea, mouth_dict, basin ) else: removed_balance_arable = ascraster.duplicategrid(N_bal_grass) removed_balance_arable.add_values(N_bal_grass.length * [0.0]) removed_balance_grs = ascraster.duplicategrid(N_bal_grass) removed_balance_grs.add_values(N_bal_grass.length * [0.0]) removed_balance_nat = ascraster.duplicategrid(N_bal_grass) removed_balance_nat.add_values(N_bal_grass.length * [0.0]) for icell in xrange(N_bal_grass.length): N_bal_grs_cell = N_bal_grass.get_data(icell, 0.0) N_bal_arable_cell = N_bal_arable.get_data(icell, 0.0) N_bal_nat_cell = N_bal_natural.get_data(icell, 0.0) total_load = N_bal_grs_cell + N_bal_arable_cell + N_bal_nat_cell balance_total.set_data(icell, total_load) return balance_total, removed_balance_arable, removed_balance_grs, removed_balance_nat
def make_balance_total(params,N_bal_grass,N_bal_arable,N_bal_natural,\ grassarea,croparea,natarea,mouth_dict,basin,check=1): ''' Adds all positive balances to one total balance. Balances are changed when balance term is smaller than params.epsilon_load. When area does not match with the balances, than the balances are made zero. Input argument check determines whether the negative mass is counted for. ''' errorlevel = 1.0e-15 if params.ldebug: print("Start with calculation of make_balance_total.") balance_total = ascraster.duplicategrid(N_bal_grass) if (check): N_bal_grass,N_bal_arable,N_bal_natural,removed_balance_arable,removed_balance_grs,removed_balance_nat = \ clean_balance(params,N_bal_grass,N_bal_arable,N_bal_natural,\ grassarea,croparea,natarea,mouth_dict,basin) else: removed_balance_arable = ascraster.duplicategrid(N_bal_grass) removed_balance_arable.add_values(N_bal_grass.length * [0.0]) removed_balance_grs = ascraster.duplicategrid(N_bal_grass) removed_balance_grs.add_values(N_bal_grass.length * [0.0]) removed_balance_nat = ascraster.duplicategrid(N_bal_grass) removed_balance_nat.add_values(N_bal_grass.length * [0.0]) for icell in range(N_bal_grass.length): N_bal_grs_cell = N_bal_grass.get_data(icell,0.0) N_bal_arable_cell = N_bal_arable.get_data(icell,0.0) N_bal_nat_cell = N_bal_natural.get_data(icell,0.0) total_load = N_bal_grs_cell + N_bal_arable_cell + N_bal_nat_cell balance_total.set_data(icell,total_load) return balance_total,removed_balance_arable,removed_balance_grs,removed_balance_nat
def griddivide(grid1,grid2,default_nodata_value = 0): ''' Calculate result of grid1/grid2 ''' # Make a copy of the first grid. grid3 = ascraster.duplicategrid(grid1) for icell in range(grid3.length): # Get values from both grids. val1 = grid1.get_data(icell) val2 = grid2.get_data(icell) # If both grids have nodata, keep nodata. if (val1 == None or val2 == None): continue # Do the calculation try: val3 = val1/val2 except (ZeroDivisionError,TypeError): val3 = default_nodata_value # Put result in grid. grid3.set_data(icell,val3) return grid3
def calculate_discharge(params, mask, pnet): ''' Calculate the accumulated water discharge ''' ldd = ascraster.Asciigrid(ascii_file=params.ldd, mask=mask, numtype=int) if params.ldebug: print(params.ldd + " has been read.") landarea = ascraster.Asciigrid(ascii_file=params.landarea, mask=mask, numtype=float) if params.ldebug: print(params.landarea + " has been read.") water = ascraster.duplicategrid(landarea) # Calculate accumulated water flux of each grid cell to the mouth of the river basin. Make discharge in km3 # Convert pnet [mm/yr] to km3 by multiplying with landarea and 10e-6 (conversion from mm to km) for icell in range(landarea.length): wt = pnet.get_data(icell, 0.0) * landarea.get_data(icell, 0.0) * 1.0e-6 water.set_data(icell, wt) discharge = accuflux.accuflux(ldd, water, negative_flux_possible=1) # Write discharge to output file: discharge.write_ascii_file(os.path.join(params.outputdir, "discharge.asc")) return discharge
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 list(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 list(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)
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)
def calculate(params, mask, residence_time_grid, lake_icell_dict): ''' This function calculates the hydraulic load in the water bodies. ''' # Depth water of waterbody in metres (result of residence time function) depth_grid = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"depth_waterbody_grid.asc"),\ mask=mask,numtype=float) hydraulic_load_grid = ascraster.duplicategrid(residence_time_grid) hydraulic_load_grid.add_values(hydraulic_load_grid.length * [0.0]) for icell in range(hydraulic_load_grid.length): depth = depth_grid.get_data(icell, 0.0) resi_time = residence_time_grid.get_data(icell, 0.0) try: Hl = depth / resi_time except ZeroDivisionError: Hl = 0.0 hydraulic_load_grid.set_data(icell, Hl) # Write hydraulic load to output file: hydraulic_load_grid.write_ascii_file( os.path.join(params.outputdir, "hydraulic_load.asc")) return hydraulic_load_grid
def determine_order(lddmap): # Make output raster with order of the cell ordermap = ascraster.duplicategrid(lddmap) # Fill all cells with zero for the order and one for the valuemap. ordermap.add_values(ordermap.length * [0]) # Loop over all cells: for icell in range(lddmap.length): end_of_path = False icell_loop = icell icell_loop_prev = icell while not end_of_path: lfirst = (icell_loop_prev == icell_loop) # Get direction of the ldd direction = int(lddmap.get_data(icell_loop, -1)) neighbour = int(ordermap.get_data(icell_loop_prev, 0)) if (direction < 1): # Go to next cell end_of_path = True elif (direction == 5): # Mouth of river basin is found. prev = int(ordermap.get_data(icell_loop, 0)) if (lfirst): if (prev < neighbour): ordermap.set_data(icell_loop, neighbour + 1) else: if (prev < neighbour + 1): ordermap.set_data(icell_loop, neighbour + 1) # Go to next cell end_of_path = True elif (direction > 9): # Go to next cell end_of_path = True else: prev = int(ordermap.get_data(icell_loop, 0)) if (lfirst): if (prev < neighbour): ordermap.set_data(icell_loop, neighbour + 1) else: if (prev < neighbour + 1): ordermap.set_data(icell_loop, neighbour + 1) # Go to next cell icell_loop_prev = icell_loop icell_loop = goto_nextcell(icell_loop, direction, lddmap.ncols, mask=lddmap.mask) if (icell_loop < 0): # Already printed a message. Go to next grid cell. end_of_path = True return ordermap
def calculate(params, mask, isocode, isogrid, popgrid_coast, N_emiss_coast, P_emiss_coast): """ Calculate the N and P emission on the grid and write to output grid files. Nothing is returned. """ # Create table of number of population at the coast Ncoast = ascraster.duplicategrid(popgrid_coast) Pcoast = ascraster.duplicategrid(popgrid_coast) for icell in range(isogrid.length): id = isogrid.get_data(icell, -1) if id > 0: if id in isocode: Nemiss_per_inh = N_emiss_coast[id] Pemiss_per_inh = P_emiss_coast[id] pop = popgrid_coast.get_data(icell, 0.0) Ncoast.set_data(icell, pop * Nemiss_per_inh) Pcoast.set_data(icell, pop * Pemiss_per_inh) # Write to oupt file Ncoast.write_ascii_file(params.filegEmNcoast) Pcoast.write_ascii_file(params.filegEmPcoast)
def determine_order(lddmap): # Make output raster with order of the cell ordermap = ascraster.duplicategrid(lddmap) # Fill all cells with zero for the order and one for the valuemap. ordermap.add_values(ordermap.length*[0]) # Loop over all cells: for icell in range(lddmap.length): end_of_path=False icell_loop = icell icell_loop_prev = icell while not end_of_path: lfirst = (icell_loop_prev == icell_loop) # Get direction of the ldd direction = int(lddmap.get_data(icell_loop,-1)) neighbour = int(ordermap.get_data(icell_loop_prev,0)) if (direction < 1): # Go to next cell end_of_path=True elif (direction == 5): # Mouth of river basin is found. prev = int(ordermap.get_data(icell_loop,0)) if (lfirst): if (prev < neighbour): ordermap.set_data(icell_loop,neighbour + 1) else: if (prev < neighbour + 1): ordermap.set_data(icell_loop,neighbour + 1) # Go to next cell end_of_path=True elif (direction > 9): # Go to next cell end_of_path=True else: prev = int(ordermap.get_data(icell_loop,0)) if (lfirst): if (prev < neighbour): ordermap.set_data(icell_loop,neighbour + 1) else: if (prev < neighbour + 1): ordermap.set_data(icell_loop,neighbour + 1) # Go to next cell icell_loop_prev = icell_loop icell_loop = goto_nextcell(icell_loop,direction,lddmap.ncols,mask=lddmap.mask) if (icell_loop < 0): # Already printed a message. Go to next grid cell. end_of_path=True return ordermap
def make_strahlerordermap(lddmap): ''' ''' cell = [] source_array = [cell] * lddmap.length strahler = ascraster.duplicategrid(lddmap) order_map = determine_order(lddmap) max_order = order_map.maximum() order_map.write_ascii_file('order_map.asc') # Loop over all cells to create source list: for o in range(0, max_order + 1): ordermask = ascraster.create_mask('order_map.asc', o, 'EQ', numtype=int) for icell in ordermask: if (lddmap.get_data(icell) != None): if (o == 0): strahler.set_data(icell, 6) icell_next = goto_nextcell(icell, lddmap.get_data(icell), lddmap.ncols) if (source_array[icell_next] == []): source_array[icell_next] = [icell] else: source_array[icell_next].append(icell) if (o != 0): dum = list() for source_icell in source_array[icell]: dum.append(strahler.get_data(source_icell)) if (len(dum) > 1): if (all(x == dum[0] for x in dum)): strahler.set_data(icell, dum[0] + 1) else: strahler.set_data(icell, max(dum)) else: strahler.set_data(icell, dum[0]) strahler.write_ascii_file('real_strahler.asc')
def make_fraction(params,source,total,divisionerror_outcome=0.0): ''' Calculates the fraction of the source on the total for each grid cell. ''' if params.ldebug: print "Start with calculation of make_fraction." fraction = ascraster.duplicategrid(total) for icell in range(total.length): total_cell = total.get_data(icell,0.0) source_cell = source.get_data(icell,0.0) try: frac = source_cell/total_cell except ZeroDivisionError: frac = divisionerror_outcome # Put result in raster fraction.set_data(icell,frac) return fraction
def calculate(params,mask,residence_time,lake_icell_dict): ''' This function calculates the hydraulic load in the water bodies. ''' flooding_depth_file = params.flooding_depth flooding_depth = ascraster.Asciigrid(ascii_file=flooding_depth_file,\ mask=mask,numtype=float) # Calculate the hydraulic load (Hl = depth/residence_time) hydraulic_load = ascraster.duplicategrid(flooding_depth) hydraulic_load.divide(residence_time,default_nodata_value = 0.0) # Put hydraulic load of the water body (lakes and reservoirs) in the grid. for icell in lake_icell_dict: if (lake_icell_dict[icell].outcell == 1): hydraulic_load.set_data(icell,lake_icell_dict[icell].hydraulic_load) # Write hydraulic load to output file: hydraulic_load.write_ascii_file(os.path.join(params.outputdir,"hydraulic_load.asc")) return hydraulic_load
def write_diffmap(mapA, mapB, outputfilename): ''' Create the cell-by-cell comparison of all cells and write this to ans ascii raster file. ''' if (mapA.length != mapB.length): raise MyError( "COMPARE_RASTERS: To compare two rasters, length should be equal.") # Duplicate output map. outgrid = ascraster.duplicategrid(mapA) # Set all data on nodata. if (not outgrid.nodata): outgrid.nodata_value = -9999. outgrid.add_values(outgrid.length * [outgrid.nodata_value]) # Create the diffences map. for icell in range(mapA.length): valA = mapA.get_data(icell) valB = mapB.get_data(icell) if (valA == None): # Nodata is excluded. continue if (valB == None): # Nodata is excluded. continue valA = iround(valA) valB = iround(valB) # Set this cell. if (valA == valB): outgrid.set_data(icell, 1) else: outgrid.set_data(icell, 0) # Write to output file outgrid.write_ascii_file(outputfilename)
def make_fraction(params, source, total, divisionerror_outcome=0.0): ''' Calculates the fraction of the source on the total for each grid cell. ''' if params.ldebug: print("Start with calculation of make_fraction.") fraction = ascraster.duplicategrid(total) if (fraction.nodata_value == None): fraction.nodata_value = -1 for icell in range(total.length): total_cell = total.get_data(icell, 0.0) source_cell = source.get_data(icell, 0.0) try: frac = source_cell / total_cell except ZeroDivisionError: frac = divisionerror_outcome # Put result in raster fraction.set_data(icell, frac) return fraction
def calculate(inputdir,mask,outputdir): ''' Calculate the net precipitation from temperature and precipitation. Formula is based on Turc-Langbein Input file annual temperature in Kelvin and precipitation in mm per hour. Output will be a grid file with net precipitation in mm per year ''' # Read precipitation data precip = ascraster.Asciigrid(ascii_file=os.path.join(inputdir,"2012annprec.asc"),mask=mask,numtype=float) # Read temperature data temp = ascraster.Asciigrid(ascii_file=os.path.join(inputdir,"2012annatem.asc"),mask=mask,numtype=float) # Change precipitation to mm/yr and temperature to Celcius precip.multiply(365*24) temp.add(-273.0) # Initialisation of net precipitation net_precip = ascraster.duplicategrid(temp) net_precip.add_values(net_precip.length*[net_precip.nodata_value]) # Calculate net precipitation for icell in range(net_precip.length): temperature = temp.get_data(icell) precipitation = precip.get_data(icell) if (precipitation != None and temperature != None): # Calculate Potential evapotranspiration epot = 325 + 21 * temperature + 0.9 * temperature*temperature eact = precipitation/math.sqrt(0.9 + ((precipitation*precipitation)/(epot*epot))) # print precipitation,temperature,eact,epot,precipitation - eact net = precipitation - eact net_precip.set_data(icell,net) net_precip.write_ascii_file(os.path.join(outputdir,"netprecip.asc")) return net_precip
def calculate_discharge(params,mask,pnet): ''' Calculate the accumulated water discharge ''' ldd = ascraster.Asciigrid(ascii_file=params.ldd,mask=mask,numtype=int) if params.ldebug: print params.ldd + " has been read." landarea = ascraster.Asciigrid(ascii_file=params.landarea,mask=mask,numtype=float) if params.ldebug: print params.landarea + " has been read." water = ascraster.duplicategrid(landarea) # Calculate accumulated water flux of each grid cell to the mouth of the river basin. Make discharge in km3 # Convert pnet [mm/yr] to km3 by multiplying with landarea and 10e-6 (conversion from mm to km) for icell in range(landarea.length): wt = pnet.get_data(icell,0.0) * landarea.get_data(icell,0.0) * 1.0e-6 water.set_data(icell,wt) discharge = accuflux.accuflux(ldd,water,negative_flux_possible=1) # Write discharge to output file: discharge.write_ascii_file(os.path.join(params.outputdir,"discharge.asc")) return discharge
def read_unf_as_raster(filename, example_raster): ''' Reads UNF files from IMAGE model and stores it as ascraster object. The example raster is used to convert the unformatted file to a ascraster. ''' # Determine the datatype dt, number_of_grids = unf_datatype(filename) # Read unformatted file datavalues = np.fromfile(filename, dtype=dt).tolist() gridout = [] for item in range(number_of_grids): gridout.append(ascraster.duplicategrid(example_raster)) if (len(datavalues) == number_of_grids * gridout[0].length): # Size is okay if (number_of_grids == 1): gridout[0].values = copy.deepcopy(datavalues) else: # Datavalues are stored for each cell. for igrid in range(number_of_grids): for icell in range(gridout[0].length): gridout[igrid].set_data( icell, datavalues[icell * number_of_grids + igrid]) else: raise MyError("Size of example raster is not equal to unformatted file.",\ "Size of example raster: " + str(gridout.length),\ "Size of unformatted datafile: " + str(len(datavalues)) + " in file: " + filename) if (number_of_grids == 1): # Return the ascraster object (not as a list). return gridout[0] else: # Return all the grids as list return gridout
def calculate(params): #print("The critical N deposition rate is " + str(params.crit_dep) + " kg N ha-1 yr-1") # load needed variables for calculations biome = ascraster.Asciigrid(ascii_file=os.path.join( params.inputdir, "gnlct.asc"), numtype=float, mask=params.mask) a_tot = ascraster.Asciigrid(ascii_file=os.path.join( params.inputdir, "a_tot.asc"), numtype=float, mask=params.mask) nfix_ara = ascraster.Asciigrid( ascii_file=params.filename_nfixation_cropland, numtype=float, mask=params.mask) nfix_igl = ascraster.Asciigrid(ascii_file=params.filename_nfixation_intgl, numtype=float, mask=params.mask) nox_em = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nox_em.asc"), numtype=float, mask=params.mask) nh3_tot_egl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_tot_egl.asc"), numtype=float, mask=params.mask) nh3_tot_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_tot_igl.asc"), numtype=float, mask=params.mask) nh3_tot_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_tot_ara.asc"), numtype=float, mask=params.mask) nh3_ef_man_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_ara.asc"), numtype=float, mask=params.mask) nh3_ef_man_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_igl.asc"), numtype=float, mask=params.mask) nh3_ef_fer_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_fer_ara.asc"), numtype=float, mask=params.mask) nh3_ef_fer_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_fer_igl.asc"), numtype=float, mask=params.mask) frnfe_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnfe_ara.asc"), numtype=float, mask=params.mask) frnfe_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnfe_igl.asc"), numtype=float, mask=params.mask) fara = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "fara.asc"), numtype=float, mask=params.mask) figl = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "figl.asc"), numtype=float, mask=params.mask) fsro_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fsro_ag.asc"), numtype=float, mask=params.mask) frnup_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnup_ara.asc"), numtype=float, mask=params.mask) frnup_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnup_igl.asc"), numtype=float, mask=params.mask) nup_max_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nup_max_ara.asc"), numtype=float, mask=params.mask) nup_max_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nup_max_igl.asc"), numtype=float, mask=params.mask) nin_max_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nin_max_ara.asc"), numtype=float, mask=params.mask) nin_max_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nin_max_igl.asc"), numtype=float, mask=params.mask) # make grid with critical N deposition per biome ndep_crit_ha = ascraster.duplicategrid(nfix_ara) # watch out: can ndep_crit_ha become both -9999 and -1 (NA value?) for i in range(ndep_crit_ha.length): ndep_crit_ha.set_data(i, -9999) for icell in range(biome.length): val = biome.get_data(icell) # Ice (7) or Hot desert (16) if (val == 7 or val == 16): cl = 5.0 # Boreal forest (10), Cool coniferous forest (11) or scrubland (17) elif (val == 10 or val == 11 or val == 17): cl = 7.5 # Tundra (8) or wooded tundra (9)or Warm mixed forest (14) elif (val == 8 or val == 9 or val == 14): cl = 10.0 # Temperate mixed forest (12) Temperate deciduous forest (13) elif (val == 12 or val == 13): cl = 12.5 # Savanna (18) elif (val == 18): cl = 15.0 # Grassland/steppe (15) elif (val == 15): cl = 17.5 # Tropical woodland (19) or Tropical forest (20) elif (val == 19 or val == 20): cl = 20 # Biome can also have value 0 or none (-1) else: continue ndep_crit_ha.set_data(icell, cl) print_debug(biome, "biome =") fileout = os.path.join(params.outputdir, "ndep_crit_ha.asc") ndep_crit_ha.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_ha, "ndep_crit_ha =") ## * Total critical deposition * ndep_crit_tot = ascraster.duplicategrid(ndep_crit_ha) ndep_crit_tot.multiply(a_tot) fileout = os.path.join(params.outputdir, "ndep_crit_tot.asc") ndep_crit_tot.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_tot, "ndep_crit_tot =") ## * Critical NH3 emissions * nh3em_ara_igl = ascraster.duplicategrid(nh3_tot_ara) nh3em_ara_igl.add(nh3_tot_igl) # 'ara' nh3_fraction_ara = ascraster.duplicategrid(nh3_tot_ara) nh3_fraction_ara.divide(nh3em_ara_igl, default_nodata_value=-9999) nh3em_crit_ara = ascraster.duplicategrid(ndep_crit_tot) nh3em_crit_ara.substract(nox_em) nh3em_crit_ara.substract(nh3_tot_egl) nh3em_crit_ara.multiply(nh3_fraction_ara) print_debug(nh3em_crit_ara, "nh3em_crit_ara =") # 'igl' nh3_fraction_igl = ascraster.duplicategrid(nh3_tot_igl) nh3_fraction_igl.divide(nh3em_ara_igl, default_nodata_value=-9999) nh3em_crit_igl = ascraster.duplicategrid(ndep_crit_tot) nh3em_crit_igl.substract(nox_em) nh3em_crit_igl.substract(nh3_tot_egl) nh3em_crit_igl.multiply(nh3_fraction_igl) print_debug(nh3em_crit_igl, "nh3em_crit_igl =") ## * Critical N inputs from manure * one_grid = ascraster.duplicategrid(frnfe_ara) for i in range(one_grid.length): one_grid.set_data(i, 1.0) # 'ara' one_min_frnfe_ara = ascraster.duplicategrid(one_grid) one_min_frnfe_ara.substract(frnfe_ara) frnfe_division_ara = ascraster.duplicategrid(frnfe_ara) frnfe_division_ara.divide(one_min_frnfe_ara, default_nodata_value=-9999) denominator_ara = ascraster.duplicategrid(frnfe_division_ara) denominator_ara.multiply(nh3_ef_fer_ara) denominator_ara.add(nh3_ef_man_ara) nman_crit_dep_ara = ascraster.duplicategrid(nh3em_crit_ara) nman_crit_dep_ara.divide(denominator_ara, default_nodata_value=-9999) for icell in range(nman_crit_dep_ara.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) if (f_ara == 0 and f_igl > 0): nman_ara = 0 else: continue nman_crit_dep_ara.set_data(icell, nman_ara) for icell in range(nman_crit_dep_ara.length): nman_ara3 = nman_crit_dep_ara.get_data(icell) if (nman_ara3 is None): continue if (nman_ara3 < 0): nman_ara = 0 else: continue nman_crit_dep_ara.set_data(icell, nman_ara) fileout = os.path.join(params.outputdir, "nman_crit_dep_ara.asc") nman_crit_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nman_crit_dep_ara, "nman_crit_dep_ara =") # 'igl' one_min_frnfe_igl = ascraster.duplicategrid(one_grid) one_min_frnfe_igl.substract(frnfe_igl) frnfe_division_igl = ascraster.duplicategrid(frnfe_igl) frnfe_division_igl.divide(one_min_frnfe_igl, default_nodata_value=-9999) denominator_igl = ascraster.duplicategrid(frnfe_division_igl) denominator_igl.multiply(nh3_ef_fer_igl) denominator_igl.add(nh3_ef_man_igl) nman_crit_dep_igl = ascraster.duplicategrid(nh3em_crit_igl) nman_crit_dep_igl.divide(denominator_igl, default_nodata_value=-9999) for icell in range(nman_crit_dep_igl.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) if (f_igl == 0 and f_ara > 0): nman_igl = 0 else: continue nman_crit_dep_igl.set_data(icell, nman_igl) for icell in range(nman_crit_dep_igl.length): nman_igl3 = nman_crit_dep_igl.get_data(icell) if (nman_igl3 is None): continue if (nman_igl3 < 0): nman_igl = 0 else: continue nman_crit_dep_igl.set_data(icell, nman_igl) fileout = os.path.join(params.outputdir, "nman_crit_dep_igl.asc") nman_crit_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nman_crit_dep_igl, "nman_crit_dep_igl =") ## calculate critical N input from fertilizer # 'ara' nfer_crit_dep_ara = ascraster.duplicategrid(nman_crit_dep_ara) nfer_crit_dep_ara.multiply(frnfe_division_ara) for icell in range(nfer_crit_dep_ara.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) if (f_ara == 0 and f_igl > 0): nfer_ara = 0 else: continue nfer_crit_dep_ara.set_data(icell, nfer_ara) fileout = os.path.join(params.outputdir, "nfer_crit_dep_ara.asc") nfer_crit_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nfer_crit_dep_ara, "nfer_crit_dep_ara =") # 'igl' nfer_crit_dep_igl = ascraster.duplicategrid(nman_crit_dep_igl) nfer_crit_dep_igl.multiply(frnfe_division_igl) for icell in range(nfer_crit_dep_igl.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) if (f_igl == 0 and f_ara > 0): nfer_igl = 0 else: continue nfer_crit_dep_igl.set_data(icell, nfer_igl) fileout = os.path.join(params.outputdir, "nfer_crit_dep_igl.asc") nfer_crit_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nfer_crit_dep_igl, "nfer_crit_dep_igl =") ## * Critical N inputs from fertilizer plus manure * ## # 'ara' nman_fer_crit_dep_ara = ascraster.duplicategrid(nman_crit_dep_ara) nman_fer_crit_dep_ara.add(nfer_crit_dep_ara) fileout = os.path.join(params.outputdir, "nman_fer_crit_dep_ara.asc") nman_fer_crit_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'igl' nman_fer_crit_dep_igl = ascraster.duplicategrid(nman_crit_dep_igl) nman_fer_crit_dep_igl.add(nfer_crit_dep_igl) fileout = os.path.join(params.outputdir, "nman_fer_crit_dep_igl.asc") nman_fer_crit_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ## * NH3 emissions at critical N input * # 'ara' nh3em_man_crit_dep_ara = ascraster.duplicategrid(nman_crit_dep_ara) nh3em_man_crit_dep_ara.multiply(nh3_ef_man_ara) nh3em_fer_crit_dep_ara = ascraster.duplicategrid(nfer_crit_dep_ara) nh3em_fer_crit_dep_ara.multiply(nh3_ef_fer_ara) nh3em_crit_dep_ara = ascraster.duplicategrid(nh3em_fer_crit_dep_ara) nh3em_crit_dep_ara.add(nh3em_man_crit_dep_ara) print_debug(nh3em_crit_dep_ara, "nh3em_crit_dep_ara =") # 'igl' nh3em_man_crit_dep_igl = ascraster.duplicategrid(nman_crit_dep_igl) nh3em_man_crit_dep_igl.multiply(nh3_ef_man_igl) nh3em_fer_crit_dep_igl = ascraster.duplicategrid(nfer_crit_dep_igl) nh3em_fer_crit_dep_igl.multiply(nh3_ef_fer_igl) nh3em_crit_dep_igl = ascraster.duplicategrid(nh3em_fer_crit_dep_igl) nh3em_crit_dep_igl.add(nh3em_man_crit_dep_igl) print_debug(nh3em_crit_dep_igl, "nh3em_crit_dep_igl =") ## * N deposition at critical N inputs * ndep_crit_dep_tot = ascraster.duplicategrid(nh3em_crit_dep_ara) ndep_crit_dep_tot.add(nh3em_crit_dep_igl) ndep_crit_dep_tot.add(nox_em) ndep_crit_dep_tot.add(nh3_tot_egl) fileout = os.path.join(params.outputdir, "ndep_crit_dep_tot.asc") ndep_crit_dep_tot.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_dep_tot, "ndep_crit_dep_tot =") # 'ara' ndep_crit_dep_ara = ascraster.duplicategrid(ndep_crit_dep_tot) ndep_crit_dep_ara.multiply(fara) print_debug(ndep_crit_dep_ara, "ndep_crit_dep_ara =") # 'igl' ndep_crit_dep_igl = ascraster.duplicategrid(ndep_crit_dep_tot) ndep_crit_dep_igl.multiply(figl) print_debug(ndep_crit_dep_igl, "ndep_crit_dep_igl =") ## * Total critical N inputs * # 'ara' nin_crit_dep_ara = ascraster.duplicategrid(nman_crit_dep_ara) nin_crit_dep_ara.add(nfer_crit_dep_ara) nin_crit_dep_ara.add(ndep_crit_dep_ara) nin_crit_dep_ara.add(nfix_ara) fileout = os.path.join(params.outputdir, "nin_crit_dep_ara.asc") nin_crit_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nin_crit_dep_ara, "nin_crit_dep_ara =") # 'igl' nin_crit_dep_igl = ascraster.duplicategrid(nman_crit_dep_igl) nin_crit_dep_igl.add(nfer_crit_dep_igl) nin_crit_dep_igl.add(ndep_crit_dep_igl) nin_crit_dep_igl.add(nfix_igl) fileout = os.path.join(params.outputdir, "nin_crit_dep_igl.asc") nin_crit_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nin_crit_dep_igl, "nin_crit_dep_igl =") # 'ara+igl' nin_crit_dep_araigl = ascraster.duplicategrid(nin_crit_dep_ara) nin_crit_dep_araigl.add(nin_crit_dep_igl) fileout = os.path.join(params.outputdir, "nin_crit_dep_araigl.asc") nin_crit_dep_araigl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ## * N surface runoff at critical N inputs * # 'ara' nsro_crit_dep_ara = ascraster.duplicategrid(nin_crit_dep_ara) nsro_crit_dep_ara.multiply(fsro_ag) print_debug(nsro_crit_dep_ara, "nsro_crit_dep_ara =") # 'igl' nsro_crit_dep_igl = ascraster.duplicategrid(nin_crit_dep_igl) nsro_crit_dep_igl.multiply(fsro_ag) print_debug(nsro_crit_dep_igl, "nsro_crit_dep_igl =") ## * N uptake at critical N inputs * # 'ara' nup_crit_dep_ara = ascraster.duplicategrid(nin_crit_dep_ara) nup_crit_dep_ara.substract(nsro_crit_dep_ara) nup_crit_dep_ara.multiply(frnup_ara) fileout = os.path.join(params.outputdir, "nup_crit_dep_ara.asc") nup_crit_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nup_crit_dep_ara, "nup_crit_dep_ara =") # 'igl' nup_crit_dep_igl = ascraster.duplicategrid(nin_crit_dep_igl) nup_crit_dep_igl.substract(nsro_crit_dep_igl) nup_crit_dep_igl.multiply(frnup_igl) fileout = os.path.join(params.outputdir, "nup_crit_dep_igl.asc") nup_crit_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nup_crit_dep_igl, "nup_crit_dep_igl =") ## * NUE at critical N inputs * # 'ara' nue_crit_dep_ara = ascraster.duplicategrid(nup_crit_dep_ara) nue_crit_dep_ara.divide(nin_crit_dep_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nue_crit_dep_ara.asc") nue_crit_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_crit_dep_ara, "nue_crit_dep_ara =") # 'igl' nue_crit_dep_igl = ascraster.duplicategrid(nup_crit_dep_igl) nue_crit_dep_igl.divide(nin_crit_dep_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nue_crit_dep_igl.asc") nue_crit_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_crit_dep_igl, "nue_crit_dep_igl =") ## * Maximum uptake fraction * # 'ara' fnup_max_dep_ara = ascraster.duplicategrid(nup_max_ara) fnup_max_dep_ara.divide(nup_crit_dep_ara) fileout = os.path.join(params.outputdir, "fnup_max_dep_ara.asc") fnup_max_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_max_dep_ara, "fnup_max_dep_ara =") # 'igl' fnup_max_dep_igl = ascraster.duplicategrid(nup_max_igl) fnup_max_dep_igl.divide(nup_crit_dep_igl) fileout = os.path.join(params.outputdir, "fnup_max_dep_igl.asc") fnup_max_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_max_dep_igl, "fnup_max_dep_igl =") ## * Correction factor for grid cells where Nup,crit > Nup,max * # 'ara' fnup_corr_dep_ara = ascraster.duplicategrid(nin_max_ara) fnup_corr_dep_ara.substract(nfix_ara) temp2_ara = ascraster.duplicategrid(nh3_tot_egl) temp2_ara.add(nox_em) temp2_ara.multiply(fara) fnup_corr_dep_ara.substract(temp2_ara) temp3_ara = ascraster.duplicategrid(nh3em_crit_dep_ara) temp3_ara.multiply(fara) temp3_ara.add(nman_crit_dep_ara) temp3_ara.add(nfer_crit_dep_ara) fnup_corr_dep_ara.divide(temp3_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fnup_corr_dep_ara.asc") fnup_corr_dep_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_corr_dep_ara, "fnup_corr_dep_ara =") # 'igl' fnup_corr_dep_igl = ascraster.duplicategrid(nin_max_igl) fnup_corr_dep_igl.substract(nfix_igl) temp2_igl = ascraster.duplicategrid(nh3_tot_egl) temp2_igl.add(nox_em) temp2_igl.multiply(figl) fnup_corr_dep_igl.substract(temp2_igl) temp3_igl = ascraster.duplicategrid(nh3em_crit_dep_igl) temp3_igl.multiply(figl) temp3_igl.add(nman_crit_dep_igl) temp3_igl.add(nfer_crit_dep_igl) fnup_corr_dep_igl.divide(temp3_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fnup_corr_dep_igl.asc") fnup_corr_dep_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_corr_dep_igl, "fnup_corr_dep_igl =") ########### FORWARD CALCULATIONS TO CHECK ########### if icell_debug < 0: pass else: fw = ndep_crit_dep_tot.get_data(icell_debug) bw = ndep_crit_tot.get_data(icell_debug) if fw is None: print( "FW/BW_TEST:_Forward_calculation_not_possible:_Nin,crit = None" ) else: fw = round(fw, 4) bw = round(bw, 4) if fw == bw: print("FW/BW_TEST = SUCCESFUL") else: print("FW/BW_TEST = NOT_SUCCESFUL")
def accutime(lddmap,timemap,lake_icell_dict): ''' ACCUTIME PURPOSE: Accumulate residence time for each grid cell to the mouth of the river. The output map contains accumulated residence time [grid]. When a endoreic lake is encountered then, residence time is to the lake and not to the sea. All files are ascii-grid formatted. Lddmap: network of local drain directions flow_direction can be coded as follows: UNH/GRDC PCraster(LDD) 32 64 128 meaning: NW N NE 7 8 9 16 - 1 W - E 4 5 6 8 4 2 SW S SE 1 2 3 We use the PCraster LDD-format; negative and zero values are assumed ''' # Make output rasters accutimemap = ascraster.duplicategrid(timemap) # Loop over all cells: for icell in range(lddmap.length): # Get residence time at the cell. restime = timemap.get_data(icell) if (restime == None): # No data value continue if (restime < 0.0): print "Negative residence time of " + str(restime) + " at cell: " + str(icell) # Go to next cell. accutimemap.set_data(icell,0.0) continue end_of_path=False icell_loop = icell cumtime = restime while not end_of_path: # Get direction of the ldd direction = int(lddmap.get_data(icell_loop,-1)) # Check whether the cell is in a endoreic lake try: lendo_lake = lake_icell_dict[icell].lendolake except KeyError: lendo_lake = 0 if (direction < 1 or direction > 9): #print "Something is wrong with the lddmap (< 1). No river mouth found for icell: ",icell, " with load: ", flux, " and direction: ",direction # Go to next cell end_of_path=True elif (direction == 5): # Mouth of river basin is found. end_of_path=True elif (lendo_lake == 1): # Endoreic lake found. end_of_path=True else: # Go to next cell icell_loop = goto_nextcell(icell_loop,direction,lddmap.ncols,mask=lddmap.mask) if (icell_loop < 0): # Already printed a message. Go to next grid cell. end_of_path=True # Set accutime in grid or fetch new restime for next cell if (end_of_path): accutimemap.set_data(icell,cumtime) else: restime = timemap.get_data(icell_loop,0.0) cumtime += restime return accutimemap
def temp_values(params): ### --------- 1. LAND UNSE FRACTIONS --------- ### # read input files land areas a_tot = ascraster.Asciigrid(ascii_file=params.filename_gridcell_area, numtype=float, mask=params.mask) a_ag = ascraster.Asciigrid(ascii_file=params.filename_agri_area, numtype=float, mask=params.mask) a_ara = ascraster.Asciigrid(ascii_file=params.filename_cropland_area, numtype=float, mask=params.mask) a_igl = ascraster.Asciigrid(ascii_file=params.filename_intgl_area, numtype=float, mask=params.mask) a_egl = ascraster.Asciigrid(ascii_file=params.filename_extgl_area, numtype=float, mask=params.mask) a_nat = ascraster.Asciigrid(ascii_file=params.filename_natural_area, numtype=float, mask=params.mask) # calculate f*g f*g = ascraster.duplicategrid(a_ag) f*g.divide(a_tot, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "f*g.asc") f*g.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(f*g, "f*g =") # calculate fara fara = ascraster.duplicategrid(a_ara) fara.divide(a_tot, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fara.asc") fara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fara, "fara =") # calculate figl figl = ascraster.duplicategrid(a_igl) figl.divide(a_tot, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "figl.asc") figl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(figl, "figl =") # calculate fagri fagri = ascraster.duplicategrid(a_ara) fagri.add(a_igl) fagri.divide(a_tot, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fagri.asc") fagri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fagri, "fagri =") # calculate fegl fegl = ascraster.duplicategrid(a_egl) fegl.divide(a_tot, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fegl.asc") fegl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fegl, "fegl =") # calculate fnat fnat = ascraster.duplicategrid(a_nat) fnat.divide(a_tot, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fnat.asc") fnat.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnat, "fnat =") ### --------- 2. INPUTS FERTILIZER, MANURE, FIXATION --------- ### # read input files N inputs n_fert_ag = ascraster.Asciigrid(ascii_file=params.filename_fert_inp, numtype=float, mask=params.mask) n_fert_ara = ascraster.Asciigrid( ascii_file=params.filename_fert_inp_cropland, numtype=float, mask=params.mask) n_fert_igl = ascraster.Asciigrid( ascii_file=params.filename_fert_inp_grassland, numtype=float, mask=params.mask) n_man_ag = ascraster.Asciigrid(ascii_file=params.filename_manure_inp, numtype=float, mask=params.mask) n_man_ara = ascraster.Asciigrid( ascii_file=params.filename_manure_inp_cropland, numtype=float, mask=params.mask) n_man_igl = ascraster.Asciigrid( ascii_file=params.filename_manure_inp_intgl, numtype=float, mask=params.mask) n_man_egl = ascraster.Asciigrid( ascii_file=params.filename_manure_inp_extgl, numtype=float, mask=params.mask) n_fix_ag = ascraster.Asciigrid(ascii_file=params.filename_nfixation_agri, numtype=float, mask=params.mask) n_fix_ara = ascraster.Asciigrid( ascii_file=params.filename_nfixation_cropland, numtype=float, mask=params.mask) n_fix_igl = ascraster.Asciigrid(ascii_file=params.filename_nfixation_intgl, numtype=float, mask=params.mask) n_fix_egl = ascraster.Asciigrid(ascii_file=params.filename_nfixation_extgl, numtype=float, mask=params.mask) nh3_stor = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_storage, numtype=float, mask=params.mask) #$#V1.4#$# #''' # split nh3 emissions from storage over intensive and extensive grassland #$#V1.4#$# # intensive grassland #$#V1.3#$# nh3_stor_igl = ascraster.duplicategrid(nh3_stor) #$#V1.3#$# for icell in range(nh3_stor_igl.length): #$#V1.3#$# igl = a_igl.get_data(icell) #$#V1.3#$# nh3stor = nh3_stor.get_data(icell) #$#V1.3#$# if (igl == None or igl == 0): #$#V1.3#$# nh3emigl = 0 #$#V1.3#$# elif (igl > 0): #$#V1.3#$# nh3emigl = nh3stor #$#V1.3#$# else: #$#V1.3#$# continue #$#V1.3#$# nh3_stor_igl.set_data(icell, nh3emigl) #$#V1.3#$# fileout = os.path.join(params.outputdir, "nh3_stor_igl.asc") #$#V1.3#$# nh3_stor_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) #$#V1.3#$# print_debug(nh3_stor_igl, "nh3_stor_igl =") #$#V1.3#$# # extensive grassland #$#V1.3#$# nh3_stor_egl = ascraster.duplicategrid(nh3_stor) #$#V1.3#$# for icell in range(nh3_stor_egl.length): #$#V1.3#$# egl = a_egl.get_data(icell) #$#V1.3#$# nh3stor = nh3_stor.get_data(icell) #$#V1.3#$# if (egl == None or egl == 0): #$#V1.3#$# nh3emegl = 0 #$#V1.3#$# elif (egl > 0): #$#V1.3#$# nh3emegl = nh3stor #$#V1.3#$# else: #$#V1.3#$# continue #$#V1.3#$# nh3_stor_egl.set_data(icell, nh3emegl) #$#V1.3#$# fileout = os.path.join(params.outputdir, "nh3_stor_egl.asc") #$#V1.3#$# nh3_stor_egl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) #$#V1.3#$# print_debug(nh3_stor_egl, "nh3_stor_egl =") #$#V1.3#$# # arable land #$#V1.3#$# nh3_stor_ara = ascraster.duplicategrid(nh3_stor) #$#V1.3#$# for icell in range(nh3_stor_ara.length): #$#V1.3#$# ara = a_ara.get_data(icell) #$#V1.3#$# igl = a_igl.get_data(icell) #$#V1.3#$# egl = a_egl.get_data(icell) #$#V1.3#$# nh3stor = nh3_stor.get_data(icell) #$#V1.3#$# if (ara == None): #$#V1.3#$# nh3emara = 0 #$#V1.3#$# elif (egl == 0 and igl == 0): #$#V1.3#$# nh3emara = nh3stor #$#V1.3#$# elif (egl > 0 or igl > 0): #$#V1.3#$# nh3emara = 0 #$#V1.3#$# nh3emara = 0 #$#V1.3#$# else: #$#V1.3#$# continue #$#V1.3#$# nh3_stor_ara.set_data(icell, nh3emara) #$#V1.3#$# fileout = os.path.join(params.outputdir, "nh3_stor_ara.asc") #$#V1.3#$# nh3_stor_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) #$#V1.3#$# print_debug(nh3_stor_ara, "nh3_stor_ara =") #$#V1.3#$# #''' # Calculate N inputs to 'agri' - fertilizer n_fert_agri_eff = ascraster.duplicategrid(n_fert_ara) n_fert_agri_eff.add(n_fert_igl) print_debug(n_fert_agri_eff, "n_fert_agri_eff =") # Calculate N inputs to 'agri' - manure n_man_agri_eff = ascraster.duplicategrid(n_man_ara) n_man_agri_eff.add(n_man_igl) print_debug(n_man_agri_eff, "n_man_agri_eff =") #''' #$# Add NH3 emissions to input from FERTILIZER #$#V1.2#$# # ag #$#V1.2#$# nh3_spread_fert = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_fert, numtype=float, mask=params.mask) #$#V1.2#$# n_fert_ag_nh3 = ascraster.duplicategrid(n_fert_ag) #$#V1.2#$# n_fert_ag_nh3.add(nh3_spread_fert) #$#V1.2#$# print_debug(n_fert_ag_nh3, "n_fert_ag_nh3 =") #$#V1.2#$# # replace original calculations of n_fert_ag #$#V1.2#$# n_fert_ag = ascraster.duplicategrid(n_fert_ag_nh3) #$#V1.2#$# # agri #$#V1.2#$# nh3_spread_fert_ara = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_fert_cropland, numtype=float, mask=params.mask) #$#V1.2#$# nh3_spread_fert_igl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_fert_intgl, numtype=float, mask=params.mask) #$#V1.2#$# n_fert_agri_nh3 = ascraster.duplicategrid(n_fert_agri_eff) #$#V1.2#$# n_fert_agri_nh3.add(nh3_spread_fert_ara) #$#V1.2#$# n_fert_agri_nh3.add(nh3_spread_fert_igl) #$#V1.2#$# print_debug(n_fert_agri_nh3, "n_fert_agri_nh3 =") #$#V1.2#$# # replace original calculations of n_fert_agri #$#V1.2#$# n_fert_agri = ascraster.duplicategrid(n_fert_agri_nh3) #$#V1.2#$# fileout = os.path.join(params.outputdir, "n_fert_agri.asc") n_fert_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(n_fert_agri, "n_fert_agri =") #$# Add NH3 emissions to input from MANURE #$#V1.2#$# # ag #$#V1.2#$# nh3_spread_man = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure, numtype=float, mask=params.mask) #$#V1.2#$# nh3_stor = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_storage, numtype=float, mask=params.mask) #$#V1.2#$# nh3_graz = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_grazing, numtype=float, mask=params.mask) #$#V1.2#$# n_man_ag_nh3 = ascraster.duplicategrid(n_man_ag) #$#V1.2#$# n_man_ag_nh3.add(nh3_spread_man) #$#V1.2#$# n_man_ag_nh3.add(nh3_stor) #$#V1.2#$# n_man_ag_nh3.add(nh3_graz) #$#V1.2#$# print_debug(n_man_ag_nh3, "n_man_ag_nh3 =") #$#V1.2#$# # replace original calculations of n_man_ag #$#V1.2#$# n_man_ag = ascraster.duplicategrid(n_man_ag_nh3) #$#V1.2#$# # agri #$#V1.2#$# nh3_spread_man_ara = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure_cropland, numtype=float, mask=params.mask) #$#V1.2#$# nh3_spread_man_igl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure_intgl, numtype=float, mask=params.mask) #$#V1.2#$# nh3_graz_igl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_grazing_int, numtype=float, mask=params.mask) #$#V1.2#$# n_man_agri_nh3 = ascraster.duplicategrid(n_man_agri_eff) #$#V1.2#$# n_man_agri_nh3.add(nh3_spread_man_ara) #$#V1.2#$# n_man_agri_nh3.add(nh3_spread_man_igl) #$#V1.2#$# #n_man_agri_nh3.add(nh3_stor) #$#V1.2#$# n_man_agri_nh3.add(nh3_stor_ara) #$#V1.4#$# n_man_agri_nh3.add(nh3_stor_igl) #$#V1.4#$# n_man_agri_nh3.add(nh3_graz_igl) #$#V1.2#$# print_debug(n_man_agri_nh3, "n_man_agri_nh3 =") #$#V1.2#$# # replace original calculations of n_man_agri #$#V1.2#$# n_man_agri = ascraster.duplicategrid(n_man_agri_nh3) #$#V1.2#$# fileout = os.path.join(params.outputdir, "n_man_agri.asc") n_man_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(n_man_agri, "n_man_agri =") # 'egl' nh3_graz_egl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_grazing_ext, numtype=float, mask=params.mask) #$#V1.2#$# nh3_spread_man_egl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure_extgl, numtype=float, mask=params.mask) n_man_egl_nh3 = ascraster.duplicategrid(n_man_egl) n_man_egl_nh3.add(nh3_spread_man_egl) n_man_egl_nh3.add(nh3_stor_egl) n_man_egl_nh3.add(nh3_graz_egl) # replace original calculations of n_man_egl #$#V1.2#$# n_man_egl = ascraster.duplicategrid(n_man_egl_nh3) #$#V1.2#$# fileout = os.path.join(params.outputdir, "nman_egl.asc") n_man_egl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(n_man_egl, "n_man_egl =") #''' # Calculate N inputs to 'agri' - N fixation n_fix_agri = ascraster.duplicategrid(n_fix_ara) n_fix_agri.add(n_fix_igl) fileout = os.path.join(params.outputdir, "n_fix_agri.asc") n_fix_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(n_fix_agri, "n_fix_agri =") # calculate frNfe_ag fert_man_ag = ascraster.duplicategrid(n_man_ag) fert_man_ag.add(n_fert_ag) frnfe_ag = griddivide(n_fert_ag, fert_man_ag, default_nodata_value=0) # replace '0' by 0.0001 in frNfe_ag for icell in range(frnfe_ag.length): val = frnfe_ag.get_data(icell) if (val == None or val > 0): continue if val == 0.0: res = 0.0001 frnfe_ag.set_data(icell, res) # replace '1' by 0.9999 in frNfe_ag for icell in range(frnfe_ag.length): val = frnfe_ag.get_data(icell) if (val == None or val < 1): continue if val == 1.0: res = 0.9999 frnfe_ag.set_data(icell, res) print_debug(frnfe_ag, "frNfe_ag =") #fileout = os.path.join(params.outputdir,"frnfe_ag.asc") #frnfe_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) ####CHECK: INDEED OK TO GET NA VALUES FOR DIV ZERO WITH frNfe? # calculate frNfe_agri fert_man_agri = ascraster.duplicategrid(n_fert_agri) fert_man_agri.add(n_man_agri) #fileout = os.path.join(params.outputdir,"fert_man_agri.asc") #fert_man_agri.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) frnfe_agri = ascraster.duplicategrid(n_fert_agri) frnfe_agri.divide(fert_man_agri) #frnfe_agri = griddivide(n_fert_agri,fert_man_agri,default_nodata_value = 0) # replace '0' by 0.0001 in frNfe_agri for icell in range(frnfe_agri.length): val = frnfe_agri.get_data(icell) if (val == None or val > 0): continue if val == 0.0: res = 0.0001 frnfe_agri.set_data(icell, res) # replace '1' by 0.9999 in frnfe_agri for icell in range(frnfe_agri.length): val = frnfe_agri.get_data(icell) if (val == None or val < 1): continue if val == 1.0: res = 0.9999 frnfe_agri.set_data(icell, res) print_debug(frnfe_agri, "frnfe_agri =") fileout = os.path.join(params.outputdir, "frnfe_agri.asc") frnfe_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ### --------- 3. NH3 EMISSIONS & EMISSION FRACTIONS --------- ### # read input files NH3 emissions nh3_spread_man = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure, numtype=float, mask=params.mask) nh3_spread_man_ara = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure_cropland, numtype=float, mask=params.mask) nh3_spread_man_igl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure_intgl, numtype=float, mask=params.mask) nh3_spread_man_egl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_manure_extgl, numtype=float, mask=params.mask) nh3_stor = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_storage, numtype=float, mask=params.mask) nh3_graz = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_grazing, numtype=float, mask=params.mask) nh3_graz_igl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_grazing_int, numtype=float, mask=params.mask) nh3_graz_egl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_grazing_ext, numtype=float, mask=params.mask) nh3_spread_fert = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_fert, numtype=float, mask=params.mask) nh3_spread_fert_ara = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_fert_cropland, numtype=float, mask=params.mask) nh3_spread_fert_igl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_fert_intgl, numtype=float, mask=params.mask) nh3_spread_fert_egl = ascraster.Asciigrid( ascii_file=params.filename_nh3_em_spread_fert_extgl, numtype=float, mask=params.mask) # calculate total NH3 emission (all agriculture) nh3_tot = ascraster.duplicategrid(nh3_spread_man) nh3_tot.add(nh3_stor) nh3_tot.add(nh3_graz) nh3_tot.add(nh3_spread_fert) print_debug(nh3_tot, "nh3_tot =") # calculate total NH3 emission (ara + igl) nh3_spread_fert_agri = ascraster.duplicategrid(nh3_spread_fert_ara) nh3_spread_fert_agri.add(nh3_spread_fert_igl) nh3_tot_agri = ascraster.duplicategrid(nh3_spread_fert_agri) nh3_tot_agri.add(nh3_spread_man_ara) nh3_tot_agri.add(nh3_spread_man_igl) nh3_tot_agri.add(nh3_stor_igl) #$#V1.3#$# nh3_tot_agri.add(nh3_stor_ara) #$#V1.3#$# #nh3_tot_agri.add(nh3_stor) #$#V1.1#$# nh3_tot_agri.add(nh3_graz_igl) fileout = os.path.join(params.outputdir, "nh3_tot_agri.asc") nh3_tot_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nh3_tot_agri, "nh3_tot_agri =") # calculate total NH3 emission (egl) nh3_tot_egl = ascraster.duplicategrid(nh3_spread_man_egl) nh3_tot_egl.add(nh3_graz_egl) nh3_tot_egl.add(nh3_spread_fert_egl) nh3_tot_egl.add(nh3_stor_egl) #$#V1.3#$# fileout = os.path.join(params.outputdir, "nh3_tot_egl.asc") nh3_tot_egl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nh3_tot_egl, "nh3_tot_egl =") # calculate fnh3em,man,ag nh3_man_tot = ascraster.duplicategrid(nh3_tot) nh3_man_tot.substract(nh3_spread_fert) nh3_ef_man = griddivide(nh3_man_tot, n_man_ag, default_nodata_value=0) #fileout = os.path.join(params.outputdir,"nh3_ef_man.asc") #nh3_ef_man.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_man, "nh3_ef_man =") # calculate fnh3em,man,agri nh3_man_tot_agri = ascraster.duplicategrid(nh3_tot_agri) nh3_man_tot_agri.substract(nh3_spread_fert_agri) nh3_ef_man_agri = griddivide(nh3_man_tot_agri, n_man_agri, default_nodata_value=0) fileout = os.path.join(params.outputdir, "nh3_ef_man_agri.asc") nh3_ef_man_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nh3_ef_man_agri, "nh3_ef_man_agri =") # calculate fnh3em,fert nh3_ef_fert = griddivide(nh3_spread_fert, n_fert_ag, default_nodata_value=0) #fileout = os.path.join(params.outputdir,"nh3_ef_fert.asc") #nh3_ef_fert.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_fert, "nh3_ef_fert =") # calculate fnh3em,fert,agri nh3_ef_fert_agri = griddivide(nh3_spread_fert_agri, n_fert_agri, default_nodata_value=0) fileout = os.path.join(params.outputdir, "nh3_ef_fert_agri.asc") nh3_ef_fert_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nh3_ef_fert_agri, "nh3_ef_fert_agri =") ### --------- 4. N DEPOSITION & NOx emission --------- ### # calculate corrected N deposition grid - for all cells where Ndep < NH3em, replace Ndep by NH3em ndep_tot = ascraster.Asciigrid(ascii_file=params.filename_n_deposition, numtype=float, mask=params.mask) ndep_corr_tot = ascraster.duplicategrid(ndep_tot) for icell in range(nh3_tot.length): # Get values from both grids. nh3 = nh3_tot.get_data(icell) dep = ndep_tot.get_data(icell) # If both grids have nodata, keep nodata. if (nh3 == None or dep == None or dep >= nh3): continue if dep < nh3: depcorr = nh3 ndep_corr_tot.set_data(icell, depcorr) fileout = os.path.join(params.outputdir, "ndep_corr_tot.asc") ndep_corr_tot.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_tot, "ndep_tot =") print_debug(ndep_corr_tot, "ndep_corr_tot =") # calculate NOx emissions: NOx = *corrected* Ndep - (NH3,spread,fe+NH3,spread,man+NH3stor+NH3,graz) nox_em = ascraster.duplicategrid(ndep_corr_tot) nox_em.substract(nh3_tot) #factor = 0 #nox_em.multiply(factor) fileout = os.path.join(params.outputdir, "nox_em.asc") nox_em.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nox_em, "nox_em =") # calculate ndep_ag ndep_ag = ascraster.duplicategrid(ndep_corr_tot) ndep_ag.multiply(f*g) #fileout = os.path.join(params.outputdir,"ndep_ag.asc") #ndep_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_ag, "ndep_ag =") # calculate ndep_ara ndep_ara = ascraster.duplicategrid(ndep_corr_tot) ndep_ara.multiply(fara) #fileout = os.path.join(params.outputdir,"ndep_ara.asc") #ndep_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_ara, "ndep_ara =") # calculate ndep_igl ndep_igl = ascraster.duplicategrid(ndep_corr_tot) ndep_igl.multiply(figl) #fileout = os.path.join(params.outputdir,"ndep_igl.asc") #ndep_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_igl, "ndep_igl =") # calculate ndep_agri ndep_agri = ascraster.duplicategrid(ndep_corr_tot) ndep_agri.multiply(fagri) #fileout = os.path.join(params.outputdir,"ndep_agri.asc") #ndep_agri.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_agri, "ndep_agri =") # calculate ndep_egl ndep_egl = ascraster.duplicategrid(ndep_corr_tot) ndep_egl.multiply(fegl) #fileout = os.path.join(params.outputdir,"ndep_egl.asc") #ndep_egl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_egl, "ndep_egl =") ### --------- 5. TOTAL INPUTS --------- ### # calculate n_in_ag n_in_ag = ascraster.duplicategrid(n_fert_ag) n_in_ag.add(n_man_ag) n_in_ag.add(n_fix_ag) n_in_ag.add(ndep_ag) #fileout = os.path.join(params.outputdir,"n_in_ag.asc") #n_in_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(n_in_ag, "n_in_ag =") # calculate n_in_ara n_in_ara = ascraster.duplicategrid(n_fert_ara) n_in_ara.add(n_man_ara) n_in_ara.add(n_fix_ara) n_in_ara.add(ndep_ara) #fileout = os.path.join(params.outputdir,"n_in_ara.asc") #n_in_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(n_in_ara, "n_in_ara =") # calculate n_in_igl n_in_igl = ascraster.duplicategrid(n_fert_igl) n_in_igl.add(n_man_igl) n_in_igl.add(n_fix_igl) n_in_igl.add(ndep_igl) #fileout = os.path.join(params.outputdir,"n_in_igl.asc") #n_in_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(n_in_igl, "n_in_igl =") # calculate n_in_agri n_in_agri = ascraster.duplicategrid(n_fert_agri) n_in_agri.add(n_man_agri) n_in_agri.add(n_fix_agri) n_in_agri.add(ndep_agri) fileout = os.path.join(params.outputdir, "n_in_agri.asc") n_in_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(n_in_agri, "n_in_agri =") # calculate n_in_egl n_in_egl = ascraster.duplicategrid(n_man_egl) n_in_egl.add(n_fix_egl) n_in_egl.add(ndep_egl) #fileout = os.path.join(params.outputdir,"n_in_egl.asc") #n_in_egl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(n_in_egl, "n_in_egl =") ### --------- 6. SURFACE RUNOFF, UPTAKE, FRNUP, NUE --------- ### # read input files uptake, surface runoff nsro_ag = ascraster.Asciigrid(ascii_file=params.filename_nsro_ag, numtype=float, mask=params.mask) n_up_ara = ascraster.Asciigrid(ascii_file=params.filename_uptake_cropland, numtype=float, mask=params.mask) n_up_igl = ascraster.Asciigrid(ascii_file=params.filename_uptake_intgl, numtype=float, mask=params.mask) n_up_egl = ascraster.Asciigrid(ascii_file=params.filename_uptake_extgl, numtype=float, mask=params.mask) regions = ascraster.Asciigrid(ascii_file=params.filename_regions, numtype=float, mask=params.mask) #$# To manipulate results for 1999 so that I can also get uptake per land-use type (assuming equal NUE) #$#n_up_ag = ascraster.Asciigrid(ascii_file=params.filename_uptake_agriculture, numtype=float,mask=params.mask) #$# #$#nue_ag = ascraster.duplicategrid(n_up_ag) #$#nue_ag.divide(n_in_ag, default_nodata_value = -9999) #$#n_up_ara = ascraster.duplicategrid(n_in_ara) #$#n_up_ara.multiply(nue_ag) #$#fileout = os.path.join(params.inputdir,"n_up_crops.asc") #$#n_up_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) #$#n_up_igl = ascraster.duplicategrid(n_in_igl) #$#n_up_igl.multiply(nue_ag) #$#fileout = os.path.join(params.inputdir,"n_up_grass_int.asc") #$#n_up_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) #$#n_up_egl = ascraster.duplicategrid(n_in_egl) #$#n_up_egl.multiply(nue_ag) #$#fileout = os.path.join(params.inputdir,"n_up_grass_ext.asc") #$#n_up_egl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) # calculate uptake,agri n_up_agri = ascraster.duplicategrid(n_up_ara) n_up_agri.add(n_up_igl) #fileout = os.path.join(params.outputdir,"n_up_agri.asc") #n_up_agri.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(n_up_agri, "n_up_agri =") # calculate uptake,ag n_up_ag = ascraster.duplicategrid(n_up_ara) n_up_ag.add(n_up_igl) n_up_ag.add(n_up_egl) #fileout = os.path.join(params.outputdir,"n_up_ag.asc") #n_up_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(n_up_ag, "n_up_ag =") # calculate runoff fraction fsro,ag fsro_ag = griddivide(nsro_ag, n_in_ag, default_nodata_value=0) fileout = os.path.join(params.outputdir, "fsro_ag.asc") fsro_ag.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fsro_ag, "fsro_ag =") # calculate nsro,agri nsro_agri = ascraster.duplicategrid(fsro_ag) nsro_agri.multiply(n_in_agri) #fileout = os.path.join(params.outputdir,"nsro_agri.asc") #nsro_agri.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nsro_agri, "nsro_agri =") # calculate frnup_agri n_in_min_nsro_agri = ascraster.duplicategrid(n_in_agri) n_in_min_nsro_agri.substract(nsro_agri) frnup_agri = griddivide(n_up_agri, n_in_min_nsro_agri, default_nodata_value=0) fileout = os.path.join(params.outputdir, "frnup_agri.asc") frnup_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(frnup_agri, "frnup_agri =") # calculate nue_agri nue_agri = ascraster.duplicategrid(n_up_agri) nue_agri.divide(n_in_agri, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nue_agri.asc") nue_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_agri, "nue_agri =") # maximum N uptake # make grid with yield increase per region yieldgap_region = ascraster.duplicategrid(n_up_ara) for i in range(yieldgap_region.length): yieldgap_region.set_data(i, -9999) for icell in range(regions.length): val = regions.get_data(icell) # Canada (1) if val == 1: yg = 1.274 # USA (2) elif val == 2: yg = 1.252 # Mexico (3) elif val == 3: yg = 1.566 # Central America (4) elif val == 4: yg = 1.797 # Brazil (5) elif val == 5: yg = 1.343 # Rest of South America (6) elif val == 6: yg = 1.532 # Northern Africa (7) elif val == 7: yg = 2.711 # Western Africa (8) elif val == 8: yg = 2.363 # Eastern Africa (9) elif val == 9: yg = 2.424 # South Africa (10) elif val == 10: yg = 1.848 # Western Europe (11) elif val == 11: yg = 1.177 # Central Europe (12) elif val == 12: yg = 1.982 # Turkey (13) elif val == 13: yg = 1.797 # Ukraine region (14) elif val == 14: yg = 2.633 # Central Asia (15) elif val == 15: yg = 2.928 # Russia region(16) elif val == 16: yg = 2.391 # Middle East (17) elif val == 17: yg = 2.170 # India (18) elif val == 18: yg = 1.508 # Korea region (19) elif val == 19: yg = 1.180 # China region (20) elif val == 20: yg = 1.503 # Southeastern Asia (21) elif val == 21: yg = 1.479 # Indonesia region (22) elif val == 22: yg = 1.267 # Japan (23) elif val == 23: yg = 1.180 # Oceania (24) elif val == 24: yg = 1.487 # Rest of South Asia (25) elif val == 25: yg = 1.870 # Rest of Southern Africa (26) elif val == 26: yg = 2.551 # Greenland (27) elif val == 27: yg = 1.000 # Region can also have value none (-9999) else: continue yieldgap_region.set_data(icell, yg) print_debug(regions, "The region number is") fileout = os.path.join(params.outputdir, "yieldgap_region.asc") yieldgap_region.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(yieldgap_region, "The yieldgap for this region is") # calculate Nup(max) = Nup(agri) * yieldgap_region n_up_max = ascraster.duplicategrid(n_up_agri) n_up_max.multiply(yieldgap_region) fileout = os.path.join(params.outputdir, "n_up_max.asc") n_up_max.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(n_up_max, "The maximum N uptake is") # calculate corrected NUE (NUE used to calculate Nin at Nup,max should never be higher than 0.8) nue_corr_agri = ascraster.duplicategrid(nue_agri) for icell in range(nue_corr_agri.length): val = nue_corr_agri.get_data(icell) if (val == None or val <= 0.8): continue if val > 0.8: res = 0.8 nue_corr_agri.set_data(icell, res) fileout = os.path.join(params.outputdir, "nue_corr_agri.asc") nue_corr_agri.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_corr_agri, "The corrected NUE (max=0.8) is") # calculate n_in_max (total N inputs from all sources that correspond to maximum uptake and a max. NUE of 0.8) n_in_max = ascraster.duplicategrid(n_up_max) n_in_max.divide(nue_corr_agri, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "n_in_max.asc") n_in_max.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(n_in_max, "The maximum N input is") ### --------- 7. BUDGET, LEACHING, DENITRIFICATION --------- ### # read input files ngw_ag = ascraster.Asciigrid(ascii_file=params.filename_groundwaterload_ag, numtype=float, mask=params.mask) fgw_rec_ag = ascraster.Asciigrid( ascii_file=params.filename_fraction_recent_groundwaterload_ag, numtype=float, mask=params.mask) nle_ag = ascraster.Asciigrid(ascii_file=params.filename_leaching_ag, numtype=float, mask=params.mask) # calculate N budget agriculture: Nbud,ag = Nin,ag - Nup,ag nbud_ag = ascraster.duplicategrid(n_in_ag) nbud_ag.substract(n_up_ag) fileout = os.path.join(params.outputdir, "nbud_ag.asc") nbud_ag.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nbud_ag, "nbud_ag =") # calculate N load to surface water via groundwater due to *recent* N inputs: agriculture ngw_rec_ag = ascraster.duplicategrid(ngw_ag) ngw_rec_ag.multiply(fgw_rec_ag) #fileout = os.path.join(params.outputdir,"ngw_rec_ag.asc") #ngw_rec_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ngw_rec_ag, "ngw_rec_ag =") # calculate Denitrification in soil: Nde,ag = Nbud,ag - Nsro,ag - Nle,ag nde_ag = ascraster.duplicategrid(nbud_ag) nde_ag.substract(nsro_ag) nde_ag.substract(nle_ag) fileout = os.path.join(params.outputdir, "nde_ag.asc") nde_ag.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nde_ag, "nde_ag =") # calculate leaching fraction fle,ag nbud_min_nsro_ag = ascraster.duplicategrid(nbud_ag) nbud_min_nsro_ag.substract(nsro_ag) fle_ag = griddivide(nle_ag, nbud_min_nsro_ag, default_nodata_value=0) fileout = os.path.join(params.outputdir, "fle_ag.asc") fle_ag.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fle_ag, "fle_ag =") # calculate fraction of N leaching that is delivered to surface water via groundwater in first x years fgw_rec_le_ag = griddivide(ngw_rec_ag, nle_ag, default_nodata_value=0) fileout = os.path.join(params.outputdir, "fgw_rec_le_ag.asc") fgw_rec_le_ag.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fgw_rec_le_ag, "fgw_rec_le_ag =") # calculate ndep_nat ndep_nat = ascraster.duplicategrid(ndep_corr_tot) ndep_nat.multiply(fnat) #fileout = os.path.join(params.outputdir,"ndep_nat.asc") #ndep_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_nat, "ndep_nat =") # calculate N budget nature: Nbud,nat = Ndep,nat + Nfix,nat n_fix_nat = ascraster.Asciigrid(ascii_file=params.filename_nfixation_nat, numtype=float, mask=params.mask) nbud_nat = ascraster.duplicategrid(ndep_nat) nbud_nat.add(n_fix_nat) fileout = os.path.join(params.outputdir, "nbud_nat.asc") nbud_nat.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nbud_nat, "nbud_nat =") # calculate N load to surface water via groundwater due to *recent* N inputs: natural areas ngw_nat = ascraster.Asciigrid( ascii_file=params.filename_groundwaterload_nat, numtype=float, mask=params.mask) fgw_rec_nat = ascraster.Asciigrid( ascii_file=params.filename_fraction_recent_groundwaterload_nat, numtype=float, mask=params.mask) ngw_rec_nat = ascraster.duplicategrid(ngw_nat) ngw_rec_nat.multiply(fgw_rec_nat) #fileout = os.path.join(params.outputdir,"ngw_rec_nat.asc") #ngw_rec_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ngw_rec_nat, "ngw_rec_nat =") # calculate Denitrification in soil: Nde,nat = Nbud,nat - Nsro,nat - Nle,nat nsro_nat = ascraster.Asciigrid(ascii_file=params.filename_nsro_nat, numtype=float, mask=params.mask) nle_nat = ascraster.Asciigrid(ascii_file=params.filename_leaching_nat, numtype=float, mask=params.mask) nde_nat = ascraster.duplicategrid(nbud_nat) nde_nat.substract(nsro_nat) nde_nat.substract(nle_nat) fileout = os.path.join(params.outputdir, "nde_nat.asc") nde_nat.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nde_nat, "nde_nat =") # calculate leaching fraction fle,nat nbud_min_nsro_nat = ascraster.duplicategrid(nbud_nat) nbud_min_nsro_nat.substract(nsro_nat) fle_nat = griddivide(nle_nat, nbud_min_nsro_nat, default_nodata_value=0) fileout = os.path.join(params.outputdir, "fle_nat.asc") fle_nat.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fle_nat, "fle_nat =") # calculate runoff fraction fsro,nat fsro_nat = griddivide(nsro_nat, nbud_nat, default_nodata_value=0) fileout = os.path.join(params.outputdir, "fsro_nat.asc") fsro_nat.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fsro_nat, "fsro_nat =") # calculate fraction of N leaching that is delivered to surface water via groundwater in first x years - natural areas fgw_rec_le_nat = griddivide(ngw_rec_nat, nle_nat, default_nodata_value=0) fileout = os.path.join(params.outputdir, "fgw_rec_le_nat.asc") fgw_rec_le_nat.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fgw_rec_le_nat, "fgw_rec_le_nat =") # calculate variable load to surface water from agriculture: Nload,var,ag = Nsro,ag + Ngw,rec,ag nload_var_ag = ascraster.duplicategrid(ngw_rec_ag) nload_var_ag.add(nsro_ag) #fileout = os.path.join(params.outputdir,"nload_var_ag.asc") #nload_var_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nload_var_ag, "nload_var_ag =") # calculate variable load to surface water from nature: Nload,var,nat = Nsro,nat + Ngw,rec,nat nload_var_nat = ascraster.duplicategrid(ngw_rec_nat) nload_var_nat.add(nsro_nat) #fileout = os.path.join(params.outputdir,"nload_var_nat.asc") #nload_var_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nload_var_nat, "nload_var_nat =") # calculate fixed load to surface water from agriculture: Ngw,fixed,ag = Ngw,ag * (1-fgw,rec,ag) grid1 = ascraster.duplicategrid(fgw_rec_ag) for i in range(grid1.length): grid1.set_data(i, 1.0) grid1.substract(fgw_rec_ag) nload_fixed_ag = ascraster.duplicategrid(ngw_ag) nload_fixed_ag.multiply(grid1) fileout = os.path.join(params.outputdir, "nload_fixed_ag.asc") nload_fixed_ag.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nload_fixed_ag, "nload_fixed_ag =") # calculate fixed load to surface water from nature: Ngw,fixed,nat = Ngw,nat * (1-fgw,rec,nat) grid2 = ascraster.duplicategrid(fgw_rec_nat) for i in range(grid2.length): grid2.set_data(i, 1.0) grid2.substract(fgw_rec_nat) nload_fixed_nat = ascraster.duplicategrid(ngw_nat) nload_fixed_nat.multiply(grid2) fileout = os.path.join(params.outputdir, "nload_fixed_nat.asc") nload_fixed_nat.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nload_fixed_nat, "nload_fixed_nat =") # calculate total load from point sources nallo = ascraster.Asciigrid( ascii_file=params.filename_n_point_alloch_matter, numtype=float, mask=params.mask) nww = ascraster.Asciigrid(ascii_file=params.filename_n_point_wastewater, numtype=float, mask=params.mask) naqua = ascraster.Asciigrid(ascii_file=params.filename_n_point_aquaculture, numtype=float, mask=params.mask) ndep_sw = ascraster.Asciigrid( ascii_file=params.filename_n_point_dep_surfacewater, numtype=float, mask=params.mask) #factor = 0 #nww.multiply(factor) #naqua.multiply(factor) npoint_tot = ascraster.duplicategrid(nallo) npoint_tot.add(nww) npoint_tot.add(naqua) npoint_tot.add(ndep_sw) fileout = os.path.join(params.outputdir, "npoint_tot.asc") npoint_tot.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(npoint_tot, "npoint_tot =") # calculate total load from erosion nero_ag = ascraster.Asciigrid(ascii_file=params.filename_n_in_erosion_ag, numtype=float, mask=params.mask) nero_nat = ascraster.Asciigrid(ascii_file=params.filename_n_in_erosion_nat, numtype=float, mask=params.mask) nero_tot = ascraster.duplicategrid(nero_ag) nero_tot.add(nero_nat) fileout = os.path.join(params.outputdir, "nero_tot.asc") nero_tot.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nero_tot, "nero_tot =") # calculate total n load to surface water: Nload,tot = Nload,var,ag + Nload,var,nat + Ngw,fixed,ag + Ngw,fixed,nat + Npoint + Nero nload_tot = ascraster.duplicategrid(nload_var_ag) nload_tot.add(nload_var_nat) nload_tot.add(nload_fixed_ag) nload_tot.add(nload_fixed_nat) nload_tot.add(npoint_tot) nload_tot.add(nero_tot) #fileout = os.path.join(params.outputdir,"nload_tot.asc") #nload_tot.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nload_tot, "nload_tot =")
if os.path.exists(__general): sys.path.insert(0, __general) print __general + " is added to the python search path for modules." # Import general python modules # Import own general modules import ascraster glob_pnet = ascraster.Asciigrid(ascii_file="/home/arthur/globalnutrients/input_5min/water_input/pnet.map",numtype=float) inputdir = "../input" outputdir = "../output" file_area = os.path.join(inputdir,"landarea.asc") landarea = ascraster.Asciigrid(ascii_file=file_area,numtype=float) new = ascraster.duplicategrid(landarea) # Make all values nodata new.add_values(new.length*[new.nodata_value]) for icell in xrange(landarea.length): val = landarea.get_data(icell) if (val != None): # Now we have to get information in the global grid. # Get coordinates of this cell x,y = landarea.get_coordin_from_index(icell) # Get index in global grid ind = glob_pnet.get_index_from_coordin(x,y) # Get value from global map val_glob = glob_pnet.get_data(ind) if (val_glob != None): new.set_data(icell,val_glob)
def calculate(params, mask, mouth_dict, basin): ''' Calculates the area of each grass and arable land use cell. It returns two ascraster object with the area grass and area arable land in ha ''' # Read grass files gras1 = ascraster.Asciigrid(ascii_file=params.pgrass, mask=mask, numtype=float) if params.ldebug: print(params.pgrass + " has been read.") gras2 = ascraster.Asciigrid(ascii_file=params.igrass, mask=mask, numtype=float) if params.ldebug: print(params.igrass + " has been read.") # Read crop files crop1 = ascraster.Asciigrid(ascii_file=params.cropmixp, mask=mask, numtype=float) if params.ldebug: print(params.cropmixp + " has been read.") crop2 = ascraster.Asciigrid(ascii_file=params.croppasp, mask=mask, numtype=float) if params.ldebug: print(params.croppasp + " has been read.") # Read land area landarea = ascraster.Asciigrid(ascii_file=params.landarea, mask=mask, numtype=float) if params.ldebug: print(params.landarea + " has been read.") # Aggregate landarea on river basin scale aggregate.aggregate_grid(basin, landarea, mouth_dict, item="landarea") # Make a copy (alias not a deepcopy) of the return values area_grass = gras1 area_crop = crop1 area_natural = landarea # Calculate the total grass and crop land in ha. Because the LU file are in percentage, and the # landarea is in km2, the product of (crop1_cell+crop2_cell) * landarea_cell is then in ha. for icell in range(crop1.length): crop1_cell = crop1.get_data(icell, 0.0) crop2_cell = crop2.get_data(icell, 0.0) gras1_cell = gras1.get_data(icell, 0.0) gras2_cell = gras2.get_data(icell, 0.0) landarea_cell = landarea.get_data(icell, 0.0) # Put result in crop1 and gras1 crop_area = landarea_cell * (crop1_cell + crop2_cell) gras_area = landarea_cell * (gras1_cell + gras2_cell) if ((crop_area + gras_area) - (100.0 * landarea_cell) > 1.): print("Crop and grass area is too large: ", crop_area + gras_area, 100. * landarea_cell, (crop_area + gras_area) - (100.0 * landarea_cell)) try: fac = (100 * landarea_cell) / (crop_area + gras_area) except ZeroDivisionError: fac = 0.0 crop_area *= fac gras_area *= fac nat_area = max(0.0, (100.0 * landarea_cell) - crop_area - gras_area) # Put result in the maps in km2 (factor 0.01) area_crop.set_data(icell, 0.01 * crop_area) area_grass.set_data(icell, 0.01 * gras_area) area_natural.set_data(icell, 0.01 * nat_area) # Aggregate landarea on river basin scale aggregate.aggregate_grid(basin, area_crop, mouth_dict, item="croparea") aggregate.aggregate_grid(basin, area_grass, mouth_dict, item="grasarea") aggregate.aggregate_grid(basin, area_natural, mouth_dict, item="natarea") # Calculate the number of cells in a region/basin one = ascraster.duplicategrid(landarea) # Set all cells to one. one.add_values(one.length * [1.0]) aggregate.aggregate_grid(basin, one, mouth_dict, item="number_of_cells") # Delete the grid objects which are used anymore del crop1 del crop2 del gras1 del gras2 del landarea del one return area_grass, area_crop, area_natural
def accutime(lddmap, timemap, lake_icell_dict): ''' ACCUTIME PURPOSE: Accumulate residence time for each grid cell to the mouth of the river. The output map contains accumulated residence time [grid]. When a endoreic lake is encountered then, residence time is to the lake and not to the sea. All files are ascii-grid formatted. Lddmap: network of local drain directions flow_direction can be coded as follows: UNH/GRDC PCraster(LDD) 32 64 128 meaning: NW N NE 7 8 9 16 - 1 W - E 4 5 6 8 4 2 SW S SE 1 2 3 We use the PCraster LDD-format; negative and zero values are assumed ''' # Make output rasters accutimemap = ascraster.duplicategrid(timemap) # Loop over all cells: for icell in range(lddmap.length): # Get residence time at the cell. restime = timemap.get_data(icell) if (restime == None): # No data value continue if (restime < 0.0): print("Negative residence time of " + str(restime) + " at cell: " + str(icell)) # Go to next cell. accutimemap.set_data(icell, 0.0) continue end_of_path = False icell_loop = icell cumtime = restime while not end_of_path: # Get direction of the ldd direction = int(lddmap.get_data(icell_loop, -1)) # Check whether the cell is in a endoreic lake try: lendo_lake = lake_icell_dict[icell].lendolake except KeyError: lendo_lake = 0 if (direction < 1 or direction > 9): #print "Something is wrong with the lddmap (< 1). No river mouth found for icell: ",icell, " with load: ", flux, " and direction: ",direction # Go to next cell end_of_path = True elif (direction == 5): # Mouth of river basin is found. end_of_path = True elif (lendo_lake == 1): # Endoreic lake found. end_of_path = True else: # Go to next cell icell_loop = goto_nextcell(icell_loop, direction, lddmap.ncols, mask=lddmap.mask) if (icell_loop < 0): # Already printed a message. Go to next grid cell. end_of_path = True # Set accutime in grid or fetch new restime for next cell if (end_of_path): accutimemap.set_data(icell, cumtime) else: restime = timemap.get_data(icell_loop, 0.0) cumtime += restime return accutimemap
def calculate(params, mask, mouth_dict, lake_icell_dict, basin, discharge, lddmap, Pload): ''' This function calculates the retention in the grid cells. ''' # Read in the PCGLOBWB files water_storage_file = params.water_storage water_storage = ascraster.Asciigrid(ascii_file=water_storage_file,\ mask=mask,numtype=float) flooding_depth_file = params.flooding_depth flooding_depth = ascraster.Asciigrid(ascii_file=flooding_depth_file,\ mask=mask,numtype=float) flooding_fraction = ascraster.Asciigrid(ascii_file=params.flooding_fraction,\ mask=mask,numtype=float) fraction_water_grid = ascraster.Asciigrid(ascii_file=params.fraction_water,\ mask=mask,numtype=float) cellarea_grid = ascraster.Asciigrid(ascii_file=params.cellarea,\ mask=mask,numtype=float) lakeid_grid = ascraster.Asciigrid(ascii_file=params.lakeid,\ mask=mask,numtype=int) outlakeid_grid = ascraster.Asciigrid(ascii_file=params.outlakeid,\ mask=mask,numtype=int) water_area_grid = ascraster.Asciigrid(ascii_file=params.water_area,\ mask=mask,numtype=int) # Water volume flooding area volume_flooding_grid = ascraster.duplicategrid(flooding_depth) volume_flooding_grid.multiply(flooding_fraction, default_nodata_value=0.0) volume_flooding_grid.multiply(cellarea_grid, default_nodata_value=0.0) volume_flooding_grid.write_ascii_file( os.path.join(params.outputdir, "volume_flooding_grid.asc")) # Water volume of river. volume_river_grid = ascraster.duplicategrid(water_storage) volume_river_grid.write_ascii_file( os.path.join(params.outputdir, "volume_river_grid.asc")) # Area water of river. area_river_grid = ascraster.duplicategrid(cellarea_grid) area_river_grid.multiply(fraction_water_grid, default_nodata_value=0.0) area_river_grid.write_ascii_file( os.path.join(params.outputdir, "area_river_grid.asc")) # Correct river volume and area when there is a reservoir or a lake. for icell in range(lakeid_grid.length): id = lakeid_grid.get_data(icell, -1) if (id > 0): # It is a lake or reservoir # Check whether it is a outlet of a lake or reservoir id = outlakeid_grid.get_data(icell, -1) if (id > 0): # It is an outlet. So put lake properties into the gridcell volume_river_grid.set_data(icell, water_storage.get_data(icell, 0.0)) area_river_grid.set_data(icell, water_area_grid.get_data(icell, 0.0)) else: # It is not an outlet. So remove the calculated river properties. volume_river_grid.set_data(icell, 0.0) area_river_grid.set_data(icell, 0.0) volume_river_grid.write_ascii_file( os.path.join(params.outputdir, "volume_river_grid_with_lakes.asc")) area_river_grid.write_ascii_file( os.path.join(params.outputdir, "area_river_grid_with_lakes.asc")) # Depth water of river in metres depth_river_grid = ascraster.duplicategrid(volume_river_grid) depth_river_grid.divide(area_river_grid, default_nodata_value=0.0) depth_river_grid.write_ascii_file( os.path.join(params.outputdir, "depth_river_grid.asc")) # Change water_storage from m3 into km3 volume_river_grid.multiply(1.0e-9) volume_flooding_grid.multiply(1.0e-9) # Residence time is the volume divided by discharge. # Water storage is in km3. Discharge is km3/yr. So residence time is in years. residence_time_river_grid = ascraster.duplicategrid(volume_river_grid) residence_time_flooding_grid = ascraster.duplicategrid( volume_flooding_grid) # Calculate residence times by dividing water_storage through discharge. residence_time_river_grid.divide(discharge, default_nodata_value=0.0) residence_time_flooding_grid.divide( discharge, default_nodata_value=0.0, maximum=params.max_residence_time_per_cell) # If residence times are very high (e.g in dry areas), # set the residence time to a maximum # Apply maximum on gridcells which are not the outlet of a reservoir or lake. # In the flooding map there are no lakes/reservoirs for icell in range(residence_time_river_grid.length): resi = residence_time_river_grid.get_data(icell, -1) if (resi > params.max_residence_time_per_cell): # Check whether this is a outlet of a lake or reservoir try: outcell = lake_icell_dict[icell].outcell if (outcell == 1): # Outlet of a lake/reservoir if (resi > params.max_residence_time_per_lake): resi = params.max_residence_time_per_lake else: resi = params.max_residence_time_per_cell residence_time_river_grid.set_data(icell, resi) except KeyError: # This is no reservoir or lake residence_time_river_grid.set_data( icell, params.max_residence_time_per_cell) residence_time_river_grid.write_ascii_file( os.path.join(params.outputdir, "residence_time_river_grid.asc")) residence_time_flooding_grid.write_ascii_file( os.path.join(params.outputdir, "residence_time_flooding_grid.asc")) # Put residence time of the water body (lakes and reservoirs) in the grid. for icell in lake_icell_dict: if (lake_icell_dict[icell].outcell == 1): lake_icell_dict[ icell].residence_time = residence_time_river_grid.get_data( icell, 0.0) # Calculate the water volume in the grid cell volume_grid = ascraster.duplicategrid(volume_flooding_grid) volume_grid.add(volume_river_grid, default_nodata_value=0.0) volume_grid.write_ascii_file( os.path.join(params.outputdir, "volume_grid.asc")) # Calculate the average residence time with as weighing factors the volumes of the flooding - river residence_time_grid = ascraster.duplicategrid(volume_river_grid) residence_time_grid.multiply(residence_time_river_grid, default_nodata_value=0.0) temp_grid = ascraster.duplicategrid(volume_flooding_grid) temp_grid.multiply(residence_time_flooding_grid, default_nodata_value=0.0) residence_time_grid.add(temp_grid, default_nodata_value=0.0) residence_time_grid.divide(volume_grid, default_nodata_value=0.0) del temp_grid # Write residence_time to output file: residence_time_grid.write_ascii_file( os.path.join(params.outputdir, "residence_time.asc")) # Calculate the travel time of each grid cell to the river mouth traveltime = accuflux.accutime(lddmap, residence_time_grid, lake_icell_dict) traveltime.write_ascii_file( os.path.join(params.outputdir, "traveltime.asc")) # Aggregate traveltime over the river basin. aggregate.aggregate_grid(basin, traveltime, mouth_dict, item="sum_traveltime") # Calculate the average traveltime for each river basin for key in list(mouth_dict.keys()): try: mouth_dict[key].avg_traveltime = mouth_dict[ key].sum_traveltime / mouth_dict[key].number_of_cells except ZeroDivisionError: mouth_dict[key].avg_traveltime = 0.0 except AttributeError: pass # Calculate the hydraulic load (Hl = depth/residence_time) hydraulic_load_flooding_grid = ascraster.duplicategrid(flooding_depth) hydraulic_load_flooding_grid.divide(residence_time_flooding_grid, default_nodata_value=0.0) hydraulic_load_river_grid = ascraster.duplicategrid(depth_river_grid) hydraulic_load_river_grid.divide(residence_time_river_grid, default_nodata_value=0.0) hydraulic_load_river_grid.write_ascii_file( os.path.join(params.outputdir, "hydraulic_load_river.asc")) hydraulic_load_flooding_grid.write_ascii_file( os.path.join(params.outputdir, "hydraulic_load_flooding.asc")) # Calculate the average hydraulic load with as weighing factors the volumes of the flooding - river hydraulic_load_grid = ascraster.duplicategrid(volume_river_grid) hydraulic_load_grid.multiply(hydraulic_load_river_grid, default_nodata_value=0.0) temp_grid = ascraster.duplicategrid(volume_flooding_grid) temp_grid.multiply(hydraulic_load_flooding_grid, default_nodata_value=0.0) hydraulic_load_grid.add(temp_grid, default_nodata_value=0.0) hydraulic_load_grid.divide(volume_grid, default_nodata_value=0.0) del temp_grid # Write hydraulic load to output file: hydraulic_load_grid.write_ascii_file( os.path.join(params.outputdir, "hydraulic_load.asc")) temperature_grid = ascraster.Asciigrid(ascii_file=params.water_temperature,\ mask=mask,numtype=float) # Read endoreic lakes endo_lakes_grid = ascraster.Asciigrid(ascii_file=params.endo_lakes,\ mask=mask,numtype=int) # Calculate the retention for rivers. retention_river_grid = ascraster.duplicategrid(volume_river_grid) for icell in range(retention_river_grid.length): id = endo_lakes_grid.get_data(icell, 0) if (id > 0): # This is an endoreic lake. So the calculation retention_river_grid.set_data(icell, 1.0) continue vol = volume_river_grid.get_data(icell, -1) if (vol > 0): temperature = temperature_grid.get_data(icell, 20.0) hydraulic_load = hydraulic_load_river_grid.get_data(icell, 0.0) ret = calculate_retention(params, hydraulic_load, vol, temperature) retention_river_grid.set_data(icell, ret) else: retention_river_grid.set_data(icell, 0.0) # Calculate the retention for flood planes. retention_flooding_grid = ascraster.duplicategrid(volume_flooding_grid) for icell in range(retention_flooding_grid.length): vol = volume_flooding_grid.get_data(icell, -1) if (vol > 0): temperature = temperature_grid.get_data(icell, 20.0) hydraulic_load = hydraulic_load_flooding_grid.get_data(icell, 0.0) ret = calculate_retention(params, hydraulic_load, vol, temperature) retention_flooding_grid.set_data(icell, ret) else: retention_flooding_grid.set_data(icell, 0.0) # Calculate the average retention with as weighing factors the volumes of the flooding - river retention_grid = ascraster.duplicategrid(volume_river_grid) retention_grid.multiply(retention_river_grid, default_nodata_value=0.0) temp_grid = ascraster.duplicategrid(volume_flooding_grid) temp_grid.multiply(retention_flooding_grid, default_nodata_value=0.0) retention_grid.add(temp_grid, default_nodata_value=0.0) retention_grid.divide(water_storage, default_nodata_value=0.0) del temp_grid # Set the lake database for icell in range(outlakeid_grid.length): if (id > 0): # It is an outlet. So put lake properties into the gridcell # Recalculate the temperature temp = 0.0 number_of_cells = len(lake_icell_dict[icell].cells) for item in range(number_of_cells): icell_lake = lake_icell_dict[icell].cells[item] temp += temperature.get_data(icell_lake, 0.0) # Take average over the cells. temperature_cell = temp / float(number_of_cells) ret_cell = retention_river_grid.get_data(icell, 0.0) setattr(lake_icell_dict[icell], "retention", ret_cell) setattr(lake_icell_dict[icell], "fraction_water", -99) setattr(lake_icell_dict[icell], "temperature", temperature_cell) accuPload = P_accuflux(params, mask, lake_icell_dict, lddmap, Pload, retention_grid) return residence_time_grid, traveltime, retention_grid, accuPload, hydraulic_load_grid
def accuflux(lddmap, fluxmap, retentionmap=None, negative_flux_possible=0): ''' ACCUFLUX Based on Gerard van Drecht, RIVM, Bilthoven, February 2002 April 2002: accu fraction flux and accu fraction state added PURPOSE: Accumulate flow of mass, given by a material map [grid], along a flowpath, given by a local drain direction(LDD) map [grid]. The output map contains accumulated flux [grid]. All files are ascii-grid formatted. Lddmap: network of local drain directions flow_direction can be coded as follows: UNH/GRDC PCraster(LDD) 32 64 128 meaning: NW N NE 7 8 9 16 - 1 W - E 4 5 6 8 4 2 SW S SE 1 2 3 We use the PCraster LDD-format; negative and zero values are assumed ''' if (negative_flux_possible == 1): # Call the other version of accuflux return accuflux_negative(lddmap, fluxmap, retentionmap=retentionmap, negative_flux_possible=1) # Make output rasters accufluxmap = ascraster.duplicategrid(fluxmap) # Make nodata on all cells. accufluxmap.add_values(accufluxmap.length * [accufluxmap.nodata_value]) # Loop over all cells: for icell in range(lddmap.length): # Get mass flux at the cell. flux = fluxmap.get_data(icell) if (flux == None): # No data value continue if (flux < 0.0): if (negative_flux_possible == 0): print("Negative mass flow of " + str(flux) + " at cell: " + str(icell)) # Go to next cell. continue end_of_path = False icell_loop = icell while not end_of_path: # Get direction of the ldd direction = int(lddmap.get_data(icell_loop, -1)) if (direction < 1): #print "Something is wrong with the lddmap (< 1). No river mouth found for icell: ",icell, " with load: ", flux, " and direction: ",direction # Go to next cell end_of_path = True elif (direction == 5): # Mouth of river basin is found. prev = accufluxmap.get_data(icell_loop, 0.0) accufluxmap.set_data( icell_loop, prev + flux * factor(icell_loop, retentionmap)) # Go to next cell end_of_path = True elif (direction > 9): #print "Something is wrong with the lddmap (> 9). No river mouth found for icell: ",icell, " with load: ", flux, " and direction: ",direction # Go to next cell end_of_path = True else: prev = accufluxmap.get_data(icell_loop, 0.0) flux = flux * factor(icell_loop, retentionmap) accufluxmap.set_data(icell_loop, prev + flux) # Go to next cell icell_loop = goto_nextcell(icell_loop, direction, lddmap.ncols, mask=lddmap.mask) if (icell_loop < 0): # Already printed a message. Go to next grid cell. end_of_path = True return accufluxmap
def get_all_files(args): ''' Get all files to create one year of the input directory to calculate of the critical load. ''' # Parse command-line arguments and set parameters for script # Startup logging and runtime start param = read_ini_file.start_init(args) params = param.options # End reading arguments list of the commandline. Start the computation. # Check source directories. if not os.path.exists(mandistdir): raise MyError("Directory '%s' does not exist" % mandistdir) if not os.path.exists(gnm_outputdir): raise MyError("Directory '%s' does not exist" % gnm_outputdir) if not os.path.exists(gnm_inputdir): raise MyError("Directory '%s' does not exist" % gnm_inputdir) if not os.path.exists(water_inputdir): raise MyError("Directory '%s' does not exist" % water_inputdir) if not os.path.exists(os.path.join(mandistdir,"in"+str(params.year))): raise MyError("Input for year '%s' is not found on directory '%s'" % (params.year,mandistdir)) if not os.path.exists(os.path.join(mandistdir,"out"+str(params.year))): raise MyError("Output for year '%s' is not found on directory '%s'" % (params.year,mandistdir)) if not os.path.exists(os.path.join(gnm_outputdir,str(params.year))): raise MyError("Output for year '%s' is not found on directory '%s'" % (params.year,gnm_outputdir)) if not os.path.exists(os.path.join(gnm_inputdir,str(params.year))): raise MyError("Input for year '%s' is not found on directory '%s'" % (params.year,gnm_inputdir)) if not os.path.exists(os.path.join(water_inputdir,str(params.year))): raise MyError("Input for year '%s' is not found on directory '%s'" % (params.year,water_inputdir)) # Change the input and source directories to this year. inputdir = os.path.join(params.root, params.inputdir,str(params.year)) mandistdir_in = os.path.join(mandistdir,"in"+str(params.year)) mandistdir_out = os.path.join(mandistdir,"out"+str(params.year)) gnmdir_in = os.path.join(gnm_inputdir,str(params.year)) gnmdir_out = os.path.join(gnm_outputdir,str(params.year)) waterdir = os.path.join(water_inputdir,str(params.year)) # Create input directory for this year when it does not exist. if not os.path.exists(inputdir): os.makedirs(inputdir) # Make a log file write_log(inputdir,mandistdir,gnm_inputdir,gnm_outputdir,water_inputdir) # Read mandist ini file (manure.ini) mandist_files_dict = read_mandist_ini.read_mandist_ini(mandistdir_in) # Create landmask filename = os.path.join(mandistdir_in,mandist_files_dict["LAND AREA ASC FILE"]) mask = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Make all values one. for icell in range(mask.length): val = mask.get_data(icell) if (val != None): mask.set_data(icell,1) # Open output file for all world totals of the produced files. fp = open(os.path.join(inputdir,"global_totals.txt"),"w") # Areas in ha. # Read cellarea file in m2. area = ascraster.Asciigrid(ascii_file = os.path.join(params.root,"..","fix_input","cellarea30.asc"),numtype = float) # Convert to ha area.multiply(0.0001) # Calculate the area agricultural land filename = os.path.join(mandistdir_in,mandist_files_dict["LAND AREA ASC FILE"]) landarea = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT INTENSIVE GRASS GRID FILE"]) grass_int = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT EXTENSIVE GRASS GRID FILE"]) grass_ext = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT INTENSIVE CROP GRID FILE"]) crop_int = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT EXTENSIVE CROP GRID FILE"]) crop_ext = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Landarea is in km2, the different landuse types are in percentages, so result is in ha. grass_int.multiply(landarea) grass_ext.multiply(landarea) crop_int.multiply(landarea) crop_ext.multiply(landarea) print_total(crop_int,"Total area int crops:",fp=fp) print_total(crop_ext,"Total area ext crops:",fp=fp) print_total(grass_int,"Total area int grass:",fp=fp) print_total(grass_ext,"Total area ext grass:",fp=fp) landarea = ascraster.duplicategrid(grass_int) landarea.add(grass_ext) landarea.add(crop_int) landarea.add(crop_ext) # Create agricultural land and non-agricultural land. natarea = ascraster.duplicategrid(landarea) for icell in range(landarea.length): lndarea = landarea.get_data(icell) if (lndarea == None): area.set_data(icell,area.nodata_value) else: cellarea = area.get_data(icell,0.0) # This step causes a difference between the table info of mandist and the gridinfo. #lndarea = min(cellarea,lndarea) #landarea.set_data(icell,lndarea) natarea.set_data(icell,max(0.0,cellarea - lndarea)) # Make the cell area of the total area inclusive the coast. rownum = ascraster.duplicategrid(landarea) maxarea = landarea.nrows * [0.0] for icell in range(landarea.length): cellarea = area.get_data(icell) if (cellarea != None): # Get row number irow,icol = area.get_row_col_from_index(icell) rownum.set_data(icell,irow) if (cellarea > maxarea[irow]): maxarea[irow] = cellarea for icell in range(landarea.length): cellarea = area.get_data(icell) if (cellarea != None): irow = rownum.get_data(icell) area.set_data(icell,maxarea[irow]) # Write areas in ha to file area.write_ascii_file(os.path.join(inputdir,params.filename_gridcell_area)) landarea.write_ascii_file(os.path.join(inputdir,params.filename_agri_area)) natarea.write_ascii_file(os.path.join(inputdir,params.filename_natural_area)) print_total(area,"Total cellarea:",fp=fp) print_total(landarea,"Total agricultural area:",fp=fp) print_total(natarea,"Total natural area:",fp=fp) # Calculate the fraction recent groundwater to surface water # Read runoff in mm filename = os.path.join(waterdir,"runoff.asc") runoff = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Correct runoff because this could be negative runoff.multiply(mask,minimum=0.0) # Calculate the fraction recent groundwater that enters the surface water. fr_recent_grw_grid = ascraster.duplicategrid(runoff) for icell in range(landarea.length): val = fr_recent_grw_grid.get_data(icell) if (val != None): fr = fr_recent_grw(params,val) fr_recent_grw_grid.set_data(icell,fr) # Write fraction recent groundwater to file fr_recent_grw_grid.write_ascii_file(os.path.join(inputdir,params.filename_fraction_recent_groundwaterload_ag)) fr_recent_grw_grid.write_ascii_file(os.path.join(inputdir,params.filename_fraction_recent_groundwaterload_nat)) # Calculate the precipitation surplus in dm3 runoff.multiply(area) # Conversion from mm*ha to dm3 runoff.multiply(1.0e4) # Write the precipitation surplus in dm3 to file runoff.write_ascii_file(os.path.join(inputdir,params.filename_precipitation_surplus)) print_total(runoff,"Total runoff:",fp=fp) # Deposition filename = os.path.join(gnmdir_in,"ndeposition.asc") # Read deposition in mg N/m2/yr depo = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with total cell area (ha). depo.multiply(area) # Conversion to get kg N yr-1 depo.multiply(1.0e-2) # Write N deposition in kg N yr-1 to file depo.write_ascii_file(os.path.join(inputdir,params.filename_n_deposition)) print_total(depo,"Total N deposition:",fp=fp) # Inputs [kg N yr-1] #filename = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT FERTILIZER GRID FILE"]) #filename = os.path.splitext(filename)[0] +"_N" + os.path.splitext(filename)[1] # Read fertilizer in kg N ha-1 #fert = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Read agricultural area in ha #filename = os.path.join(mandistdir_in,mandist_files_dict["LAND AREA ASC FILE"]) #agri_area = ascraster.Asciigrid(ascii_file = os.path.join(inputdir,params.filename_agri_area),numtype = float) # Substract extentive grass. #agri_area.substract(grass_ext) # Make kg N yr-1 #fert.multiply(agri_area,default_nodata_value=-9999.) #fert.write_ascii_file(os.path.join(inputdir,params.filename_fert_inp)) #print_total(fert,"Total fertilizer:") # Inputs [kg N yr-1] filename_org = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT FERTILIZER GRID FILE"]) # Read landarea in km2 filename = os.path.join(mandistdir_in,mandist_files_dict["LAND AREA ASC FILE"]) landarea = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Read fertilizer on upland crops in kg N ha-1 filename = os.path.splitext(filename_org)[0] +"_UPLANDCROP" + os.path.splitext(filename)[1] fert_upl = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Read upland area in percentage of landarea filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT FERTILIZER UPLAND CROPS GRID FILE"]) area_upl = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Calculate area upland crops in ha. area_upl.multiply(landarea,default_nodata_value=-9999.) # Calculate total fertilizer on upland crop fert_upl.multiply(area_upl,default_nodata_value=-9999.) print_total(fert_upl,"Total fertilizer upland crops:",fp=fp) # Read fertilizer on legumes in kg N ha-1 filename = os.path.splitext(filename_org)[0] +"_LEGUMES" + os.path.splitext(filename)[1] fert_leg = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Read legumes area in percentage of landarea filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT FERTILIZER LEGUMES GRID FILE"]) area_leg = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Calculate area legumes in ha. area_leg.multiply(landarea,default_nodata_value=-9999.) # Calculate total fertilizer on legumes fert_leg.multiply(area_leg,default_nodata_value=-9999.) print_total(fert_leg,"Total fertilizer legumes:",fp=fp) # Read fertilizer on wrice in kg N ha-1 filename = os.path.splitext(filename_org)[0] +"_WRICE" + os.path.splitext(filename)[1] fert_wrice = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Read legumes area in percentage of landarea filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT FERTILIZER WET RICE GRID FILE"]) area_wrice = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Calculate area legumes in ha. area_wrice.multiply(landarea,default_nodata_value=-9999.) # Calculate total fertilizer on wrice fert_wrice.multiply(area_wrice,default_nodata_value=-9999.) print_total(fert_wrice,"Total fertilizer wrice:",fp=fp) # Read fertilizer on grass in kg N ha-1 filename = os.path.splitext(filename_org)[0] +"_GRASS" + os.path.splitext(filename)[1] fert_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Read legumes area in percentage of landarea filename = os.path.join(mandistdir_in,mandist_files_dict["INPUT FERTILIZER GRASS GRID FILE"]) area_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Calculate area grass in ha. area_grass.multiply(landarea,default_nodata_value=-9999.) # Calculate total fertilizer on grass fert_grass.multiply(area_grass,default_nodata_value=-9999.) print_total(fert_grass,"Total fertilizer grass:",fp=fp) # Calculate total fertilizer in kg N yr-1 fert = fert_upl fert.add(fert_leg) fert.add(fert_wrice) fert.add(fert_grass) fert.write_ascii_file(os.path.join(inputdir,params.filename_fert_inp)) print_total(fert,"Total fertilizer:",fp=fp) filename = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT TOTAL MANURE APPLICATION GRID FILE"]) # Read manure in kg N ha-1 manure = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Read landarea in km2 filename = os.path.join(mandistdir_in,mandist_files_dict["LAND AREA ASC FILE"]) landarea = ascraster.Asciigrid(ascii_file = os.path.join(inputdir,params.filename_agri_area),numtype = float) # Make kg N yr-1 #manure_int_crops = ascraster.duplicategrid(manure) #manure_ext_crops = ascraster.duplicategrid(manure) #manure_int_grass = ascraster.duplicategrid(manure) #manure_ext_grass = ascraster.duplicategrid(manure) #manure_int_crops.multiply(crop_int,default_nodata_value=-9999.) #manure_ext_crops.multiply(crop_ext,default_nodata_value=-9999.) #manure_int_grass.multiply(grass_int,default_nodata_value=-9999.) #manure_ext_grass.multiply(grass_ext,default_nodata_value=-9999.) #print_total(manure_int_crops,"Total manure int crops:") #print_total(manure_ext_crops,"Total manure ext crops:") #print_total(manure_int_grass,"Total manure int grass:") #print_total(manure_ext_grass,"Total manure ext grass:") #print("TOT MANURE: ", grid_total(manure_int_crops) + grid_total(manure_ext_crops) + grid_total(manure_int_grass) + grid_total(manure_ext_grass) ) manure.multiply(landarea,default_nodata_value=-9999.) manure.write_ascii_file(os.path.join(inputdir,params.filename_manure_inp)) print_total(manure,"Total manure:",fp=fp) # N fixation filename = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT N NATURAL FIXATION GRID FILE"]) # Read N fixation for natural area in kg N yr-1 Nfix_nat = ascraster.Asciigrid(ascii_file = filename,numtype = float) Nfix_nat.multiply(mask,default_nodata_value=-9999.) # Write N fixation for natural areas in kg N yr-1 to file Nfix_nat.write_ascii_file(os.path.join(inputdir,params.filename_nfixation_nat)) print_total(Nfix_nat,"Total N natural fixation:",fp=fp) filename = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT N CROP FIXATION GRID FILE"]) # Read N fixation for agricultural area in kg N yr-1 Nfix_agri = ascraster.Asciigrid(ascii_file = filename,numtype = float) Nfix_agri.multiply(mask,default_nodata_value=-9999.) # Write N fixation for agricultural areas in kg N yr-1 to file Nfix_agri.write_ascii_file(os.path.join(inputdir,params.filename_nfixation_agri)) print_total(Nfix_agri,"Total N agricultural fixation:",fp=fp) # N uptake filename = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT UPTAKE GRID FILE"]) filename = os.path.splitext(filename)[0] +"_N" + os.path.splitext(filename)[1] # Read uptake in kg N yr-1 uptake = ascraster.Asciigrid(ascii_file = filename,numtype = float) uptake.multiply(mask,default_nodata_value=-9999.) # Write N uptake in kg N yr-1 to file uptake.write_ascii_file(os.path.join(inputdir,params.filename_crop_uptake)) print_total(uptake,"Total N uptake:",fp=fp) # N uptake #filename_org = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT UPTAKE GRID FILE"]) #filename = os.path.splitext(filename_org)[0] +"_N_ARABLE" + os.path.splitext(filename)[1] # Read uptake in kg N yr-1 #uptake_arable = ascraster.Asciigrid(ascii_file = filename,numtype = float) #print_total(uptake_arable,"Total N uptake crops:") #filename = os.path.splitext(filename_org)[0] +"_N_GRS" + os.path.splitext(filename)[1] # Read uptake in kg N yr-1 #uptake_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) #print_total(uptake_grass,"Total N uptake grass:") #uptake.multiply(mask,default_nodata_value=-9999.) # Write N uptake in kg N yr-1 to file #uptake.write_ascii_file(os.path.join(inputdir,params.filename_crop_uptake)) #print_total(uptake,"Total N uptake:") # Emission spreading fertilizer filename_org = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT SPREADING GRID FILE"]) filename = os.path.splitext(filename_org)[0] +"_EXT_GRASS_FERT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading fertilizer in extensive grass systems in kg N ha-1 fert_ext_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with extensive grass area fert_ext_grass.multiply(grass_ext,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_INT_GRASS_FERT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading fertilizer in intensive grass systems in kg N ha-1 fert_int_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with intensive grass area fert_int_grass.multiply(grass_int,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_EXT_CROP_FERT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading fertilizer in extensive crop systems in kg N ha-1 fert_ext_crop = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with extensive crop area fert_ext_crop.multiply(crop_ext,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_INT_CROP_FERT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading fertilizer in intensive crop systems in kg N ha-1 fert_int_crop = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with intensive crop area fert_int_crop.multiply(crop_int,default_nodata_value=-9999.) # Add the four components. fert_ext_grass.add(fert_int_grass) fert_ext_grass.add(fert_ext_crop) fert_ext_grass.add(fert_int_crop) # Write NH3 emission spreading fertilizer in kg N yr-1 to file fert_ext_grass.write_ascii_file(os.path.join(inputdir,params.filename_nh3_em_spread_fert)) print_total(fert_ext_grass,"Total NH3 emission spreading fertilizer:",fp=fp) # Emission spreading manure filename_org = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT SPREADING GRID FILE"]) filename = os.path.splitext(filename_org)[0] +"_EXT_GRASS_MANURE_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading manure in extensive grass systems in kg N ha-1 manure_ext_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with extensive grass area manure_ext_grass.multiply(grass_ext,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_INT_GRASS_MANURE_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading manure in intensive grass systems in kg N ha-1 manure_int_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with intensive grass area manure_int_grass.multiply(grass_int,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_EXT_CROP_MANURE_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading manure in extensive crop systems in kg N ha-1 manure_ext_crop = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with extensive crop area manure_ext_crop.multiply(crop_ext,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_INT_CROP_MANURE_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of spreading manure in intensive crop systems in kg N ha-1 manure_int_crop = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with intensive crop area manure_int_crop.multiply(crop_int,default_nodata_value=-9999.) # Add the four components. manure_ext_grass.add(manure_int_grass) manure_ext_grass.add(manure_ext_crop) manure_ext_grass.add(manure_int_crop) # Write NH3 emission spreading manure in kg N yr-1 to file manure_ext_grass.write_ascii_file(os.path.join(inputdir,params.filename_nh3_em_spread_manure)) print_total(manure_ext_grass,"Total NH3 emission spreading manure:",fp=fp) # Area of extensive systems and mixed and landless systems area_int = ascraster.duplicategrid(crop_int) area_int.add(grass_int) area_ext = ascraster.duplicategrid(crop_ext) area_ext.add(grass_ext) # Emission from storage filename_org = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT STORAGE GRID FILE"]) filename = os.path.splitext(filename_org)[0] +"_EXT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of storage in extensive systems in kg N ha-1 storage_ext = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with extensive area storage_ext.multiply(area_ext,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_INT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of storage in intensive grass systems in kg N ha-1 storage_int = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with intensive area storage_int.multiply(area_int,default_nodata_value=-9999.) # Add the two components. storage_ext.add(storage_int) # Write NH3 emission of storage in kg N yr-1 to file storage_ext.write_ascii_file(os.path.join(inputdir,params.filename_nh3_em_storage)) print_total(storage_ext,"Total NH3 emission storage:",fp=fp) # Emission from grazing filename_org = os.path.join(mandistdir_out,mandist_files_dict["OUTPUT GRAZING GRID FILE"]) filename = os.path.splitext(filename_org)[0] +"_EXT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of grazing in extensive systems in kg N ha-1 grazing_ext = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with extensive grass area grazing_ext.multiply(grass_ext,default_nodata_value=-9999.) filename = os.path.splitext(filename_org)[0] +"_INT_NH3" + os.path.splitext(filename_org)[1] # Read NH3 volatilisation of grazing in intensive grass systems in kg N ha-1 grazing_int = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Multiply with intensive grass area grazing_int.multiply(grass_int,default_nodata_value=-9999.) # Add the two components. grazing_ext.add(grazing_int) # Write NH3 emission of grazing in kg N yr-1 to file grazing_ext.write_ascii_file(os.path.join(inputdir,params.filename_nh3_em_grazing)) print_total(grazing_ext,"Total NH3 emission grazing:",fp=fp) # Budget, runoff, leaching & groundwater: agriculture my_sys.my_copyfile(os.path.join(gnmdir_out,"Nleaching_nat.asc"),\ os.path.join(inputdir,params.filename_leaching_nat)) gridfile_total(os.path.join(inputdir,params.filename_leaching_nat),"Total leaching natural soils:",fp=fp) # Leaching filename = os.path.join(gnmdir_out,"Nleaching_arable.asc") le_crop = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(gnmdir_out,"Nleaching_grass.asc") le_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) le_crop.add(le_grass) # Write N of leaching on agricultural soils in kg N yr-1 to file le_crop.write_ascii_file(os.path.join(inputdir,params.filename_leaching_ag)) print_total(le_crop,"Total leaching on agricultural soils:",fp=fp) # Groundwater filename = os.path.join(gnmdir_out,"Nsgrw.asc") sgrw = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(gnmdir_out,"N_deep_grw.asc") dgrw = ascraster.Asciigrid(ascii_file = filename,numtype = float) sgrw.add(dgrw) # Use leaching to distribute groundwater load into agricultural and natural filename = os.path.join(gnmdir_out,"Nleaching_nat.asc") le_nat = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(gnmdir_out,"Nleaching.asc") le_tot = ascraster.Asciigrid(ascii_file = filename,numtype = float) # Determine the fraction of nat in the total leaching. le_nat.divide(le_tot,default_nodata_value=-9999.) grw_nat = ascraster.duplicategrid(sgrw) grw_agri = ascraster.duplicategrid(sgrw) grw_nat.multiply(le_nat) grw_agri.substract(grw_nat) # Write N of leaching on agricultural soils in kg N yr-1 to file grw_nat.write_ascii_file(os.path.join(inputdir,params.filename_groundwaterload_nat)) grw_agri.write_ascii_file(os.path.join(inputdir,params.filename_groundwaterload_ag)) print_total(grw_nat,"Total groundwater on natural soils:",fp=fp) print_total(grw_agri,"Total groundwater on agricultural soils:",fp=fp) # Point sources & fixed diffuse sources (erosion)[kg N yr-1] my_sys.my_copyfile(os.path.join(gnmdir_in,"Npoint.asc"),\ os.path.join(inputdir,params.filename_n_point_wastewater)) my_sys.my_copyfile(os.path.join(gnmdir_in,"N_aquaculture.asc"),\ os.path.join(inputdir,params.filename_n_point_aquaculture)) my_sys.my_copyfile(os.path.join(gnmdir_out,"N_deposition_water.asc"),\ os.path.join(inputdir,params.filename_n_point_dep_surfacewater)) my_sys.my_copyfile(os.path.join(gnmdir_out,"N_gnpp.asc"),\ os.path.join(inputdir,params.filename_n_point_alloch_matter)) my_sys.my_copyfile(os.path.join(gnmdir_out,"Nsoilloss_nat.asc"),\ os.path.join(inputdir,params.filename_n_in_erosion_nat)) my_sys.my_copyfile(os.path.join(gnmdir_out,"N_sro_nat.asc"),\ os.path.join(inputdir,params.filename_nsro_nat)) gridfile_total(os.path.join(inputdir,params.filename_n_point_wastewater),"Total point sources:",fp=fp) gridfile_total(os.path.join(inputdir,params.filename_n_point_aquaculture),"Total aquaculture:",fp=fp) gridfile_total(os.path.join(inputdir,params.filename_n_point_dep_surfacewater),"Total deposition on water:",fp=fp) gridfile_total(os.path.join(inputdir,params.filename_n_point_alloch_matter),"Total alloch matter:",fp=fp) gridfile_total(os.path.join(inputdir,params.filename_n_in_erosion_nat),"Total erosion natural soils:",fp=fp) gridfile_total(os.path.join(inputdir,params.filename_nsro_nat),"Total surface runoff natural soils:",fp=fp) # N erosion filename = os.path.join(gnmdir_out,"Nsoilloss_arable.asc") eros_crop = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(gnmdir_out,"Nsoilloss_grass.asc") eros_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) eros_crop.add(eros_grass) # Write N of erosion on agricultural soils in kg N yr-1 to file eros_crop.write_ascii_file(os.path.join(inputdir,params.filename_n_in_erosion_ag)) print_total(eros_crop,"Total erosion on agricultural soils:",fp=fp) # Surface runoff filename = os.path.join(gnmdir_out,"N_sro_arable.asc") nsro_crop = ascraster.Asciigrid(ascii_file = filename,numtype = float) filename = os.path.join(gnmdir_out,"N_sro_grs.asc") nsro_grass = ascraster.Asciigrid(ascii_file = filename,numtype = float) nsro_crop.add(nsro_grass) # Write N of surface runoff on agricultural soils in kg N yr-1 to file nsro_crop.write_ascii_file(os.path.join(inputdir,params.filename_nsro_ag)) print_total(nsro_crop,"Total surface runoff on agricultural soils:",fp=fp) fp.close()
def pkl_to_ascraster_allorders(filename, outputdir, unmask_raster, new_raster=None, label='', norders=6): # Convert output file in pkl format from rive_framework to ascraster format for each specie. # Open pkl file and read the header. #print('filename_outputconv=',filename) fp = open(filename, 'rb') time, names = general_func.read_header(fp=fp) # Create for each specie an grid file. if (new_raster == None): duplicate = ascraster.duplicategrid(unmask_raster) lcoordinates_conversion = False else: duplicate = ascraster.duplicategrid(new_raster) lcoordinates_conversion = True grids = [] for iorder in range(norders): grids.append([ascraster.duplicategrid(duplicate)]) for iname in range(1, len(names)): grids[-1].append(ascraster.duplicategrid(duplicate)) # Now read the file line per line and put information into rasters try: order = 1 while True: line = pickle.load(fp) # First element contains riverid, second the cell number in unmasked environment and then for each specie a value. icell = line[1] # Get index in output raster. if (lcoordinates_conversion): #x,y = dummy.get_coordin_from_index(icell) x, y = unmask_raster.get_coordin_from_index(icell) icell = duplicate.get_index_from_coordin(x, y) # Set the values for each species for item in range(len(names)): grids[order - 1][item].set_data(icell, line[item + 2]) order += 1 if (order > norders): order = 1 except EOFError: # End of file encountered. pass # Write all grids to disk for iorder in range(norders): for item in range(len(names)): strtime = str(round(time, 3)) orderlabel = '' if (norders > 1): orderlabel = '_order' + str(iorder + 1) grids[iorder][item].write_ascii_file( os.path.join( outputdir, os.path.join(strtime, label + names[item] + orderlabel + '.asc')))
def calculate(params): print("nconc_le_crit_gw =", params.crit_gw) # load needed variables for calculations q = ascraster.Asciigrid(ascii_file=os.path.join(params.inputdir, "q.asc"), numtype=float, mask=params.mask) nle_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.inputdir, "nle_ag.asc"), numtype=float, mask=params.mask) nfix_ara = ascraster.Asciigrid( ascii_file=params.filename_nfixation_cropland, numtype=float, mask=params.mask) nfix_igl = ascraster.Asciigrid(ascii_file=params.filename_nfixation_intgl, numtype=float, mask=params.mask) fsro_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fsro_ag.asc"), numtype=float, mask=params.mask) fara = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "fara.asc"), numtype=float, mask=params.mask) figl = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "figl.asc"), numtype=float, mask=params.mask) fegl = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "fegl.asc"), numtype=float, mask=params.mask) fnat = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "fnat.asc"), numtype=float, mask=params.mask) fle_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fle_ag.asc"), numtype=float, mask=params.mask) frnup_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnup_ara.asc"), numtype=float, mask=params.mask) frnup_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnup_igl.asc"), numtype=float, mask=params.mask) nup_max_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nup_max_ara.asc"), numtype=float, mask=params.mask) nup_max_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nup_max_igl.asc"), numtype=float, mask=params.mask) nox_em = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nox_em.asc"), numtype=float, mask=params.mask) nh3_tot_egl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_tot_egl.asc"), numtype=float, mask=params.mask) nh3_tot_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_tot_igl.asc"), numtype=float, mask=params.mask) nh3_tot_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_tot_ara.asc"), numtype=float, mask=params.mask) nh3_ef_man_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_ara.asc"), numtype=float, mask=params.mask) nh3_ef_man_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_igl.asc"), numtype=float, mask=params.mask) nh3_ef_fer_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_fer_ara.asc"), numtype=float, mask=params.mask) nh3_ef_fer_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_fer_igl.asc"), numtype=float, mask=params.mask) frnfe_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnfe_ara.asc"), numtype=float, mask=params.mask) frnfe_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnfe_igl.asc"), numtype=float, mask=params.mask) nin_max_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nin_max_ara.asc"), numtype=float, mask=params.mask) nin_max_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nin_max_igl.asc"), numtype=float, mask=params.mask) nle_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nle_ara.asc"), numtype=float, mask=params.mask) nle_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nle_igl.asc"), numtype=float, mask=params.mask) ## * Critical N leaching * one_grid = ascraster.duplicategrid(q) for i in range(one_grid.length): one_grid.set_data(i, 1.0) one_min_fsro = ascraster.duplicategrid(one_grid) one_min_fsro.substract(fsro_ag) # 'ara' nle_crit_gw_ara = ascraster.duplicategrid(one_min_fsro) nle_crit_gw_ara.multiply(q) nle_crit_gw_ara.multiply(fara) nle_crit_gw_ara.multiply(params.crit_gw) fileout = os.path.join(params.outputdir, "nle_crit_gw_ara.asc") nle_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nle_crit_gw_ara, "nle_crit_gw_ara =") # 'igl' nle_crit_gw_igl = ascraster.duplicategrid(one_min_fsro) nle_crit_gw_igl.multiply(q) nle_crit_gw_igl.multiply(figl) nle_crit_gw_igl.multiply(params.crit_gw) fileout = os.path.join(params.outputdir, "nle_crit_gw_igl.asc") nle_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nle_crit_gw_igl, "nle_crit_gw_igl =") ## * Parameter v * # 'ara' v_ara_part1 = ascraster.duplicategrid(one_grid) v_ara_part1.substract(frnup_ara) v_ara_part2 = ascraster.duplicategrid(fsro_ag) v_ara_part2.multiply(frnup_ara) v_ara = ascraster.duplicategrid(v_ara_part1) v_ara.add(v_ara_part2) v_ara.substract(fsro_ag) v_ara.multiply(fle_ag) # 'igl' v_igl_part1 = ascraster.duplicategrid(one_grid) v_igl_part1.substract(frnup_igl) v_igl_part2 = ascraster.duplicategrid(fsro_ag) v_igl_part2.multiply(frnup_igl) v_igl = ascraster.duplicategrid(v_igl_part1) v_igl.add(v_igl_part2) v_igl.substract(fsro_ag) v_igl.multiply(fle_ag) ## * Critical N input from manure * ## OPTION 1 - for grid cells with EITHER 'ara' OR 'igl' # 'ara' num1_ara = ascraster.duplicategrid(nle_crit_gw_ara) num1_ara.divide(v_ara, default_nodata_value=-9999) num1_ara.substract(nfix_ara) num2_V1_ara = ascraster.duplicategrid(nox_em) num2_V1_ara.add(nh3_tot_egl) num2_V1_ara.multiply(fara) num_V1_ara = ascraster.duplicategrid(num1_ara) num_V1_ara.substract(num2_V1_ara) den1_ara = ascraster.duplicategrid(fara) den1_ara.multiply(nh3_ef_man_ara) den1_ara.add(one_grid) den2_ara = ascraster.duplicategrid(fara) den2_ara.multiply(nh3_ef_fer_ara) den2_ara.add(one_grid) one_min_frnfe_ara = ascraster.duplicategrid(one_grid) one_min_frnfe_ara.substract(frnfe_ara) frnfe_division_ara = ascraster.duplicategrid(frnfe_ara) frnfe_division_ara.divide(one_min_frnfe_ara, default_nodata_value=-9999) den2_ara.multiply(frnfe_division_ara) den_ara = ascraster.duplicategrid(den1_ara) den_ara.add(den2_ara) nman_crit_gw_V1_ara = ascraster.duplicategrid(num_V1_ara) nman_crit_gw_V1_ara.divide(den_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_gw_V1_ara.asc") nman_crit_gw_V1_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'igl' num1_igl = ascraster.duplicategrid(nle_crit_gw_igl) num1_igl.divide(v_igl, default_nodata_value=-9999) num1_igl.substract(nfix_igl) num2_V1_igl = ascraster.duplicategrid(nox_em) num2_V1_igl.add(nh3_tot_egl) num2_V1_igl.multiply(figl) num_V1_igl = ascraster.duplicategrid(num1_igl) num_V1_igl.substract(num2_V1_igl) den1_igl = ascraster.duplicategrid(figl) den1_igl.multiply(nh3_ef_man_igl) den1_igl.add(one_grid) den2_igl = ascraster.duplicategrid(figl) den2_igl.multiply(nh3_ef_fer_igl) den2_igl.add(one_grid) one_min_frnfe_igl = ascraster.duplicategrid(one_grid) one_min_frnfe_igl.substract(frnfe_igl) frnfe_division_igl = ascraster.duplicategrid(frnfe_igl) frnfe_division_igl.divide(one_min_frnfe_igl, default_nodata_value=-9999) den2_igl.multiply(frnfe_division_igl) den_igl = ascraster.duplicategrid(den1_igl) den_igl.add(den2_igl) nman_crit_gw_V1_igl = ascraster.duplicategrid(num_V1_igl) nman_crit_gw_V1_igl.divide(den_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_gw_V1_igl.asc") nman_crit_gw_V1_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ## OPTION2 - for grid cells with BOTH 'ara' AND 'igl' # 'ara' num2_V2_ara = ascraster.duplicategrid(nle_crit_gw_igl) num2_V2_ara.divide(nle_igl, default_nodata_value=-9999) num2_V2_ara.multiply(nh3_tot_igl) num2_V2_ara.add(nox_em) num2_V2_ara.add(nh3_tot_egl) num2_V2_ara.multiply(fara) num_V2_ara = ascraster.duplicategrid(num1_ara) num_V2_ara.substract(num2_V2_ara) nman_crit_gw_V2_ara = ascraster.duplicategrid(num_V2_ara) nman_crit_gw_V2_ara.divide(den_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_gw_V2_ara.asc") nman_crit_gw_V2_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'igl' num2_V2_igl = ascraster.duplicategrid(nle_crit_gw_ara) num2_V2_igl.divide(nle_ara, default_nodata_value=-9999) num2_V2_igl.multiply(nh3_tot_ara) num2_V2_igl.add(nox_em) num2_V2_igl.add(nh3_tot_egl) num2_V2_igl.multiply(figl) num_V2_igl = ascraster.duplicategrid(num1_igl) num_V2_igl.substract(num2_V2_igl) nman_crit_gw_V2_igl = ascraster.duplicategrid(num_V2_igl) nman_crit_gw_V2_igl.divide(den_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_gw_V2_igl.asc") nman_crit_gw_V2_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # MAKE GRID WITH CRITICAL INPUTS FROM MANURE DEPENDING ON OPTION # ara nman_crit_gw_ara = ascraster.duplicategrid(nman_crit_gw_V1_ara) for icell in range(fara.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) nman_ara2 = nman_crit_gw_V2_ara.get_data(icell) nle = nle_ag.get_data(icell) if (f_ara is None or f_igl is None): continue elif (f_ara > 0 and f_igl > 0 and nle > 0): nman_ara = nman_ara2 elif (f_ara == 0 and f_igl > 0): nman_ara = 0 else: continue nman_crit_gw_ara.set_data(icell, nman_ara) for icell in range(nman_crit_gw_ara.length): nman_ara3 = nman_crit_gw_ara.get_data(icell) if (nman_ara3 is None): continue if (nman_ara3 < 0): nman_ara = 0 else: continue nman_crit_gw_ara.set_data(icell, nman_ara) fileout = os.path.join(params.outputdir, "nman_crit_gw_ara.asc") nman_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nman_crit_gw_ara, "nman_crit_gw_ara =") # igl nman_crit_gw_igl = ascraster.duplicategrid(nman_crit_gw_V1_igl) for icell in range(figl.length): f_igl = figl.get_data(icell) f_ara = fara.get_data(icell) nman_igl2 = nman_crit_gw_V2_igl.get_data(icell) nle = nle_ag.get_data(icell) if (f_ara is None or f_igl is None): continue elif (f_ara > 0 and f_igl > 0 and nle > 0): nman_igl = nman_igl2 elif (f_ara > 0 and f_igl == 0): nman_igl = 0 else: continue nman_crit_gw_igl.set_data(icell, nman_igl) for icell in range(nman_crit_gw_igl.length): nman_igl3 = nman_crit_gw_igl.get_data(icell) if (nman_igl3 is None): continue if (nman_igl3 < 0): nman_igl = 0 else: continue nman_crit_gw_igl.set_data(icell, nman_igl) fileout = os.path.join(params.outputdir, "nman_crit_gw_igl.asc") nman_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nman_crit_gw_igl, "nman_crit_gw_igl =") ## * Critical N input from fertilizer * # 'ara' nfer_crit_gw_ara = ascraster.duplicategrid(nman_crit_gw_ara) nfer_crit_gw_ara.multiply(frnfe_division_ara) # set to zero for all cells with no ara but igl (to avoid error in calculating nh3 emissions / deposition for these cells) for icell in range(nfer_crit_gw_ara.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) if (f_ara == 0 and f_igl > 0): nfer_ara = 0 else: continue nfer_crit_gw_ara.set_data(icell, nfer_ara) fileout = os.path.join(params.outputdir, "nfer_crit_gw_ara.asc") nfer_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nfer_crit_gw_ara, "nfer_crit_gw_ara =") # 'igl' nfer_crit_gw_igl = ascraster.duplicategrid(nman_crit_gw_igl) nfer_crit_gw_igl.multiply(frnfe_division_igl) # set to zero for all cells with no igl but ara (to avoid error in calculating nh3 emissions / deposition for these cells) for icell in range(nfer_crit_gw_igl.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) if (f_igl == 0 and f_ara > 0): nfer_igl = 0 else: continue nfer_crit_gw_igl.set_data(icell, nfer_igl) fileout = os.path.join(params.outputdir, "nfer_crit_gw_igl.asc") nfer_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nfer_crit_gw_igl, "nfer_crit_gw_igl =") ## * Critical N inputs from fertilizer plus manure * ## # 'ara' nman_fer_crit_gw_ara = ascraster.duplicategrid(nman_crit_gw_ara) nman_fer_crit_gw_ara.add(nfer_crit_gw_ara) fileout = os.path.join(params.outputdir, "nman_fer_crit_gw_ara.asc") nman_fer_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'igl' nman_fer_crit_gw_igl = ascraster.duplicategrid(nman_crit_gw_igl) nman_fer_crit_gw_igl.add(nfer_crit_gw_igl) fileout = os.path.join(params.outputdir, "nman_fer_crit_gw_igl.asc") nman_fer_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ## * NH3 emissions at critical N input * # 'ara' nh3em_man_crit_gw_ara = ascraster.duplicategrid(nman_crit_gw_ara) nh3em_man_crit_gw_ara.multiply(nh3_ef_man_ara) nh3em_fer_crit_gw_ara = ascraster.duplicategrid(nfer_crit_gw_ara) nh3em_fer_crit_gw_ara.multiply(nh3_ef_fer_ara) nh3em_crit_gw_ara = ascraster.duplicategrid(nh3em_man_crit_gw_ara) nh3em_crit_gw_ara.add(nh3em_fer_crit_gw_ara) print_debug(nh3em_crit_gw_ara, "nh3em_crit_gw_ara =") # 'igl' nh3em_man_crit_gw_igl = ascraster.duplicategrid(nman_crit_gw_igl) nh3em_man_crit_gw_igl.multiply(nh3_ef_man_igl) nh3em_fer_crit_gw_igl = ascraster.duplicategrid(nfer_crit_gw_igl) nh3em_fer_crit_gw_igl.multiply(nh3_ef_fer_igl) nh3em_crit_gw_igl = ascraster.duplicategrid(nh3em_man_crit_gw_igl) nh3em_crit_gw_igl.add(nh3em_fer_crit_gw_igl) print_debug(nh3em_crit_gw_igl, "nh3em_crit_gw_igl =") ## * N deposition at critical N input * ndep_crit_gw_tot = ascraster.duplicategrid(nh3em_crit_gw_ara) ndep_crit_gw_tot.add(nh3em_crit_gw_igl) ndep_crit_gw_tot.add(nox_em) ndep_crit_gw_tot.add(nh3_tot_egl) fileout = os.path.join(params.outputdir, "ndep_crit_gw_tot.asc") ndep_crit_gw_tot.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_gw_tot, "ndep_crit_gw_tot =") # OPTION 1 - for grid cells with EITHER ara OR igl # 'ara' ndep_crit_gw_V1_ara = ascraster.duplicategrid(ndep_crit_gw_tot) ndep_crit_gw_V1_ara.multiply(fara) # 'igl' ndep_crit_gw_V1_igl = ascraster.duplicategrid(ndep_crit_gw_tot) ndep_crit_gw_V1_igl.multiply(figl) # OPTION 2 - for grid cells with BOTH ara + igl # 'ara' ndep_crit_gw_V2_ara = ascraster.duplicategrid(nle_crit_gw_igl) ndep_crit_gw_V2_ara.divide(nle_igl, default_nodata_value=-9999) ndep_crit_gw_V2_ara.multiply(nh3_tot_igl) ndep_crit_gw_V2_ara.add(nh3em_crit_gw_ara) ndep_crit_gw_V2_ara.add(nox_em) ndep_crit_gw_V2_ara.add(nh3_tot_egl) ndep_crit_gw_V2_ara.multiply(fara) # 'igl' ndep_crit_gw_V2_igl = ascraster.duplicategrid(nle_crit_gw_ara) ndep_crit_gw_V2_igl.divide(nle_ara, default_nodata_value=-9999) ndep_crit_gw_V2_igl.multiply(nh3_tot_ara) ndep_crit_gw_V2_igl.add(nh3em_crit_gw_igl) ndep_crit_gw_V2_igl.add(nox_em) ndep_crit_gw_V2_igl.add(nh3_tot_egl) ndep_crit_gw_V2_igl.multiply(figl) # MAKE ONE GRID FOR N DEPOSITION # 'ara' ndep_crit_gw_ara = ascraster.duplicategrid(ndep_crit_gw_V1_ara) for icell in range(ndep_crit_gw_ara.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) ndep_ara2 = ndep_crit_gw_V2_ara.get_data(icell) nle = nle_ag.get_data(icell) if (f_ara is None or f_igl is None): continue elif (f_ara > 0 and f_igl > 0 and nle > 0): ndep_ara = ndep_ara2 else: continue ndep_crit_gw_ara.set_data(icell, ndep_ara) fileout = os.path.join(params.outputdir, "ndep_crit_gw_ara.asc") ndep_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_gw_ara, "ndep_crit_gw_ara =") # 'igl' ndep_crit_gw_igl = ascraster.duplicategrid(ndep_crit_gw_V1_igl) for icell in range(ndep_crit_gw_igl.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) ndep_igl2 = ndep_crit_gw_V2_igl.get_data(icell) nle = nle_ag.get_data(icell) if (f_ara is None or f_igl is None): continue elif (f_ara > 0 and f_igl > 0 and nle > 0): ndep_igl = ndep_igl2 else: continue ndep_crit_gw_igl.set_data(icell, ndep_igl) fileout = os.path.join(params.outputdir, "ndep_crit_gw_igl.asc") ndep_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_gw_igl, "ndep_crit_gw_igl =") ##TEST: Total N deposition as sum of depositions# ndep_crit_gw_egl = ascraster.duplicategrid(ndep_crit_gw_tot) ndep_crit_gw_egl.multiply(fegl) ndep_crit_gw_nat = ascraster.duplicategrid(ndep_crit_gw_tot) ndep_crit_gw_nat.multiply(fnat) ndep_crit_gw_tot_TEST = ascraster.duplicategrid(ndep_crit_gw_ara) ndep_crit_gw_tot_TEST.add(ndep_crit_gw_igl) ndep_crit_gw_tot_TEST.add(ndep_crit_gw_egl) ndep_crit_gw_tot_TEST.add(ndep_crit_gw_nat) fileout = os.path.join(params.outputdir, "ndep_crit_gw_tot_TEST.asc") ndep_crit_gw_tot_TEST.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_gw_tot_TEST, "ndep_crit_gw_tot_TEST =") ## * Total critical N inputs * # 'ara' nin_crit_gw_ara = ascraster.duplicategrid(nman_crit_gw_ara) nin_crit_gw_ara.add(nfer_crit_gw_ara) nin_crit_gw_ara.add(ndep_crit_gw_ara) nin_crit_gw_ara.add(nfix_ara) fileout = os.path.join(params.outputdir, "nin_crit_gw_ara.asc") nin_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nin_crit_gw_ara, "nin_crit_gw_ara =") # 'igl' nin_crit_gw_igl = ascraster.duplicategrid(nman_crit_gw_igl) nin_crit_gw_igl.add(nfer_crit_gw_igl) nin_crit_gw_igl.add(ndep_crit_gw_igl) nin_crit_gw_igl.add(nfix_igl) fileout = os.path.join(params.outputdir, "nin_crit_gw_igl.asc") nin_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nin_crit_gw_igl, "nin_crit_gw_igl =") # 'ara+igl' nin_crit_gw_araigl = ascraster.duplicategrid(nin_crit_gw_ara) nin_crit_gw_araigl.add(nin_crit_gw_igl) fileout = os.path.join(params.outputdir, "nin_crit_gw_araigl.asc") nin_crit_gw_araigl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ## * N surface runoff at critical N inputs * # 'ara' nsro_crit_gw_ara = ascraster.duplicategrid(nin_crit_gw_ara) nsro_crit_gw_ara.multiply(fsro_ag) print_debug(nsro_crit_gw_ara, "nsro_crit_gw_ara =") # 'igl' nsro_crit_gw_igl = ascraster.duplicategrid(nin_crit_gw_igl) nsro_crit_gw_igl.multiply(fsro_ag) print_debug(nsro_crit_gw_igl, "nsro_crit_gw_igl =") ## * N uptake at critical N inputs * # 'ara' nup_crit_gw_ara = ascraster.duplicategrid(nin_crit_gw_ara) nup_crit_gw_ara.substract(nsro_crit_gw_ara) nup_crit_gw_ara.multiply(frnup_ara) fileout = os.path.join(params.outputdir, "nup_crit_gw_ara.asc") nup_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nup_crit_gw_ara, "nup_crit_gw_ara =") # 'igl' nup_crit_gw_igl = ascraster.duplicategrid(nin_crit_gw_igl) nup_crit_gw_igl.substract(nsro_crit_gw_igl) nup_crit_gw_igl.multiply(frnup_igl) fileout = os.path.join(params.outputdir, "nup_crit_gw_igl.asc") nup_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nup_crit_gw_igl, "nup_crit_gw_igl =") ## * NUE at critical N inputs * # 'ara' nue_crit_gw_ara = ascraster.duplicategrid(nup_crit_gw_ara) nue_crit_gw_ara.divide(nin_crit_gw_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nue_crit_gw_ara.asc") nue_crit_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_crit_gw_ara, "nue_crit_gw_ara =") # 'igl' nue_crit_gw_igl = ascraster.duplicategrid(nup_crit_gw_igl) nue_crit_gw_igl.divide(nin_crit_gw_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nue_crit_gw_igl.asc") nue_crit_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_crit_gw_igl, "nue_crit_gw_igl =") ## * Maximum uptake fraction * # 'ara' fnup_max_gw_ara = ascraster.duplicategrid(nup_max_ara) fnup_max_gw_ara.divide(nup_crit_gw_ara) fileout = os.path.join(params.outputdir, "fnup_max_gw_ara.asc") fnup_max_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_max_gw_ara, "fnup_max_gw_ara =") # 'igl' fnup_max_gw_igl = ascraster.duplicategrid(nup_max_igl) fnup_max_gw_igl.divide(nup_crit_gw_igl) fileout = os.path.join(params.outputdir, "fnup_max_gw_igl.asc") fnup_max_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_max_gw_igl, "fnup_max_gw_igl =") ## * Correction factor for grid cells where Nup,crit > Nup,max * # 'ara' fnup_corr_gw_ara = ascraster.duplicategrid(nin_max_ara) fnup_corr_gw_ara.substract(nfix_ara) temp2_ara = ascraster.duplicategrid(nh3_tot_egl) temp2_ara.add(nox_em) temp2_ara.multiply(fara) fnup_corr_gw_ara.substract(temp2_ara) temp3_ara = ascraster.duplicategrid(nh3em_crit_gw_ara) temp3_ara.multiply(fara) temp3_ara.add(nman_crit_gw_ara) temp3_ara.add(nfer_crit_gw_ara) fnup_corr_gw_ara.divide(temp3_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fnup_corr_gw_ara.asc") fnup_corr_gw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_corr_gw_ara, "fnup_corr_gw_ara =") # 'igl' fnup_corr_gw_igl = ascraster.duplicategrid(nin_max_igl) fnup_corr_gw_igl.substract(nfix_igl) temp2_igl = ascraster.duplicategrid(nh3_tot_egl) temp2_igl.add(nox_em) temp2_igl.multiply(figl) fnup_corr_gw_igl.substract(temp2_igl) temp3_igl = ascraster.duplicategrid(nh3em_crit_gw_igl) temp3_igl.multiply(figl) temp3_igl.add(nman_crit_gw_igl) temp3_igl.add(nfer_crit_gw_igl) fnup_corr_gw_igl.divide(temp3_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fnup_corr_gw_igl.asc") fnup_corr_gw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_corr_gw_igl, "fnup_corr_gw_igl =") ########### Checking degree of exceedance of critical N leaching by FIXED N inputs ############ # Calculate N leaching caused by N fixation alone nle_nfix_gw_ara = ascraster.duplicategrid(nfix_ara) nle_nfix_gw_ara.multiply(v_ara) nle_nfix_gw_igl = ascraster.duplicategrid(nfix_igl) nle_nfix_gw_igl.multiply(v_igl) nle_nfix_gw = ascraster.duplicategrid(nle_nfix_gw_ara) nle_nfix_gw.add(nle_nfix_gw_igl) fileout = os.path.join(params.outputdir, "nle_nfix_gw.asc") nle_nfix_gw.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) #print_debug(nle_nfix_gw,"The N leaching caused by N fixation alone is") # Calculate N leaching caused by NOx emissions alone nle_nox_gw_ara = ascraster.duplicategrid(nox_em) nle_nox_gw_ara.multiply(fara) nle_nox_gw_ara.multiply(v_ara) nle_nox_gw_igl = ascraster.duplicategrid(nox_em) nle_nox_gw_igl.multiply(figl) nle_nox_gw_igl.multiply(v_igl) nle_nox_gw = ascraster.duplicategrid(nle_nox_gw_ara) nle_nox_gw.add(nle_nox_gw_igl) fileout = os.path.join(params.outputdir, "nle_nox_gw.asc") nle_nox_gw.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) #print_debug(nle_nox_gw,"The N leaching caused by NOx emissions alone is") # Calculate N leaching caused by NH3,egl emissions alone nle_nh3egl_gw_ara = ascraster.duplicategrid(nh3_tot_egl) nle_nh3egl_gw_ara.multiply(fara) nle_nh3egl_gw_ara.multiply(v_ara) nle_nh3egl_gw_igl = ascraster.duplicategrid(nh3_tot_egl) nle_nh3egl_gw_igl.multiply(figl) nle_nh3egl_gw_igl.multiply(v_igl) nle_nh3egl_gw = ascraster.duplicategrid(nle_nh3egl_gw_ara) nle_nh3egl_gw.add(nle_nh3egl_gw_igl) fileout = os.path.join(params.outputdir, "nle_nh3egl_gw.asc") nle_nh3egl_gw.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) #print_debug(nle_nh3egl_gw,"The N leaching caused by NH3 emissions from ext grassland alone is") ############################################################################################# ########### FORWARD CALCULATIONS TO CHECK ########### ## * Critical N budget * # 'ara' nbud_crit_gw_ara = ascraster.duplicategrid(nin_crit_gw_ara) nbud_crit_gw_ara.substract(nup_crit_gw_ara) print_debug(nbud_crit_gw_ara, "nbud_crit_gw_ara =") # 'igl' nbud_crit_gw_igl = ascraster.duplicategrid(nin_crit_gw_igl) nbud_crit_gw_igl.substract(nup_crit_gw_igl) print_debug(nbud_crit_gw_igl, "nbud_crit_gw_igl =") ## * Critical leaching * # 'ara' nle_crit_gw_test_ara = ascraster.duplicategrid(nbud_crit_gw_ara) nle_crit_gw_test_ara.substract(nsro_crit_gw_ara) nle_crit_gw_test_ara.multiply(fle_ag) fileout = os.path.join(params.outputdir, "nle_crit_gw_test_ara.asc") nle_crit_gw_test_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nle_crit_gw_test_ara, "nle_crit_gw_test_ara =") # 'igl' nle_crit_gw_test_igl = ascraster.duplicategrid(nbud_crit_gw_igl) nle_crit_gw_test_igl.substract(nsro_crit_gw_igl) nle_crit_gw_test_igl.multiply(fle_ag) fileout = os.path.join(params.outputdir, "nle_crit_gw_test_igl.asc") nle_crit_gw_test_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nle_crit_gw_test_igl, "nle_crit_gw_test_igl =") ## *TEST IF FORWARD CALCULATIONS EQUAL BACKWARD CALLCULATION* # 'ara' if icell_debug < 0: pass else: fw_ara = nle_crit_gw_test_ara.get_data(icell_debug) bw_ara = nle_crit_gw_ara.get_data(icell_debug) if fw_ara is None: print( "FW/BW_TEST:_Forward_calculation_not_possible:_Nin,crit = None" ) else: fw_ara = round(fw_ara, 4) bw_ara = round(bw_ara, 4) if fw_ara == bw_ara: print("FW/BW_TEST_ARABLE_LAND = SUCCESFUL") else: print("FW/BW_TEST_ARABLE_LAND = NOT_SUCCESFUL") # 'igl' if icell_debug < 0: pass else: fw_igl = nle_crit_gw_test_igl.get_data(icell_debug) bw_igl = nle_crit_gw_igl.get_data(icell_debug) if fw_igl is None: print( "FW/BW_TEST:_Forward_calculation_not_possible:_Nin,crit = None" ) else: fw_igl = round(fw_igl, 4) bw_igl = round(bw_igl, 4) if fw_igl == bw_igl: print("FW/BW_TEST_INTENSIVE_GRASSLAND = SUCCESFUL") else: print("FW/BW_TEST_INTENSIVE_GRASSLAND = NOT_SUCCESFUL")
kappa, kappa_loc, kappa_histo = calculate_statistics(matrix_class) output_dict[min_num + iclass] = [kappa, kappa_loc, kappa_histo] return output_dict # Source code to test this functions. if (__name__ == "__main__"): import ascraster mapA = ascraster.Asciigrid(ncols = 4,nrows = 4, xllcorner = 0.0, yllcorner = 0.0, \ cellsize = 1.0, nodata_value = -1, numtype = int) mapB = ascraster.duplicategrid(mapA) mapA.values = [-1,-1,-1,-1, 1, 1, 1, 1,\ 2, 2, 2, 2, 3, 3, 3, 3] mapB.values = [-1,-1,-1,-1, 1, 1, 1, 1,\ 3, 2, 2, 2, 3, 3, 3, 3] print("Raster are equal.") print(compare_rasters(mapA, mapA)) print("Cramer: ", calculate_cramer_v(mapA, mapA)) print("Raster are equal. PER CLASS") print(compare_rasters_per_class(mapA, mapA)) print("Raster are equal except one cell (3 versus 2).") print(compare_rasters(mapA, mapB)) print(compare_rasters_per_class(mapA, mapB)) print("Cramer: ", calculate_cramer_v(mapA, mapA)) mapA.values = [-1,-1,-1,-1, 1, 1, 1, 1,\ 2, 3, 2, 2, 3, 3, 3, 3]
def allocation_emission(params,mask,isocode,isogrid,PopNum,popgrid,PopCon,PopUrb,\ NtotConnected_eff,PtotConnected_eff,NnotConnected_eff,PnotConnected_eff,\ NtotConnected,\ N_PrimRemoval,PrimTreatment,\ N_SecRemoval,SecTreatment,\ N_TertRemoval,TertTreatment,\ Nemiss_rural_sw,Pemiss_rural_sw,\ PopNum_coast,popgrid_coast): ''' Allocation of the emission on the basis of the population grid (actually the population density). ''' # Create a list to store key numbers which are not used on the grid. keys_lost = [] # Read land area landarea = ascraster.Asciigrid(ascii_file=params.landarea,mask=mask,numtype=float) # Calculate the number of connected people and the number of non-connected people (with emission to surface water in urban areas). PopConNum = {} PopNoConNum = {} PopNum_rural = {} for key in isocode: PopConNum[key] = (0.01 * PopCon[key]) * PopNum[key] PopNoConNum[key] = (0.01 * max(0.0,PopUrb[key] - PopCon[key])) * PopNum[key] PopNum_rural[key] = PopNum[key] - PopConNum[key] - PopNoConNum[key] print_debug("PopConNum begin allocation function",PopConNum) print_debug("PopNoConNum",PopNoConNum) print_debug("NtotConnected_eff",NtotConnected_eff) print_debug("PtotConnected_eff",PtotConnected_eff) print_debug("NnotConnected_eff",NnotConnected_eff) print_debug("PnotConnected_eff",PnotConnected_eff) print_debug("NtotConnected",NtotConnected) print_debug("PrimTreatment",PrimTreatment) print_debug("SecTreatment",SecTreatment) print_debug("TertTreatment",TertTreatment) print_debug("N_PrimRemoval",N_PrimRemoval) print_debug("N_SecRemoval",N_SecRemoval) print_debug("N_TertRemoval",N_TertRemoval) print_debug("Nemiss_rural_sw",Nemiss_rural_sw) print_debug("Pemiss_rural_sw",Pemiss_rural_sw) # Distribute the connected and the no connected urban people with as weighing the population density map. # Here a ranking method is used. Highest population density gets first, until all connected and non connected # people are assigned. # Create two output grids with zeros and fill these with the ranking method. gPopNum = ascraster.duplicategrid(popgrid) gPopNum.add_values(popgrid.length * [0.0]) gPopConNum = ascraster.duplicategrid(popgrid) gPopConNum.add_values(popgrid.length * [0.0]) gPopNoConNum = ascraster.duplicategrid(popgrid) gPopNoConNum.add_values(popgrid.length * [0.0]) gPopNum_rural = ascraster.duplicategrid(popgrid) gPopNum_rural.add_values(popgrid.length * [0.0]) gEmNsw = ascraster.duplicategrid(landarea) gEmNsw.add_values(landarea.length * [0.0]) gEmPsw = ascraster.duplicategrid(landarea) gEmPsw.add_values(landarea.length * [0.0]) if (params.output_per_treatment == 1): gEmNsw_notreat = ascraster.duplicategrid(landarea) gEmNsw_notreat.add_values(landarea.length * [0.0]) gEmNsw_prim = ascraster.duplicategrid(landarea) gEmNsw_prim.add_values(landarea.length * [0.0]) gEmNsw_sec = ascraster.duplicategrid(landarea) gEmNsw_sec.add_values(landarea.length * [0.0]) gEmNsw_tert = ascraster.duplicategrid(landarea) gEmNsw_tert.add_values(landarea.length * [0.0]) gEmNsw_notcon = ascraster.duplicategrid(landarea) gEmNsw_notcon.add_values(landarea.length * [0.0]) gEmNsw_con = ascraster.duplicategrid(landarea) gEmNsw_con.add_values(landarea.length * [0.0]) gEmNsw_rural = ascraster.duplicategrid(landarea) gEmNsw_rural.add_values(landarea.length * [0.0]) # Make a dictionairy of pointers for all the isocodes in the grid. pointer_dict = {} for icell in xrange(isogrid.length): iso = isogrid.get_data(icell) if (iso != None): iso = int(iso) try: pointer_dict[iso].append(icell) except KeyError: pointer_dict[iso] = [icell] for key in isocode: # Select population of the key country # First step is to allocate the people which are connected with ranking. weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: pointer1 = [] sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: area = landarea.get_data(icell,0.0) pop = popgrid.get_data(icell,0.0) pop_coast = popgrid_coast.get_data(icell,0.0) # Fill weighing data and max data qmax_key.append(pop-pop_coast) # Here weighing with population density is needed in stead of population numbers. try: weight_key.append(pop/area) except ZeroDivisionError: weight_key.append(0.0) sumqmax += qmax_key[-1] sumweight += weight_key[-1] # Grid these country connected population data with help of the population density map PopNum_reg = PopConNum[key] popconnum_new = allocranking.allocranking(PopNum_reg,sumweight,weight_key,qmax_key) # Fill gridded result for item in xrange(len(popconnum_new)): gPopConNum.set_data(pointer1[item],popconnum_new[item]) # Second step is to allocate the people which are not connected with ranking. # Note that the results of the first step are used here. Where connected people are living, # there are no non connected people. Because all input has been changed by allocranking, we have to # recalculate the input again. weight_key = [] qmax_key = [] sumqmax = 0.0 sumweight = 0.0 for item in xrange(len(pointer1)): icell = pointer1[item] area = landarea.get_data(icell,0.0) pop = popgrid.get_data(icell,0.0) pop_coast = popgrid_coast.get_data(icell,0.0) # Fill weighing data and max data qmax_key.append(pop - popconnum_new[item] - pop_coast) # Here weighing with population density is needed in stead of population numbers. try: weight_key.append(pop/area) except ZeroDivisionError: weight_key.append(0.0) sumqmax += qmax_key[-1] sumweight += weight_key[-1] # Grid these country not connected population data with help of the population density map PopNum_reg = PopNoConNum[key] popnoconnum_new = allocranking.allocranking(PopNum_reg,sumweight,weight_key,qmax_key) # Fill gridded result for item in xrange(len(popnoconnum_new)): gPopNoConNum.set_data(pointer1[item],popnoconnum_new[item]) # Calculate the rural population ( as rest of total minus connected and not-connected) # Substract the connect people and the not connected people. popnum_rural_new = [] for item in xrange(len(popnoconnum_new)): val = max(popgrid.get_data(pointer1[item],0.0) - popgrid_coast.get_data(pointer1[item],0.0)- popconnum_new[item] - popnoconnum_new[item],0.0) popnum_rural_new.append(val) gPopNum_rural.set_data(pointer1[item],val) # # calculate P and N emission per gridcell # # Fill gridded result try: NConnected_per_inh = NtotConnected[key]/PopConNum[key] except ZeroDivisionError: NConnected_per_inh = 0.0 try: NConnected_eff_per_inh = NtotConnected_eff[key]/PopConNum[key] except ZeroDivisionError: NConnected_eff_per_inh = 0.0 try: NnoConnected_eff_per_inh = NnotConnected_eff[key]/PopNoConNum[key] except ZeroDivisionError: NnoConnected_eff_per_inh = 0.0 try: PConnected_eff_per_inh = PtotConnected_eff[key]/PopConNum[key] except ZeroDivisionError: PConnected_eff_per_inh = 0.0 try: PnoConnected_eff_per_inh = PnotConnected_eff[key]/PopNoConNum[key] except ZeroDivisionError: PnoConnected_eff_per_inh = 0.0 try: Nemiss_rural_sw_per_inh = Nemiss_rural_sw[key]/PopNum_rural[key] except ZeroDivisionError: Nemiss_rural_sw_per_inh = 0.0 try: Pemiss_rural_sw_per_inh = Pemiss_rural_sw[key]/PopNum_rural[key] except ZeroDivisionError: Pemiss_rural_sw_per_inh = 0.0 # Allocate the load on the grid. for item in xrange(len(popnoconnum_new)): # Popconnum has a length of whole region. load = popconnum_new[item] * NConnected_eff_per_inh + popnoconnum_new[item] * NnoConnected_eff_per_inh +\ popnum_rural_new[item] * Nemiss_rural_sw_per_inh gEmNsw.set_data(pointer1[item],load) load = popconnum_new[item] * PConnected_eff_per_inh + popnoconnum_new[item] * PnoConnected_eff_per_inh +\ popnum_rural_new[item] * Pemiss_rural_sw_per_inh gEmPsw.set_data(pointer1[item],load) if (params.output_per_treatment == 1): load = popconnum_new[item] * max(0.0,(1.0 - PrimTreatment[key] - \ SecTreatment[key] - TertTreatment[key])) * NConnected_per_inh gEmNsw_notreat.set_data(pointer1[item],load) load = popconnum_new[item] * PrimTreatment[key] * (1.0 - N_PrimRemoval[key] * 0.01) * NConnected_per_inh gEmNsw_prim.set_data(pointer1[item],load) load = popconnum_new[item] * SecTreatment[key] * (1.0 - N_SecRemoval[key] * 0.01) * NConnected_per_inh gEmNsw_sec.set_data(pointer1[item],load) load = popconnum_new[item] * TertTreatment[key] * (1.0 - N_TertRemoval[key] * 0.01) * NConnected_per_inh gEmNsw_tert.set_data(pointer1[item],load) load = popconnum_new[item] * NConnected_eff_per_inh gEmNsw_con.set_data(pointer1[item],load) load = popnoconnum_new[item] * NnoConnected_eff_per_inh gEmNsw_notcon.set_data(pointer1[item],load) # Fill rural emissions load = popnum_rural_new[item] * Nemiss_rural_sw_per_inh gEmNsw_rural.set_data(pointer1[item],load) # Write to output file gEmNsw.write_ascii_file(params.filegEmNsw) gEmPsw.write_ascii_file(params.filegEmPsw) gPopConNum.write_ascii_file(params.filegPopConNum) gPopNoConNum.write_ascii_file(params.filegPopNoConNum) gPopNum_rural.write_ascii_file(params.filegPopNum_rural) if (params.output_per_treatment == 1): gEmNsw_notreat.write_ascii_file(params.filegEmNsw_notreat) gEmNsw_prim.write_ascii_file(params.filegEmNsw_prim) gEmNsw_sec.write_ascii_file(params.filegEmNsw_sec) gEmNsw_tert.write_ascii_file(params.filegEmNsw_tert) gEmNsw_con.write_ascii_file(params.filegEmNsw_con) gEmNsw_notcon.write_ascii_file(params.filegEmNsw_notcon) gEmNsw_rural.write_ascii_file(params.filegEmNsw_rural) print_debug("Nsw_total_grid",total(isogrid,gEmNsw)) print_debug("Psw_total_grid",total(isogrid,gEmPsw)) print_debug("Nsw_popconnum_grid",total(isogrid,gPopConNum)) print_debug("Nsw_popnoconnum_grid",total(isogrid,gPopNoConNum)) print_debug("Nsw_popnum_rural_grid",total(isogrid,gPopNum_rural)) if (params.output_per_treatment == 1): print_debug("Nsw_notreat_grid",total(isogrid,gEmNsw_notreat)) print_debug("Nsw_prim_grid",total(isogrid,gEmNsw_prim)) print_debug("Nsw_sec_grid",total(isogrid,gEmNsw_sec)) print_debug("Nsw_tert_grid",total(isogrid,gEmNsw_tert)) print_debug("Nsw_con_grid",total(isogrid,gEmNsw_con)) print_debug("Nsw_notcon_grid",total(isogrid,gEmNsw_notcon)) print_debug("Nsw_rural_grid",total(isogrid,gEmNsw_rural)) print_debug("GRID: Global total N to surface water: ",total_dict(total(isogrid,gEmNsw))) print_debug("Global total N to surface water: ",total_dict(NtotConnected_eff)+total_dict(NnotConnected_eff)) print_debug("GRID: Global total P to surface water: ",total_dict(total(isogrid,gEmPsw))) print_debug("Global total P to surface water: ",total_dict(PtotConnected_eff)+total_dict(PnotConnected_eff)) if (params.output_per_treatment == 1): print_debug("GRID: Global total N not_treated to surface water: ",total_dict(total(isogrid,gEmNsw_notreat))) print_debug("GRID: Global total N primairy treatment to surface water: ",total_dict(total(isogrid,gEmNsw_prim))) print_debug("GRID: Global total N secondary treatment to surface water: ",total_dict(total(isogrid,gEmNsw_sec))) print_debug("GRID: Global total N tertairy treatment to surface water: ",total_dict(total(isogrid,gEmNsw_tert))) print_debug("GRID: Global total N connected part to surface water: ",total_dict(total(isogrid,gEmNsw_con))) print_debug("Global total N connected part to surface water: ",total_dict(NtotConnected_eff)) print_debug("GRID: Global total N non-connected part to surface water: ",total_dict(total(isogrid,gEmNsw_notcon))) print_debug("Global total N non-connected part to surface water: ",total_dict(NnotConnected_eff)) print_debug("GRID: Global total N rural part to surface water: ",total_dict(total(isogrid,gEmNsw_rural))) print_debug("Global total N rural part to surface water: ",total_dict(Nemiss_rural_sw)) # Make sum of all treatments to check whether everything is oke. gcheck = ascraster.duplicategrid(gEmNsw_notreat) gcheck.add(gEmNsw_prim) gcheck.add(gEmNsw_sec) gcheck.add(gEmNsw_tert) print_debug("GRID: Global total N connected part (as sum of all the treatment grids to surface water: ",total_dict(total(isogrid,gcheck))) print_debug("GRID: Global total N connected part to surface water: ",total_dict(total(isogrid,gEmNsw_con)))
def read_popnum(params,mask,isogrid,isocode): ''' Read population numbers from grid or from table. If it is given on a table then a weighing grid is needed to allocate the population on the grid. Table and grid is returned. ''' # Scale the population of timescen so that the # total population of the region is correct. PopNum = data_class.get_data(params.filePopNum,year=params.year,sep=params.sep) # PopNum is given in thousand people. So we have to multiply by 1000 for key in PopNum: PopNum[key] *= 1000 # Add isocodes when they are not in list isocode for key in PopNum: try: qq=isocode.index(key) except ValueError: # Isocode found which is not taken into account print "ISOCODE " + str(key) +" is not used for number of people: " + str(PopNum[key]) + " people are missed." PopNum[key] = 0.0 # Add popnum for missing isocodes. Population is zero for key in isocode: try: qq=PopNum[key] except KeyError: # New iso code found. PopNum[key] = 0.0 print "Number of people read : " + str(sum(PopNum.itervalues())) + " is found." print_debug("PopNum in read_popnum",PopNum) # Read population number grid which is used to scale the table population numbers information popgrid_scale = ascraster.Asciigrid(ascii_file=params.filePopNumgrid,mask=mask,numtype=float) # Read land area landarea = ascraster.Asciigrid(ascii_file=params.landarea,mask=mask,numtype=float) # Make new population number grid zero popgrid = ascraster.duplicategrid(popgrid_scale) popgrid.add_values(popgrid.length * [0.0]) # Make a dictionary of pointers for all the isocodes in the grid. pointer_dict = {} for icell in xrange(isogrid.length): iso = isogrid.get_data(icell) if (iso != None): iso = int(iso) try: pointer_dict[iso].append(icell) except KeyError: pointer_dict[iso] = [icell] for key in isocode: if (PopNum[key] <= 0.): print "WEIGHING: table population is ZERO in region: " + str(key) continue # Select population of the key country weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: print "Key: " + str(key) + " is not found in the isogrid." print "Table information of population numbers is changed for region: " + str(int(key)) +\ " from " + str(PopNum[key]) + " to 0.0" continue sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: pop = popgrid_scale.get_data(icell,0.0) # Fill weighing data and max data qmax_key.append(params.max_popdens * landarea.get_data(icell,0.0)) weight_key.append(pop) sumqmax += qmax_key[-1] sumweight += weight_key[-1] # Warn for possible errors if (sumweight <= 0.): print "WEIGHING: grid population is ZERO in region: " + str(key) if (len(weight_key) > 0): # There are cells on the grid for this region. So make a uniform distribution weight_key = len(weight_key) * [1.0] sumweight = sum(weight_key) if (sumqmax < PopNum[key]): print "WEIGHING: PopNum ",PopNum[key], " is bounded by sumqmax",sumqmax, " in region: " + str(key) # Grid these country population data with help of the popgrid_scale map PopNum_reg = PopNum[key] popnum_new = allocweighing.allocweighing(PopNum_reg,sumweight,weight_key,qmax_key) if (key == debug_code): sum1 = 0.0 for item in xrange(len(popnum_new)): sum1 += popnum_new[item] print "New population number: ",sum1 # Fill gridded result sum1 = 0.0 for item in xrange(len(popnum_new)): popgrid.set_data(pointer1[item],popnum_new[item]) sum1 += popnum_new[item] # Check whether the table information has landed in the popgrid if (math.fabs(sum1 - PopNum[key]) > 0.01): print "Table information of population numbers is changed for region: " + str(int(key)) +\ " from " + str(PopNum[key]) + " to " + str(sum1) print "Total number of people: " + str(sum(PopNum.itervalues())) + " is found." return PopNum,popgrid
def calculate(params, mask, mouth_dict, basin, pnet, discharge): """ This function calculates the water area and the water body. Here the discharge of the mouth and qs is set and calculated. """ m2tokm2 = 1.0e-6 mmtokm = 1.0e-6 kmtom = 1.0e3 flooding_fraction_file = params.flooding_fraction flooding_fraction = ascraster.Asciigrid(ascii_file=flooding_fraction_file, mask=mask, numtype=float) fraction_water_grid = ascraster.Asciigrid(ascii_file=params.fraction_water, mask=mask, numtype=float) cellarea_grid = ascraster.Asciigrid(ascii_file=params.cellarea, mask=mask, numtype=float) cellarea_grid.multiply(m2tokm2) # Calculate water area water_area = ascraster.duplicategrid(flooding_fraction) local_discharge = ascraster.duplicategrid(discharge) # Make nodata on all cells. water_area.add_values(water_area.length * [water_area.nodata_value]) for icell in xrange(flooding_fraction.length): flooding_fraction_cell = flooding_fraction.get_data(icell, 0.0) flooding_fraction_cell += fraction_water_grid.get_data(icell, 0.0) if flooding_fraction_cell > 1.0: flooding_fraction_cell = 1.0 area = cellarea_grid.get_data(icell, 0.0) water_area.set_data(icell, (flooding_fraction_cell) * area) # Calculation of local discharge. discharge_cell = pnet.get_data(icell, 0.0) if discharge_cell > 0.0: # Convert pnet [mm/yr] to km3 by multiplying with cellarea and 10e-6 (conversion from mm to km) flux = discharge_cell * area * mmtokm local_discharge.set_data(icell, flux) else: local_discharge.set_data(icell, 0.0) # Take the discharge of the mouth of the river divided by the water area of the mouth cell. for key in mouth_dict.keys(): mouth_dict[key].discharge_mouth = discharge.get_data(mouth_dict[key].index_grid, 0.0) mouth_dict[key].waterarea = 0.0 # Calculate the water body area for each river basin. # Create a start residence time with zero's. water_body = ascraster.duplicategrid(discharge) # Make nodata on all cells. As long as we can not calculate the waterarea, we use a waterbody of one instead of zero! water_body.add_values(water_body.length * [0]) for icell in range(0, basin.length): basinid = basin.get_data(icell, -1) if basinid > 0: try: area = water_area.get_data(icell, 0.0) if area > 0.0: mouth_dict[int(basinid)].waterarea += area water_body.set_data(icell, 1) except KeyError: # We don't not do anything with this river. print "Basinid " + str(basinid) + " found in basinid map but not in river mouth file." for key in mouth_dict.keys(): try: mouth_dict[key].qs = kmtom * mouth_dict[key].discharge_mouth / mouth_dict[key].waterarea except ZeroDivisionError: mouth_dict[key].qs = 0.0 # Write local discharge to output file local_discharge.write_ascii_file(os.path.join(params.outputdir, "discharge_local.asc")) return water_area, water_body
def calculate(params,mask,mouth_dict,basin,pnet,discharge): ''' This function calculates the water area and the water body. Here the discharge of the mouth and qs is set and calculated. ''' m2tokm2 = 1.0e-6 mmtokm = 1.0e-6 kmtom = 1.0e3 # Read flooding areas as fraction of the cellarea. flooding_fraction = ascraster.Asciigrid(ascii_file=params.flooding_fraction,\ mask=mask,numtype=float) # Read rivers and lakes/reservoirs areas as fraction of the cellarea. fraction_water_grid = ascraster.Asciigrid(ascii_file=params.fraction_water,\ mask=mask,numtype=float) # Read the cellarea cellarea_grid = ascraster.Asciigrid(ascii_file=params.cellarea,\ mask=mask,numtype=float) cellarea_grid.multiply(m2tokm2) # Read lake/reservoir id lakeid_grid = ascraster.Asciigrid(ascii_file=params.lakeid,\ mask=mask,numtype=int) # Calculate water area water_area = ascraster.duplicategrid(flooding_fraction) local_discharge = ascraster.duplicategrid(discharge) # Make nodata on all cells. water_area.add_values(water_area.length*[water_area.nodata_value]) flooding_area = ascraster.duplicategrid(water_area) for icell in range(flooding_fraction.length): id = lakeid_grid.get_data(icell,-1) if (id > 0): waterbody_fraction_cell = fraction_water_grid.get_data(icell,0.0) flooding_fraction_cell = 0.0 else: flooding_fraction_cell = flooding_fraction.get_data(icell,0.0) waterbody_fraction_cell = fraction_water_grid.get_data(icell,0.0) waterbody_fraction_cell += flooding_fraction_cell if (waterbody_fraction_cell > 1.0): waterbody_fraction_cell = 1.0 area = cellarea_grid.get_data(icell,0.0) water_area.set_data(icell,waterbody_fraction_cell * area) flooding_area.set_data(icell,flooding_fraction_cell * area) # Calculation of local discharge. discharge_cell = pnet.get_data(icell,0.0) if (discharge_cell > 0.): # Convert pnet [mm/yr] to km3 by multiplying with cellarea and 10e-6 (conversion from mm to km) flux = discharge_cell * area * mmtokm local_discharge.set_data(icell,flux) else: local_discharge.set_data(icell,0.0) # Take the discharge of the mouth of the river divided by the water area of the mouth cell. for key in list(mouth_dict.keys()): mouth_dict[key].discharge_mouth = discharge.get_data(mouth_dict[key].index_grid,0.0) mouth_dict[key].waterarea = 0.0 # Calculate the water body area for each river basin. # Create a start residence time with zero's. water_body = ascraster.duplicategrid(discharge) # Make nodata on all cells. As long as we can not calculate the waterarea, we use a waterbody of one instead of zero! water_body.add_values(water_body.length*[0]) for icell in range(0,basin.length): basinid = basin.get_data(icell,-1) if (basinid > 0): try: area = water_area.get_data(icell,0.0) if (area > 0.0): mouth_dict[int(basinid)].waterarea += area water_body.set_data(icell,1) mouth_dict[int(basinid)].flooding_area += flooding_area.get_data(icell,0.0) except KeyError: # We don't not do anything with this river. print("Basinid " + str(basinid) + " found in basinid map but not in river mouth file.") for key in list(mouth_dict.keys()): try: mouth_dict[key].qs = kmtom * mouth_dict[key].discharge_mouth/mouth_dict[key].waterarea except ZeroDivisionError: mouth_dict[key].qs = 0.0 # Write local discharge to output file local_discharge.write_ascii_file(os.path.join(params.outputdir,"discharge_local.asc")) return water_area, water_body
def calculate(params): #print("The critical N concentration in surface water is", params.crit_sw) # load needed variables for calculations nfix_ara = ascraster.Asciigrid( ascii_file=params.filename_nfixation_cropland, numtype=float, mask=params.mask) nfix_igl = ascraster.Asciigrid(ascii_file=params.filename_nfixation_intgl, numtype=float, mask=params.mask) nallo = ascraster.Asciigrid( ascii_file=params.filename_n_point_alloch_matter, numtype=float, mask=params.mask) nww = ascraster.Asciigrid(ascii_file=params.filename_n_point_wastewater, numtype=float, mask=params.mask) naqua = ascraster.Asciigrid(ascii_file=params.filename_n_point_aquaculture, numtype=float, mask=params.mask) ndep_sw = ascraster.Asciigrid( ascii_file=params.filename_n_point_dep_surfacewater, numtype=float, mask=params.mask) nfix_egl = ascraster.Asciigrid(ascii_file=os.path.join( params.inputdir, "nfix_grass_ext.asc"), numtype=float, mask=params.mask) nfix_nat = ascraster.Asciigrid(ascii_file=os.path.join( params.inputdir, "nfix_nat.asc"), numtype=float, mask=params.mask) nup_egl = ascraster.Asciigrid(ascii_file=os.path.join( params.inputdir, "n_up_grass_ext.asc"), numtype=float, mask=params.mask) q = ascraster.Asciigrid(ascii_file=os.path.join(params.inputdir, "q.asc"), numtype=float, mask=params.mask) npoint_tot = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "npoint_tot.asc"), numtype=float, mask=params.mask) nero_tot = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nero_tot.asc"), numtype=float, mask=params.mask) nload_fixed_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nload_fixed_ag.asc"), numtype=float, mask=params.mask) nload_fixed_nat = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nload_fixed_nat.asc"), numtype=float, mask=params.mask) nload_var_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nload_var_ag.asc"), numtype=float, mask=params.mask) nload_var_nat = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nload_var_nat.asc"), numtype=float, mask=params.mask) fle_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fle_ag.asc"), numtype=float, mask=params.mask) fle_nat = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fle_nat.asc"), numtype=float, mask=params.mask) fsro_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fsro_ag.asc"), numtype=float, mask=params.mask) fsro_nat = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fsro_nat.asc"), numtype=float, mask=params.mask) frnup_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnup_ara.asc"), numtype=float, mask=params.mask) frnup_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnup_igl.asc"), numtype=float, mask=params.mask) fgw_rec_le_ag = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fgw_rec_le_ag.asc"), numtype=float, mask=params.mask) fgw_rec_le_nat = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "fgw_rec_le_nat.asc"), numtype=float, mask=params.mask) nox_em = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nox_em.asc"), numtype=float, mask=params.mask) nh3_tot_egl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_tot_egl.asc"), numtype=float, mask=params.mask) nh3_ef_man_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_ara.asc"), numtype=float, mask=params.mask) nh3_ef_man_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_igl.asc"), numtype=float, mask=params.mask) nh3_ef_fer_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_fer_ara.asc"), numtype=float, mask=params.mask) nh3_ef_fer_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_fer_igl.asc"), numtype=float, mask=params.mask) nh3_ef_man_fer_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_fer_ara.asc"), numtype=float, mask=params.mask) nh3_ef_man_fer_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nh3_ef_man_fer_igl.asc"), numtype=float, mask=params.mask) frnfe_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnfe_ara.asc"), numtype=float, mask=params.mask) frnfe_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frnfe_igl.asc"), numtype=float, mask=params.mask) frn_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frn_ara.asc"), numtype=float, mask=params.mask) frn_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "frn_igl.asc"), numtype=float, mask=params.mask) fara = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "fara.asc"), numtype=float, mask=params.mask) figl = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "figl.asc"), numtype=float, mask=params.mask) fegl = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "fegl.asc"), numtype=float, mask=params.mask) fnat = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir, "fnat.asc"), numtype=float, mask=params.mask) nup_max_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nup_max_ara.asc"), numtype=float, mask=params.mask) nup_max_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nup_max_igl.asc"), numtype=float, mask=params.mask) nin_max_ara = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nin_max_ara.asc"), numtype=float, mask=params.mask) nin_max_igl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nin_max_igl.asc"), numtype=float, mask=params.mask) nman_egl = ascraster.Asciigrid(ascii_file=os.path.join( params.outputdir, "nman_egl.asc"), numtype=float, mask=params.mask) ## One grid one_grid = ascraster.duplicategrid(nfix_ara) for i in range(one_grid.length): one_grid.set_data(i, 1.0) # calculate Nload,crit,sw =Q*Nconc,sw(crit) nload_crit_sw = ascraster.duplicategrid(q) nload_crit_sw.multiply(params.crit_sw) fileout = os.path.join(params.outputdir, "nload_crit_sw.asc") nload_crit_sw.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nload_crit_sw, "nload_crit_sw =") # calculate fixed N load to surface water nload_fixed_tot = ascraster.duplicategrid(nallo) nload_fixed_tot.add(nero_tot) nload_fixed_tot.add(nload_fixed_nat) print_debug(nload_fixed_tot, "nload_fixed_tot =") nload_var_ag_nat = ascraster.duplicategrid(nload_var_ag) nload_var_ag_nat.add(nload_var_nat) nload_var_other = ascraster.duplicategrid(nww) nload_var_other.add(naqua) nload_var_other.add(ndep_sw) nload_var_other.add( nload_fixed_ag ) # is zero if combined with scenario 1 (all ag. N load = variable) nload_var_tot = ascraster.duplicategrid(nload_var_ag_nat) nload_var_tot.add(nload_var_other) nload_var_ag_nat_percent = ascraster.duplicategrid(nload_var_ag_nat) nload_var_ag_nat_percent.divide(nload_var_tot, default_nodata_value=-9999) nload_var_other_percent = ascraster.duplicategrid(nload_var_other) nload_var_other_percent.divide(nload_var_tot, default_nodata_value=-9999) nload_var_crit_tot = ascraster.duplicategrid(nload_crit_sw) nload_var_crit_tot.substract(nload_fixed_tot) nload_var_crit_ag_nat = ascraster.duplicategrid(nload_var_crit_tot) nload_var_crit_ag_nat.multiply(nload_var_ag_nat_percent) nload_var_crit_other = ascraster.duplicategrid(nload_var_crit_tot) nload_var_crit_other.multiply(nload_var_other_percent) ## Parameter 'v' # 'ara' v_ara_part1 = ascraster.duplicategrid(fgw_rec_le_ag) v_ara_part1.multiply(fle_ag) v_ara_part2 = ascraster.duplicategrid(v_ara_part1) v_ara_part2.multiply(frnup_ara) v_ara_part3 = ascraster.duplicategrid(v_ara_part2) v_ara_part3.multiply(fsro_ag) v_ara_part4 = ascraster.duplicategrid(fgw_rec_le_ag) v_ara_part4.multiply(fle_ag) v_ara_part4.multiply(fsro_ag) v_ara = ascraster.duplicategrid(v_ara_part1) v_ara.substract(v_ara_part2) v_ara.add(v_ara_part3) v_ara.substract(v_ara_part4) v_ara.add(fsro_ag) print_debug(v_ara, "v_ara =") # 'igl' v_igl_part1 = ascraster.duplicategrid(fgw_rec_le_ag) v_igl_part1.multiply(fle_ag) v_igl_part2 = ascraster.duplicategrid(v_igl_part1) v_igl_part2.multiply(frnup_igl) v_igl_part3 = ascraster.duplicategrid(v_igl_part2) v_igl_part3.multiply(fsro_ag) v_igl_part4 = ascraster.duplicategrid(fgw_rec_le_ag) v_igl_part4.multiply(fle_ag) v_igl_part4.multiply(fsro_ag) v_igl = ascraster.duplicategrid(v_igl_part1) v_igl.substract(v_igl_part2) v_igl.add(v_igl_part3) v_igl.substract(v_igl_part4) v_igl.add(fsro_ag) print_debug(v_igl, "v_igl =") ## parameter 'w' # 'egl' w_egl_part1 = ascraster.duplicategrid(fgw_rec_le_ag) w_egl_part1.multiply(fle_ag) w_egl_part2 = ascraster.duplicategrid(w_egl_part1) w_egl_part2.multiply(fsro_ag) w_egl = ascraster.duplicategrid(w_egl_part1) w_egl.substract(w_egl_part2) w_egl.add(fsro_ag) print_debug(w_egl, "w_egl =") # 'nat' w_nat_part1 = ascraster.duplicategrid(fgw_rec_le_nat) w_nat_part1.multiply(fle_nat) w_nat_part2 = ascraster.duplicategrid(w_nat_part1) w_nat_part2.multiply(fsro_nat) w_nat = ascraster.duplicategrid(w_nat_part1) w_nat.substract(w_nat_part2) w_nat.add(fsro_nat) print_debug(w_nat, "w_nat =") ## parameter 'y1' y1_part1 = ascraster.duplicategrid(nfix_ara) y1_part1.multiply(v_ara) y1_part2 = ascraster.duplicategrid(nfix_igl) y1_part2.multiply(v_igl) y1_part3 = ascraster.duplicategrid(nfix_egl) y1_part3.add(nman_egl) y1_part3.multiply(w_egl) y1_part4 = ascraster.duplicategrid(nfix_nat) y1_part4.multiply(w_nat) y1 = ascraster.duplicategrid(y1_part1) y1.add(y1_part2) y1.add(y1_part3) y1.add(y1_part4) print_debug(y1, "y1 =") ## parameter 'y2' y2_part1 = ascraster.duplicategrid(fara) y2_part1.multiply(v_ara) y2_part2 = ascraster.duplicategrid(figl) y2_part2.multiply(v_igl) y2_part3 = ascraster.duplicategrid(fegl) y2_part3.multiply(w_egl) y2_part4 = ascraster.duplicategrid(fnat) y2_part4.multiply(w_nat) y2 = ascraster.duplicategrid(y2_part1) y2.add(y2_part2) y2.add(y2_part3) y2.add(y2_part4) print_debug(y2, "y2 =") # calculate parameter 'z' # 'ara' (LET OP: for z_ara, we use frn_igl!) one_min_frn_igl = ascraster.duplicategrid(one_grid) one_min_frn_igl.substract(frn_igl) z_ara = ascraster.duplicategrid(frn_igl) z_ara.divide(one_min_frn_igl, default_nodata_value=-9999) print_debug(z_ara, "z_ara =") # 'igl' (LET OP: for z_igl, we use frn_ara!) one_min_frn_ara = ascraster.duplicategrid(one_grid) one_min_frn_ara.substract(frn_ara) z_igl = ascraster.duplicategrid(frn_ara) z_igl.divide(one_min_frn_ara, default_nodata_value=-9999) print_debug(z_igl, "z_igl =") # calculate parameter 'x' # ara x_ara_part1 = ascraster.duplicategrid(y2) x_ara_part1.multiply(nh3_ef_man_fer_ara) x_ara = ascraster.duplicategrid(y2) x_ara.multiply(nh3_ef_man_fer_igl) x_ara.add(v_igl) x_ara.multiply(z_ara) x_ara.add(x_ara_part1) x_ara.add(v_ara) print_debug(x_ara, "x_ara =") # igl x_igl_part1 = ascraster.duplicategrid(y2) x_igl_part1.multiply(nh3_ef_man_fer_igl) x_igl = ascraster.duplicategrid(y2) x_igl.multiply(nh3_ef_man_fer_ara) x_igl.add(v_ara) x_igl.multiply(z_igl) x_igl.add(x_igl_part1) x_igl.add(v_igl) print_debug(x_igl, "x_igl =") ## calculate critical N input from manure ## OPTION2 - for grid cells with BOTH 'ara' AND 'igl' # 'ara' numerator_V2_ara = ascraster.duplicategrid(nload_var_crit_ag_nat) n1_V2_ara = ascraster.duplicategrid(nox_em) n1_V2_ara.add(nh3_tot_egl) n1_V2_ara.multiply(y2) numerator_V2_ara.substract(y1) numerator_V2_ara.substract(n1_V2_ara) one_min_frnfe_ara = ascraster.duplicategrid(one_grid) one_min_frnfe_ara.substract(frnfe_ara) frnfe_division_ara = ascraster.duplicategrid(frnfe_ara) frnfe_division_ara.divide(one_min_frnfe_ara, default_nodata_value=-9999) denominator_V2_ara = ascraster.duplicategrid(frnfe_division_ara) denominator_V2_ara.add(one_grid) denominator_V2_ara.multiply(x_ara) nman_crit_sw_V2_ara = ascraster.duplicategrid(numerator_V2_ara) nman_crit_sw_V2_ara.divide(denominator_V2_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_sw_V2_ara.asc") nman_crit_sw_V2_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'igl' numerator_V2_igl = ascraster.duplicategrid(numerator_V2_ara) one_min_frnfe_igl = ascraster.duplicategrid(one_grid) one_min_frnfe_igl.substract(frnfe_igl) frnfe_division_igl = ascraster.duplicategrid(frnfe_igl) frnfe_division_igl.divide(one_min_frnfe_igl, default_nodata_value=-9999) denominator_V2_igl = ascraster.duplicategrid(frnfe_division_igl) denominator_V2_igl.add(one_grid) denominator_V2_igl.multiply(x_igl) nman_crit_sw_V2_igl = ascraster.duplicategrid(numerator_V2_igl) nman_crit_sw_V2_igl.divide(denominator_V2_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_sw_V2_igl.asc") nman_crit_sw_V2_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ## OPTION 2 - for grid cells with EITHER 'ara' OR 'igl' # 'ara' numerator_V1_ara = ascraster.duplicategrid(numerator_V2_ara) n1_V1_ara = ascraster.duplicategrid(nup_egl) n1_V1_ara.multiply(fgw_rec_le_ag) n1_V1_ara.multiply(fle_ag) numerator_V1_ara.add(n1_V1_ara) d1_V1_ara = ascraster.duplicategrid(nh3_ef_man_ara) d1_V1_ara.multiply(y2) d1_V1_ara.add(v_ara) d2_V1_ara = ascraster.duplicategrid(nh3_ef_fer_ara) d2_V1_ara.multiply(y2) d2_V1_ara.add(v_ara) d2_V1_ara.multiply(frnfe_division_ara) denominator_V1_ara = ascraster.duplicategrid(d1_V1_ara) denominator_V1_ara.add(d2_V1_ara) nman_crit_sw_V1_ara = ascraster.duplicategrid(numerator_V1_ara) nman_crit_sw_V1_ara.divide(denominator_V1_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_sw_V1_ara.asc") nman_crit_sw_V1_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'igl' numerator_V1_igl = ascraster.duplicategrid(numerator_V1_ara) d1_V1_igl = ascraster.duplicategrid(nh3_ef_man_igl) d1_V1_igl.multiply(y2) d1_V1_igl.add(v_igl) d2_V1_igl = ascraster.duplicategrid(nh3_ef_fer_igl) d2_V1_igl.multiply(y2) d2_V1_igl.add(v_ara) d2_V1_igl.multiply(frnfe_division_igl) denominator_V1_igl = ascraster.duplicategrid(d1_V1_igl) denominator_V1_igl.add(d2_V1_igl) nman_crit_sw_V1_igl = ascraster.duplicategrid(numerator_V1_igl) nman_crit_sw_V1_igl.divide(denominator_V1_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nman_crit_sw_V1_igl.asc") nman_crit_sw_V1_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # MAKE GRID WITH CRITICAL INPUTS FROM MANURE DEPENDING ON OPTION # ara nman_crit_sw_ara = ascraster.duplicategrid(nman_crit_sw_V1_ara) for icell in range(fara.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) nman_ara2 = nman_crit_sw_V2_ara.get_data(icell) if (f_ara is None or f_igl is None): continue elif (f_ara > 0 and f_igl > 0): nman_ara = nman_ara2 elif (f_ara == 0 and f_igl > 0): nman_ara = 0 else: continue nman_crit_sw_ara.set_data(icell, nman_ara) for icell in range(nman_crit_sw_ara.length): nman_ara3 = nman_crit_sw_ara.get_data(icell) if (nman_ara3 is None): continue if (nman_ara3 < 0): nman_ara = 0 else: continue nman_crit_sw_ara.set_data(icell, nman_ara) fileout = os.path.join(params.outputdir, "nman_crit_sw_ara.asc") nman_crit_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nman_crit_sw_ara, "nman_crit_sw_ara =") # igl nman_crit_sw_igl = ascraster.duplicategrid(nman_crit_sw_V1_igl) for icell in range(figl.length): f_igl = figl.get_data(icell) f_ara = fara.get_data(icell) nman_igl2 = nman_crit_sw_V2_igl.get_data(icell) if (f_ara is None or f_igl is None): continue elif (f_ara > 0 and f_igl > 0): nman_igl = nman_igl2 elif (f_ara > 0 and f_igl == 0): nman_igl = 0 else: continue nman_crit_sw_igl.set_data(icell, nman_igl) for icell in range(nman_crit_sw_igl.length): nman_igl3 = nman_crit_sw_igl.get_data(icell) if (nman_igl3 is None): continue if (nman_igl3 < 0): nman_igl = 0 else: continue nman_crit_sw_igl.set_data(icell, nman_igl) fileout = os.path.join(params.outputdir, "nman_crit_sw_igl.asc") nman_crit_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nman_crit_sw_igl, "nman_crit_sw_igl =") ## * Critical N input from fertilizer * # 'ara' nfer_crit_sw_ara = ascraster.duplicategrid(nman_crit_sw_ara) nfer_crit_sw_ara.multiply(frnfe_division_ara) # set to zero for all cells with no ara but igl (to avoid error in calculating nh3 emissions / deposition for these cells) for icell in range(nfer_crit_sw_ara.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) nfer_ara = nfer_crit_sw_ara.get_data(icell) if (f_ara == 0 and f_igl > 0): nfer_ara = 0 else: continue nfer_crit_sw_ara.set_data(icell, nfer_ara) fileout = os.path.join(params.outputdir, "nfer_crit_sw_ara.asc") nfer_crit_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nfer_crit_sw_ara, "nfer_crit_sw_ara =") # 'igl' nfer_crit_sw_igl = ascraster.duplicategrid(nman_crit_sw_igl) nfer_crit_sw_igl.multiply(frnfe_division_igl) # set to zero for all cells with no igl but ara (to avoid error in calculating nh3 emissions / deposition for these cells) for icell in range(nfer_crit_sw_igl.length): f_ara = fara.get_data(icell) f_igl = figl.get_data(icell) nfer_igl = nfer_crit_sw_igl.get_data(icell) if (f_igl == 0 and f_ara > 0): nfer_igl = 0 else: continue nfer_crit_sw_igl.set_data(icell, nfer_igl) fileout = os.path.join(params.outputdir, "nfer_crit_sw_igl.asc") nfer_crit_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nfer_crit_sw_igl, "nfer_crit_sw_igl =") ## * Critical N inputs from fertilizer plus manure * ## # 'ara' nman_fer_crit_sw_ara = ascraster.duplicategrid(nman_crit_sw_ara) nman_fer_crit_sw_ara.add(nfer_crit_sw_ara) fileout = os.path.join(params.outputdir, "nman_fer_crit_sw_ara.asc") nman_fer_crit_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'igl' nman_fer_crit_sw_igl = ascraster.duplicategrid(nman_crit_sw_igl) nman_fer_crit_sw_igl.add(nfer_crit_sw_igl) fileout = os.path.join(params.outputdir, "nman_fer_crit_sw_igl.asc") nman_fer_crit_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ## * NH3 emissions at critical N input * # 'ara' nh3em_man_crit_sw_ara = ascraster.duplicategrid(nman_crit_sw_ara) nh3em_man_crit_sw_ara.multiply(nh3_ef_man_ara) nh3em_fer_crit_sw_ara = ascraster.duplicategrid(nfer_crit_sw_ara) nh3em_fer_crit_sw_ara.multiply(nh3_ef_fer_ara) nh3em_crit_sw_ara = ascraster.duplicategrid(nh3em_man_crit_sw_ara) nh3em_crit_sw_ara.add(nh3em_fer_crit_sw_ara) print_debug(nh3em_crit_sw_ara, "nh3em_crit_sw_ara =") # 'igl' nh3em_man_crit_sw_igl = ascraster.duplicategrid(nman_crit_sw_igl) nh3em_man_crit_sw_igl.multiply(nh3_ef_man_igl) nh3em_fer_crit_sw_igl = ascraster.duplicategrid(nfer_crit_sw_igl) nh3em_fer_crit_sw_igl.multiply(nh3_ef_fer_igl) nh3em_crit_sw_igl = ascraster.duplicategrid(nh3em_man_crit_sw_igl) nh3em_crit_sw_igl.add(nh3em_fer_crit_sw_igl) print_debug(nh3em_crit_sw_igl, "nh3em_crit_sw_igl =") ## * N deposition at critical N input * ndep_crit_sw_tot = ascraster.duplicategrid(nh3em_crit_sw_ara) ndep_crit_sw_tot.add(nh3em_crit_sw_igl) ndep_crit_sw_tot.add(nox_em) ndep_crit_sw_tot.add(nh3_tot_egl) fileout = os.path.join(params.outputdir, "ndep_crit_sw_tot.asc") ndep_crit_sw_tot.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(ndep_crit_sw_tot, "ndep_crit_sw_tot =") # 'ara' ndep_crit_sw_ara = ascraster.duplicategrid(ndep_crit_sw_tot) ndep_crit_sw_ara.multiply(fara) print_debug(ndep_crit_sw_ara, "ndep_crit_sw_ara =") # 'igl' ndep_crit_sw_igl = ascraster.duplicategrid(ndep_crit_sw_tot) ndep_crit_sw_igl.multiply(figl) print_debug(ndep_crit_sw_igl, "ndep_crit_sw_igl =") # 'nat' ndep_crit_sw_nat = ascraster.duplicategrid(ndep_crit_sw_tot) ndep_crit_sw_nat.multiply(fnat) print_debug(ndep_crit_sw_nat, "ndep_crit_sw_nat =") # 'egl' ndep_crit_sw_egl = ascraster.duplicategrid(ndep_crit_sw_tot) ndep_crit_sw_egl.multiply(fegl) print_debug(ndep_crit_sw_egl, "ndep_crit_sw_egl =") ## * Total critical N inputs * # 'ara' nin_crit_sw_ara = ascraster.duplicategrid(nman_crit_sw_ara) nin_crit_sw_ara.add(nfer_crit_sw_ara) nin_crit_sw_ara.add(ndep_crit_sw_ara) nin_crit_sw_ara.add(nfix_ara) fileout = os.path.join(params.outputdir, "nin_crit_sw_ara.asc") nin_crit_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nin_crit_sw_ara, "nin_crit_sw_ara =") # 'igl' nin_crit_sw_igl = ascraster.duplicategrid(nman_crit_sw_igl) nin_crit_sw_igl.add(nfer_crit_sw_igl) nin_crit_sw_igl.add(ndep_crit_sw_igl) nin_crit_sw_igl.add(nfix_igl) fileout = os.path.join(params.outputdir, "nin_crit_sw_igl.asc") nin_crit_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nin_crit_sw_igl, "nin_crit_sw_igl =") # 'ara+igl' nin_crit_sw_araigl = ascraster.duplicategrid(nin_crit_sw_ara) nin_crit_sw_araigl.add(nin_crit_sw_igl) fileout = os.path.join(params.outputdir, "nin_crit_sw_araigl.asc") nin_crit_sw_araigl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) # 'nat' nin_crit_sw_nat = ascraster.duplicategrid(ndep_crit_sw_nat) nin_crit_sw_nat.add(nfix_nat) print_debug(nin_crit_sw_nat, "nin_crit_sw_nat =") # 'egl' nin_crit_sw_egl = ascraster.duplicategrid(ndep_crit_sw_egl) nin_crit_sw_egl.add(nfix_egl) nin_crit_sw_egl.add(nman_egl) print_debug(nin_crit_sw_egl, "nin_crit_sw_egl =") ## * N surface runoff at critical N inputs * # 'ara' nsro_crit_sw_ara = ascraster.duplicategrid(nin_crit_sw_ara) nsro_crit_sw_ara.multiply(fsro_ag) print_debug(nsro_crit_sw_ara, "nsro_crit_sw_ara =") # 'igl' nsro_crit_sw_igl = ascraster.duplicategrid(nin_crit_sw_igl) nsro_crit_sw_igl.multiply(fsro_ag) print_debug(nsro_crit_sw_igl, "nsro_crit_sw_igl =") # 'nat' nsro_crit_sw_nat = ascraster.duplicategrid(nin_crit_sw_nat) nsro_crit_sw_nat.multiply(fsro_nat) print_debug(nsro_crit_sw_nat, "nsro_crit_sw_nat =") # 'egl' nsro_crit_sw_egl = ascraster.duplicategrid(nin_crit_sw_egl) nsro_crit_sw_egl.multiply(fsro_ag) print_debug(nsro_crit_sw_egl, "nsro_crit_sw_egl =") ## * N uptake at critical N inputs * # 'ara' nup_crit_sw_ara = ascraster.duplicategrid(nin_crit_sw_ara) nup_crit_sw_ara.substract(nsro_crit_sw_ara) nup_crit_sw_ara.multiply(frnup_ara) fileout = os.path.join(params.outputdir, "nup_crit_sw_ara.asc") nup_crit_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nup_crit_sw_ara, "nup_crit_sw_ara =") # 'igl' nup_crit_sw_igl = ascraster.duplicategrid(nin_crit_sw_igl) nup_crit_sw_igl.substract(nsro_crit_sw_igl) nup_crit_sw_igl.multiply(frnup_igl) fileout = os.path.join(params.outputdir, "nup_crit_sw_igl.asc") nup_crit_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nup_crit_sw_igl, "nup_crit_sw_igl =") ## * NUE at critical N inputs * # 'ara' nue_crit_sw_ara = ascraster.duplicategrid(nup_crit_sw_ara) nue_crit_sw_ara.divide(nin_crit_sw_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nue_crit_sw_ara.asc") nue_crit_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_crit_sw_ara, "nue_crit_sw_ara =") # 'igl' nue_crit_sw_igl = ascraster.duplicategrid(nup_crit_sw_igl) nue_crit_sw_igl.divide(nin_crit_sw_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "nue_crit_sw_igl.asc") nue_crit_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(nue_crit_sw_igl, "nue_crit_sw_igl =") ## * Maximum uptake fraction * # 'ara' fnup_max_sw_ara = ascraster.duplicategrid(nup_max_ara) fnup_max_sw_ara.divide(nup_crit_sw_ara) fileout = os.path.join(params.outputdir, "fnup_max_sw_ara.asc") fnup_max_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_max_sw_ara, "fnup_max_sw_ara =") # 'igl' fnup_max_sw_igl = ascraster.duplicategrid(nup_max_igl) fnup_max_sw_igl.divide(nup_crit_sw_igl) fileout = os.path.join(params.outputdir, "fnup_max_sw_igl.asc") fnup_max_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_max_sw_igl, "fnup_max_sw_igl =") ## * Correction factor for grid cells where Nup,crit > Nup,max * # 'ara' fnup_corr_sw_ara = ascraster.duplicategrid(nin_max_ara) fnup_corr_sw_ara.substract(nfix_ara) temp2_ara = ascraster.duplicategrid(nh3_tot_egl) temp2_ara.add(nox_em) temp2_ara.multiply(fara) fnup_corr_sw_ara.substract(temp2_ara) temp3_ara = ascraster.duplicategrid(nh3em_crit_sw_ara) temp3_ara.multiply(fara) temp3_ara.add(nman_crit_sw_ara) temp3_ara.add(nfer_crit_sw_ara) fnup_corr_sw_ara.divide(temp3_ara, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fnup_corr_sw_ara.asc") fnup_corr_sw_ara.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_corr_sw_ara, "fnup_corr_sw_ara =") # 'igl' fnup_corr_sw_igl = ascraster.duplicategrid(nin_max_igl) fnup_corr_sw_igl.substract(nfix_igl) temp2_igl = ascraster.duplicategrid(nh3_tot_egl) temp2_igl.add(nox_em) temp2_igl.multiply(figl) fnup_corr_sw_igl.substract(temp2_igl) temp3_igl = ascraster.duplicategrid(nh3em_crit_sw_igl) temp3_igl.multiply(figl) temp3_igl.add(nman_crit_sw_igl) temp3_igl.add(nfer_crit_sw_igl) fnup_corr_sw_igl.divide(temp3_igl, default_nodata_value=-9999) fileout = os.path.join(params.outputdir, "fnup_corr_sw_igl.asc") fnup_corr_sw_igl.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) print_debug(fnup_corr_sw_igl, "fnup_corr_sw_igl =") ########### FORWARD CALCULATIONS TO CHECK ########### ## * Critical N budget * # 'ara' nbud_crit_sw_ara = ascraster.duplicategrid(nin_crit_sw_ara) nbud_crit_sw_ara.substract(nup_crit_sw_ara) print_debug(nbud_crit_sw_ara, "nbud_crit_sw_ara =") # 'igl' nbud_crit_sw_igl = ascraster.duplicategrid(nin_crit_sw_igl) nbud_crit_sw_igl.substract(nup_crit_sw_igl) print_debug(nbud_crit_sw_igl, "nbud_crit_sw_igl =") # 'nat' nbud_crit_sw_nat = ascraster.duplicategrid(nin_crit_sw_nat) print_debug(nbud_crit_sw_nat, "nbud_crit_sw_nat =") # 'egl' nbud_crit_sw_egl = ascraster.duplicategrid(nin_crit_sw_egl) nbud_crit_sw_egl.substract(nup_egl) print_debug(nbud_crit_sw_egl, "nbud_crit_sw_egl =") ## * Critical leaching * # 'ara' nle_crit_sw_ara = ascraster.duplicategrid(nbud_crit_sw_ara) nle_crit_sw_ara.substract(nsro_crit_sw_ara) nle_crit_sw_ara.multiply(fle_ag) print_debug(nle_crit_sw_ara, "nle_crit_sw_ara =") # 'igl' nle_crit_sw_igl = ascraster.duplicategrid(nbud_crit_sw_igl) nle_crit_sw_igl.substract(nsro_crit_sw_igl) nle_crit_sw_igl.multiply(fle_ag) print_debug(nle_crit_sw_igl, "nle_crit_sw_igl =") # 'nat' nle_crit_sw_nat = ascraster.duplicategrid(nbud_crit_sw_nat) nle_crit_sw_nat.substract(nsro_crit_sw_nat) nle_crit_sw_nat.multiply(fle_nat) print_debug(nle_crit_sw_nat, "nle_crit_sw_nat =") # 'egl' nle_crit_sw_egl = ascraster.duplicategrid(nbud_crit_sw_egl) nle_crit_sw_egl.substract(nsro_crit_sw_egl) nle_crit_sw_egl.multiply(fle_ag) print_debug(nle_crit_sw_egl, "nle_crit_sw_egl =") ## * groundwater N load from recent inputs * # 'ara' ngw_rec_crit_sw_ara = ascraster.duplicategrid(nle_crit_sw_ara) ngw_rec_crit_sw_ara.multiply(fgw_rec_le_ag) print_debug(ngw_rec_crit_sw_ara, "ngw_rec_crit_sw_ara =") # 'igl' ngw_rec_crit_sw_igl = ascraster.duplicategrid(nle_crit_sw_igl) ngw_rec_crit_sw_igl.multiply(fgw_rec_le_ag) print_debug(ngw_rec_crit_sw_igl, "ngw_rec_crit_sw_igl =") # 'nat' ngw_rec_crit_sw_nat = ascraster.duplicategrid(nle_crit_sw_nat) ngw_rec_crit_sw_nat.multiply(fgw_rec_le_nat) print_debug(ngw_rec_crit_sw_nat, "ngw_rec_crit_sw_nat =") # 'egl' ngw_rec_crit_sw_egl = ascraster.duplicategrid(nle_crit_sw_egl) ngw_rec_crit_sw_egl.multiply(fgw_rec_le_ag) print_debug(ngw_rec_crit_sw_egl, "ngw_rec_crit_sw_egl =") ## * Variable critical N load to surface water * # 'ara' nload_var_crit_sw_ara = ascraster.duplicategrid(nsro_crit_sw_ara) nload_var_crit_sw_ara.add(ngw_rec_crit_sw_ara) print_debug(nload_var_crit_sw_ara, "nload_var_crit_sw_ara =") # 'igl' nload_var_crit_sw_igl = ascraster.duplicategrid(nsro_crit_sw_igl) nload_var_crit_sw_igl.add(ngw_rec_crit_sw_igl) print_debug(nload_var_crit_sw_igl, "nload_var_crit_sw_igl =") # 'nat' nload_var_crit_sw_nat = ascraster.duplicategrid(nsro_crit_sw_nat) nload_var_crit_sw_nat.add(ngw_rec_crit_sw_nat) print_debug(nload_var_crit_sw_nat, "nload_var_crit_sw_nat =") # 'egl' nload_var_crit_sw_egl = ascraster.duplicategrid(nsro_crit_sw_egl) nload_var_crit_sw_egl.add(ngw_rec_crit_sw_egl) print_debug(nload_var_crit_sw_egl, "nload_var_crit_sw_egl =") ## * calculate n load tot crit sw TEST * nload_crit_sw_test = ascraster.duplicategrid(nload_var_crit_sw_ara) nload_crit_sw_test.add(nload_var_crit_sw_igl) nload_crit_sw_test.add(nload_var_crit_sw_nat) nload_crit_sw_test.add(nload_var_crit_sw_egl) nload_crit_sw_test.add(nload_var_crit_other) nload_crit_sw_test.add(nload_fixed_tot) fileout = os.path.join(params.outputdir, "nload_crit_sw_test.asc") nload_crit_sw_test.write_ascii_file(fileout, output_nodata_value=-9999, compress=params.lcompress) ########### FORWARD CALCULATIONS TO CHECK ########### if icell_debug < 0: pass else: fw = nload_crit_sw_test.get_data(icell_debug) bw = nload_crit_sw.get_data(icell_debug) #print(fw) #print(bw) if fw is None: print( "FW/BW_TEST:_Forward_calculation_not_possible:_Nin,crit = None" ) else: fw = round(fw, 2) bw = round(bw, 2) if fw == bw: print("FW/BW_TEST = SUCCESFUL") else: print("FW/BW_TEST = NOT_SUCCESFUL")
def accuflux_negative(lddmap, fluxmap, retentionmap=None, negative_flux_possible=1): ''' ACCUFLUX Based on Gerard van Drecht, RIVM, Bilthoven, February 2002 April 2002: accu fraction flux and accu fraction state added PURPOSE: Accumulate flow of mass, given by a material map [grid], along a flowpath, given by a local drain direction(LDD) map [grid]. The output map contains accumulated flux [grid]. All files are ascii-grid formatted. Lddmap: network of local drain directions flow_direction can be coded as follows: UNH/GRDC PCraster(LDD) 32 64 128 meaning: NW N NE 7 8 9 16 - 1 W - E 4 5 6 8 4 2 SW S SE 1 2 3 We use the PCraster LDD-format; negative and zero values are assumed The flux is allowed to be negative, but the accufluxmap is only allowed to be positive! ''' # Make output rasters accufluxmap = ascraster.duplicategrid(fluxmap) # Make nodata on all cells. accufluxmap.nodata_value = -1 accufluxmap.add_values(accufluxmap.length * [accufluxmap.nodata_value]) # Make order of all the cells. ordermap = determine_order(lddmap) # Make a pointer for the calculation order pointer1 = [] for icell in range(ordermap.length): pointer1.append([int(ordermap.get_data(icell)), icell]) # Sort the pointer array so that lowest order is first calculated. pointer1.sort() # Loop over all cells: for item in range(len(pointer1)): icell = pointer1[item][1] # Get mass flux at the cell. flux = fluxmap.get_data(icell) if (flux == None): # No data value continue # Set current accufluxmap prev = accufluxmap.get_data(icell, 0.0) flux = max(0.0, (flux + prev) * factor(icell, retentionmap)) accufluxmap.set_data(icell, flux) # Bring mass to the next cell direction = int(lddmap.get_data(icell, -1)) if (direction == 5): continue icell_next = goto_nextcell(icell, direction, lddmap.ncols, mask=lddmap.mask) if (icell_next > -1): prev_next = accufluxmap.get_data(icell_next, 0.0) accufluxmap.set_data(icell_next, prev_next + flux) return accufluxmap
def calculate(params, mask, isocode, isogrid, agri_area): """ Allocation of manure on the basis of agricultural landarea grid. The N and P manure map is returned. """ # Read heads per province. Here no interpolation is done. So the exact year must be specified. animals = general_class.read_general_file(params.fileanimal_heads, sep=";", key=None, out_type="list") # Read N and P excretion. File must contain the header Species;N_excretion;P_excretion excretion = general_class.read_general_file(params.fileanimal_excretion, sep=";", key="Species", out_type="dict") # Calculate the total N and P manure per province for each line in the animals input file Nmanure = {} Pmanure = {} for item in range(len(animals)): # Get the number of heads for the year specified. head = animals[item].get_val(str(params.year)) spec = animals[item].get_val("Species") try: # Get the N and P excretion for this animal Nexcret = excretion[spec].get_val("N_excretion") Pexcret = excretion[spec].get_val("P_excretion") except KeyError: raise MyError("This animal " + spec + " has no excretion rate in file: " + params.fileanimal_excretion) # Multiply heads with excretion animals[item].add_item("Nmanure", float(Nexcret) * float(head)) animals[item].add_item("Pmanure", float(Pexcret) * float(head)) # Calculate total manure per province iso = int(animals[item].get_val("ISO-code")) try: Nmanure[iso] += animals[item].get_val("Nmanure") Pmanure[iso] += animals[item].get_val("Pmanure") except KeyError: Nmanure[iso] = animals[item].get_val("Nmanure") Pmanure[iso] = animals[item].get_val("Pmanure") # Create two output grids with zeros and fill these with the weighing method. Nmanure_grid = ascraster.duplicategrid(agri_area) Nmanure_grid.add_values(Nmanure_grid.length * [0.0]) Pmanure_grid = ascraster.duplicategrid(Nmanure_grid) # Make a dictionairy of pointers for all the isocodes in the grid. pointer_dict = {} for icell in xrange(isogrid.length): iso = isogrid.get_data(icell) if iso != None: iso = int(iso) try: pointer_dict[iso].append(icell) except KeyError: pointer_dict[iso] = [icell] for key in isocode: # Select agricultural land of the key country # First step is to allocate the Nmanure weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: pointer1 = [] sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: area = agri_area.get_data(icell, 0.0) maxarea = 10000000000 # Fill weighing data and max data qmax_key.append(maxarea) weight_key.append(area) sumqmax += qmax_key[-1] sumweight += weight_key[-1] if sumweight < 0.0001: # Make uniform weighing to all cells. for icell in range(len(weight_key)): weight_key[icell] = 1 sumweight += weight_key[icell] # Take the table information on agricultural area. man_demand = Nmanure[key] # Do the allocation man_new = allocweighing.allocweighing(man_demand, sumweight, weight_key, qmax_key) if abs(sum(man_new) - Nmanure[key]) > 0.001 * Nmanure[key]: print "***** There is not enough allocated for Nmanure for region " + str(key) + ". Difference: " + str( Nmanure[key] - sum(man_new) ) # Fill gridded result for item in xrange(len(man_new)): Nmanure_grid.set_data(pointer1[item], man_new[item]) for key in isocode: # Select agricultural land of the key country # Second step is to allocate the Pmanure weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: pointer1 = [] sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: area = agri_area.get_data(icell, 0.0) maxarea = 10000000000 # Fill weighing data and max data qmax_key.append(maxarea) weight_key.append(area) sumqmax += qmax_key[-1] sumweight += weight_key[-1] if sumweight < 0.0001: # Make uniform weighing to all cells. for icell in range(len(weight_key)): weight_key[icell] = 1 sumweight += weight_key[icell] # Take the table information on agricultural area. man_demand = Pmanure[key] # Do the allocation man_new = allocweighing.allocweighing(man_demand, sumweight, weight_key, qmax_key) if abs(sum(man_new) - Pmanure[key]) > 0.001 * Pmanure[key]: print "***** There is not enough allocated for Pmanure for region " + str(key) + ". Difference: " + str( Pmanure[key] - sum(man_new) ) # Fill gridded result for item in xrange(len(man_new)): Pmanure_grid.set_data(pointer1[item], man_new[item]) # Write to output file Nmanure_grid.write_ascii_file(params.fileNmanure) Pmanure_grid.write_ascii_file(params.filePmanure) total = sum(agri_area.values) print "Total N manure in kg N: ", sum(Nmanure_grid.values) print "Total P manure in kg P: ", sum(Pmanure_grid.values) print "Total N manure in kg N/ha: ", sum(Nmanure_grid.values) / (100 * total) print "Total P manure in kg P/ha: ", sum(Pmanure_grid.values) / (100 * total) fp = open(os.path.join(params.outputdir, "manure.csv"), "w") lheader = True for item in range(len(animals)): animals[item].write(fp, sep=";", lheader=lheader, NoneValue="") lheader = False fp.close() return Nmanure_grid, Pmanure_grid
def temp_values(params): ### --------- 1. LAND UNSE FRACTIONS --------- ### # read input files land areas a_tot = ascraster.Asciigrid(ascii_file=params.filename_gridcell_area, numtype=float,mask=params.mask) a_ag = ascraster.Asciigrid(ascii_file=params.filename_agri_area, numtype=float,mask=params.mask) a_ara = ascraster.Asciigrid(ascii_file=params.filename_cropland_area, numtype=float,mask=params.mask) a_igl = ascraster.Asciigrid(ascii_file=params.filename_intgl_area, numtype=float,mask=params.mask) a_egl = ascraster.Asciigrid(ascii_file=params.filename_extgl_area, numtype=float,mask=params.mask) a_nat = ascraster.Asciigrid(ascii_file=params.filename_natural_area, numtype=float,mask=params.mask) # calculate f*g f*g = ascraster.duplicategrid(a_ag) f*g.divide(a_tot, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"f*g.asc") f*g.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(f*g,"f*g =") # calculate fara fara = ascraster.duplicategrid(a_ara) fara.divide(a_tot, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"fara.asc") fara.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(fara,"fara =") # calculate figl figl = ascraster.duplicategrid(a_igl) figl.divide(a_tot, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"figl.asc") figl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(figl,"figl =") # calculate fegl fegl = ascraster.duplicategrid(a_egl) fegl.divide(a_tot, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"fegl.asc") fegl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(fegl,"fegl =") # calculate fnat fnat = ascraster.duplicategrid(a_nat) fnat.divide(a_tot, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"fnat.asc") fnat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fnat,"fnat =") ### --------- 2. INPUTS FERTILIZER, MANURE, FIXATION --------- ### # read input files N inputs nfer_eff_ag = ascraster.Asciigrid(ascii_file=params.filename_fert_inp, numtype=float,mask=params.mask) nfer_eff_ara = ascraster.Asciigrid(ascii_file=params.filename_fert_inp_cropland, numtype=float,mask=params.mask) nfer_eff_igl = ascraster.Asciigrid(ascii_file=params.filename_fert_inp_grassland, numtype=float,mask=params.mask) nman_eff_ag = ascraster.Asciigrid(ascii_file=params.filename_manure_inp, numtype=float,mask=params.mask) nman_eff_ara = ascraster.Asciigrid(ascii_file=params.filename_manure_inp_cropland, numtype=float,mask=params.mask) nman_eff_igl = ascraster.Asciigrid(ascii_file=params.filename_manure_inp_intgl, numtype=float,mask=params.mask) nman_eff_egl = ascraster.Asciigrid(ascii_file=params.filename_manure_inp_extgl, numtype=float,mask=params.mask) nfix_ag = ascraster.Asciigrid(ascii_file=params.filename_nfixation_agri, numtype=float,mask=params.mask) nfix_ara = ascraster.Asciigrid(ascii_file=params.filename_nfixation_cropland, numtype=float,mask=params.mask) nfix_igl = ascraster.Asciigrid(ascii_file=params.filename_nfixation_intgl, numtype=float,mask=params.mask) nfix_egl = ascraster.Asciigrid(ascii_file=params.filename_nfixation_extgl, numtype=float,mask=params.mask) nfix_nat = ascraster.Asciigrid(ascii_file=params.filename_nfixation_nat, numtype=float,mask=params.mask) # read input files NH3 emissions nh3_spread_man = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_manure, numtype=float,mask=params.mask) nh3_spread_man_ara = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_manure_cropland, numtype=float,mask=params.mask) nh3_spread_man_igl = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_manure_intgl, numtype=float,mask=params.mask) nh3_spread_man_egl = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_manure_extgl, numtype=float,mask=params.mask) nh3_stor = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_storage, numtype=float,mask=params.mask) nh3_graz = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_grazing, numtype=float,mask=params.mask) nh3_graz_igl = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_grazing_int, numtype=float,mask=params.mask) nh3_graz_egl = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_grazing_ext, numtype=float,mask=params.mask) nh3_spread_fer = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_fert, numtype=float,mask=params.mask) nh3_spread_fer_ara = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_fert_cropland, numtype=float,mask=params.mask) nh3_spread_fer_igl = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_fert_intgl, numtype=float,mask=params.mask) nh3_spread_fer_egl = ascraster.Asciigrid(ascii_file=params.filename_nh3_em_spread_fert_extgl, numtype=float,mask=params.mask) # split nh3 emissions from storage over intensive grassland, extensive grassland & arable land # intensive grassland nh3_stor_igl = ascraster.duplicategrid(nh3_stor) for icell in range(nh3_stor_igl.length): igl = a_igl.get_data(icell) nh3stor = nh3_stor.get_data(icell) if (igl == None or igl==0) : nh3emigl = 0 elif (igl > 0) : nh3emigl = nh3stor else: continue nh3_stor_igl.set_data(icell,nh3emigl) fileout = os.path.join(params.outputdir, "nh3_stor_igl.asc") nh3_stor_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_stor_igl,"nh3_stor_igl =") # extensive grassland nh3_stor_egl = ascraster.duplicategrid(nh3_stor) for icell in range(nh3_stor_egl.length): egl = a_egl.get_data(icell) nh3stor = nh3_stor.get_data(icell) if (egl == None or egl==0) : nh3emegl = 0 elif (egl > 0) : nh3emegl = nh3stor else: continue nh3_stor_egl.set_data(icell,nh3emegl) fileout = os.path.join(params.outputdir, "nh3_stor_egl.asc") nh3_stor_egl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_stor_egl,"nh3_stor_egl =") # arable land nh3_stor_ara = ascraster.duplicategrid(nh3_stor) for icell in range(nh3_stor_ara.length): ara = a_ara.get_data(icell) igl = a_igl.get_data(icell) egl = a_egl.get_data(icell) nh3stor = nh3_stor.get_data(icell) if (ara == None) : nh3emara = 0 elif (egl == 0 and igl == 0) : nh3emara = nh3stor elif (egl > 0 or igl > 0): nh3emara = 0 nh3emara = 0 else: continue nh3_stor_ara.set_data(icell,nh3emara) fileout = os.path.join(params.outputdir, "nh3_stor_ara.asc") nh3_stor_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_stor_ara,"nh3_stor_ara =") # Calculate total N inputs from *FERTILIZER* (incl. NH3 emissions) # 'ag' nfer_ag = ascraster.duplicategrid(nfer_eff_ag) nfer_ag.add(nh3_spread_fer) fileout = os.path.join(params.outputdir,"nfer_ag.asc") nfer_ag.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(nfer_ag,"nfer_ag =") # 'ara' nfer_ara = ascraster.duplicategrid(nfer_eff_ara) nfer_ara.add(nh3_spread_fer_ara) fileout = os.path.join(params.outputdir,"nfer_ara.asc") nfer_ara.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(nfer_ara,"nfer_ara =") # 'igl' nfer_igl = ascraster.duplicategrid(nfer_eff_igl) nfer_igl.add(nh3_spread_fer_igl) fileout = os.path.join(params.outputdir,"nfer_igl.asc") nfer_igl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(nfer_igl,"nfer_igl =") # 'araigl' nfer_araigl = ascraster.duplicategrid(nfer_ara) nfer_araigl.add(nfer_igl) fileout = os.path.join(params.outputdir,"nfer_araigl.asc") nfer_araigl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) # Calculate total N inputs from *MANURE* (incl. NH3 emissions) # 'ag' nman_ag = ascraster.duplicategrid(nman_eff_ag) nman_ag.add(nh3_spread_man) nman_ag.add(nh3_stor) nman_ag.add(nh3_graz) fileout = os.path.join(params.outputdir,"nman_ag.asc") nman_ag.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(nman_ag,"nman_ag =") # 'ara' nman_ara = ascraster.duplicategrid(nman_eff_ara) nman_ara.add(nh3_spread_man_ara) nman_ara.add(nh3_stor_ara) fileout = os.path.join(params.outputdir,"nman_ara.asc") nman_ara.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(nman_ara,"nman_ara =") # 'igl' nman_igl = ascraster.duplicategrid(nman_eff_igl) nman_igl.add(nh3_spread_man_igl) nman_igl.add(nh3_stor_igl) nman_igl.add(nh3_graz_igl) fileout = os.path.join(params.outputdir,"nman_igl.asc") nman_igl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(nman_igl,"nman_igl =") # 'egl' nman_egl = ascraster.duplicategrid(nman_eff_egl) nman_egl.add(nh3_spread_man_egl) nman_egl.add(nh3_stor_egl) nman_egl.add(nh3_graz_egl) fileout = os.path.join(params.outputdir,"nman_egl.asc") nman_egl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) print_debug(nman_egl,"nman_egl =") # 'araigl' nman_araigl = ascraster.duplicategrid(nman_ara) nman_araigl.add(nman_igl) fileout = os.path.join(params.outputdir,"nman_araigl.asc") nman_araigl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) # Calculate total N inputs from *MANURE AND FERTILIZER* (incl. NH3 emissions) # 'ara' nman_fer_ara = ascraster.duplicategrid(nman_ara) nman_fer_ara.add(nfer_ara) fileout = os.path.join(params.outputdir,"nman_fer_ara.asc") nman_fer_ara.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) # 'igl' nman_fer_igl = ascraster.duplicategrid(nman_igl) nman_fer_igl.add(nfer_igl) fileout = os.path.join(params.outputdir,"nman_fer_igl.asc") nman_fer_igl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) # 'araigl' nman_fer_araigl = ascraster.duplicategrid(nman_fer_ara) nman_fer_araigl.add(nman_fer_igl) fileout = os.path.join(params.outputdir,"nman_fer_araigl.asc") nman_fer_araigl.write_ascii_file(fileout, output_nodata_value=-9999,compress=params.lcompress) ## calculate *frNfe* # 'ara' fer_man_ara = ascraster.duplicategrid(nman_ara) fer_man_ara.add(nfer_ara) frnfe_ara = ascraster.duplicategrid(nfer_ara) frnfe_ara.divide(fer_man_ara, default_nodata_value = -9999) # replace '0' by 0.0001 in frnfe_ara for icell in range(frnfe_ara.length): val = frnfe_ara.get_data(icell) if (val == None or val > 0): continue if val == 0.0: res = 0.0001 frnfe_ara.set_data(icell,res) # replace '1' by 0.9999 in frnfe_ara for icell in range(frnfe_ara.length): val = frnfe_ara.get_data(icell) if (val == None or val < 1): continue if val == 1.0: res = 0.9999 frnfe_ara.set_data(icell,res) fileout = os.path.join(params.outputdir,"frnfe_ara.asc") frnfe_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(frnfe_ara,"frnfe_ara =") # 'igl' fer_man_igl = ascraster.duplicategrid(nman_igl) fer_man_igl.add(nfer_igl) frnfe_igl = ascraster.duplicategrid(nfer_igl) frnfe_igl.divide(fer_man_igl, default_nodata_value = -9999) # replace '0' by 0.0001 in frnfe_igl for icell in range(frnfe_igl.length): val = frnfe_igl.get_data(icell) if (val == None or val > 0): continue if val == 0.0: res = 0.0001 frnfe_igl.set_data(icell,res) # replace '1' by 0.9999 in frnfe_igl for icell in range(frnfe_igl.length): val = frnfe_igl.get_data(icell) if (val == None or val < 1): continue if val == 1.0: res = 0.9999 frnfe_igl.set_data(icell,res) fileout = os.path.join(params.outputdir,"frnfe_igl.asc") frnfe_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(frnfe_igl,"frnfe_igl =") ## Calculate proportion of N inputs in total (arable + intensive grassland) N inputs # 'ara' frn_ara = ascraster.duplicategrid(nman_ara) frn_ara.add(nfer_ara) denominator_frn_ara = ascraster.duplicategrid(frn_ara) denominator_frn_ara.add(nman_igl) denominator_frn_ara.add(nfer_igl) frn_ara.divide(denominator_frn_ara, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"frn_ara.asc") frn_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(frn_ara,"frn_ara =") # 'igl' frn_igl = ascraster.duplicategrid(nman_igl) frn_igl.add(nfer_igl) denominator_frn_igl = ascraster.duplicategrid(frn_igl) denominator_frn_igl.add(nman_ara) denominator_frn_igl.add(nfer_ara) frn_igl.divide(denominator_frn_igl, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"frn_igl.asc") frn_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(frn_igl,"frn_igl =") ### --------- 3. NH3 EMISSIONS & EMISSION FRACTIONS --------- ### # calculate *TOTAL NH3 EMISSION* # 'ag' nh3_tot_ag = ascraster.duplicategrid(nh3_spread_man) nh3_tot_ag.add(nh3_spread_fer) nh3_tot_ag.add(nh3_stor) nh3_tot_ag.add(nh3_graz) print_debug(nh3_tot_ag,"nh3_tot_ag =") # 'ara' nh3_tot_ara = ascraster.duplicategrid(nh3_spread_man_ara) nh3_tot_ara.add(nh3_spread_fer_ara) nh3_tot_ara.add(nh3_stor_ara) fileout = os.path.join(params.outputdir,"nh3_tot_ara.asc") nh3_tot_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_tot_ara,"nh3_tot_ara =") # 'igl' nh3_tot_igl = ascraster.duplicategrid(nh3_spread_man_igl) nh3_tot_igl.add(nh3_spread_fer_igl) nh3_tot_igl.add(nh3_stor_igl) nh3_tot_igl.add(nh3_graz_igl) fileout = os.path.join(params.outputdir,"nh3_tot_igl.asc") nh3_tot_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_tot_igl,"nh3_tot_igl =") # 'egl' nh3_tot_egl = ascraster.duplicategrid(nh3_spread_man_egl) nh3_tot_egl.add(nh3_spread_fer_egl) nh3_tot_egl.add(nh3_stor_egl) nh3_tot_egl.add(nh3_graz_egl) fileout = os.path.join(params.outputdir,"nh3_tot_egl.asc") nh3_tot_egl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_tot_egl,"nh3_tot_egl =") # calculate *FNH3EM,MAN* # 'ara' nh3_man_tot_ara = ascraster.duplicategrid(nh3_spread_man_ara) nh3_man_tot_ara.add(nh3_stor_ara) nh3_ef_man_ara = griddivide(nh3_man_tot_ara,nman_ara,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"nh3_ef_man_ara.asc") nh3_ef_man_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_man_ara,"nh3_ef_man_ara =") # 'igl' nh3_man_tot_igl = ascraster.duplicategrid(nh3_spread_man_igl) nh3_man_tot_igl.add(nh3_stor_igl) nh3_man_tot_igl.add(nh3_graz_igl) nh3_ef_man_igl = griddivide(nh3_man_tot_igl,nman_igl,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"nh3_ef_man_igl.asc") nh3_ef_man_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_man_igl,"nh3_ef_man_igl =") # calculate *FNH3EM,FER* # 'ara' nh3_ef_fer_ara = griddivide(nh3_spread_fer_ara,nfer_ara,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"nh3_ef_fer_ara.asc") nh3_ef_fer_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_fer_ara,"nh3_ef_fer_ara =") # 'igl' nh3_ef_fer_igl = griddivide(nh3_spread_fer_igl,nfer_igl,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"nh3_ef_fer_igl.asc") nh3_ef_fer_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_fer_igl,"nh3_ef_fer_igl =") # calculate *FNH3EM,MAN,FER* # 'ara' nh3_ef_man_fer_ara = griddivide(nh3_tot_ara,fer_man_ara,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"nh3_ef_man_fer_ara.asc") nh3_ef_man_fer_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_man_fer_ara,"nh3_ef_man_fer_ara =") # 'igl' nh3_ef_man_fer_igl = griddivide(nh3_tot_igl,fer_man_igl,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"nh3_ef_man_fer_igl.asc") nh3_ef_man_fer_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nh3_ef_man_fer_igl,"nh3_ef_man_fer_igl =") ### --------- 4. N DEPOSITION & NOx emission --------- ### # calculate corrected N deposition grid - for all cells where Ndep < NH3em, replace Ndep by NH3em ndep_tot = ascraster.Asciigrid(ascii_file=params.filename_n_deposition,numtype=float,mask=params.mask) ndep_corr_tot = ascraster.duplicategrid(ndep_tot) for icell in range(nh3_tot_ag.length): # Get values from both grids. nh3 = nh3_tot_ag.get_data(icell) dep = ndep_tot.get_data(icell) # If both grids have nodata, keep nodata. if (nh3 == None or dep == None or dep >= nh3): continue if dep < nh3: depcorr = nh3 ndep_corr_tot.set_data(icell,depcorr) fileout = os.path.join(params.outputdir,"ndep_corr_tot.asc") ndep_corr_tot.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_tot,"ndep_tot =") print_debug(ndep_corr_tot,"ndep_corr_tot =") # calculate NOx emissions: NOx = *corrected* Ndep - (NH3,spread,fe+NH3,spread,man+NH3stor+NH3,graz) nox_em = ascraster.duplicategrid(ndep_corr_tot) nox_em.substract(nh3_tot_ag) #factor = 0 #nox_em.multiply(factor) fileout = os.path.join(params.outputdir,"nox_em.asc") nox_em.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nox_em,"nox_em =") ## *N DEPOSITION* # 'ag' ndep_ag = ascraster.duplicategrid(ndep_corr_tot) ndep_ag.multiply(f*g) print_debug(ndep_ag,"ndep_ag =") # 'ara' ndep_ara = ascraster.duplicategrid(ndep_corr_tot) ndep_ara.multiply(fara) print_debug(ndep_ara,"ndep_ara =") # 'igl' ndep_igl = ascraster.duplicategrid(ndep_corr_tot) ndep_igl.multiply(figl) print_debug(ndep_igl,"ndep_igl =") # 'egl' ndep_egl = ascraster.duplicategrid(ndep_corr_tot) ndep_egl.multiply(fegl) print_debug(ndep_egl,"ndep_egl =") # 'nat' ndep_nat = ascraster.duplicategrid(ndep_corr_tot) ndep_nat.multiply(fnat) print_debug(ndep_nat,"ndep_nat =") ### --------- 5. TOTAL INPUTS --------- ### ## Calculate *Total N Inputs* # 'ag' nin_ag = ascraster.duplicategrid(nfer_ag) nin_ag.add(nman_ag) nin_ag.add(nfix_ag) nin_ag.add(ndep_ag) print_debug(nin_ag,"nin_ag =") # 'ara' nin_ara = ascraster.duplicategrid(nfer_ara) nin_ara.add(nman_ara) nin_ara.add(nfix_ara) nin_ara.add(ndep_ara) fileout = os.path.join(params.outputdir,"nin_ara.asc") nin_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nin_ara,"nin_ara =") # 'igl' nin_igl = ascraster.duplicategrid(nfer_igl) nin_igl.add(nman_igl) nin_igl.add(nfix_igl) nin_igl.add(ndep_igl) fileout = os.path.join(params.outputdir,"nin_igl.asc") nin_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nin_igl,"nin_igl =") # 'araigl' nin_araigl = ascraster.duplicategrid(nin_ara) nin_araigl.add(nin_igl) fileout = os.path.join(params.outputdir,"nin_araigl.asc") nin_araigl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) # 'egl' nin_egl = ascraster.duplicategrid(nman_egl) nin_egl.add(nfix_egl) nin_egl.add(ndep_egl) print_debug(nin_egl,"nin_egl =") # 'nat' nin_nat = ascraster.duplicategrid(ndep_nat) nin_nat.add(nfix_nat) print_debug(nin_nat,"nin_nat =") ### --------- 6. SURFACE RUNOFF, UPTAKE, FRNUP, NUE --------- ### # read input files uptake, surface runoff nsro_ag = ascraster.Asciigrid(ascii_file=params.filename_nsro_ag, numtype=float,mask=params.mask) nsro_nat = ascraster.Asciigrid(ascii_file=params.filename_nsro_nat, numtype=float,mask=params.mask) nup_ara = ascraster.Asciigrid(ascii_file=params.filename_uptake_cropland, numtype=float,mask=params.mask) nup_igl = ascraster.Asciigrid(ascii_file=params.filename_uptake_intgl, numtype=float,mask=params.mask) nup_egl = ascraster.Asciigrid(ascii_file=params.filename_uptake_extgl, numtype=float,mask=params.mask) regions = ascraster.Asciigrid(ascii_file=params.filename_regions, numtype=float,mask=params.mask) #$# To manipulate results for 1999 so that I can also get uptake per land-use type (assuming equal NUE) #$#nup_ag = ascraster.Asciigrid(ascii_file=params.filename_uptake_agriculture, numtype=float,mask=params.mask) #$# #$#nue_ag = ascraster.duplicategrid(nup_ag) #$#nue_ag.divide(nin_ag, default_nodata_value = -9999) #$#nup_ara = ascraster.duplicategrid(nin_ara) #$#nup_ara.multiply(nue_ag) #$#fileout = os.path.join(params.inputdir,"n_up_crops.asc") #$#nup_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) #$#nup_igl = ascraster.duplicategrid(nin_igl) #$#nup_igl.multiply(nue_ag) #$#fileout = os.path.join(params.inputdir,"n_up_grass_int.asc") #$#nup_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) #$#nup_egl = ascraster.duplicategrid(nin_egl) #$#nup_egl.multiply(nue_ag) #$#fileout = os.path.join(params.inputdir,"n_up_grass_ext.asc") #$#nup_egl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) ## *N UPTAKE* # 'ag' nup_ag = ascraster.duplicategrid(nup_ara) nup_ag.add(nup_igl) nup_ag.add(nup_egl) print_debug(nup_ag,"nup_ag =") ## *SURFACE RUNOFF FRACTION* # 'ag' fsro_ag = griddivide(nsro_ag,nin_ag,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"fsro_ag.asc") fsro_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fsro_ag,"fsro_ag =") # 'nat' fsro_nat = griddivide(nsro_nat,nin_nat,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"fsro_nat.asc") fsro_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fsro_nat,"fsro_nat =") ## *N LOAD FROM SURFACE RUNOFF* # 'ara' nsro_ara = ascraster.duplicategrid(nin_ara) nsro_ara.multiply(fsro_ag) print_debug(nsro_ara,"nsro_ara =") # 'igl' nsro_igl = ascraster.duplicategrid(nin_igl) nsro_igl.multiply(fsro_ag) print_debug(nsro_igl,"nsro_igl =") ## *N UPTAKE FRACTION* # 'ara' nin_min_nsro_ara = ascraster.duplicategrid(nin_ara) nin_min_nsro_ara.substract(nsro_ara) frnup_ara = griddivide(nup_ara,nin_min_nsro_ara,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"frnup_ara.asc") frnup_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(frnup_ara,"frnup_ara =") # 'igl' nin_min_nsro_igl = ascraster.duplicategrid(nin_igl) nin_min_nsro_igl.substract(nsro_igl) frnup_igl = griddivide(nup_igl,nin_min_nsro_igl,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"frnup_igl.asc") frnup_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(frnup_igl,"frnup_igl =") ## *NUE* # 'ara' nue_ara = ascraster.duplicategrid(nup_ara) nue_ara.divide(nin_ara, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"nue_ara.asc") nue_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nue_ara,"nue_ara =") # 'igl' nue_igl = ascraster.duplicategrid(nup_igl) nue_igl.divide(nin_igl, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"nue_igl.asc") nue_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nue_igl,"nue_igl =") ## *MAXIMUM N UPTAKE* # make grid with yield increase per region yieldgap_region = ascraster.duplicategrid(nup_ara) for i in range(yieldgap_region.length): yieldgap_region.set_data(i,-9999) for icell in range(regions.length): val = regions.get_data(icell) # Canada (1) if val == 1: yg = 1.274 # USA (2) elif val == 2: yg = 1.252 # Mexico (3) elif val == 3: yg = 1.566 # Central America (4) elif val == 4: yg = 1.797 # Brazil (5) elif val == 5: yg = 1.343 # Rest of South America (6) elif val == 6: yg = 1.532 # Northern Africa (7) elif val == 7: yg = 2.711 # Western Africa (8) elif val == 8: yg = 2.363 # Eastern Africa (9) elif val == 9: yg = 2.424 # South Africa (10) elif val == 10: yg = 1.848 # Western Europe (11) elif val == 11: yg = 1.177 # Central Europe (12) elif val == 12: yg = 1.982 # Turkey (13) elif val == 13: yg = 1.797 # Ukraine region (14) elif val == 14: yg = 2.633 # Central Asia (15) elif val == 15: yg = 2.928 # Russia region(16) elif val == 16: yg = 2.391 # Middle East (17) elif val == 17: yg = 2.170 # India (18) elif val == 18: yg = 1.508 # Korea region (19) elif val == 19: yg = 1.180 # China region (20) elif val == 20: yg = 1.503 # Southeastern Asia (21) elif val == 21: yg = 1.479 # Indonesia region (22) elif val == 22: yg = 1.267 # Japan (23) elif val == 23: yg = 1.180 # Oceania (24) elif val == 24: yg = 1.487 # Rest of South Asia (25) elif val == 25: yg = 1.870 # Rest of Southern Africa (26) elif val == 26: yg = 2.551 # Greenland (27) elif val == 27: yg = 1.000 # Region can also have value none (-9999) else: continue yieldgap_region.set_data(icell,yg) print_debug(regions,"region_number =") fileout = os.path.join(params.outputdir,"yieldgap_region.asc") yieldgap_region.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(yieldgap_region,"yieldgap =") # calculate Nup(max) = Nup * yieldgap_region # 'ara' nup_max_ara = ascraster.duplicategrid(nup_ara) nup_max_ara.multiply(yieldgap_region) fileout = os.path.join(params.outputdir,"nup_max_ara.asc") nup_max_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nup_max_ara,"nup_max_ara =") # 'igl' nup_max_igl = ascraster.duplicategrid(nup_igl) nup_max_igl.multiply(yieldgap_region) fileout = os.path.join(params.outputdir,"nup_max_igl.asc") nup_max_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nup_max_igl,"nup_max_igl =") ## *CORRECTED NUE* (NUE used to calculate Nin at Nup,max should never be higher than 0.8) # 'ara' nue_corr_ara = ascraster.duplicategrid(nue_ara) for icell in range(nue_corr_ara.length): val = nue_corr_ara.get_data(icell) if (val == None or val <= 0.8): continue if val > 0.8: res = 0.8 nue_corr_ara.set_data(icell,res) fileout = os.path.join(params.outputdir,"nue_corr_ara.asc") nue_corr_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nue_corr_ara,"nue_corr_ara =") # 'igl' nue_corr_igl = ascraster.duplicategrid(nue_igl) for icell in range(nue_corr_igl.length): val = nue_corr_igl.get_data(icell) if (val == None or val <= 0.8): continue if val > 0.8: res = 0.8 nue_corr_igl.set_data(icell,res) fileout = os.path.join(params.outputdir,"nue_corr_igl.asc") nue_corr_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nue_corr_igl,"nue_corr_igl =") ## *MAXIMUM N INPUTS* (total N inputs from all sources that correspond to maximum uptake and a max. NUE of 0.8) # 'ara' nin_max_ara = ascraster.duplicategrid(nup_max_ara) nin_max_ara.divide(nue_corr_ara, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"nin_max_ara.asc") nin_max_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nin_max_ara,"nin_max_ara =") # 'igl' nin_max_igl = ascraster.duplicategrid(nup_max_igl) nin_max_igl.divide(nue_corr_igl, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"nin_max_igl.asc") nin_max_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nin_max_igl,"nin_max_igl =") ### --------- 7. BUDGET, LEACHING, DENITRIFICATION --------- ### # read input files ngw_ag = ascraster.Asciigrid(ascii_file=params.filename_groundwaterload_ag, numtype=float,mask=params.mask) ngw_nat = ascraster.Asciigrid(ascii_file=params.filename_groundwaterload_nat, numtype=float,mask=params.mask) fgw_rec_ag = ascraster.Asciigrid(ascii_file=params.filename_fraction_recent_groundwaterload_ag, numtype=float,mask=params.mask) fgw_rec_nat = ascraster.Asciigrid(ascii_file=params.filename_fraction_recent_groundwaterload_nat, numtype=float,mask=params.mask) nle_ag = ascraster.Asciigrid(ascii_file=params.filename_leaching_ag, numtype=float,mask=params.mask) nle_nat = ascraster.Asciigrid(ascii_file=params.filename_leaching_nat, numtype=float,mask=params.mask) # Scenarios 1+2+3 surface water #for i in range(fgw_rec_ag.length): # fgw_rec_ag.set_data(i,1.0) ## *N BUDGET* # 'ag' nbud_ag = ascraster.duplicategrid(nin_ag) nbud_ag.substract(nup_ag) print_debug(nbud_ag,"nbud_ag =") # 'ara' nbud_ara = ascraster.duplicategrid(nin_ara) nbud_ara.substract(nup_ara) print_debug(nbud_ara,"nbud_ara =") # 'igl' nbud_igl = ascraster.duplicategrid(nin_igl) nbud_igl.substract(nup_igl) print_debug(nbud_igl,"nbud_igl =") # 'nat' nbud_nat = ascraster.duplicategrid(nin_nat) print_debug(nbud_nat,"nbud_nat =") ## *N load to surface water via groundwater due to *recent* N inputs* # 'ag' ngw_rec_ag = ascraster.duplicategrid(ngw_ag) ngw_rec_ag.multiply(fgw_rec_ag) print_debug(ngw_rec_ag,"ngw_rec_ag =") # 'nat' ngw_rec_nat = ascraster.duplicategrid(ngw_nat) ngw_rec_nat.multiply(fgw_rec_nat) print_debug(ngw_rec_nat,"ngw_rec_nat =") ## *LEACHING FRACTION* # 'ag' nbud_min_nsro_ag = ascraster.duplicategrid(nbud_ag) nbud_min_nsro_ag.substract(nsro_ag) fle_ag = griddivide(nle_ag,nbud_min_nsro_ag,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"fle_ag.asc") fle_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fle_ag,"fle_ag =") # 'nat' nbud_min_nsro_nat = ascraster.duplicategrid(nbud_nat) nbud_min_nsro_nat.substract(nsro_nat) fle_nat = griddivide(nle_nat,nbud_min_nsro_nat,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"fle_nat.asc") fle_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fle_nat,"fle_nat =") ## *N LEACHING* # 'ara' nle_ara = ascraster.duplicategrid(nbud_ara) nle_ara.substract(nsro_ara) nle_ara.multiply(fle_ag) fileout = os.path.join(params.outputdir,"nle_ara.asc") nle_ara.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nle_ara,"nle_ara =") # 'igl' nle_igl = ascraster.duplicategrid(nbud_igl) nle_igl.substract(nsro_igl) nle_igl.multiply(fle_ag) fileout = os.path.join(params.outputdir,"nle_igl.asc") nle_igl.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nle_igl,"nle_igl =") ## *FRACTION OF RECENT DELIVERY TO LEACHING* (fraction of N leaching that is delivered to surface water via groundwater in first x years) # 'ag' fgw_rec_le_ag = griddivide(ngw_rec_ag,nle_ag,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"fgw_rec_le_ag.asc") fgw_rec_le_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fgw_rec_le_ag,"fgw_rec_le_ag =") # 'nat' fgw_rec_le_nat = griddivide(ngw_rec_nat,nle_nat,default_nodata_value = 0) fileout = os.path.join(params.outputdir,"fgw_rec_le_nat.asc") fgw_rec_le_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fgw_rec_le_nat,"fgw_rec_le_nat =") ## *VARIABLE N LOAD TO SURFACE WATER* # 'ag' nload_var_ag = ascraster.duplicategrid(ngw_rec_ag) nload_var_ag.add(nsro_ag) fileout = os.path.join(params.outputdir,"nload_var_ag.asc") nload_var_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nload_var_ag,"nload_var_ag =") # 'nat' nload_var_nat = ascraster.duplicategrid(ngw_rec_nat) nload_var_nat.add(nsro_nat) fileout = os.path.join(params.outputdir,"nload_var_nat.asc") nload_var_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nload_var_nat,"nload_var_nat =") ## *FIXED LOAD TO SURFACE WATER* # 'ag' grid1 = ascraster.duplicategrid(fgw_rec_ag) for i in range(grid1.length): grid1.set_data(i,1.0) grid1.substract(fgw_rec_ag) nload_fixed_ag = ascraster.duplicategrid(ngw_ag) nload_fixed_ag.multiply(grid1) fileout = os.path.join(params.outputdir,"nload_fixed_ag.asc") nload_fixed_ag.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nload_fixed_ag,"nload_fixed_ag =") # 'nat' grid2 = ascraster.duplicategrid(fgw_rec_nat) for i in range(grid2.length): grid2.set_data(i,1.0) grid2.substract(fgw_rec_nat) nload_fixed_nat = ascraster.duplicategrid(ngw_nat) nload_fixed_nat.multiply(grid2) fileout = os.path.join(params.outputdir,"nload_fixed_nat.asc") nload_fixed_nat.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nload_fixed_nat,"nload_fixed_nat =") ## *TOTAL N LOAD FROM POINT SOURCES* nallo = ascraster.Asciigrid(ascii_file=params.filename_n_point_alloch_matter,numtype=float,mask=params.mask) nww = ascraster.Asciigrid(ascii_file=params.filename_n_point_wastewater,numtype=float,mask=params.mask) naqua = ascraster.Asciigrid(ascii_file=params.filename_n_point_aquaculture,numtype=float,mask=params.mask) ndep_sw = ascraster.Asciigrid(ascii_file=params.filename_n_point_dep_surfacewater,numtype=float,mask=params.mask) npoint_tot = ascraster.duplicategrid(nallo) npoint_tot.add(nww) npoint_tot.add(naqua) npoint_tot.add(ndep_sw) fileout = os.path.join(params.outputdir,"npoint_tot.asc") npoint_tot.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(npoint_tot,"npoint_tot =") ## *TOTAL N LOAD FROM EROSION* nero_ag = ascraster.Asciigrid(ascii_file=params.filename_n_in_erosion_ag,numtype=float,mask=params.mask) nero_nat = ascraster.Asciigrid(ascii_file=params.filename_n_in_erosion_nat,numtype=float,mask=params.mask) nero_tot = ascraster.duplicategrid(nero_ag) nero_tot.add(nero_nat) fileout = os.path.join(params.outputdir,"nero_tot.asc") nero_tot.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nero_tot,"nero_tot =") ## *TOTAL N LOAD TO SURFACE WATER* (Nload,tot = Nload,var,ag + Nload,var,nat + Ngw,fixed,ag + Ngw,fixed,nat + Npoint + Nero) nload_tot = ascraster.duplicategrid(nload_var_ag) nload_tot.add(nload_var_nat) nload_tot.add(nload_fixed_ag) nload_tot.add(nload_fixed_nat) nload_tot.add(npoint_tot) nload_tot.add(nero_tot) print_debug(nload_tot,"nload_tot =")
def clean_balance(params, N_bal_grass, N_bal_arable, N_bal_natural, grassarea, croparea, natarea, mouth_dict, basin): """ Adds all positive balances to one total balance. Balances are changed when balance term is smaller than params.epsilon_load. When area does not match with the balances, than the balances are made zero. Input argument check determines whether the negative mass is counted for. """ errorlevel = 10 if params.ldebug: print "Start with calculation of clean_balance." removed_balance_arable = ascraster.duplicategrid(N_bal_grass) removed_balance_arable.add_values(N_bal_grass.length * [0.0]) removed_balance_grs = ascraster.duplicategrid(N_bal_grass) removed_balance_grs.add_values(N_bal_grass.length * [0.0]) removed_balance_nat = ascraster.duplicategrid(N_bal_grass) removed_balance_nat.add_values(N_bal_grass.length * [0.0]) for icell in xrange(N_bal_grass.length): grass_cell = grassarea.get_data(icell, 0.0) N_bal_cell = N_bal_grass.get_data(icell, 0.0) if grass_cell > 0.0: if N_bal_cell < params.epsilon_load: # Make balance really zero removed_balance_grs.set_data(icell, N_bal_cell) N_bal_grass.set_data(icell, 0.0) elif N_bal_cell > 0.0: if N_bal_cell > errorlevel: print "Grass area and grasbalance do not belong to each other. Gras area = 0.0 and balance_grass = " + str( N_bal_cell ) N_bal_grass.set_data(icell, 0.0) removed_balance_grs.set_data(icell, N_bal_cell) elif N_bal_cell < 0.0: if N_bal_cell < -errorlevel: print "Grass area and grasbalance do not belong to each other. Gras area = 0.0 and balance_grass = " + str( N_bal_cell ) N_bal_grass.set_data(icell, 0.0) removed_balance_grs.set_data(icell, N_bal_cell) crop_cell = croparea.get_data(icell, 0.0) N_bal_cell = N_bal_arable.get_data(icell, 0.0) if crop_cell > 0.0: if N_bal_cell < params.epsilon_load: # Make balance really zero N_bal_arable.set_data(icell, 0.0) removed_balance_arable.set_data(icell, N_bal_cell) elif N_bal_cell > 0.0: if N_bal_cell > errorlevel: print "Crop area and cropbalance do not belong to each other. Crop area = 0.0 and balance_crop = " + str( N_bal_cell ) N_bal_arable.set_data(icell, 0.0) removed_balance_arable.set_data(icell, N_bal_cell) elif N_bal_cell < 0.0: if N_bal_cell < -errorlevel: print "Crop area and cropbalance do not belong to each other. Crop area = 0.0 and balance_crop = " + str( N_bal_cell ) N_bal_arable.set_data(icell, 0.0) removed_balance_arable.set_data(icell, N_bal_cell) nat_cell = natarea.get_data(icell, 0.0) N_bal_cell = N_bal_natural.get_data(icell, 0.0) if nat_cell > 0.0: if N_bal_cell < params.epsilon_load: # Make balance really zero N_bal_natural.set_data(icell, 0.0) removed_balance_nat.set_data(icell, N_bal_cell) elif N_bal_cell > 0.0: if N_bal_cell > errorlevel: print "Natural area and natural balance do not belong to each other. Natural area = 0.0 and balance_nat = " + str( N_bal_cell ) N_bal_natural.set_data(icell, 0.0) removed_balance_nat.set_data(icell, N_bal_cell) elif N_bal_cell < 0.0: if N_bal_cell < -errorlevel: print "Natural area and natural balance do not belong to each other. Natural area = 0.0 and balance_nat = " + str( N_bal_cell ) N_bal_natural.set_data(icell, 0.0) removed_balance_nat.set_data(icell, N_bal_cell) return N_bal_grass, N_bal_arable, N_bal_natural, removed_balance_arable, removed_balance_grs, removed_balance_nat
def calculate_subgrid_retention(params,mask,mouth_dict,basin,lake_icell_dict,load,\ water_body,pnet,vf): ''' The subgrid retention is based on Wollheim (2006, GBC). This method is based on the stream order. In each cell, which is not a lake or reservoir, the subgrid retention is calculated. Only the local situation is used. For the load only the diffuse source from this cell are used. The runoff is used (so only local water). Also the concentration effect or temperature effect on retention is not used here. ''' # Make the subgrid stream order properties. # Setup the stream order river length,area and distribution and flowpath. Everything is stored in params. define_subgrid_streamorder(params) # Set the relation between concentration and net uptake velocity try: accuflux_retention.set_conc_relation_retention(params) except AttributeError: # This function is only for N and not for P pass # Make output rasters load_grid = ascraster.duplicategrid(load) retention = ascraster.duplicategrid(load) # Make nodata on all cells. retention.add_values(retention.length*[retention.nodata_value]) retentionload = ascraster.duplicategrid(retention) # Read water temperature temperature = ascraster.Asciigrid(ascii_file=params.water_temperature,mask=mask,numtype=float) # Loop over all cells: for icell in range(load_grid.length): # Get mass flux at the cell. load_cell = load_grid.get_data(icell) if (load_cell == None): # No data value continue if load_cell < 0.0: print("Negative mass flow of " + str(load_cell) + " at cell: " + str(icell)) # Go to next cell. continue # Retention in cell water_body_cell = water_body.get_data(icell,0) if (water_body_cell > 0): runoff_cell = pnet.get_data(icell,0.0) # Check whether this cell is an outflow of a lake/reservoir try: loutflow = lake_icell_dict[icell].outcell except KeyError: # No lake or reservoir loutflow = -1 try: if (loutflow == -1): # Normal cell, no lake or reservoir. # Default temperature of 20C because then temperature has no effect. temperature_cell = temperature.get_data(icell,20.0) ret_cell = calculate_localretention(params,runoff_cell,vf,load_cell,temperature_cell) else: #TODO: local retention when it is a lake or reservoir. For example as normal retention * fr_land. # Lake or reservoir. ret_cell = 0.0 except OverflowError: raise OverflowError else: ret_cell = 0.0 # Fill retention grid with retention value and retention load retention.set_data(icell,ret_cell) retentionload.set_data(icell,load_cell*ret_cell) # Write to output files retention.write_ascii_file(os.path.join(params.outputdir,"retention_subgrid.asc")) retentionload.write_ascii_file(os.path.join(params.outputdir,"removed_subgridload.asc")) # Write in mouth_dict database aggregate.aggregate_grid(basin,retentionload,mouth_dict,item="retentionload_subgrid") aggregate.aggregate_grid(basin,load_grid,mouth_dict,item="subgrid_load") # Put the retention_subgrid of the river in the mouth database for key in list(mouth_dict.keys()): try: mouth_dict[key].retention_subgrid = mouth_dict[key].retentionload_subgrid/mouth_dict[key].subgrid_load except ZeroDivisionError: mouth_dict[key].retention_subgrid = 0.0 return retentionload,retention
def calculate(params,mask,isocode,isogrid): ''' Allocation of fertilizer on the basis of agricultural landarea grid. The new map of agricultural land in km2 is returned as well as the N and P fertilizer. ''' # Read region codes (regcodes) reggrid = ascraster.Asciigrid(ascii_file=params.fileregion,mask=mask,numtype=int) # Make a list of isocodes for the provinces. regcode = list(set(reggrid.values)) # Read P fertilizer per region, missing regions are set to zero. Pfert_reg = data_class.get_data(params.filePfertuse,year=params.year,sep=params.sep,isocode=regcode,method=0,weighing=0.0) print_debug("Pfert_reg",Pfert_reg) # Read N fertilizer per region, missing regions are set to zero. Nfert_reg = data_class.get_data(params.fileNfertuse,year=params.year,sep=params.sep,isocode=regcode,method=0,weighing=0.0) print_debug("Nfert_reg",Nfert_reg) # Read agricultural land per province, missing provinces are set to zero. agri_area_table = data_class.get_data(params.filefertarea,year=params.year,sep=params.sep,isocode=isocode,method=0,weighing=0.0) print_debug("agri_area_table",agri_area_table) # Read the basic map with the amount of agricultural land in km2 per grid cell agriland = ascraster.Asciigrid(ascii_file=params.fileagrilandarea,mask=mask,numtype=float) # Read the basic map with the amount of land in km2 per grid cell arealand = ascraster.Asciigrid(ascii_file=params.landarea,mask=mask,numtype=float) # Create two output grids with zeros and fill these with the ranking method. agri_area = ascraster.duplicategrid(agriland) agri_area.add_values(agri_area.length * [0.0]) Pfert = ascraster.duplicategrid(agri_area) Nfert = ascraster.duplicategrid(agri_area) # Make a dictionairy of pointers for all the isocodes in the grid. pointer_dict = {} for icell in xrange(isogrid.length): iso = isogrid.get_data(icell) if (iso != None): iso = int(iso) try: pointer_dict[iso].append(icell) except KeyError: pointer_dict[iso] = [icell] for key in isocode: # Select agricultural land of the key country # First step is to allocate the agricultural area for each province. weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: pointer1 = [] sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: area = agriland.get_data(icell,0.0) maxarea = arealand.get_data(icell,0.0) # Fill weighing data and max data qmax_key.append(maxarea) weight_key.append(area) sumqmax += qmax_key[-1] sumweight += weight_key[-1] if (sumweight < 0.0001): # Make uniform weighing to all cells. for icell in range(len(weight_key)): weight_key[icell] = 1 sumweight += weight_key[icell] # Take the table information on agricultural area. area_demand = agri_area_table[key] if (area_demand > sumqmax): raise MyError("It is not possible to allocate " + str(area_demand) + " km2 in provincenumber " + str(key),\ "Maximum area that is possible to allocate in this province is: "+str(sumqmax)) # Do the allocation area_new = allocweighing.allocweighing(area_demand,sumweight,weight_key,qmax_key) if (abs(sum(area_new) - agri_area_table[key]) > 0.001*agri_area_table[key]): print "***** There is not enough allocated for agri_area for region "+str(key)+". Difference: " + str(agri_area_table[key]-sum(area_new)) print "***** Needed for agri_area for region "+str(key)+" " + str(agri_area_table[key]) # Fill gridded result for item in xrange(len(area_new)): agri_area.set_data(pointer1[item],area_new[item]) # Now the fertilizer is allocated to the gridcells, based on agricultural land area. This means that # each grid cell will have another load but the same application rate (kg N/ha) pointer_dict = {} for icell in xrange(reggrid.length): iso = reggrid.get_data(icell) if (iso != None): iso = int(iso) try: pointer_dict[iso].append(icell) except KeyError: pointer_dict[iso] = [icell] for key in regcode: weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: pointer1 = [] sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: # Note the new map of the previous step is used here. area = agri_area.get_data(icell,0.0) maxarea = 10000000. # Fill weighing data and max data qmax_key.append(maxarea) weight_key.append(area) sumqmax += qmax_key[-1] sumweight += weight_key[-1] if (sumweight < 0.0001): # Make uniform weighing to all cells. for icell in range(len(weight_key)): weight_key[icell] = 1 sumweight += weight_key[icell] # Grid these country connected population data with help of the population density map fert_demand = Nfert_reg[key] fert_new = allocweighing.allocweighing(fert_demand,sumweight,weight_key,qmax_key) if (abs(sum(fert_new) - Nfert_reg[key]) > 0.001*Nfert_reg[key]): print "***** There is not enough allocated for Nfert_reg for region "+str(key)+". Difference: " + str(Nfert_reg[key]-sum(fert_new)) print "***** Needed for Nfert_reg for region "+str(key)+" " + str(Nfert_reg[key]) # Fill gridded result for item in xrange(len(fert_new)): Nfert.set_data(pointer1[item],fert_new[item]) for key in regcode: weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: pointer1 = [] sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: # Note the new map of the previous step is used here. area = agri_area.get_data(icell,0.0) maxarea = 10000000. # Fill weighing data and max data qmax_key.append(maxarea) weight_key.append(area) sumqmax += qmax_key[-1] sumweight += weight_key[-1] if (sumweight < 0.0001): # Make uniform weighing to all cells. for icell in range(len(weight_key)): weight_key[icell] = 1 sumweight += weight_key[icell] # Grid these country connected population data with help of the population density map fert_demand = Pfert_reg[key] # Change fertilizer from P2O5 to P fert_demand *= 62.0/142.0 fert_new = allocweighing.allocweighing(fert_demand,sumweight,weight_key,qmax_key) if (abs(sum(fert_new) - Pfert_reg[key]* 62.0/142.0) > 0.001*Pfert_reg[key]* 62.0/142.0): print "***** There is not enough allocated for Pfert_reg for region "+str(key)+". Difference: " + str(Pfert_reg[key]* (62.0/142.0)-sum(fert_new)) print "***** Needed for Pfert_reg for region "+str(key)+" " + str(Pfert_reg[key]) # Fill gridded result for item in xrange(len(fert_new)): Pfert.set_data(pointer1[item],fert_new[item]) # Write to output file agri_area.write_ascii_file(params.fileagri_area) Nfert.write_ascii_file(params.fileNfert) Pfert.write_ascii_file(params.filePfert) total = sum(agri_area.values) print "Total agricultural area in km2: ",total print "Total N fertilzer in kg N: ",sum(Nfert.values) print "Total P fertilizer in kg P: ",sum(Pfert.values) print "Total N fertilzer in kg N/ha: ",sum(Nfert.values)/(100*total) print "Total P fertilizer in kg P/ha: ",sum(Pfert.values)/(100*total) return agri_area,Nfert,Pfert
def calculate(params): #print("The critical N deposition rate is " + str(params.crit_dep) + " kg N ha-1 yr-1") # load needed variables for calculations biome = ascraster.Asciigrid(ascii_file=os.path.join(params.inputdir,"gnlct.asc") ,numtype=float,mask=params.mask) a_tot = ascraster.Asciigrid(ascii_file=os.path.join(params.inputdir,"a_tot.asc") ,numtype=float,mask=params.mask) nox_em = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"nox_em.asc") ,numtype=float,mask=params.mask) nh3_tot_egl = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"nh3_tot_egl.asc") ,numtype=float,mask=params.mask) nh3_ef_man_agri = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"nh3_ef_man_agri.asc") ,numtype=float,mask=params.mask) nh3_ef_fert_agri = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"nh3_ef_fert_agri.asc"),numtype=float,mask=params.mask) frnfe_agri = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"frnfe_agri.asc") ,numtype=float,mask=params.mask) fagri = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"fagri.asc") ,numtype=float,mask=params.mask) n_fix_agri = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"n_fix_agri.asc") ,numtype=float,mask=params.mask) fsro_ag = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"fsro_ag.asc") ,numtype=float,mask=params.mask) frnup_agri = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"frnup_agri.asc") ,numtype=float,mask=params.mask) n_up_max = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"n_up_max.asc") ,numtype=float,mask=params.mask) n_in_max = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"n_in_max.asc") ,numtype=float,mask=params.mask) # make grid with critical N deposition per biome ndep_crit_ha = ascraster.duplicategrid(n_fix_agri) # watch out: can ndep_crit_ha become both -9999 and -1 (NA value?) for i in range(ndep_crit_ha.length): ndep_crit_ha.set_data(i,-9999) for icell in range(biome.length): val = biome.get_data(icell) # Ice (7) or Hot desert (16) if (val == 7 or val == 16): cl = 5.0 # Boreal forest (10), Cool coniferous forest (11) or scrubland (17) elif (val == 10 or val == 11 or val == 17): cl = 7.5 # Tundra (8) or wooded tundra (9)or Warm mixed forest (14) elif (val == 8 or val == 9 or val == 14): cl = 10.0 # Temperate mixed forest (12) Temperate deciduous forest (13) elif (val == 12 or val == 13): cl = 12.5 # Savanna (18) elif (val == 18): cl = 15.0 # Grassland/steppe (15) elif (val == 15): cl = 17.5 # Tropical woodland (19) or Tropical forest (20) elif (val == 19 or val == 20): cl = 20 # Biome can also have value 0 or none (-1) else: continue ndep_crit_ha.set_data(icell,cl) print_debug(biome,"The biome ID is") fileout = os.path.join(params.outputdir,"ndep_crit_ha.asc") ndep_crit_ha.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_crit_ha,"The critical N deposition per hectare is") # calculate total critical deposition: Ndep,tot(crit) = Ndep,crit,ha * A ndep_crit_tot = ascraster.duplicategrid(ndep_crit_ha) ndep_crit_tot.multiply(a_tot) #fileout = os.path.join(params.outputdir,"ndep_crit_tot.asc") #ndep_crit_tot.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(ndep_crit_tot,"The total critical N deposition is") # calculate critical N input from manure nh3_em_crit_agri = ascraster.duplicategrid(ndep_crit_tot) nh3_em_crit_agri.substract(nox_em) nh3_em_crit_agri.substract(nh3_tot_egl) one_grid = ascraster.duplicategrid(frnfe_agri) for i in range(one_grid.length): one_grid.set_data(i,1.0) one_min_frnfe = ascraster.duplicategrid(one_grid) one_min_frnfe.substract(frnfe_agri) frnfe_division = ascraster.duplicategrid(frnfe_agri) frnfe_division.divide(one_min_frnfe, default_nodata_value = -9999) denominator = ascraster.duplicategrid(frnfe_division) denominator.multiply(nh3_ef_fert_agri) denominator.add(nh3_ef_man_agri) nman_crit_dep = ascraster.duplicategrid(nh3_em_crit_agri) nman_crit_dep.divide(denominator, default_nodata_value = -9999) for icell in range (nman_crit_dep.length): nman = nman_crit_dep.get_data(icell) if (nman is None): continue if (nman < 0): man = 0 else: continue nman_crit_dep.set_data(icell,man) fileout = os.path.join(params.outputdir,"nman_crit_dep.asc") nman_crit_dep.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nman_crit_dep,"The critical N input from manure for the N deposition criterion is") # calculate critical N input from fertilizer nfert_crit_dep = ascraster.duplicategrid(nman_crit_dep) nfert_crit_dep.multiply(frnfe_division) fileout = os.path.join(params.outputdir,"nfert_crit_dep.asc") nfert_crit_dep.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nfert_crit_dep,"The critical N input from fertilizer for the N deposition criterion is") # calculate related N deposition nh3em_man_crit_dep = ascraster.duplicategrid(nman_crit_dep) nh3em_man_crit_dep.multiply(nh3_ef_man_agri) fileout = os.path.join(params.outputdir,"nh3em_man_crit_dep.asc") nh3em_man_crit_dep.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) nh3em_fert_crit_dep = ascraster.duplicategrid(nfert_crit_dep) nh3em_fert_crit_dep.multiply(nh3_ef_fert_agri) fileout = os.path.join(params.outputdir,"nh3em_fert_crit_dep.asc") nh3em_fert_crit_dep.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) nh3em_crit_dep = ascraster.duplicategrid(nh3em_fert_crit_dep) nh3em_crit_dep.add(nh3em_man_crit_dep) # fileout = os.path.join(params.outputdir,"nh3em_crit_dep.asc") nh3em_crit_dep.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) # #nh3em_crit_dep.add(nh3_tot_egl) ndep_crit_dep_tot = ascraster.duplicategrid(nh3em_crit_dep) ndep_crit_dep_tot.add(nox_em) ndep_crit_dep_tot.add(nh3_tot_egl) print_debug(ndep_crit_dep_tot,"The total critical N deposition for the N deposition criterion is") ndep_crit_dep_agri = ascraster.duplicategrid(ndep_crit_dep_tot) ndep_crit_dep_agri.multiply(fagri) print_debug(ndep_crit_dep_agri,"The critical N deposition on agricultural land for the N deposition criterion is") # calculate total critical N inputs wrt N deposition nin_crit_dep_agri = ascraster.duplicategrid(nman_crit_dep) nin_crit_dep_agri.add(nfert_crit_dep) nin_crit_dep_agri.add(ndep_crit_dep_agri) nin_crit_dep_agri.add(n_fix_agri) fileout = os.path.join(params.outputdir,"nin_crit_dep_agri.asc") nin_crit_dep_agri.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nin_crit_dep_agri,"The total critical input to agriclture for the N deposition criterion is") # calculate N surface runoff at critical N inputs deposition nsro_crit_dep_agri = ascraster.duplicategrid(nin_crit_dep_agri) nsro_crit_dep_agri.multiply(fsro_ag) print_debug(nsro_crit_dep_agri,"The critical N surface runoff for the N deposition criterion is") # calculate N uptake at critical N inputs deposition nup_crit_dep_agri = ascraster.duplicategrid(nin_crit_dep_agri) nup_crit_dep_agri.substract(nsro_crit_dep_agri) nup_crit_dep_agri.multiply(frnup_agri) fileout = os.path.join(params.outputdir,"nup_crit_dep_agri.asc") nup_crit_dep_agri.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nup_crit_dep_agri,"The N uptake for the N deposition criterion is") # calculate implied NUE nue_crit_dep_agri = ascraster.duplicategrid(nup_crit_dep_agri) nue_crit_dep_agri.divide(nin_crit_dep_agri, default_nodata_value = -9999) #fileout = os.path.join(params.outputdir,"nue_crit_dep_agri.asc") #nue_crit_dep_agri.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(nue_crit_dep_agri,"The NUE for the N deposition criterion is") # calculate maximum uptake fraction fnup_max_dep = ascraster.duplicategrid(n_up_max) fnup_max_dep.divide(nup_crit_dep_agri) fileout = os.path.join(params.outputdir,"fnup_max_dep.asc") fnup_max_dep.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fnup_max_dep,"The fraction maximum uptake / critical uptake for deposition is") # calculate correction factor for those cases where critical N uptake exceeds max. N uptake fnup_corr_dep = ascraster.duplicategrid(n_in_max) fnup_corr_dep.substract(n_fix_agri) temp2 = ascraster.duplicategrid(nh3_tot_egl) temp2.add(nox_em) temp2.multiply(fagri) fnup_corr_dep.substract(temp2) temp3 = ascraster.duplicategrid(nh3em_crit_dep) temp3.multiply(fagri) temp3.add(nman_crit_dep) temp3.add(nfert_crit_dep) fnup_corr_dep.divide(temp3, default_nodata_value = -9999) fileout = os.path.join(params.outputdir,"fnup_corr_dep.asc") fnup_corr_dep.write_ascii_file(fileout,output_nodata_value=-9999,compress=params.lcompress) print_debug(fnup_corr_dep,"The correction factor for cases where Nup,crit>Nup,max is") ########### FORWARD CALCULATIONS TO CHECK ########### if icell_debug<0: pass else: fw = ndep_crit_dep_tot.get_data(icell_debug) bw = ndep_crit_tot.get_data(icell_debug) if fw is None: print("FW / BW TEST: Forward calculation not possible (Nin,crit=None)") else: fw = round(fw,4) bw = round(bw,4) if fw == bw: print("FW / BW TEST: SUCCESFUL") else: print("FW / BW TEST: NOT SUCCESFUL") ############################################################################################
def calculate_water_litho(params,mask): ''' Calculate the total discharge for each litho class. This is needed to fill in the table of litho_lib with information from Jens Hartmann ''' pnet = ascraster.Asciigrid(ascii_file=params.pnet,mask=mask,numtype=float) if params.ldebug: print(params.pnet + " has been read.") landarea = ascraster.Asciigrid(ascii_file=params.landarea,mask=mask,numtype=float) if params.ldebug: print(params.landarea + " has been read.") # Calculate accumulated water flux of each grid cell to the mouth of the river basin. Make discharge in km3 # Convert pnet [mm/yr] to km3 by multiplying with landarea and 10e-6 (conversion from mm to km) water = ascraster.duplicategrid(landarea) for icell in range(landarea.length): wt = pnet.get_data(icell,0.0) * landarea.get_data(icell,0.0) * 1.0e-6 water.set_data(icell,wt) # Compare first grid with another grid of the run equal = ascraster.compare_grids(params.pgrass,os.path.join(params.litho_dir,"nodatgrid.asc")) if (not equal): raise MyError("Litho maps don't have same header as other input files.") grid0 = ascraster.Asciigrid(ascii_file=os.path.join(params.litho_dir,"nodatgrid.asc"),\ mask=mask,numtype=float) # Check whether there are fractions given in grid0 max_value = max(grid0.values) if (max_value > 1.0): raise MyError("Litho maps must be a fraction. Found values greater than 1 (found: " + str(max_value) + ").") # Make a default output list: out = len(litho_lib) * [0.0] area = len(litho_lib) * [0.0] # Loop over all the classes of litho map. Start with class 3 because first two are major water bodies and ice: for iclass in range(1,18): print(iclass) # Check header of input file equal = ascraster.compare_grids(params.pgrass,os.path.join(params.litho_dir,"grid" + str(iclass) + ".asc")) if (not equal): raise MyError("Litho maps don't have same header as other input files.") grid = ascraster.Asciigrid(ascii_file=os.path.join(params.litho_dir,"grid" + str(iclass) + ".asc"),\ mask=mask,numtype=float) print(os.path.join(params.litho_dir,"grid" + str(iclass) + ".asc") + " read.") for icell in range(0,grid0.length): grid0_cell = grid0.get_data(icell,0.0) if (grid0_cell < 1.0): # There is something to do. grid_cell = grid.get_data(icell,0.0) if (grid_cell > 0.0): # There is something of this class in this cell: out[iclass] += grid_cell * water.get_data(icell,0.0) area[iclass] += grid_cell * landarea.get_data(icell,0.0) if (iclass == 1): out[0] += grid0_cell * water.get_data(icell,0.0) area[0] += grid0_cell * landarea.get_data(icell,0.0) return out,area
def calculate(params, mask, mouth_dict, basin): """ Calculates the area of each grass and arable land use cell. It returns two ascraster object with the area grass and area arable land in ha """ # Read grass files gras1 = ascraster.Asciigrid(ascii_file=params.pgrass, mask=mask, numtype=float) if params.ldebug: print params.pgrass + " has been read." gras2 = ascraster.Asciigrid(ascii_file=params.igrass, mask=mask, numtype=float) if params.ldebug: print params.igrass + " has been read." # Read crop files crop1 = ascraster.Asciigrid(ascii_file=params.cropmixp, mask=mask, numtype=float) if params.ldebug: print params.cropmixp + " has been read." crop2 = ascraster.Asciigrid(ascii_file=params.croppasp, mask=mask, numtype=float) if params.ldebug: print params.croppasp + " has been read." # Read land area landarea = ascraster.Asciigrid(ascii_file=params.landarea, mask=mask, numtype=float) if params.ldebug: print params.landarea + " has been read." # Aggregate landarea on river basin scale aggregate.aggregate_grid(basin, landarea, mouth_dict, item="landarea") # Make a copy (alias not a deepcopy) of the return values area_grass = gras1 area_crop = crop1 area_natural = landarea # Calculate the total grass and crop land in ha. Because the LU file are in percentage, and the # landarea is in km2, the product of (crop1_cell+crop2_cell) * landarea_cell is then in ha. for icell in range(crop1.length): crop1_cell = crop1.get_data(icell, 0.0) crop2_cell = crop2.get_data(icell, 0.0) gras1_cell = gras1.get_data(icell, 0.0) gras2_cell = gras2.get_data(icell, 0.0) landarea_cell = landarea.get_data(icell, 0.0) # Put result in crop1 and gras1 crop_area = landarea_cell * (crop1_cell + crop2_cell) gras_area = landarea_cell * (gras1_cell + gras2_cell) if (crop_area + gras_area) - (100.0 * landarea_cell) > params.epsilon: print "Crop and grass area is too large: ", crop_area + gras_area, 100.0 * landarea_cell, ( crop_area + gras_area ) - (100.0 * landarea_cell) try: fac = (100 * landarea_cell) / (crop_area + gras_area) except ZeroDivisionError: fac = 0.0 crop_area *= fac gras_area *= fac nat_area = max(0.0, (100.0 * landarea_cell) - crop_area - gras_area) # Put result in the maps in km2 (factor 0.01) area_crop.set_data(icell, 0.01 * crop_area) area_grass.set_data(icell, 0.01 * gras_area) area_natural.set_data(icell, 0.01 * nat_area) # Aggregate landarea on river basin scale aggregate.aggregate_grid(basin, area_crop, mouth_dict, item="croparea") aggregate.aggregate_grid(basin, area_grass, mouth_dict, item="grasarea") aggregate.aggregate_grid(basin, area_natural, mouth_dict, item="natarea") # Calculate the number of cells in a region/basin one = ascraster.duplicategrid(landarea) # Set all cells to one. one.add_values(one.length * [1.0]) aggregate.aggregate_grid(basin, one, mouth_dict, item="number_of_cells") # Delete the grid objects which are used anymore del crop1 del crop2 del gras1 del gras2 del landarea del one return area_grass, area_crop, area_natural
def calculate(params,mask,mouth_dict,lake_icell_dict,basin,discharge,lddmap): ''' This function calculates the residence time in the grid cells. ''' # Read in the PCGLOBWB files water_storage_file = params.water_storage water_storage = ascraster.Asciigrid(ascii_file=water_storage_file,\ mask=mask,numtype=float) # Change water_storage from m3 into km3 water_storage.multiply(1.0e-9) # Residence time is the volume divided by discharge. # Water storage is in km3. Discharge is km3/yr. So residence time is in years. residence_time_grid = ascraster.duplicategrid(water_storage) # Calculate residence times by dividing water_storage through discharge. residence_time_grid.divide(discharge,default_nodata_value = 0.0) # If residence times are very high (e.g in dry areas), # set the residence time to a maximum # Apply maximum on gridcells which are not the outlet of a reservoir or lake. for icell in xrange(residence_time_grid.length): resi = residence_time_grid.get_data(icell,-1) if (resi > params.max_residence_time_per_cell): # Check whether this is a outlet of a lake or reservoir try: outcell = lake_icell_dict[icell].outcell if (outcell == 1): # Outlet of a lake/reservoir if (resi > params.max_residence_time_per_lake): resi = params.max_residence_time_per_lake # Change also the dictionary value of this waterbody lake_icell_dict[icell].residence_time = resi else: resi = params.max_residence_time_per_cell residence_time_grid.set_data(icell,resi) except KeyError: # This is no reservoir or lake residence_time_grid.set_data(icell,params.max_residence_time_per_cell) # Put residence time of the water body (lakes and reservoirs) in the grid. for icell in lake_icell_dict: if (lake_icell_dict[icell].outcell == 1): residence_time_grid.set_data(icell,lake_icell_dict[icell].residence_time) # Write residence_time to output file: residence_time_grid.write_ascii_file(os.path.join(params.outputdir,"residence_time.asc")) # Calculate the travel time of each grid cell to the river mouth traveltime = accuflux.accutime(lddmap,residence_time_grid,lake_icell_dict) traveltime.write_ascii_file(os.path.join(params.outputdir,"traveltime.asc")) # Aggregate traveltime over the river basin. aggregate.aggregate_grid(basin,traveltime,mouth_dict,item="sum_traveltime") # Calculate the average traveltime for each river basin for key in mouth_dict.keys(): try: mouth_dict[key].avg_traveltime = mouth_dict[key].sum_traveltime/mouth_dict[key].number_of_cells except ZeroDivisionError: mouth_dict[key].avg_traveltime = 0.0 except AttributeError: pass return residence_time_grid,traveltime
def calculate_water_litho(params,mask): ''' Calculate the total discharge for each litho class. This is needed to fill in the table of litho_lib with information from Jens Hartmann ''' pnet = ascraster.Asciigrid(ascii_file=params.pnet,mask=mask,numtype=float) if params.ldebug: print params.pnet + " has been read." landarea = ascraster.Asciigrid(ascii_file=params.landarea,mask=mask,numtype=float) if params.ldebug: print params.landarea + " has been read." # Calculate accumulated water flux of each grid cell to the mouth of the river basin. Make discharge in km3 # Convert pnet [mm/yr] to km3 by multiplying with landarea and 10e-6 (conversion from mm to km) water = ascraster.duplicategrid(landarea) for icell in range(landarea.length): wt = pnet.get_data(icell,0.0) * landarea.get_data(icell,0.0) * 1.0e-6 water.set_data(icell,wt) # Compare first grid with another grid of the run equal = ascraster.compare_grids(params.pgrass,os.path.join(params.litho_dir,"nodatgrid.asc")) if (not equal): raise MyError("Litho maps don't have same header as other input files.") grid0 = ascraster.Asciigrid(ascii_file=os.path.join(params.litho_dir,"nodatgrid.asc"),\ mask=mask,numtype=float) # Check whether there are fractions given in grid0 max_value = max(grid0.values) if (max_value > 1.0): raise MyError("Litho maps must be a fraction. Found values greater than 1 (found: " + str(max_value) + ").") # Make a default output list: out = len(litho_lib) * [0.0] area = len(litho_lib) * [0.0] # Loop over all the classes of litho map. Start with class 3 because first two are major water bodies and ice: for iclass in range(1,18): print iclass # Check header of input file equal = ascraster.compare_grids(params.pgrass,os.path.join(params.litho_dir,"grid" + str(iclass) + ".asc")) if (not equal): raise MyError("Litho maps don't have same header as other input files.") grid = ascraster.Asciigrid(ascii_file=os.path.join(params.litho_dir,"grid" + str(iclass) + ".asc"),\ mask=mask,numtype=float) print os.path.join(params.litho_dir,"grid" + str(iclass) + ".asc") + " read." for icell in range(0,grid0.length): grid0_cell = grid0.get_data(icell,0.0) if (grid0_cell < 1.0): # There is something to do. grid_cell = grid.get_data(icell,0.0) if (grid_cell > 0.0): # There is something of this class in this cell: out[iclass] += grid_cell * water.get_data(icell,0.0) area[iclass] += grid_cell * landarea.get_data(icell,0.0) if (iclass == 1): out[0] += grid0_cell * water.get_data(icell,0.0) area[0] += grid0_cell * landarea.get_data(icell,0.0) return out,area
import sys __general = os.path.join(os.getcwd(), 'trunk') if os.path.exists(__general): sys.path.insert(0, __general) print(__general + " is added to the python search path for modules.") import ascraster import my_sys # First three tests are on a grid with no nodata # Test 1 # Multiply grid1 with a scalar of type integer # Read ascii grid grid1 = ascraster.Asciigrid(ascii_file='testgrid1.asc', numtype=int) factor = 1 grid1_old = ascraster.duplicategrid(grid1) grid1.multiply(factor) # Grid1 and grid1_old must be the same ltest1 = 1 for i in range(grid1_old.length): if (grid1.values[i] != grid1_old.values[i]): ltest1 = 0 print('Test 1 is not a succes for item: ' + str(i) + ". Values found: " + str(grid1.values[i]) + " and " + str(grid1_old.values[i])) if (ltest1 == 1): print("Test1 passed.") else: print("Multiplying with factor 1") print(grid1_old.values) print(grid1.values)
def accuflux(lddmap,fluxmap,retentionmap=None,negative_flux_possible=0): ''' ACCUFLUX Based on Gerard van Drecht, RIVM, Bilthoven, February 2002 April 2002: accu fraction flux and accu fraction state added PURPOSE: Accumulate flow of mass, given by a material map [grid], along a flowpath, given by a local drain direction(LDD) map [grid]. The output map contains accumulated flux [grid]. All files are ascii-grid formatted. Lddmap: network of local drain directions flow_direction can be coded as follows: UNH/GRDC PCraster(LDD) 32 64 128 meaning: NW N NE 7 8 9 16 - 1 W - E 4 5 6 8 4 2 SW S SE 1 2 3 We use the PCraster LDD-format; negative and zero values are assumed ''' # Make output rasters accufluxmap = ascraster.duplicategrid(fluxmap) # Make nodata on all cells. accufluxmap.add_values(accufluxmap.length*[accufluxmap.nodata_value]) #print "Length accufluxmap:",accufluxmap.length #print "Length fluxmap:",fluxmap.length # Loop over all cells: for icell in range(lddmap.length): #print "Start cell:",icell,accufluxmap.mask[icell] # Get mass flux at the cell. flux = fluxmap.get_data(icell) if (flux == None): # No data value continue if (flux < 0.0): if (negative_flux_possible == 0): print "Negative mass flow of " + str(flux) + " at cell: " + str(icell) # Go to next cell. continue end_of_path=False icell_loop = icell while not end_of_path: # Get direction of the ldd direction = int(lddmap.get_data(icell_loop,-1)) if (direction < 1): #print "Something is wrong with the lddmap (< 1). No river mouth found for icell: ",icell, " with load: ", flux, " and direction: ",direction # Go to next cell end_of_path=True elif (direction == 5): # Mouth of river basin is found. prev = accufluxmap.get_data(icell_loop,0.0) accufluxmap.set_data(icell_loop,prev + flux * factor(icell_loop,retentionmap)) # Go to next cell end_of_path=True elif (direction > 9): #print "Something is wrong with the lddmap (> 9). No river mouth found for icell: ",icell, " with load: ", flux, " and direction: ",direction # Go to next cell end_of_path=True else: prev = accufluxmap.get_data(icell_loop,0.0) flux = flux * factor(icell_loop,retentionmap) accufluxmap.set_data(icell_loop,prev + flux) # Go to next cell #print icell_loop,direction,accufluxmap.mask[icell_loop], icell_loop = goto_nextcell(icell_loop,direction,lddmap.ncols,mask=lddmap.mask) #print icell_loop,accufluxmap.mask[icell_loop] if (icell_loop < 0): # Already printed a message. Go to next grid cell. end_of_path=True return accufluxmap
def run_watermodel(args): ''' Run N model main routine @param listargs: list of arguments passed trough command-line or other script Must look like sys.argv so make sure is starts with scriptname. ''' # Parse command-line arguments and set parameters for script try: param = cmd_options_water.InputWater(args) params = param.options params_var = param.options_var except SystemExit: raise MyError("Error has occured in the reading of the commandline options.") # Start timer and logging s = my_sys.SimpleTimer() log = my_logging.Log(params.outputdir,"%s_%i.log" % (params.scenarioname,params.year)) print "Log will be written to %s" % log.logFile # If no arguments are provided do a run with defaults in params if len(args) == 0: log.write_and_print("No arguments provided: starting default run...") # time start of run log.write_and_print("Starting run....") log.write("# Parameters used:",print_time=False,lcomment=False) for option in str(params_var).split(", "): log.write("--%s = %s" % (option.split(": ")[0].strip("{").strip("'"), option.split(": ")[1].strip("}").strip("'")), print_time=False,lcomment=False) log.write("All parameters used:") for option in str(params).split(", "): log.write("# %s = %s" % (option.split(": ")[0].strip("{").strip("'"), option.split(": ")[1].strip("}").strip("'")), print_time=False,lcomment=False) log.write("# End of all parameters used.",print_time=False,lcomment=False) # Check whether there are command-line arguments which are not used if (len(param.args) > 0): txt = "The following command line arguments will not be used:" log.write_and_print(txt + str(param.args)) # Write svn information of input and scripts to log file. log.write("******************************************************",print_time=False,lcomment=True) log.write("Version information:",print_time=False,lcomment=True) log.write("Version information main script:",print_time=False,lcomment=True) log.write("Revision $LastChangedDate: 2013-09-25 13:37:10 +0200 (Tue, 25 Sep 2013)",print_time=False,lcomment=True) log.write("Date $LastChangedRevision: 344 $",print_time=False,lcomment=True) #message = get_versioninfo.get_versioninfo(params.inputdir,params.outputdir) #message.extend(get_versioninfo.get_versioninfo("tools",params.outputdir)) #for item in range(len(message)): # log.write(str(message[item]),print_time=False,lcomment=True) log.write("******************************************************",print_time=False,lcomment=True) # Read mask of the input grids. We take the iso grid as mask for this. # The mask takes care to do the calculations on an efficient way. Only # the grid cells which are in the mask are calculated and stored. if (params.lmask): mask = ascraster.create_mask(params.file_mask, 0.0,'GT',numtype=float) log.write_and_print(s.interval("Reading mask")) else: mask = None log.write_and_print(s.interval("No mask is used for this simulation.")) # Read original flow path direction map. Determination of the flow path is only possible in masked mode! # flowdir is expected on the fixed input directory. # if (params.lcreate_ldd_basinid == 1): # flowdir = ascraster.Asciigrid(ascii_file=os.path.join(params.fixinputdir,params.file_flowdir),mask=mask,numtype=int) # Change the flow dir numbers to PCraster format and create ldd and basinid map. # ldd = change_flowdir.change_flowdir(flowdir,mask,params.outputdir) # log.write_and_print(s.interval("Ldd conversion ready.")) # raise MyError0("Ready with creation of ldd and basinid") ldd = ascraster.Asciigrid(ascii_file=params.file_ldd,mask=mask,numtype=int) # Make dummy map with nodata in it. dummy_grid = ascraster.duplicategrid(ldd) # Make all values nodata dummy_grid.add_values(dummy_grid.length*[dummy_grid.nodata_value]) # Read landarea in km2 landarea_grid = ascraster.Asciigrid(ascii_file=params.landarea,mask=mask,numtype=float) # Convert landarea from m2 to km2 #landarea_grid.multiply(1.0e-6) # Calculate net precipitation in mm/yr #pnet = netprecip.calculate(params.inputdir,mask,params.outputdir) # Calculate accumulated water flux of each grid cell to the mouth of the river basin. Make discharge in km3 # Convert pnet [mm/yr] to km3 by multiplying with landarea (m2) and 10e-6 (conversion from mm to km) #water = ascraster.duplicategrid(landarea_grid) #for icell in range(landarea_grid.length): # wt = pnet.get_data(icell,0.0) * landarea_grid.get_data(icell,0.0) * 1.0e-6 # # Add water use of the population (and conversion from liters per day to km3 per year) # water.set_data(icell,wt) #discharge = accuflux.accuflux(ldd,water,negative_flux_possible=1) # Write discharge to output file: #discharge.write_ascii_file(params.filedischarge) #log.write_and_print(s.interval("Ready with calculating discharge.")) # Get the N emission from population. This are yearly loads. So divide with timespan. N_emiss_point = ascraster.Asciigrid(ascii_file=params.file_gemnsw,mask=mask,numtype=float) P_emiss_point = ascraster.Asciigrid(ascii_file=params.file_gempsw,mask=mask,numtype=float) N_emiss_point.divide(float(params.timespan)) P_emiss_point.divide(float(params.timespan)) # Retention on point sources N_emiss_point.multiply(1.0 - float(params.N_retention_point)) P_emiss_point.multiply(1.0 - float(params.P_retention_point)) # Get the fertilizer emission from agriculture N_emiss_agri_fert = ascraster.Asciigrid(ascii_file=params.fileNfert,mask=mask,numtype=float) P_emiss_agri_fert = ascraster.Asciigrid(ascii_file=params.filePfert,mask=mask,numtype=float) N_emiss_agri_fert.divide(float(params.timespan)) P_emiss_agri_fert.divide(float(params.timespan)) # Retention on agricultural sources N_emiss_agri_fert.multiply(1.0 - float(params.N_retention_agri)) P_emiss_agri_fert.multiply(1.0 - float(params.P_retention_agri)) # Get the manure emission from agriculture (livestock) N_emiss_agri_man = ascraster.Asciigrid(ascii_file=params.fileNmanure,mask=mask,numtype=float) P_emiss_agri_man = ascraster.Asciigrid(ascii_file=params.filePmanure,mask=mask,numtype=float) N_emiss_agri_man.divide(float(params.timespan)) P_emiss_agri_man.divide(float(params.timespan)) # Retention on agricultural sources N_emiss_agri_man.multiply(1.0 - float(params.N_retention_agri)) P_emiss_agri_man.multiply(1.0 - float(params.P_retention_agri)) # Get the emission from aquaculture N_emiss_aqua = ascraster.Asciigrid(ascii_file=params.fileNaqua,mask=mask,numtype=float) P_emiss_aqua = ascraster.Asciigrid(ascii_file=params.filePaqua,mask=mask,numtype=float) # Retention on aquaculture sources N_emiss_aqua.multiply(1.0 - float(params.N_retention_aqua)) P_emiss_aqua.multiply(1.0 - float(params.P_retention_aqua)) # Route all to the streams to the mouth of the river. accu_area = accuflux.accuflux(ldd,landarea_grid,negative_flux_possible=0) accu_N_emiss_point = accuflux.accuflux(ldd,N_emiss_point,negative_flux_possible=0) accu_P_emiss_point = accuflux.accuflux(ldd,P_emiss_point,negative_flux_possible=0) accu_N_emiss_agri_fert = accuflux.accuflux(ldd,N_emiss_agri_fert,negative_flux_possible=0) accu_P_emiss_agri_fert = accuflux.accuflux(ldd,P_emiss_agri_fert,negative_flux_possible=0) accu_N_emiss_agri_man = accuflux.accuflux(ldd,N_emiss_agri_man,negative_flux_possible=0) accu_P_emiss_agri_man = accuflux.accuflux(ldd,P_emiss_agri_man,negative_flux_possible=0) accu_N_emiss_aqua = accuflux.accuflux(ldd,N_emiss_aqua,negative_flux_possible=0) accu_P_emiss_aqua = accuflux.accuflux(ldd,P_emiss_aqua,negative_flux_possible=0) # Add all sources into one file. accu_N_emiss = ascraster.duplicategrid(accu_N_emiss_point) accu_N_emiss.add(accu_N_emiss_agri_fert) accu_N_emiss.add(accu_N_emiss_agri_man) accu_N_emiss.add(accu_N_emiss_aqua) accu_P_emiss = ascraster.duplicategrid(accu_P_emiss_point) accu_P_emiss.add(accu_P_emiss_agri_fert) accu_P_emiss.add(accu_P_emiss_agri_man) accu_P_emiss.add(accu_P_emiss_aqua) # Create retention grid for N and P. #Nret_grid = ascraster.duplicategrid(dummy_grid) #Nret_grid.add_values(Nret_grid.length*[params.N_retention]) #Pret_grid = ascraster.duplicategrid(dummy_grid) #Pret_grid.add_values(Nret_grid.length*[params.P_retention]) # Let the nitrogen flow through the basins. #accu_N_emiss = accuflux.accuflux(ldd,N_emiss,retentionmap=Nret_grid,negative_flux_possible=0) #accu_P_emiss = accuflux.accuflux(ldd,P_emiss,retentionmap=Pret_grid,negative_flux_possible=0) #accu_N_emiss = accuflux.accuflux(ldd,N_emiss,negative_flux_possible=0) #accu_P_emiss = accuflux.accuflux(ldd,P_emiss,negative_flux_possible=0) # Calculate the concentrations in the stream #N_conc = ascraster.duplicategrid(accu_N_emiss) #P_conc = ascraster.duplicategrid(accu_P_emiss) # Divide accu_N_emiss by discharge #N_conc.divide(discharge,default_nodata_value = 0.0) #P_conc.divide(discharge,default_nodata_value = 0.0) # Convert unit from kg/km3 to mgN/l #N_conc.multiply(1.0e-6) #P_conc.multiply(1.0e-6) # Write Nload and concentration to output file: accu_N_emiss.write_ascii_file(params.file_nload) #N_conc.write_ascii_file(params.file_nconc) accu_P_emiss.write_ascii_file(params.file_pload) #P_conc.write_ascii_file(params.file_pconc) log.write_and_print(s.interval("Ready with calculating of N and P load and concentration in grid cells.")) # Read basinid basinid = ascraster.Asciigrid(ascii_file=params.file_basinid,mask=mask,numtype=int) # Make a dictionary with the index of each river mouth mouth_dict = {} for icell in range(basinid.length): id = int(basinid.get_data(icell,-1)) if (id > 0): ldd_cell = int(ldd.get_data(icell,-1)) if (ldd_cell == 5): # I found a river mouth mouth_dict[id] = icell # Put accumulated information into a dictionary output_dict ={} for key in mouth_dict: output_dict[key] = general_class.General() output_dict[key].add_item("basinid",key) output_dict[key].add_item("Area",accu_area.get_data(mouth_dict[key])) output_dict[key].add_item("Nload_point",accu_N_emiss_point.get_data(mouth_dict[key])) output_dict[key].add_item("Nload_fert",accu_N_emiss_agri_fert.get_data(mouth_dict[key])) output_dict[key].add_item("Nload_manure",accu_N_emiss_agri_man.get_data(mouth_dict[key])) output_dict[key].add_item("Nload_aqua",accu_N_emiss_aqua.get_data(mouth_dict[key])) output_dict[key].add_item("Nload_total",accu_N_emiss.get_data(mouth_dict[key])) #output_dict[key].add_item("discharge",discharge.get_data(mouth_dict[key])) #output_dict[key].add_item("Nconc",N_conc.get_data(mouth_dict[key])) output_dict[key].add_item("Pload_point",accu_P_emiss_point.get_data(mouth_dict[key])) output_dict[key].add_item("Pload_fert",accu_P_emiss_agri_fert.get_data(mouth_dict[key])) output_dict[key].add_item("Pload_manure",accu_P_emiss_agri_man.get_data(mouth_dict[key])) output_dict[key].add_item("Pload_aqua",accu_P_emiss_aqua.get_data(mouth_dict[key])) output_dict[key].add_item("Pload_total",accu_P_emiss.get_data(mouth_dict[key])) #output_dict[key].add_item("Pconc",P_conc.get_data(mouth_dict[key])) # Make a list of keys and sort this for output purpose outputlist = [] for key in mouth_dict: outputlist.append(key) outputlist.sort() fp = open(params.fileoutput_table,"w") lheader = True for key in outputlist: output_dict[key].write(fp,lheader=lheader,sep=";") lheader = False fp.close() log.write_and_print(s.total("Total run")) del log
def clean_balance(params,N_bal_grass,N_bal_arable,N_bal_natural,\ grassarea,croparea,natarea,mouth_dict,basin): ''' Adds all positive balances to one total balance. Balances are changed when balance term is smaller than params.epsilon_load. When area does not match with the balances, than the balances are made zero. Input argument check determines whether the negative mass is counted for. ''' errorlevel = 10 if params.ldebug: print("Start with calculation of clean_balance.") removed_balance_arable = ascraster.duplicategrid(N_bal_grass) removed_balance_arable.add_values(N_bal_grass.length * [0.0]) removed_balance_grs = ascraster.duplicategrid(N_bal_grass) removed_balance_grs.add_values(N_bal_grass.length * [0.0]) removed_balance_nat = ascraster.duplicategrid(N_bal_grass) removed_balance_nat.add_values(N_bal_grass.length * [0.0]) for icell in range(N_bal_grass.length): grass_cell = grassarea.get_data(icell,0.0) N_bal_cell = N_bal_grass.get_data(icell,0.0) if (grass_cell > 0.0): if (N_bal_cell < params.epsilon_load): # Make balance really zero removed_balance_grs.set_data(icell,N_bal_cell) N_bal_grass.set_data(icell,0.0) elif (N_bal_cell > 0.0): if (N_bal_cell > errorlevel): print("Grass area and grasbalance do not belong to each other. Gras area = 0.0 and balance_grass = " + str(N_bal_cell)) N_bal_grass.set_data(icell,0.0) removed_balance_grs.set_data(icell,N_bal_cell) elif (N_bal_cell < 0.0): if (N_bal_cell < -errorlevel): print("Grass area and grasbalance do not belong to each other. Gras area = 0.0 and balance_grass = " + str(N_bal_cell)) N_bal_grass.set_data(icell,0.0) removed_balance_grs.set_data(icell,N_bal_cell) crop_cell = croparea.get_data(icell,0.0) N_bal_cell = N_bal_arable.get_data(icell,0.0) if (crop_cell > 0.0): if (N_bal_cell < params.epsilon_load): # Make balance really zero N_bal_arable.set_data(icell,0.0) removed_balance_arable.set_data(icell,N_bal_cell) elif (N_bal_cell > 0.0): if (N_bal_cell > errorlevel): print("Crop area and cropbalance do not belong to each other. Crop area = 0.0 and balance_crop = " + str(N_bal_cell)) N_bal_arable.set_data(icell,0.0) removed_balance_arable.set_data(icell,N_bal_cell) elif (N_bal_cell < 0.0): if (N_bal_cell < -errorlevel): print("Crop area and cropbalance do not belong to each other. Crop area = 0.0 and balance_crop = " + str(N_bal_cell)) N_bal_arable.set_data(icell,0.0) removed_balance_arable.set_data(icell,N_bal_cell) nat_cell = natarea.get_data(icell,0.0) N_bal_cell = N_bal_natural.get_data(icell,0.0) if (nat_cell > 0.0): if (N_bal_cell < params.epsilon_load): # Make balance really zero N_bal_natural.set_data(icell,0.0) removed_balance_nat.set_data(icell,N_bal_cell) elif (N_bal_cell > 0.0): if (N_bal_cell > errorlevel): print("Natural area and natural balance do not belong to each other. Natural area = 0.0 and balance_nat = " + str(N_bal_cell)) N_bal_natural.set_data(icell,0.0) removed_balance_nat.set_data(icell,N_bal_cell) elif (N_bal_cell < 0.0): if (N_bal_cell < -errorlevel): print("Natural area and natural balance do not belong to each other. Natural area = 0.0 and balance_nat = " + str(N_bal_cell)) N_bal_natural.set_data(icell,0.0) removed_balance_nat.set_data(icell,N_bal_cell) return N_bal_grass,N_bal_arable,N_bal_natural,removed_balance_arable,removed_balance_grs,removed_balance_nat
def change_flowdir(lddin,mask,outputdir): ''' CHANGE_FLOWDIR PURPOSE: Change the flowdir numbering from ArcInfo/GIS/UNH/GRDC to PCraster format. Lddmap: network of local drain directions flow_direction can be coded as follows: UNH/GRDC PCraster(LDD) 32 64 128 meaning: NW N NE 7 8 9 16 - 1 W - E 4 5 6 8 4 2 SW S SE 1 2 3 ''' ldebug = True if (mask == None): raise MyError("Function change_flowdir does only work when maps are masked.") # Dictionary with conversion between the two numberings. convert_table={1:6,2:3,4:2,8:1,16:4,32:7,64:8,128:9,100:5} # Make a dummy raster without mask, to determine the coordinates of a cell. dummy = ascraster.Asciigrid(ncols = lddin.ncols, nrows = lddin.nrows,\ xllcorner = lddin.xllcorner, yllcorner = lddin.yllcorner,\ cellsize = lddin.cellsize, nodata_value = lddin.nodata_value) # Make output ldd map lddout = ascraster.duplicategrid(lddin) # Make all values nodata lddout.add_values(lddout.length*[lddout.nodata_value]) for icell in xrange(lddin.length): val = lddin.get_data(icell) if (val != None): lddout.set_data(icell,convert_table[iround(val)]) # Add river mouth to the ldd map (number 5). # Number 5 is given when the next cell is a nodata cell. # Make also the basinid map num = 1 mouth_dict = {} basinid = ascraster.duplicategrid(lddout) # Make all values nodata basinid.add_values(basinid.length*[basinid.nodata_value]) for icell in xrange(lddout.length): direction = lddout.get_data(icell) if (direction != None): direction = iround(direction) if (direction == 5): if (basinid.get_data(icell) == None): basinid.set_data(icell,num) mouth_dict[num] = dummy.get_coordin_from_index(mask[icell]) num += 1 continue # Test whether next cell where the water flows to, is a nodata cell. Then is is a outflow. icell_new = accuflux.goto_nextcell(icell,direction,lddout.ncols,mask=mask) if (icell_new == -1): # Previous cell was a river mouth lddout.set_data(icell,5) if (basinid.get_data(icell) == None): basinid.set_data(icell,num) mouth_dict[num] = dummy.get_coordin_from_index(mask[icell]) num += 1 print "There are " + str(num) + " river basins." lddout.write_ascii_file(os.path.join(outputdir,"ldd.asc")) # Fill basinid map, for each cell, walk along the ldd and get the end number. for icell in xrange(lddout.length): if (ldebug): print "BEGIN CELLNNUMBER: ",icell," basinid: ",basinid.get_data(icell)," LDD: ",lddout.get_data(icell)," COORDINATES: ",dummy.get_coordin_from_index(mask[icell]) if (basinid.get_data(icell) != None): continue icell_new = icell if (lddout.get_data(icell) == None): continue if (ldebug): print "START, CELLNUMBER: ",icell_new," basinid: ",basinid.get_data(icell)," DIRECTION: ",lddout.get_data(icell)," COORDINATES: ",dummy.get_coordin_from_index(mask[icell_new]) while True: direction = iround(lddout.get_data(icell_new)) if (direction == 5): id = basinid.get_data(icell_new) # Set basinid basinid.set_data(icell,id) break else: if (ldebug): print "START_CELL: ",icell," CURRENT CELL: ",icell_new," basinid: ",basinid.get_data(icell),"DIRECTION: ",direction icell_new = accuflux.goto_nextcell(icell_new,direction,lddout.ncols,mask=mask) id = basinid.get_data(icell_new) if (id != None): basinid.set_data(icell,id) break if (ldebug): print "FINISHED, CELLNUMBER: ",icell," LAST CELLNUMBER: ",icell_new," basinid: ",basinid.get_data(icell),"DIRECTION: ",direction basinid.write_ascii_file(os.path.join(outputdir,"basinid.asc")) lddout.write_ascii_file(os.path.join(outputdir,"ldd.asc")) sep = ";" fp = open(os.path.join(outputdir,"mouth.csv"),"w") # Write header fp.write("id"+sep+"xcoor"+sep+"ycoor"+"\n") for key in sorted(mouth_dict): fp.write(str(key)+sep+str(mouth_dict[key][0])+sep+str(mouth_dict[key][1])+"\n") fp.close() return lddout
def P_accuflux(params, mask, lake_icell_dict, lddmap, Pload, retention): ''' ACCUFLUX Based on Gerard van Drecht, RIVM, Bilthoven, February 2002 April 2002: accu fraction flux and accu fraction state added PURPOSE: Accumulate flow of mass, given by a material map [grid], along a flowpath, given by a local drain direction(LDD) map [grid]. The output map contains accumulated flux [grid]. All files are ascii-grid formatted. Lddmap: network of local drain directions flow_direction can be coded as follows: UNH/GRDC PCraster(LDD) 32 64 128 meaning: NW N NE 7 8 9 16 - 1 W - E 4 5 6 8 4 2 SW S SE 1 2 3 We use the PCraster LDD-format; negative and zero values are assumed ''' # Make output rasters accuPload = ascraster.duplicategrid(Pload) # Make order of all the cells. ordermap = accuflux.determine_order(lddmap) # Make a pointer for the calculation order pointer1 = [] for icell in range(ordermap.length): pointer1.append([int(ordermap.get_data(icell)), icell]) # Sort the pointer array so that lowest order is first calculated. pointer1.sort() # Loop over all cells: for item in range(len(pointer1)): icell = pointer1[item][1] # Get mass flux at the cell. Pload_cell = accuPload.get_data(icell) if (Pload_cell == None): # No data value continue if Pload_cell < 0.0: print("Negative mass flow of " + str(Pload_cell) + " at cell: " + str(icell)) # Go to next cell. continue ret_cell = retention.get_data(icell, 0.0) try: loutflow = (lake_icell_dict[icell].outcell == 1) except KeyError: loutflow = -1 if (loutflow == 1): setattr(lake_icell_dict[icell], "load_in", Pload_cell) Pload_cell = (1.0 - ret_cell) * Pload_cell if (loutflow == 1): setattr(lake_icell_dict[icell], "load_out", Pload_cell) accuPload.set_data(icell, Pload_cell) # Get direction of the ldd direction = int(lddmap.get_data(icell, -1)) if (direction < 1 or direction > 9 or direction == 5): pass else: icell_loop = accuflux.goto_nextcell(icell, direction, lddmap.ncols, mask=lddmap.mask) if (icell_loop > -1): prev = accuPload.get_data(icell_loop, 0.0) accuPload.set_data(icell_loop, prev + Pload_cell) return accuPload
def calculate(params,mask,production,environ=None,substance=None): ''' Allocation of aquaculture on the basis of river length. BF=brackish fishponds, FF=freshwater fishponds, MF=marine water fishponds, BC=brackish cages, FC=freshwater cages, MC=marine water cages, BP=brackish pens, FP=freshwater pens, MP=marine water pens ''' lbrakish = False lfresh = False lmarine = False lcage = False lponds = False lpens = False try: if (environ[0] == "B"): lbrakish = True elif(environ[0] == "F"): lfresh = True elif(environ[0] == "M"): lmarine = True else: raise MyError("Something wrong with the environment in allocation_aquaculture.",\ "Must start with B, F or M. Found: ", environ[0]) if (environ[1] == "C"): lcage = True elif(environ[1] == "F"): lponds = True elif(environ[1] == "P"): lpens = True else: raise MyError("Something wrong with the environment in allocation_aquaculture.",\ "Must end with C, F or P. Found: ", environ[1]) except: raise MyError("Something wrong with the environment in allocation_aquaculture") if (lmarine): # Read province id's of the marine cells and the weighing map. isogrid = ascraster.Asciigrid(ascii_file=params.fileprov_marine,mask=None,numtype=int) weighgrid = ascraster.Asciigrid(ascii_file=params.fileweigh_marine,mask=None,numtype=float) else: # Read province codes (isocodes) isogrid = ascraster.Asciigrid(ascii_file=params.fileiso,mask=mask,numtype=int) if (lponds ): # Read the ponds file with the weighing factors. weighgrid = ascraster.Asciigrid(ascii_file=params.filepondarea,mask=mask,numtype=float) elif (lcage or lpens): # Read the riverlength file with the weighing factors. weighgrid = ascraster.Asciigrid(ascii_file=params.fileriverlength,mask=mask,numtype=float) # Read the coastal cells. coastgrid = ascraster.Asciigrid(ascii_file=params.filecoast,mask=mask,numtype=int) if (lfresh): # Exclude the coastal cells in the weighgrid for icell in range(weighgrid.length): coastval = coastgrid.get_data(icell,-1) if (coastval > 0.): weighgrid.set_data(icell,0.0) elif (lbrakish): # Allocate only on the coastal cells. for icell in range(weighgrid.length): coastval = coastgrid.get_data(icell,-1) if (coastval < 0.00001): weighgrid.set_data(icell,0.0) else: raise MyError("Something wrong with setting up weighing in allocation_aquaculture") total_substance ={} for item in range(len(production)): # Calculate total aquaculture per province if (production[item].get_val("Environment").strip() == environ): iso = int(production[item].get_val("ISO-code")) try: total_substance[iso] += production[item].get_val(substance+"out") except KeyError: total_substance[iso] = production[item].get_val(substance+"out") # Create two output grids with zeros and fill these with the weighing method. out_grid = ascraster.duplicategrid(isogrid) out_grid.add_values(out_grid.length * [0.0]) # Make a dictionary of pointers for all the isocodes in the grid. pointer_dict = {} for icell in xrange(isogrid.length): iso = isogrid.get_data(icell) if (iso != None): iso = int(iso) try: pointer_dict[iso].append(icell) except KeyError: pointer_dict[iso] = [icell] for key in pointer_dict: try: # Take the total information. required_amount = total_substance[key] except KeyError: continue # Make everything ready for this region to allocate the stuff. weight_key = [] qmax_key = [] try: pointer1 = pointer_dict[key] except KeyError: pointer1 = [] sumqmax = 0.0 sumweight = 0.0 for icell in pointer1: area = weighgrid.get_data(icell,0.0) maxarea = 10000000000 # Fill weighing data and max data qmax_key.append(maxarea) weight_key.append(area) sumqmax += qmax_key[-1] sumweight += weight_key[-1] if (sumweight < 0.0001): # Make uniform weighing to all cells. There is no info for this region on the weighing. for icell in range(len(weight_key)): weight_key[icell] = 1 sumweight += weight_key[icell] # Do the allocation allocated_amount = allocweighing.allocweighing(required_amount,sumweight,weight_key,qmax_key) if (abs(sum(allocated_amount) - total_substance[key]) > 0.001*total_substance[key]): print "***** There is not enough allocated for environment " + environ + " and substance " + substance + " for region "+str(key)+". Difference: " + str(total_substance[key]-sum(allocated_amount)) # Fill gridded result for item in xrange(len(allocated_amount)): out_grid.set_data(pointer1[item],allocated_amount[item]) return out_grid