Interface.py 32.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
#
#
import numpy as np
import os
import pickle
from netCDF4 import Dataset
import RPPtools as RPP
from mpi4py import MPI
#
import sys
11 12 13 14 15
from inspect import currentframe, getframeinfo
#
localdir=os.path.dirname(getframeinfo(currentframe()).filename)
sys.path.append(localdir+'/F90subroutines')
F90=localdir+'/F90subroutines'
16
if MPI.COMM_WORLD.Get_rank() == 0 :
17
    err=os.system("cd "+F90+"; make all")
18 19 20 21 22 23 24 25 26 27
    if err != 0 :
        print("Compilation error in the FORTRAN interface")
        sys.exit()
else :
    print("Not compiling on other cores")
MPI.COMM_WORLD.Barrier()
#
import routing_interface
#
import configparser
28
config = configparser.ConfigParser({'Documentation':'false', 'nbxmax':'63', 'ROUTING_RIVERS':'50'})
29
config.read("run.def")
30 31 32
gendoc = config.get("OverAll", "Documentation")
nbxmax = config.getint("OverAll", "nbxmax")
largest_pos = config.getint("OverAll", "ROUTING_RIVERS")
33 34
#
undef_int = 999999999.9
35 36
# Order of magnitude for the area precision in m^2.
prec = 100.0
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#
# Print the documentation for the FORTRAN interface
#
if gendoc.lower() == "true" : 
    docwrapper = open('DocumentationInterface', 'w')
    docwrapper.write(routing_interface.initatmgrid.__doc__)
    docwrapper.write("====================================================================\n")
    docwrapper.write(routing_interface.gethydrogrid.__doc__)
    docwrapper.write("====================================================================\n")
    docwrapper.write(routing_interface.findbasins.__doc__)
    docwrapper.write("====================================================================\n")
    docwrapper.write(routing_interface.globalize.__doc__)
    docwrapper.write("====================================================================\n")
    docwrapper.write(routing_interface.linkup.__doc__)
    docwrapper.write("====================================================================\n")
    docwrapper.write(routing_interface.fetch.__doc__)
    docwrapper.write("====================================================================\n")
54 55 56 57
    docwrapper.write(routing_interface.finish_truncate.__doc__)
    docwrapper.write("====================================================================\n")
    docwrapper.write(routing_interface.killbas.__doc__)

58 59 60 61 62 63 64
    docwrapper.close
#
# Functions to access the interfaces
#
#
# initatmgrid : Initialises the grid.f90 module and passes the description of the atmospheric grid.
#
65
def initatmgrid(rank, nbcore, nbpt, modelgrid) :
66 67 68
    print("INITATMGRID corners", np.array(modelgrid.polyll).shape)
    print("INITATMGRID area", np.array(modelgrid.area).shape)
    print("INITATMGRID neighbours", np.array(modelgrid.neighbours).shape)
69 70 71 72 73 74 75 76
    routing_interface.initatmgrid(rank, nbcore, modelgrid.polyll, modelgrid.coordll, modelgrid.area, modelgrid.contfrac, modelgrid.neighbours)
    return
#
#
#
def closeinterface(comm) :
    comm.Barrier()
    routing_interface.closeinterface()
77 78 79
    return
#
#
80
#
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
def addcoordinates(outnf, globalgrid, procgrid, part, vtyp, NCFillValue, nbcorners, cornerind) :
    #
    # Longitude
    longitude = part.gather(procgrid.lon_full)
    if part.rank == 0 :
        lon=outnf.createVariable("lon", vtyp, ('y','x'), fill_value=NCFillValue)
        lon.units="grid box centre degrees east"
        lon.title="Longitude"
        lon.axis="X"
        lon[:,:] = longitude[:,:]
    #
    # Latitude
    latitude = part.gather(procgrid.lat_full)
    if part.rank == 0 :
        lat=outnf.createVariable("lat", vtyp, ('y','x'), fill_value=NCFillValue)
        lat.units="grid box centre degrees north"
        lat.standard_name="grid latitude"
        lat.title="Latitude"
        lat.axis="Y"
        lat[:] = latitude[:,:]
    #
    # Bounds of grid box
    #
    llonpoly=np.zeros((nbcorners,procgrid.nbland))
    llatpoly=np.zeros((nbcorners,procgrid.nbland))
    for i in range(procgrid.nbland) :
        llonpoly[:,i] = [procgrid.polyll[i][ic][0] for ic in cornerind]
        llatpoly[:,i] = [procgrid.polyll[i][ic][1] for ic in cornerind]
        lon_bnd = procgrid.landscatter(llonpoly)
        lat_bnd = procgrid.landscatter(llatpoly)
    if part.rank == 0 :
        lonbnd=outnf.createVariable("lon_bnd", vtyp, ('bnd','y','x'), fill_value=NCFillValue)
        lonbnd.units="grid box corners degrees east"
        lonbnd.title="Longitude of Corners"
        latbnd=outnf.createVariable("lat_bnd", vtyp, ('bnd','y','x'), fill_value=NCFillValue)
        latbnd.units="grid box corners degrees north"
        latbnd.title="Latitude of Corners"
    else :
        lonbnd= np.zeros((1,1,1))
        latbnd= np.zeros((1,1,1))
    lonbnd[:,:,:] = part.gather(lon_bnd[:,:,:])
    latbnd[:,:,:] = part.gather(lat_bnd[:,:,:])
    #
    # Land sea mask
    #
    if part.rank == 0 :
        land=outnf.createVariable("land", vtyp, ('y','x'), fill_value=NCFillValue)
        land.units="Land Sea mask"
        land.standard_name="landsea mask"
        land.title="Land"
        land[:,:] = globalgrid.land[:,:]
    # Area
    areas = procgrid.landscatter(np.array(procgrid.area, dtype=np.float64))
    areas[np.isnan(areas)] = NCFillValue
    if part.rank == 0 :
        area=outnf.createVariable("area", vtyp, ('y','x'), fill_value=NCFillValue)
        area.units="m^2"
        area.standard_name="grid area"
        area.title="Area"
    else :
        area = np.zeros((1,1))
    area[:,:] = part.gather(areas[:,:])
    #
    return
#
# Add environment to netCDF file
#
def addenvironment(outnf, procgrid, part, vtyp, NCFillValue, nbpt) :
    #
    nbpt_proc = np.arange(1,nbpt+1, dtype=vtyp)
    proc = np.full(nbpt, part.rank, dtype=vtyp)
    # Environment
    # nbpt_proc
    subpt = procgrid.landscatter(nbpt_proc[:], order='F')
    subpt = subpt.astype(vtyp, copy=False)
    subpt[np.isnan(subpt)] = NCFillValue
    if part.rank == 0 :
        subptgrid = outnf.createVariable("nbpt_proc", vtyp, ('y','x'), fill_value=NCFillValue)
        subptgrid.title = "gridpoint reference inside each proc"
        subptgrid.units = "-"
    else :
        subptgrid = np.zeros((1,1))
    subptgrid[:,:] = part.gather(subpt)
    #
    # rank
    procnum = procgrid.landscatter(proc[:], order='F')
    procnum = procnum.astype(vtyp, copy=False)
    procnum[np.isnan(procnum)] = NCFillValue
    if part.rank == 0 :
        procn = outnf.createVariable("proc_num", vtyp, ('y','x'), fill_value=NCFillValue)
        procn.title = "rank"
        procn.units = "-"
    else :
        procn = np.zeros((1,1))
    procn[:,:] = part.gather(procnum)
    #
    return
#
#
#
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
def finalfetch(part, routing_area, basin_count, route_togrid, route_tobasin, fetch_in) :
    #
    fetch_out = np.zeros(routing_area.shape, dtype=np.float32, order='F')
    partial_sum = np.zeros(routing_area.shape, dtype=np.float32, order='F')
    old_sorted = np.zeros(largest_pos, dtype=np.float32, order='F')
    #
    maxdiff_sorted = prec*prec
    iter_count = 0
    #
    while iter_count < part.size*3 and maxdiff_sorted > prec :
        fetch_out[:,:] = 0.0
        outflow_uparea = routing_interface.finalfetch(part.landcorelist, routing_area, basin_count, route_togrid, \
                                                      route_tobasin, partial_sum, fetch_out)
        partial_sum = np.copy(fetch_out)
        part.landsendtohalo(partial_sum, order='F')
        partial_sum = part.zerocore(partial_sum, order='F')
        #
        # Find area the largest basins we need to have right.
        #
        xtmp = np.hstack(part.comm.allgather(outflow_uparea[np.where(outflow_uparea > 0.0)]))
        # Precision in m^2 of the upstream areas when sorting.
        sorted_outareas = (np.unique(np.rint(np.array(xtmp)/prec))*prec)[::-1]
        # If mono-proc no need to iterate as fetch produces the full result.
        if part.size == 1 :
            maxdiff_sorted = 0.0
        else :
            maxdiff_sorted = np.max(np.abs(sorted_outareas[0:largest_pos]-old_sorted))
        old_sorted[:] = sorted_outareas[0:largest_pos]
        iter_count += 1
210

211 212 213 214 215 216 217 218 219 220 221 222
    #
    fetch_error = np.sum(np.abs(fetch_out[part.landcorelist,:]-fetch_in[part.landcorelist,:]), axis=1)\
                                                    /np.sum(routing_area[part.landcorelist,:], axis=1)
    if np.max(fetch_error) > prec : 
        print("Rank :"+str(part.rank)+" Too large fetch error (fraction of greid area) : ", fetch_error)
          
    print("Total fetch error in fraction of grid box : ", np.sum(fetch_error))
    #
    return fetch_out
#
#
#
223 224
class HydroOverlap :
#
Anthony Schrapffer's avatar
Anthony Schrapffer committed
225
    def __init__(self, nbpt, nbvmax, sub_pts, sub_index_in, sub_area_in, sub_lon_in, sub_lat_in, part, modelgrid, hydrodata) :
226 227 228 229 230 231 232 233 234 235 236 237 238 239
        #
        # Reshape stuff so that it fits into arrays
        #
        sub_index = np.zeros((nbpt,nbvmax,2), dtype=np.int8, order='F')
        sub_area = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        sub_lon = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        sub_lat = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        for ib in range(nbpt) :
            sub_area[ib,0:sub_pts[ib]] = sub_area_in[ib][:]
            sub_lon[ib,0:sub_pts[ib]] = sub_lon_in[ib][:]
            sub_lat[ib,0:sub_pts[ib]] = sub_lat_in[ib][:]
            for ip in range(sub_pts[ib]) :
                sub_index[ib,ip,:] = [sub_index_in[ib][0][ip],sub_index_in[ib][1][ip]]
        #
240
        part.landsendtohalo(np.array(sub_area), order='F')
Anthony Schrapffer's avatar
Anthony Schrapffer committed
241
        #
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        trip_tmp = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        basins_tmp = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        topoind_tmp = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        fac_tmp = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        hierarchy_tmp = np.zeros((nbpt,nbvmax), dtype=np.float32, order='F')
        #
        trip_tmp[:,:] = np.nan
        basins_tmp[:,:] = np.nan
        for ib in range(nbpt) :
            trip_tmp[ib,0:sub_pts[ib]] = np.asarray(hydrodata.trip[ib][:])
            basins_tmp[ib,0:sub_pts[ib]] = np.asarray(hydrodata.basins[ib][:])
            topoind_tmp[ib,0:sub_pts[ib]] = np.asarray(hydrodata.topoind[ib][:])
            fac_tmp[ib,0:sub_pts[ib]] = np.asarray(hydrodata.fac[ib][:])
            hierarchy_tmp[ib,0:sub_pts[ib]] = np.asarray(hydrodata.disto[ib][:])
        #
        trip_tmp[np.isnan(trip_tmp)] = undef_int
        basins_tmp[np.isnan(trip_tmp)] = undef_int
        #
        # Go to the call of the FORTRAN interface
        #
        print("GETHYDROGRID : nbpt = ", nbpt, nbvmax)
        print("GETHYDROGRID : nbvmax = ", nbvmax)
        print("GETHYDROGRID : nbxmax = ", nbxmax)
        self.nbi, self.nbj, self.area_bx, self.trip_bx, self.basin_bx, self.topoind_bx, self.fac_bx, self.hierarchy_bx, \
266
            self.lon_bx, self.lat_bx, self.lshead_bx = \
267 268 269 270 271
                    routing_interface.gethydrogrid(nbxmax, sub_pts, sub_index, sub_area, \
                    hydrodata.basinsmax, hydrodata.topoindmin, sub_lon, sub_lat, trip_tmp, basins_tmp, topoind_tmp, fac_tmp, hierarchy_tmp)
        #
        # Plot some diagnostics for the hydrology grid within the atmospheric meshes.
        #
272
        self.nwbas = nbvmax
273 274 275 276
        # Clean-up these arrays so that they are easy to use in Python.
        self.lon_bx[self.lon_bx > 360.]=np.nan
        self.lat_bx[self.lat_bx > 90.]=np.nan
        #
277 278 279 280
        return
#
#
#
281
class HydroSuper :
282
    def __init__(self, nbvmax, hydrodata, hydrooverlap, nbasmax) :
283 284 285
        #
        # Keep largest possible number of HTUs
        #
286
        self.nbasmax = nbasmax
287
        self.nbhtuext = nbvmax
288
        self.nwbas = hydrooverlap.nwbas
289 290 291 292 293 294 295 296 297 298 299
        #
        # Call findbasins
        #
        nb_basin, basin_inbxid, basin_outlet, basin_outtp, self.basin_sz, basin_bxout, basin_bbout, self.basin_pts, basin_lshead, coast_pts = \
                    routing_interface.findbasins(nbvmax, hydrooverlap.nbi, hydrooverlap.nbj, hydrooverlap.trip_bx, \
                                                 hydrooverlap.basin_bx, hydrooverlap.fac_bx, hydrooverlap.hierarchy_bx, \
                                                 hydrooverlap.topoind_bx, hydrooverlap.lshead_bx, \
                                                 hydrooverlap.lon_bx, hydrooverlap.lat_bx)
        #
        # Call Globalize
        #
300 301 302 303 304 305
        lon_bx_tmp = hydrooverlap.lon_bx
        lon_bx_tmp[np.isnan(lon_bx_tmp)] = undef_int
        lat_bx_tmp = hydrooverlap.lat_bx
        lat_bx_tmp[np.isnan(lat_bx_tmp)] = undef_int
        self.basin_count, self.basin_notrun, self.basin_area, self.basin_cg, self.basin_hierarchy, self.basin_fac, self.basin_topoind, \
            self.basin_id, self.basin_outcoor, self.basin_type, self.basin_flowdir, \
306
            self.basin_lshead, self.outflow_grid, self.outflow_basin, self.nbcoastal, self.coastal_basin = \
307 308 309
                    routing_interface.globalize(hydrooverlap.area_bx, lon_bx_tmp, lat_bx_tmp, hydrooverlap.trip_bx, \
                                                hydrooverlap.hierarchy_bx, hydrooverlap.fac_bx, hydrooverlap.topoind_bx, hydrodata.topoindmin, \
                                                nb_basin, basin_inbxid, basin_outlet, basin_outtp, self.basin_sz, self.basin_pts, basin_bxout, \
310
                                                basin_bbout, basin_lshead, coast_pts, hydrooverlap.nwbas)
311

312
        self.nbpt = self.basin_count.shape[0]
313
        
314 315
        return
    #
316 317 318 319 320 321 322 323 324
    def linkup(self, hydrodata) :
        #
        # Call the linkup routine in routing_reg.
        #
        print("Invented basins =", hydrodata.basinsmax)
        self.inflow_number,self.inflow_grid,self.inflow_basin = routing_interface.linkup(nbxmax, self.basin_count, self.basin_area, self.basin_id, \
                                                                       self.basin_flowdir, self.basin_lshead, self.basin_hierarchy, \
                                                                       self.basin_fac, self.outflow_grid, self.outflow_basin, \
                                                                       self.nbcoastal, self.coastal_basin, float(hydrodata.basinsmax))
325
        self.nbxmax_in = self.inflow_number.shape[1]
326 327
        return
    #
328

POLCHER Jan's avatar
POLCHER Jan committed
329
    def fetch(self, part) :
330
        #
331
        fetch_basin = np.zeros(self.basin_area.shape, dtype=np.float32, order='F')
332
        #
333
        self.basin_area = routing_interface.areanorm(self.basin_count, self.basin_area, self.outflow_grid)
334
        partial_sum = np.zeros(self.basin_area.shape, dtype=np.float32, order='F')
335
        #
336
        old_sorted = np.zeros(largest_pos, dtype=np.float32, order='F')
337 338 339 340 341
        #
        maxdiff_sorted = prec*prec
        iter_count = 0
        #
        while iter_count < part.size*3 and maxdiff_sorted > prec :
342
            fetch_basin[:,:] = 0.0
343
            outflow_uparea = routing_interface.fetch(part.landcorelist, self.basin_count, self.basin_area, self.basin_id, self.basin_hierarchy, \
344
                                                         self.basin_fac, self.outflow_grid, self.outflow_basin, partial_sum, fetch_basin)
345 346
            partial_sum = np.copy(fetch_basin)
            part.landsendtohalo(partial_sum, order='F')
347 348
            partial_sum = part.zerocore(partial_sum, order='F')
            #
349 350 351 352 353 354 355 356 357 358 359 360
            # Find area the largest basins need at least to have.
            #
            xtmp = np.hstack(part.comm.allgather(outflow_uparea[np.where(outflow_uparea > 0.0)]))
            # Precision in m^2 of the upstream areas when sorting.
            sorted_outareas = (np.unique(np.rint(np.array(xtmp)/prec))*prec)[::-1]
            # If mono-proc no need to iterate as fetch produces the full result.
            if part.size == 1 :
                maxdiff_sorted = 0.0
            else :
                maxdiff_sorted = np.max(np.abs(sorted_outareas[0:largest_pos]-old_sorted))
            old_sorted[:] = sorted_outareas[0:largest_pos]
            iter_count += 1
361

362 363
        self.fetch_basin = np.copy(fetch_basin)
        #
364
        # Upstream area of the smalest river we call largest rivers. 
365
        #
366
        self.largest_rivarea = sorted_outareas[largest_pos-1]
367 368 369
        #
        #
        #
370 371 372
        self.num_largest =  routing_interface.rivclassification( part.landcorelist, self.basin_count, self.outflow_grid, self.outflow_basin, \
                   self.fetch_basin, self.largest_rivarea)
        #print("Rank :"+str(part.rank)+" Area of smallest large rivers : ", self.largest_rivarea, " Nb of Large rivers on proc : ",self.num_largest)
373
        return
374 375 376 377 378 379 380 381 382 383 384 385

    def check_fetch(self):

        routing_interface.checkfetch(nbpt = self.nbpt, nwbas = self.nwbas, fetch_basin = self.fetch_basin, outflow_grid = self.outflow_grid, outflow_basin = self.outflow_basin, basin_count = self.basin_count)

        return 

    def check_routing(self):

        routing_interface.checkrouting(nbpt = self.nbpt, nwbas = self.nwbas, outflow_grid = self.outflow_grid, outflow_basin = self.outflow_basin, basin_count = self.basin_count)

        return 
386
    #
387 388 389 390 391 392 393 394
    # 
    def killbas(self, tokill, totakeover, numops):
        ops = tokill.shape[1] 
 
        routing_interface.killbas(nbpt = self.nbpt, nbxmax_in = self.nbxmax_in, nbasmax = self.nbasmax, nwbas = self.nwbas, ops = ops, tokill = tokill, totakeover = totakeover, numops = numops, basin_count = self.basin_count, basin_area = self.basin_area, \
            basin_cg = self.basin_cg, basin_topoind = self.basin_topoind, fetch_basin = self.fetch_basin, basin_id = self.basin_id, basin_coor = self.basin_outcoor, basin_type = self.basin_type, basin_flowdir = self.basin_flowdir, outflow_grid = self.outflow_grid, outflow_basin = self.outflow_basin, \
            inflow_number = self.inflow_number, inflow_grid = self.inflow_grid, inflow_basin = self.inflow_basin)

395
    #
396 397 398 399 400 401 402 403 404 405 406
    def add_variable(self,outnf, procgrid, NCFillValue, part, coord, name, title, units, data, vtyp):
        var = procgrid.landscatter(data.astype(vtyp), order='F')
        var[np.isnan(var)] = NCFillValue
        if part.rank == 0 :
            ncvar = outnf.createVariable(name, vtyp, coord, fill_value=NCFillValue)
            ncvar.title = title
            ncvar.units = units
        else :
            ncvar = np.zeros((1,1,1))
        ncvar[:] = part.gather(var)
    
407 408 409 410 411
    #
    def dumpnetcdf(self, filename, globalgrid, procgrid, part) :
        #
        NCFillValue=1.0e20
        vtyp=np.float64
412
        inflow_size = 100
413 414 415 416 417 418 419 420 421 422
        cornerind=[0,2,4,6]
        nbcorners = len(cornerind)
        #
        if part.rank == 0 :
            outnf=Dataset(filename, 'w', format='NETCDF4_CLASSIC')
            # Dimensions
            outnf.createDimension('x', globalgrid.ni)
            outnf.createDimension('y', globalgrid.nj)
            outnf.createDimension('land', len(procgrid.area))
            outnf.createDimension('htuext', self.nbhtuext)
423 424
            outnf.createDimension('htu', self.inflow_number.shape[1])
            outnf.createDimension('in',inflow_size )
425 426 427 428 429 430 431 432 433 434
            outnf.createDimension('bnd', nbcorners)
        else :
            outnf = None
        #
        addcoordinates(outnf, globalgrid, procgrid, part, vtyp, NCFillValue, nbcorners, cornerind)
        addenvironment(outnf, procgrid, part, vtyp, NCFillValue, self.nbpt)
        # 
        # Variables
        # Once gathered on root_proc we transform them into float64. Careful, Integer variables do not have NaN !
        #
435 436 437 438 439 440
        # nbpt_glo
        nbpt_loc = np.zeros((self.nbpt,1)).astype(np.int32)
        nbpt_loc[:,0] = np.arange(1, self.nbpt+1)
        nbpt_glo = part.l2glandindex(nbpt_loc)
        self.add_variable(outnf, procgrid, NCFillValue, part, ('y','x'), "nbpt_glo", "Grid point Global", "-", nbpt_glo[:,0], vtyp)
        #
Anthony's avatar
Anthony committed
441
        # contfrac
442 443 444 445 446
        contfrac = np.array(procgrid.contfrac)
        self.add_variable(outnf, procgrid, NCFillValue, part, ('y','x'), "contfrac", "Land fraction", "-", np.array(procgrid.contfrac), vtyp)
        #
        # basin_id
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "basin_id", "ID for each HTU", "-", self.basin_id, vtyp)
447 448
        #
        #self.basin_count
449
        self.add_variable(outnf, procgrid, NCFillValue, part, ('y','x'), "basin_count", "HTU count", "-", self.basin_count, vtyp)
450
        #
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        # self.basin_notrun
        self.add_variable(outnf, procgrid, NCFillValue, part, ('y','x'), "basin_notrun", "Not run", "-", self.basin_notrun, vtyp)
        #
        # self.basin_area
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "basin_area", "Basin area", "-", self.basin_area, vtyp)
        #
        # self.basin_cg
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "CG_lon", "CG lon", "-", self.basin_cg[:,:,1], vtyp)
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "CG_lat", "CG lat", "-", self.basin_cg[:,:,0], vtyp)
        #
        # self.topoind
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "basin_topoind", "Topoindex", "-", self.basin_topoind, vtyp)
        # 
        # outcoor
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "outcoor_lon", "outcoor lon", "-", self.basin_outcoor[:,:,1], vtyp)
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "outcoor_lat", "outcoor lat", "-", self.basin_outcoor[:,:,0], vtyp)
        # 
        # type
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "basin_type", "type", "-", self.basin_type, vtyp)
470
        #
471 472 473 474
        # flowdir
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "basin_flowdir", "flowdir", "-", self.basin_flowdir, vtyp)
        #
        # 
475
        #self.outflow_grid
476 477 478 479 480 481
        grgrid = part.l2glandindex(self.outflow_grid)
        grgrid[self.outflow_grid == 0 ] = -2 # in case it flows out of the domain, the 0 should not remain
        grgrid[self.outflow_grid == -1 ] = -1
        grgrid[self.outflow_grid == -2 ] = -2
        grgrid[self.outflow_grid == -3 ] = -3
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "HTUoutgrid", "HTU outflow grid", "-", grgrid, vtyp)
482 483
        #
        #self.outflow_basin
484 485 486 487 488 489 490 491
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "HTUoutbasin", "Outflow HTU of grid", "-", self.outflow_basin, vtyp)
        #
        # self.inflow_number
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htu','y','x'), "HTUinnum", "Inflow number", "-", self.inflow_number, vtyp)
        #
        # Inflow Grid -> convert to global
        gingrid = part.l2glandindex(self.inflow_grid[:,:,:inflow_size])
        self.add_variable(outnf, procgrid, NCFillValue, part, ('in','htu','y','x'), "HTUingrid", "Inflow grid", "-", gingrid, vtyp)
Anthony's avatar
Anthony committed
492 493
        #
        # Inflow Basin
494
        self.add_variable(outnf, procgrid, NCFillValue, part, ('in','htu','y','x'), "HTUinbas", "Inflow basin", "-", self.inflow_basin[:,:,:inflow_size], vtyp)
495 496 497
        #
        # Save the fetch of each basin
        #
498
        self.add_variable(outnf, procgrid, NCFillValue, part, ('htuext','y','x'), "fetch_basin", "Fetch contributing to each HTU", "m^2", self.fetch_basin, vtyp)
499 500 501 502 503 504 505
        #
        # Close file
        #
        if part.rank == 0 :
            outnf.close()
        #
        return
506 507 508
#
#
#
509
class HydroGraph :
510
    def __init__(self, nbasmax, hydrosuper, part, modelgrid) :
511
        #
512
        self.nbasmax = nbasmax
513
        self.nbpt = hydrosuper.basin_count.shape[0]
514 515
        nwbas = hydrosuper.basin_topoind.shape[1]
        nbxmax_in = hydrosuper.inflow_grid.shape[1]
516
        #
517 518
        self.routing_area, self.routing_cg, self.topo_resid, self.route_nbbasin, self.route_togrid, self.route_tobasin, self.route_nbintobas, \
            self.global_basinid, self.route_outlet, self.route_type, self.origin_nbintobas, self.routing_fetch = \
519 520 521 522 523 524 525
                                    routing_interface.finish_truncate(nbpt = self.nbpt, nbxmax_in = nbxmax_in, nbasmax = nbasmax, nwbas = nwbas, num_largest = hydrosuper.num_largest, gridarea = modelgrid.area, cfrac = modelgrid.contfrac, basin_count = hydrosuper.basin_count, \
                                                               basin_notrun = hydrosuper.basin_notrun, basin_area = hydrosuper.basin_area, basin_cg = hydrosuper.basin_cg, \
                                                               basin_topoind = hydrosuper.basin_topoind, fetch_basin = hydrosuper.fetch_basin, basin_id = hydrosuper.basin_id, \
                                                               basin_coor = hydrosuper.basin_outcoor, basin_type = hydrosuper.basin_type, basin_flowdir = hydrosuper.basin_flowdir, \
                                                               outflow_grid = hydrosuper.outflow_grid, outflow_basin = hydrosuper.outflow_basin, \
                                                               inflow_number = hydrosuper.inflow_number, inflow_grid = hydrosuper.inflow_grid, inflow_basin = hydrosuper.inflow_basin)

526 527 528 529
        #
        self.routing_fetch = finalfetch(part, self.routing_area, self.route_nbbasin, self.route_togrid, self.route_tobasin, self.routing_fetch)
        # 
        self.num_largest = routing_interface.finalrivclass(part.landcorelist, self.route_togrid, self.route_tobasin, self.routing_fetch, \
530
                      hydrosuper.largest_rivarea)
531
        #
532 533
        return
    #
534 535 536 537 538
    def dumpnetcdf(self, filename, globalgrid, procgrid, part) :
        #
        NCFillValue=1.0e20
        vtyp=np.float64
        cornerind=[0,2,4,6]
539
        nbcorners = len(cornerind)
540 541 542 543 544 545 546 547
        #
        if part.rank == 0 :
            outnf=Dataset(filename, 'w', format='NETCDF4_CLASSIC')
            # Dimensions
            outnf.createDimension('x', globalgrid.ni)
            outnf.createDimension('y', globalgrid.nj)
            outnf.createDimension('land', len(procgrid.area))
            outnf.createDimension('htu', self.nbasmax)
548
            outnf.createDimension('bnd', nbcorners)
549
        else :
550
            outnf = None
551
        #
552 553
        addcoordinates(outnf, globalgrid, procgrid, part, vtyp, NCFillValue, nbcorners, cornerind)
        addenvironment(outnf, procgrid, part, vtyp, NCFillValue, self.nbpt)
554
        #
555 556
        # The field route_togrid is with indices on the local grid. That needs to be converted to the global grid.
        #
557 558 559 560 561 562 563 564 565
        itarget=-1
        for il in range(procgrid.nbland) :
            lo = procgrid.lon_full[procgrid.indP[il][0],procgrid.indP[il][1]]
            la = procgrid.lat_full[procgrid.indP[il][0],procgrid.indP[il][1]]
            d=np.sqrt((lo-3.13)**2+(la-39.70)**2)
            if d < 0.05 :
                itarget = il
                
        if itarget >+ 0 :
POLCHER Jan's avatar
POLCHER Jan committed
566
            print(part.rank, itarget, " Before route_togrid = ", self.route_togrid[itarget,:])
567
        grgrid = part.l2glandindex(self.route_togrid[:,:])
568
        if itarget >+ 0 :
POLCHER Jan's avatar
POLCHER Jan committed
569
            print(part.rank, itarget, " After route_togrid = ", self.route_togrid[itarget,:])
570
        rgrid = procgrid.landscatter(grgrid.astype(vtyp), order='F')
571 572 573 574 575 576 577 578 579
        rgrid[rgrid >= RPP.IntFillValue] = NCFillValue
        if part.rank == 0 :
            routetogrid = outnf.createVariable("routetogrid", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            routetogrid.title = "Grid into which the basin flows"
            routetogrid.units = "-"
        else :
            routetogrid = np.zeros((1,1,1))    
        routetogrid[:,:,:] = part.gather(rgrid)
        #
580
        rtobasin = procgrid.landscatter(self.route_tobasin[:,:].astype(vtyp), order='F')
581
        rtobasin = rtobasin.astype(vtyp, copy=False)
582 583 584 585 586 587 588 589 590
        rtobasin[rtobasin >= RPP.IntFillValue] = NCFillValue
        if part.rank == 0 :
            routetobasin = outnf.createVariable("routetobasin", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            routetobasin.title = "Basin in to which the water goes"
            routetobasin.units = "-"
        else :
            routetobasin = np.zeros((1,1,1))
        routetobasin[:,:,:] = part.gather(rtobasin)
        #
591
        rid = procgrid.landscatter(self.global_basinid[:,:].astype(vtyp), order='F')
592 593 594 595 596 597 598 599 600
        rid[rid >= RPP.IntFillValue] = NCFillValue
        if part.rank == 0 :                           
            basinid = outnf.createVariable("basinid", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            basinid.title = "ID of basin"
            basinid.units = "-"
        else :
            basinid = np.zeros((1,1,1))
        basinid[:,:,:] = part.gather(rid)
        #
601
        rintobas = procgrid.landscatter(self.route_nbintobas[:].astype(vtyp))
602 603 604 605 606 607 608 609 610
        rintobas[rintobas >= RPP.IntFillValue] = NCFillValue
        if part.rank == 0 : 
            routenbintobas = outnf.createVariable("routenbintobas", vtyp, ('y','x'), fill_value=NCFillValue)
            routenbintobas.title = "Number of basin into current one"
            routenbintobas.units = "-"
        else :
            routenbintobas = np.zeros((1,1))
        routenbintobas[:,:] = part.gather(rintobas)
        #
611
        onbintobas = procgrid.landscatter(self.origin_nbintobas[:].astype(vtyp))
612 613 614 615 616 617 618 619 620
        onbintobas[onbintobas >= RPP.IntFillValue] = NCFillValue
        if part.rank == 0 :
            originnbintobas = outnf.createVariable("originnbintobas", vtyp, ('y','x'), fill_value=NCFillValue)
            originnbintobas.title = "Number of sub-grid basin into current one before truncation"
            originnbintobas.units = "-"
        else :
            originnbintobas = np.zeros((1,1))
        originnbintobas[:,:] = part.gather(onbintobas)
        #
621
        olat = procgrid.landscatter(self.route_outlet[:,:,0].astype(vtyp), order='F')
622 623 624 625 626 627 628 629 630
        olat[np.isnan(olat)] = NCFillValue
        if part.rank == 0 :
            outletlat = outnf.createVariable("outletlat", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            outletlat.title = "Latitude of Outlet"
            outletlat.title = "degrees north"
        else :
            outletlat = np.zeros((1,1,1))
        outletlat[:,:,:] = part.gather(olat)
        #
631
        olon = procgrid.landscatter(self.route_outlet[:,:,1].astype(vtyp), order='F')
632 633 634 635 636 637 638 639 640
        olon[np.isnan(olon)] = NCFillValue
        if part.rank == 0 :
            outletlon = outnf.createVariable("outletlon", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            outletlon.title = "Longitude of outlet"
            outletlon.units = "degrees east"
        else :
            outletlon = np.zeros((1,1,1))
        outletlon[:,:,:] = part.gather(olon)
        #
641
        otype = procgrid.landscatter(self.route_type[:,:].astype(vtyp), order='F')
642 643 644 645 646 647 648 649 650
        otype[np.isnan(otype)] = NCFillValue
        if part.rank == 0 :
            outlettype = outnf.createVariable("outlettype", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            outlettype.title = "Type of outlet"
            outlettype.units = "code"
        else :
            outlettype = np.zeros((1,1,1))
        outlettype[:,:,:] = part.gather(otype)
        #
651
        tind = procgrid.landscatter(self.topo_resid[:,:].astype(vtyp), order='F')
652 653 654 655 656 657 658 659 660
        tind[np.isnan(tind)] = NCFillValue
        if part.rank == 0 :
            topoindex = outnf.createVariable("topoindex", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            topoindex.title = "Topographic index of the retention time"
            topoindex.units = "m"
        else :
            topoindex = np.zeros((1,1,1))
        topoindex[:,:,:] = part.gather(tind)
        #
661 662
        # Save centre of gravity of HTU
        #
663
        cg = procgrid.landscatter(self.routing_cg[:,:,:].astype(vtyp), order='F')
664 665 666 667 668 669 670 671 672 673 674 675 676 677
        cg[np.isnan(cg)] = NCFillValue
        if part.rank == 0 :
            CG_lon = outnf.createVariable("CG_lon", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            CG_lon.title = "Longitude of centre of gravity of HTU"
            CG_lon.units = "degrees east"
            CG_lat = outnf.createVariable("CG_lat", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            CG_lat.title = "Latitude of centre of gravity of HTU"
            CG_lat.units = "degrees north"
        else :
            CG_lon = np.zeros((1,1,1))
            CG_lat = np.zeros((1,1,1))
        CG_lon[:,:,:] = part.gather(cg[1,:,:,:])
        CG_lat[:,:,:] = part.gather(cg[0,:,:,:])
        #
678 679
        # Save the fetch of each basin
        #
680
        fe =  procgrid.landscatter(self.routing_fetch[:,:].astype(vtyp), order='F')
681 682 683 684 685 686 687 688 689
        fe[np.isnan(fe)] = NCFillValue
        if part.rank == 0 :
            fetch = outnf.createVariable("fetch", vtyp, ('htu','y','x'), fill_value=NCFillValue)
            fetch.title = "Fetch contributing to each HTU"
            fetch.units = "m^2"
        else :
            fetch = np.zeros((1,1,1))
        fetch[:,:,:] = part.gather(fe)
        #
690 691
        if part.rank == 0 :
            outnf.close()
692 693
        #
        return
694 695 696 697