Docker-in-Docker (DinD) capabilities of public runners deactivated. More info

routing_reg.f90 140 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
MODULE routing_reg

  USE defprec
  USE grid
  USE constantes_var
  USE routing_tools

  IMPLICIT NONE

  INTEGER(i_std), SAVE :: nbvmax=440 !! The maximum number of basins we can handle at any time during the generation of the maps (unitless)
  INTEGER(i_std), SAVE :: maxpercent=2 !! The maximum area percentage of a sub-basin in a grib-box (default = 2%)

  INTEGER(i_std), SAVE :: nbpt_save
  INTEGER(i_std), SAVE :: nbasmax_save
15
  REAL(r_std), SAVE    :: topoindexmin = 0.0
16 17
  REAL(r_std), SAVE    :: hydro_meanlen = 0.0
  REAL(r_std), SAVE    :: hydro_meandz = 0.0
18

19
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: routing_area_glo !! Surface of basin (m^2)
20 21 22
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: routing_orog_mean_glo !! Mean topography (m)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: routing_orog_min_glo !! Mean topography (m)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: routing_orog_max_glo !! Mean topography (m)
23
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: routing_floodp_glo !! Surface of floodplains (m^2)
24 25
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: routing_beta_glo !!
  !
26
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:,:)  :: routing_cg_glo !! Centre of gravity of HTU (Lat, Lon)
27 28 29 30
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: topo_resid_glo !! Topographic index of the retention time (km)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: topo_rlen_glo  !! HTU river length (m)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: topo_rdz_glo   !! HTU river elevation change (m)
  !
31
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:)   :: route_count_glo !! Number of basins per grid
32 33
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: route_togrid_glo !! Grid into which the basin flows (unitless)
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: route_tobasin_glo !! Basin in to which the water goes (unitless)
34 35
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:)   :: route_nbintobas_glo !! Number of basin into current one (unitless)
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:)   :: origin_nbintobas_glo !! Number of sub-grid basin into current one before truncation (unitless)
36
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: global_basinid_glo !! ID of basin (unitless)
37 38 39
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:,:)  :: route_outlet_glo !! Coordinate of outlet (-)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: route_type_glo !! Coordinate of outlet (-)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: route_fetch_glo !! Upstream area at each HTU
40
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)    :: routing_floodcri_glo !! Upstream area at each HTU
41 42 43 44
  !
  ! Options to compute the topographic index based on the information available in the Hydrological files.
  ! topo_option = 1 : Constant topographic index
  ! topo_option = 2 : Simple average without any weighting
45 46 47 48 49 50
  ! topo_option = 3 : The sum over all rivers within the HTU are computed in _findbasin. These
  !                   values are then averaged over the HTU.
  ! topo_option = 4 : The length and elevation change of all rivers within the HTU are computed.
  !                   These values are then used to compute the topoindex of the HTU.
  !
  INTEGER(i_std), SAVE :: topo_option = 4 !! Option to calculate topoindex
51
  !
52 53 54 55
  ! Options to compute the properties when merging HTUs in routing_reg_killbas
  ! kill_option = 1 : The old way of simpling building the weighted average.
  ! Kill_option = 2 : When the difference of average elevation then we assume HTUs cascade into each other
  INTEGER(i_std), SAVE :: kill_option = 2
56
  !
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
CONTAINS
!! ================================================================================================================================
!! SUBROUTINE : routing_reg_getgrid
!!
!>\BRIEF This subroutine extracts from the global high resolution fields
!! the data for the current grid box we are dealing with.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! Convention for trip on the input :
!! The trip field follows the following convention for the flow of the water :
!! trip = 1 : flow = N
!! trip = 2 : flow = NE
!! trip = 3 : flow = E
!! trip = 4 : flow = SE
!! trip = 5 : flow = S
!! trip = 6 : flow = SW
!! trip = 7 : flow = W
!! trip = 8 : flow = NW
!! trip = 97 : return flow into the ground
!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here
!! trip = 99 : river flow into the oceans
!!
!! On output, the grid boxes of the basin map which flow out of the GCM grid are identified
!! by numbers larger than 100 :
!! trip = 101 : flow = N out of the coarse grid
!! trip = 102 : flow = NE out of the coarse grid
!! trip = 103 : flow = E out of the coarse grid
!! trip = 104 : flow = SE out of the coarse grid
!! trip = 105 : flow = S out of the coarse grid
!! trip = 106 : flow = SW out of the coarse grid
!! trip = 107 : flow = W out of the coarse grid
!! trip = 108 : flow = NW out of the coarse grid
!! Inside the grid the convention remains the same as above (ie between 1 and 99).:\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES : None
!!
!! FLOWCHART : None
98
!! \n
99 100
!_ ================================================================================================================================

101
  SUBROUTINE routing_reg_getgrid(nbpt, ib, ijdimmax, sub_pts, sub_index, sub_area, max_basins, min_topoind, &
102 103 104
       & meanrlen, meanrdz, lon_rel, lat_rel, lalo, resolution, contfrac, trip, basins, topoindex, rlen, rdz, &
       & fac, hierarchy, orog, floodp, nbi, nbj, area_bx, trip_bx, basin_bx, topoind_bx, rlen_bx, rdz_bx, fac_bx, &
       & hierarchy_bx, orog_bx, floodp_bx, lon_bx, lat_bx, lshead_bx)
105 106 107 108 109 110
    !
    IMPLICIT NONE
    !
!! INPUT VARIABLES
    INTEGER(i_std), INTENT(in) :: nbpt !! Domain size (unitless)
    INTEGER(i_std), INTENT(in) :: ib !! Current basin (unitless)
111
    INTEGER(i_std), INTENT(in) :: ijdimmax !! Maximum dimension in i or j of the underlaying hydro grid.
112 113 114 115
    INTEGER(i_std), INTENT(in) :: sub_pts(nbpt) !! Number of high resolution points on this grid (unitless)
    INTEGER(i_std), INTENT(in) :: sub_index(nbpt,nbvmax,2) !! Indices of the points we need on the fine grid (unitless)
    REAL(r_std), INTENT(inout) :: max_basins !! The current maximum of basins
    REAL(r_std), INTENT(in) :: min_topoind !! The current minimum of topographic index (m)
116
    REAL(r_std), INTENT(in) :: meanrlen, meanrdz !! Mean length and altitude change in the original grid (m)
117 118 119 120 121 122 123 124 125 126 127
    REAL(r_std), INTENT(in) :: sub_area(nbpt,nbvmax) !! Area on the fine grid (m^2)
    !
    REAL(r_std), INTENT(in) :: lon_rel(nbpt,nbvmax) !!
    REAL(r_std), INTENT(in) :: lat_rel(nbpt,nbvmax) !! coordinates of the fine grid
    !
    REAL(r_std), INTENT(in) :: lalo(nbpt,2) !! Vector of latitude and longitudes (beware of the order !)
    REAL(r_std), INTENT(in) :: resolution(nbpt,2) !! The size of each grid box in X and Y (m)
    REAL(r_std), INTENT(in) :: contfrac(nbpt) !! Fraction of land in each grid box (unitless;0-1)
    !
    REAL(r_std), INTENT(inout) :: trip(nbpt,nbvmax) !! The trip field (unitless)
    REAL(r_std), INTENT(inout) :: basins(nbpt,nbvmax) !! data on the fine grid
128 129 130
    REAL(r_std), INTENT(inout) :: topoindex(nbpt,nbvmax) !! Topographic index of the residence time (km)
    REAL(r_std), INTENT(inout) :: rlen(nbpt,nbvmax) !! River length within the hydrological grid (m)
    REAL(r_std), INTENT(inout) :: rdz(nbpt,nbvmax) !! Elevation change within the hydrological grid (m)
131 132
    REAL(r_std), INTENT(inout) :: hierarchy(nbpt,nbvmax) !! data on the fine grid
    REAL(r_std), INTENT(inout) :: fac(nbpt,nbvmax) !! data on the fine grid
133 134
    REAL(r_std), INTENT(inout) :: orog(nbpt,nbvmax) !! data on the fine grid
    REAL(r_std), INTENT(inout) :: floodp(nbpt,nbvmax) !! data on the fine grid
135 136 137
    !
!! OUTPUT VARIABLES
    INTEGER(i_std), INTENT(out) :: nbi, nbj !! Number of point in x and y within the grid (unitless)
138 139 140 141 142 143
    REAL(r_std), INTENT(out) :: area_bx(ijdimmax,ijdimmax) !! Area of each small box in the grid box (m^2)
    REAL(r_std), INTENT(out) :: hierarchy_bx(ijdimmax,ijdimmax) !! Level in the basin of the point
    REAL(r_std), INTENT(out) :: fac_bx(ijdimmax,ijdimmax) !! Flow accumulation
    REAL(r_std), INTENT(out) :: lon_bx(ijdimmax,ijdimmax) !!
    REAL(r_std), INTENT(out) :: lat_bx(ijdimmax,ijdimmax) !!
    REAL(r_std), INTENT(out) :: lshead_bx(ijdimmax,ijdimmax) !! Large scale heading for outflow points.
144 145 146
    REAL(r_std), INTENT(out) :: topoind_bx(ijdimmax,ijdimmax) !! Topographic index of the residence time for each of the smaller boxes (km)
    REAL(r_std), INTENT(out) :: rlen_bx(ijdimmax,ijdimmax) !! River length within the smaller boxes (m)
    REAL(r_std), INTENT(out) :: rdz_bx(ijdimmax,ijdimmax) !! Elevation change within the smaller boxes (m)
147 148 149 150
    INTEGER(i_std), INTENT(out) :: trip_bx(ijdimmax,ijdimmax) !! The trip field for each of the smaller boxes (unitless)
    INTEGER(i_std), INTENT(out) :: basin_bx(ijdimmax,ijdimmax) !!
    REAL(i_std), INTENT(out) :: orog_bx(ijdimmax,ijdimmax) !!
    REAL(i_std), INTENT(out) :: floodp_bx(ijdimmax,ijdimmax) !!
151 152 153 154 155 156
    !
!! LOCAL VARIABLES
    INTEGER(i_std) :: ip, jp, ll(1), iloc, jloc !! Indices (unitless)
    INTEGER(i_std) :: ipp, jpp
    INTEGER(i_std), DIMENSION(8,2) :: inc
    REAL(r_std) :: cenlon, cenlat, dlon, dlat, deslon, deslat, facti, factj
157 158
    REAL(r_std) :: lonstr(ijdimmax*ijdimmax) !!
    REAL(r_std) :: latstr(ijdimmax*ijdimmax) !!
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    !

!_ ================================================================================================================================
    !
    ! The routing code (i=1, j=2)
    !
    inc(1,1) = 0
    inc(1,2) = -1
    inc(2,1) = 1
    inc(2,2) = -1
    inc(3,1) = 1
    inc(3,2) = 0
    inc(4,1) = 1
    inc(4,2) = 1
    inc(5,1) = 0
    inc(5,2) = 1
    inc(6,1) = -1
    inc(6,2) = 1
    inc(7,1) = -1
    inc(7,2) = 0
    inc(8,1) = -1
    inc(8,2) = -1
    !
182
    topoindexmin = min_topoind
183 184
    hydro_meanlen = meanrlen
    hydro_meandz = meanrdz
185
    !
186 187 188 189 190
    ! Set everything to undef to locate easily empty points
    !
    trip_bx(:,:) = undef_int
    basin_bx(:,:) = undef_int
    topoind_bx(:,:) = undef_sechiba
191 192
    rlen_bx(:,:) = undef_sechiba
    rdz_bx(:,:) = undef_sechiba
193 194 195 196 197 198
    area_bx(:,:) = undef_sechiba
    hierarchy_bx(:,:) = undef_sechiba
    fac_bx(:,:) = undef_sechiba
    lon_bx(:,:) = undef_sechiba
    lat_bx(:,:) = undef_sechiba
    lshead_bx(:,:) = undef_sechiba
199 200
    orog_bx(:,:) = undef_sechiba
    floodp_bx(:,:) = undef_sechiba
201 202 203 204 205 206
    cenlon = zero
    cenlat = zero
    !
    IF ( sub_pts(ib) > 0 ) THEN
       !
       DO ip=1,sub_pts(ib)
207 208 209
          IF ( ip >ijdimmax*ijdimmax ) THEN
             CALL ipslerr_p(3,'routing_reg_getgrid','ijdimmax too small when filling lonstr',&
                  &           'Please change method to estimate ijdimmax','')
210 211 212 213 214 215 216 217 218 219 220 221
          ENDIF
          lonstr(ip) = lon_rel(ib, ip)
          latstr(ip) = lat_rel(ib, ip)
       ENDDO
       !
       ! Get the size of the area and order the coordinates to go from North to South and West to East
       !
       CALL routing_sortcoord(sub_pts(ib), lonstr, 'WE', nbi)
       CALL routing_sortcoord(sub_pts(ib), latstr, 'NS', nbj)
       !
       ! Verify dimension and allocated space
       !
222 223 224
       IF ( nbi > ijdimmax .OR. nbj > ijdimmax ) THEN
          WRITE(numout,*) "size of area : nbi=",nbi,"nbj=",nbj, "ijdimmax=", ijdimmax
          CALL ipslerr_p(3,'routing_reg_getgrid','ijdimmax too small','Please change method to estimate ijdimmax','')
225 226 227 228 229 230 231 232 233 234 235
       ENDIF
       !
       ! Transfer the data in such a way that (1,1) is the North Western corner and
       ! (nbi, nbj) the South Eastern.
       !
       DO ip=1,sub_pts(ib)
          ll = MINLOC(ABS(lonstr(1:nbi) - lon_rel(ib, ip)))
          iloc = ll(1)
          ll = MINLOC(ABS(latstr(1:nbj) - lat_rel(ib, ip)))
          jloc = ll(1)
          !
236 237 238 239
          IF ( topoindex(ib, ip) < 0 .OR. topoindex(ib, ip) > 10000 ) THEN
             WRITE(numout,*) "There is an issue with Topoindex : ", topoindex(ib, ip), min_topoind
             WRITE(numout,*) "Check other variables : ", trip(ib, ip), basins(ib, ip), sub_area(ib, ip)
          ENDIF
240 241 242 243
          trip_bx(iloc, jloc) = NINT(trip(ib, ip))
          basin_bx(iloc, jloc) = NINT(basins(ib, ip))
          area_bx(iloc, jloc) = sub_area(ib, ip)
          topoind_bx(iloc, jloc) = topoindex(ib, ip)
244 245
          rlen_bx(iloc, jloc) = rlen(ib, ip)
          rdz_bx(iloc, jloc) = rdz(ib, ip)
246 247
          hierarchy_bx(iloc, jloc) = hierarchy(ib, ip)
          fac_bx(iloc, jloc) = fac(ib, ip)
248 249
          orog_bx(iloc, jloc) = orog(ib, ip)
          floodp_bx(iloc, jloc) = floodp(ib, ip) * sub_area(ib, ip)
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
          lon_bx(iloc, jloc) = lon_rel(ib, ip)
          lat_bx(iloc, jloc) = lat_rel(ib, ip)
          cenlon = cenlon + lon_rel(ib, ip)/sub_pts(ib)
          cenlat = cenlat + lat_rel(ib, ip)/sub_pts(ib)
       ENDDO
       !
    ELSE
       !
       ! This is the case where the model invented a continental point
       !
       nbi = 1
       nbj = 1
       iloc = 1
       jloc = 1
       trip_bx(iloc, jloc) = 98
       basin_bx(iloc, jloc) = NINT(max_basins + 1)
       max_basins = max_basins + 1
       area_bx(iloc, jloc) = resolution(ib,1)*resolution(ib,2)*contfrac(ib)
       topoind_bx(iloc, jloc) = min_topoind
269 270
       rlen_bx(iloc, jloc) = hydro_meanlen
       rdz_bx(iloc, jloc) = hydro_meandz
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
       ! Be careful here: We deal with basin_hierarchy(ib,ij) = min_topoind later!
       hierarchy_bx(iloc, jloc) = min_topoind
       fac_bx(iloc, jloc) = zero
       lon_bx(iloc, jloc) = lalo(ib,2)
       lat_bx(iloc, jloc) = lalo(ib,1)
       !
    ENDIF
    !
    ! Tag in trip all the outflow conditions. The table is thus :
    ! trip = 100+n : Outflow into another grid box
    ! trip = 99 : River outflow into the ocean
    ! trip = 98 : This will be coastal flow (not organized as a basin)
    ! trip = 97 : return flow into the soil (local)
    !
    DO jp=1,nbj
       DO ip=1,nbi
          !
          ! Compute the destination of the flow on the high resolution grid (if possible !) to see if it still within the points
          ! belonging to the grid we are working on.
          !
          IF ( trip_bx(ip,jp) < 97 ) THEN
             !
             ipp = ip+inc(trip_bx(ip,jp),1)
             jpp = jp+inc(trip_bx(ip,jp),2)
             !
             ! Check if the indices are outside of the box, then we have a point on the domain border
             !
             IF ( ipp < 1 .OR. ipp > nbi .OR. jpp < 1 .OR. jpp > nbj ) THEN
                IF (routing_nextgrid(ib,trip_bx(ip,jp)) < -1 ) THEN
                   trip_bx(ip,jp) = 98
                ELSE
                   trip_bx(ip,jp) = trip_bx(ip,jp) + 100
                ENDIF
             ELSE
                !
                ! It can also be a border point if the neighbour is not defined
307
                !
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
                IF ( basin_bx(ipp,jpp) > undef_int-1 ) THEN
                   IF (routing_nextgrid(ib,trip_bx(ip,jp)) < -1 ) THEN
                      trip_bx(ip,jp) = 98
                   ELSE
                      trip_bx(ip,jp) = trip_bx(ip,jp) + 100
                   ENDIF
                ENDIF
             ENDIF
          ELSE IF ( trip_bx(ip,jp) > 100 .AND. trip_bx(ip,jp) < 109 ) THEN
             WRITE(numout,*) 'WARNING : Point flows our of routing.nc file '
             WRITE(numout,*) 'WARNING : Point : basin = ', basin_bx(ip,jp)
             WRITE(numout,*) 'WARNING : Point : coord = ', lon_bx(ip, jp), lat_bx(ip, jp)
             WRITE(numout,*) 'WARNING : Please consider using a larger domaine for the routing.nc file'
             trip_bx(ip,jp) = 98
          ENDIF
          !
       ENDDO
    ENDDO
    !
    ! Compute the large scale flow direction for each outflow point (trip_bx > 100). This
    ! is done by walking into the direction indicated by the small scale trip. The distance of this walk
    ! will depend how far we are from the corner of the polygon. If we are in
    ! the middle of a segment we walk less far than when we are on either corner.
    !
    dlon=ABS(corners_g(ib,NbSegments,1)-corners_g(ib,1,1))
    dlat=ABS(corners_g(ib,NbSegments,2)-corners_g(ib,1,2))
    DO ip=1,NbSegments-1
       dlon = MAX(dlon,ABS(corners_g(ib,ip+1,1)-corners_g(ib,ip,1)))
       dlat = MAX(dlat,ABS(corners_g(ib,ip+1,2)-corners_g(ib,ip,2)))
    ENDDO
    !
    DO jp=1,nbj
       DO ip=1,nbi
          !
          IF ( trip_bx(ip,jp) < undef_int ) THEN
             lshead_bx(ip,jp) = zero
             IF ( trip_bx(ip,jp) > 100 ) THEN
                IF ( nbi > 1 ) THEN
                   facti = REAL(ABS((nbi-1)/2.0-(ip-1)), r_std)/((nbi-1)/2.0)
                ELSE
                   facti = un
                ENDIF
                deslon = lon_bx(ip,jp) + inc(trip_bx(ip,jp)-100,1)*dlon/2.0*facti
                IF ( nbj > 1 ) THEN
                   factj = REAL(ABS((nbj-1)/2.0-(jp-1)), r_std)/((nbj-1)/2.0)
                ELSE
                   factj = un
                ENDIF
                deslat = lat_bx(ip,jp) - inc(trip_bx(ip,jp)-100,2)*dlat/2.0*factj
                lshead_bx(ip,jp) = MOD(haversine_heading(deslon, deslat, cenlon, cenlat)+180.0, 360.0)
             ENDIF
          ENDIF
       ENDDO
    ENDDO
    !
  END SUBROUTINE routing_reg_getgrid
  !
!! ================================================================================================================================
!! SUBROUTINE : routing_reg_findbasins
!!
!>\BRIEF This subroutine finds the basins and does some clean up.
!! The aim is to return the list off all points which are within the
!! same basin of the grid box. This is the faster version of the old routing_reg_findbasins
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! We will also collect all points which directly flow into the ocean in one basin
!! Make sure that we do not have a basin with two outflows and other exceptions.
!! At this stage no effort is made to come down to the truncation of the model.
!!
!! Convention for trip \n
!! ------------------- \n
!! Inside of the box : \n
!! trip = 1 : flow = N \n
!! trip = 2 : flow = NE \n
!! trip = 3 : flow = E \n
!! trip = 4 : flow = SE \n
!! trip = 5 : flow = S \n
!! trip = 6 : flow = SW \n
!! trip = 7 : flow = W \n
!! trip = 8 : flow = NW \n
!! trip = 97 : return flow into the ground \n
!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here \n
!! trip = 99 : river flow into the oceans \n
!!
!! Out flow from the grid : \n
!! trip = 101 : flow = N out of the coarse grid \n
!! trip = 102 : flow = NE out of the coarse grid \n
!! trip = 103 : flow = E out of the coarse grid \n
!! trip = 104 : flow = SE out of the coarse grid \n
!! trip = 105 : flow = S out of the coarse grid \n
!! trip = 106 : flow = SW out of the coarse grid \n
!! trip = 107 : flow = W out of the coarse grid \n
!! trip = 108 : flow = NW out of the coarse grid! \n
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES : None
!!
!! FLOWCHART : None
!! \n
!_ ================================================================================================================================

411 412 413
  SUBROUTINE routing_reg_findbasins(nb_htu, nbv, ib, ijdimmax, nbi, nbj, trip, basin, fac, hierarchy, topoind, &
       & rlen, rdz, rweight, lshead, diaglalo, nb_basin, basin_inbxid, basin_outlet,  basin_outtp, basin_sz, &
       & basin_bxout, basin_bbout, basin_pts, basin_lshead, coast_pts, lontmp, lattmp)
414 415 416 417
    !
    IMPLICIT NONE
    !
!! INPUT VARIABLES
418
    INTEGER(i_std), INTENT(in) :: nb_htu, nbv
419
    INTEGER(i_std), INTENT(in) :: ib !!
420
    INTEGER(i_std), INTENT(in) :: ijdimmax
421 422
    INTEGER(i_std), INTENT(in) :: nbi !! Number of point in x within the grid (unitless)
    INTEGER(i_std), INTENT(in) :: nbj !! Number of point in y within the grid (unitless)
423 424 425
    REAL(r_std), INTENT(in) :: hierarchy(ijdimmax,ijdimmax) !!
    REAL(r_std), INTENT(in) :: fac(ijdimmax,ijdimmax) !!
    REAL(r_std), INTENT(in) :: lshead(ijdimmax,ijdimmax)
426 427 428 429
    REAL(r_std), DIMENSION(:,:), INTENT(in) :: diaglalo !! Point (in Lat/Lon) where diagnostics will be printed.
    !
    ! Modified
    !
430 431
    INTEGER(i_std), INTENT(inout) :: trip(ijdimmax,ijdimmax) !! The trip field (unitless)
    INTEGER(i_std), INTENT(inout) :: basin(ijdimmax,ijdimmax) !!
432
    REAL(r_std), INTENT(inout) :: topoind(ijdimmax,ijdimmax) !! Topographic index of the residence time (km)
433 434
    REAL(r_std), INTENT(inout) :: rlen(ijdimmax,ijdimmax) !! River length (m)
    REAL(r_std), INTENT(inout) :: rdz(ijdimmax,ijdimmax) !! Elevation change (m)
435
    REAL(r_std), INTENT(out)   :: rweight(ijdimmax,ijdimmax) !!
436 437 438 439 440 441 442 443
    !
    ! For debug and get coordinate of river outlet
    !
    REAL(r_std), INTENT(in) :: lontmp(:,:) !! Longitude
    REAL(r_std), INTENT(in) :: lattmp(:,:) !! Latitude
    !
!! OUTPUT VARIABLES
    INTEGER(i_std), INTENT(out) :: nb_basin               !! Number of sub-basins (unitless)
444 445 446 447 448 449 450 451 452
    INTEGER(i_std), INTENT(out) :: basin_inbxid(nb_htu)   !!
    REAL(r_std), INTENT(out)    :: basin_outlet(nb_htu,2) !!
    REAL(r_std), INTENT(out)    :: basin_outtp(nb_htu)    !!
    INTEGER(i_std), INTENT(out) :: basin_sz(nb_htu)       !!
    INTEGER(i_std), INTENT(out) :: basin_bxout(nb_htu)    !!
    REAL(r_std), INTENT(out)    :: basin_lshead(nb_htu)   !!
    INTEGER(i_std), INTENT(out) :: basin_bbout(nb_htu)    !!
    INTEGER(i_std), INTENT(out) :: basin_pts(nb_htu, nbv, 2) !!
    INTEGER(i_std), INTENT(out) :: coast_pts(nb_htu)      !! The coastal flow points (unitless)
453 454
    !
!! LOCAL VARIABLES
455
    LOGICAL, PARAMETER :: debug=.FALSE.
456 457 458 459 460 461 462 463 464 465 466
    CHARACTER(LEN=7) :: fmt !!
    CHARACTER(LEN=9) :: fmtr !!
    !
    LOGICAL :: newpoint !! (true/false)
    INTEGER(i_std), DIMENSION(8,2) :: inc !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: outtmp !!
    !
    INTEGER(i_std) :: nbb, p, cnt, ibas !! To count number of subbasin
    INTEGER(i_std) :: il, jl, ill, jll, ij, iz!!
    INTEGER(i_std) :: totsz, checksz !!
    !
467 468 469 470 471 472 473 474 475 476
    INTEGER(i_std) :: tbname(nb_htu) !!
    INTEGER(i_std) :: tsz(nb_htu) !!
    INTEGER(i_std) :: tpts(nb_htu,nbv,2) !!
    INTEGER(i_std) :: toutdir(nb_htu) !!
    INTEGER(i_std) :: toutbas(nb_htu) !!
    INTEGER(i_std) :: toutloc(nb_htu,2) !!
    REAL(r_std) :: tlon(nb_htu) !!
    REAL(r_std) :: tlat(nb_htu) !!
    REAL(r_std) :: touttp(nb_htu) !!
    REAL(r_std) :: toutlshead(nb_htu) !!
477 478 479 480 481 482
    !
    INTEGER(i_std) :: tmpsz(nbvmax) !!
    INTEGER(i_std) :: ip, jp, jpp(1), ipb !!
    INTEGER(i_std) :: ie, je !!
    INTEGER(i_std) :: sortind(nbvmax) !!
    !
483 484 485
    INTEGER(i_std) :: rivpas(ijdimmax,ijdimmax) !! Number of passage through grid when following rivers
    INTEGER(i_std) :: color(ijdimmax,ijdimmax)
    !
486 487 488 489 490
    INTEGER(i_std) :: itrans !!
    INTEGER(i_std) :: trans(nbvmax) !!
    !
    INTEGER(i_std) :: new_nb !! Number of sub-basins (unitless)
    INTEGER(i_std) :: mp !! Number of dividing sub-basin in mainstream (unitless)
491 492 493 494 495 496 497 498 499
    INTEGER(i_std) :: new_bname(nb_htu) !!
    INTEGER(i_std) :: new_outdir(nb_htu) !!
    REAL(r_std)    :: new_heading(nb_htu)!!
    INTEGER(i_std) :: new_outbas(nb_htu) !!
    INTEGER(i_std) :: new_outloc(nb_htu,2) !!
    REAL(r_std)    :: new_lon(nb_htu) !!
    REAL(r_std)    :: new_lat(nb_htu) !!
    INTEGER(i_std) :: new_sz(nb_htu) !!
    INTEGER(i_std) :: new_pts(nb_htu, nbv, 2) !!
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    INTEGER(i_std) :: oldorder, neworder !!
    !
!_ ================================================================================================================================
    !
    IF ( debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "Point: ", ib
       WRITE(numout,*) "Coord:", lalo(ib,2), lalo(ib,1)
       WRITE(numout,*) "Per: ", nbi, nbj
       !
       WRITE(fmt,"('(',I3,'I6)')") nbi
       WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) trip(1:nbi,je)
       ENDDO
    ENDIF
    !
    ! The routing code (i=1, j=2)
    !
    inc(1,1) = 0
    inc(1,2) = -1
    inc(2,1) = 1
    inc(2,2) = -1
    inc(3,1) = 1
    inc(3,2) = 0
    inc(4,1) = 1
    inc(4,2) = 1
    inc(5,1) = 0
    inc(5,2) = 1
    inc(6,1) = -1
    inc(6,2) = 1
    inc(7,1) = -1
    inc(7,2) = 0
    inc(8,1) = -1
    inc(8,2) = -1
    !
    ! 1.0 Find number of outflow point (>= 97)
    ! So basically, we get nb_basin, basin_bxout, basin_inbxid
    ! (with nbb, toutdir, tbname)
    !
    nbb = 0
    tbname(:) = undef_int
    toutdir(:) = 0
    toutloc(:,:) = 0
    outtmp(:,:) = -1
    !
    toutbas(:) = undef_int
    touttp(:) = undef_int
    toutlshead(:) = undef_sechiba
    !
    DO ip=1,nbi
       DO jp=1,nbj
          !
          !
          IF ( basin(ip,jp) .LT. undef_int) THEN
             ! Because, there is maybe difference between undef_int and undef in routing.nc
             !IF ( trip(ip,jp) .GE. 97 .AND. trip(ip,jp) .LT. undef_int ) THEN
             IF ( trip(ip,jp) .GE. 97 .AND. trip(ip,jp) .LT. 109 ) THEN
                nbb = nbb + 1
                IF ( nbb .GT. nbvmax ) CALL ipslerr_p(3,'routing_reg_findbasins','nbvmax too small','first section','')
                tbname(nbb) = basin(ip,jp)
                toutdir(nbb) = trip(ip,jp)-100
                toutlshead(nbb) = lshead(ip,jp)
                touttp(nbb) = trip(ip,jp)
                toutloc(nbb,1) = ip
                toutloc(nbb,2) = jp
                tlat(nbb) = lattmp(ip,jp)
                tlon(nbb) = lontmp(ip,jp)
                outtmp(ip,jp) = nbb
             ENDIF
          ENDIF
       ENDDO
    ENDDO
    !
    ! 2.0 Follow the flow of the water to get size and gather point for each
    ! sub-basin. So we get basin_sz, basin_pts (with tsz, tpts)
    !
    totsz = 0
    tsz(:) = 0
    tpts(:,:,:) = 0
    !
    DO ip=1,nbi
       DO jp=1,nbj
         IF ( basin(ip,jp) .LT. undef_int) THEN
         ! Think about basin .LT. undef_int here
         !IF ( trip(ip,jp) .GT. 0 .AND. trip(ip,jp) .LT. undef_int ) THEN
         IF ( trip(ip,jp) .GT. 0 .AND. trip(ip,jp) .LT. 109 ) THEN
           p = trip(ip,jp)
           cnt = 0
           il = ip ; jl = jp
           newpoint = .TRUE.
           DO WHILE ( p .GT. 0 .AND. p .LT. 9 .AND. cnt .LT. nbi*nbj .AND. newpoint )
              cnt = cnt + 1
              ill = il + inc(p,1)
              jll = jl + inc(p,2)
              il = ill ; jl = jll
              p = trip(il,jl)
              IF ( outtmp(il,jl) .NE. -1 ) newpoint = .FALSE.
           ENDDO
           !
           !
           IF ( cnt .EQ. nbi*nbj) THEN
              IF ( debug ) THEN
                 WRITE(numout,*) "Error: cnt .EQ. nbi*nbj, ib= ",ib
                 WRITE(numout,*) "Point: ", ip, jp
                 WRITE(numout,*) "Per: ", nbi, nbj
                 WRITE(numout,*) "Number of outlet: ", nbb, cnt
                 WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmt,"('(',I3,'I6)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmt) outtmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) trip(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) basin(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lontmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lattmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ HIERARCHY IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) hierarchy(1:nbi,je)
                 ENDDO
                 CALL FLUSH(numout)
              ENDIF
              CALL ipslerr_p(3,'routing_reg_findbasins','We could not route point','','')
           ENDIF
           !
           IF ( outtmp(il,jl) .NE. -1 ) THEN
              ibas = outtmp(il,jl)
              tsz(ibas) = tsz(ibas) + 1
              IF ( tsz(ibas) .GT. nbvmax ) CALL ipslerr_p(3,'routing_reg_findbasins','nbvmax too small','second section','')
              tpts(ibas, tsz(ibas), 1) = ip
              tpts(ibas, tsz(ibas), 2) = jp
              outtmp(ip,jp) = outtmp(il,jl)
           ELSE
              IF ( debug ) THEN
                 WRITE(numout,*) "Error: outtmp(il,jl) .EQ. -1 ", ib
                 WRITE(numout,*) "Point: ", ip, jp
                 WRITE(numout,*) "Per: ", nbi, nbj
                 WRITE(numout,*) "Number of outlet: ", nbb
                 WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmt,"('(',I3,'I6)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmt) outtmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) trip(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) basin(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lontmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lattmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ HIERARCHY IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) hierarchy(1:nbi,je)
                 ENDDO
              ENDIF
              CALL FLUSH(numout)
              WRITE (numout,*) ' outtmp(il,jl):', outtmp(il,jl)
              WRITE (numout,*) ' trip(il,jl):', trip(il,jl)
              CALL ipslerr_p(3,'routing_reg_findbasins','We could not find right outlet','','')
           ENDIF
           !
           totsz = totsz + 1
         ENDIF
         ! Testing this IF
         ENDIF
       ENDDO
    ENDDO
    !
    IF (  debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "=== To check grid before dividing sub-basin ==="
       WRITE(numout,*) "Number of points: ", nbi, nbj
       WRITE(numout,*) "Number of outlet: ", nbb
       WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmt,"('(',I3,'I6)')") nbi
       DO je=1,nbj
          WRITE(numout,fmt) outtmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) trip(1:nbi,je)
       ENDDO
    ENDIF
    !
    ! 4.0 Use the level 1 of the Pfafstetter coding system to divide the large
721
    ! sub-grid basin. The large sub-grid basin here is defined by the area
722 723 724 725 726 727 728 729 730 731 732 733
    ! larger than 9% of grid box area. This threshold should be discussed later.
    !
    ! Make a loop through all sub-grid basins to find if there is big sub-grid basin.
    !
    ! We need at least one subbasin with size greater than 4 (to have at least one
    ! tributary). If you run ORCHIDEE with high resolution, such as 5 km, you
    ! don't need to divide the subbasin too small.
    !
    ! Check if there is still subbasin with area larger than [maxpercent] % of total area
    !
    DO WHILE ( COUNT(tsz(:)/REAL(totsz) >= maxpercent/REAL(100) ) > 0 .AND. COUNT(tsz(:) >= 4 ) > 0 )
       !
734
       cnt = 0
735 736 737 738 739 740 741 742 743
       DO ibas = 1, nbb
          ! Only take the subbasin is bigger than 4 points
          IF (( tsz(ibas)/REAL(totsz) .GE. maxpercent/REAL(100) ) .AND. ( tsz(ibas) .GE. 4 )) THEN
             cnt = cnt + 1
             trans(cnt) = ibas
          ENDIF
       ENDDO
       !
       ! cnt should be greater or equal 1 here
744
       DO ipb = 1, cnt
745 746 747
          !
          ibas = trans(ipb)
          !
748 749
          CALL routing_reg_divbas(nb_htu, nbv, nbi, nbj, ibas, toutloc(ibas,1), toutloc(ibas,2),&
             & tsz(ibas), toutbas(ibas), toutdir(ibas), &
750
             & toutlshead(ibas), tpts, trip, basin, fac, lontmp, lattmp, &
751 752
             & new_nb, mp, new_bname, new_outdir, new_heading, new_outbas, new_lat, new_lon, new_outloc, new_sz, new_pts)
          !
753
          ! If the dividing step is ok
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
          !
          IF ( new_nb .NE. 0 ) THEN
             !
             ! If we have split the basin then we need to change the old one
             !
             tbname(ibas) = new_bname(1)
             toutdir(ibas) = new_outdir(1)
             toutlshead(ibas) = new_heading(1)
             !
             IF ( new_outbas(1) .NE. undef_int ) THEN
                IF ( mp .NE. 1 ) THEN
                   toutbas(ibas) = new_outbas(1)+nbb-1
                ELSE
                   toutbas(ibas) = new_outbas(1)
                ENDIF
             ENDIF
             !
             toutloc(ibas,:) = new_outloc(1,:)
             tlat(ibas) = new_lat(1)
             tlon(ibas) = new_lon(1)
             !
             touttp(ibas) = trip(new_outloc(1,1),new_outloc(1,2))
             !
             tsz(ibas) = new_sz(1)
             tpts(ibas,:,:) = new_pts(1,:,:)
779
             DO p = 1, tsz(ibas)
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
                outtmp(tpts(ibas,p,1),tpts(ibas,p,2)) = ibas
             ENDDO
             !
             !  Add the new sub-grid basins to the end of the list
             !
             IF ( nbb+new_nb-1 .LE. nbvmax) THEN
                DO ip = 2, new_nb
                   tbname(nbb+ip-1) = new_bname(ip)
                   toutdir(nbb+ip-1) = new_outdir(ip)
                   toutlshead(nbb+ip-1) = new_heading(ip)
                   !
                   ! Trung: Should come back here soon (small bug can come from
                   ! Trung: this point)
                   !
                   IF ( new_outbas(ip) .EQ. 1 .AND. ip .NE. mp ) THEN
                      toutbas(nbb+ip-1) = ibas
796
                   ELSE IF ( ip .NE. mp ) THEN
797 798 799 800 801 802 803 804 805 806 807 808 809
                      toutbas(nbb+ip-1) = new_outbas(ip)+nbb-1
                   ELSE
                      toutbas(nbb+ip-1) = new_outbas(ip)
                   ENDIF
                   !
                   toutloc(nbb+ip-1,:) = new_outloc(ip,:)
                   tlat(nbb+ip-1) = new_lat(ip)
                   tlon(nbb+ip-1) = new_lon(ip)
                   !
                   touttp(nbb+ip-1) = trip(new_outloc(ip,1),new_outloc(ip,2))
                   !
                   tsz(nbb+ip-1) = new_sz(ip)
                   tpts(nbb+ip-1,:,:) = new_pts(ip,:,:)
810
                   DO p = 1, tsz(nbb+ip-1)
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
                      outtmp(tpts(nbb+ip-1,p,1),tpts(nbb+ip-1,p,2)) = nbb+ip-1
                   ENDDO
                ENDDO
                nbb = nbb+new_nb-1
             ELSE
                WRITE(numout,*) 'Increase nbvmax. It is too small to contain all the basins (routing_reg_findbasins)'
                CALL ipslerr_p(3,'routing_reg_findbasins','Increase nbvmax.','It is too small to contain all the basins','')
             ENDIF
             !
          ELSE
             !
             ! Print some information if the division failed
             !
             WRITE(numout,*) 'Can not divide sub-basins (routing_reg_findbasins): ',ibas
             CALL ipslerr_p(3,'routing_reg_findbasins','new_nb = 0','Something is wrong with routing_reg_divbas','')
826
             !
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
          ENDIF
       ENDDO
       !
    ENDDO
    !
    ! 3.0 Gather coastal points
    !
    itrans = 0
    coast_pts(:) = undef_int
    !
    ! Get all the points we can collect (negative value of IDs in routing.nc)
    !
    DO ip=1,nbb
       IF ( tsz(ip) .EQ. 1 .AND. trip(tpts(ip,1,1),tpts(ip,1,2)) .EQ. 98 .AND. tbname(ip) .LT. 0 ) THEN
          itrans = itrans + 1
          trans(itrans) = ip
       ENDIF
    ENDDO
    !
    ! Put everything in the first basin (beware of tbname(trans(1)) can be negative)
    !
    IF ( itrans .GT. 1) THEN
       ipb = trans(1)
       coast_pts(tsz(ipb)) = tbname(ipb)
       tbname(ipb) = -1
       DO ip=2,itrans
          tsz(ipb) = tsz(ipb) + 1
          coast_pts(tsz(ipb)) = tbname(trans(ip))
          tsz(trans(ip)) = 0
          tpts(ipb, tsz(ipb), 1) = tpts(trans(ip), 1, 1)
          tpts(ipb, tsz(ipb), 2) = tpts(trans(ip), 1, 2)
          !
          outtmp(tpts(ipb, tsz(ipb), 1),tpts(ipb, tsz(ipb), 2)) = ipb
       ENDDO
    ENDIF
    !
    ! A.0 To check each grid when testing this subroutine
    !
    IF (  debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "=== To check grid after dividing sub-basin ==="
       WRITE(numout,*) "Number of points: ", nbi, nbj
       WRITE(numout,*) "Number of outlet: ", nbb
       WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmt,"('(',I3,'I6)')") nbi
       DO je=1,nbj
          WRITE(numout,fmt) outtmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) trip(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) basin(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) lontmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) lattmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ HIERARCHY IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) hierarchy(1:nbi,je)
       ENDDO
       WRITE(numout,*) "=== ====================================== ==="
       !
       WRITE(numout,*) '+++++++++++++++++++ FAC IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) fac(1:nbi,je)
       ENDDO
       WRITE(numout,*) "=== ====================================== ==="
    ENDIF
    !
    ! 5.0 Sort the output by size of the various basins.
    !
    nb_basin = COUNT(tsz(1:nbb) .GT. 0)
    tmpsz(:) = -1
    tmpsz(1:nbb) = tsz(1:nbb)
    DO ip=1,nbb
       jpp = MAXLOC(tmpsz(:))
       IF ( tsz(jpp(1)) .GT. 0) THEN
          sortind(ip) = jpp(1)
          tmpsz(jpp(1)) = -1
       ENDIF
    ENDDO
    basin_inbxid(1:nb_basin) = tbname(sortind(1:nb_basin))
    basin_outlet(1:nb_basin,1) = tlat(sortind(1:nb_basin))
    basin_outlet(1:nb_basin,2) = tlon(sortind(1:nb_basin))
    basin_outtp(1:nb_basin) = touttp(sortind(1:nb_basin))
    basin_sz(1:nb_basin) = tsz(sortind(1:nb_basin))
    basin_pts(1:nb_basin,:,:) = tpts(sortind(1:nb_basin),:,:)
    basin_bxout(1:nb_basin) = toutdir(sortind(1:nb_basin))
    basin_lshead(1:nb_basin) = toutlshead(sortind(1:nb_basin))
    !
    ! Correct toutbas after sorting
    !
    basin_bbout(1:nb_basin) = undef_int
    DO ip = 1, nb_basin
       IF ( toutbas(sortind(ip)) .NE. undef_int ) THEN
          neworder = 0
          oldorder = toutbas(sortind(ip))
          DO ie = 1, nb_basin
             IF ( sortind(ie) .EQ. oldorder ) THEN
                neworder = ie
             ENDIF
          ENDDO
          IF ( neworder .NE. 0 ) THEN
946
             basin_bbout(ip) = neworder
947 948 949 950 951 952 953 954 955 956 957 958 959 960
          ELSE
             WRITE(numout,*) 'ip, sortind(ip) :', ip, sortind(ip)
             WRITE(numout,*) 'toutbas(sortind(ip)) :', toutbas(sortind(ip))
             WRITE(numout,*) 'Found new order :', neworder
             !
             WRITE(numout,*) 'nb_basin & nbb :', nb_basin, nbb
             WRITE(numout,*) 'sortind(1:nb_basin) :', sortind(1:nb_basin)
             WRITE(numout,*) 'tsz(sortind(1:nb_basin)) :', tsz(sortind(1:nb_basin))
             WRITE(numout,*) 'tsz(1:nbb) :', tsz(1:nbb)
             WRITE(numout,*) 'toutbas(sortind(1:nb_basin)) :', toutbas(sortind(1:nb_basin))
             WRITE(numout,*) 'toutdir(sortind(1:nb_basin)) :', toutdir(sortind(1:nb_basin))
             WRITE(numout,*) 'tbname(sortind(1:nb_basin)) :', tbname(sortind(1:nb_basin))
             WRITE(numout,*) 'toutbas(1:nbb) :', toutbas(1:nbb)
             !
961
             CALL ipslerr_p(3,'routing_reg_findbasins','We got problem when sorting toutbas','','')
962 963
          ENDIF
       ENDIF
964
    ENDDO
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    !
    IF (  debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "Grid box: ", ib
       WRITE(numout,*) "Number of points: ", nbi, nbj
       WRITE(numout,*) mpi_rank, "=== To check coastal point simplify ==="
       WRITE(numout,*) "Number of outlet: "
       WRITE(numout,*) " + Before gather: ", nbb
       WRITE(numout,*) " + After gather: ", nb_basin
       WRITE(numout,*) mpi_rank, "=== To check dividing sub-basin process ==="
       ip = COUNT(basin_bxout(1:nb_basin) .GE. -3 .AND. basin_bxout(1:nb_basin) .LE. -1 )
       WRITE(numout,*) "Outlet to lake, ocean: ", ip
       ip = COUNT(basin_bxout(1:nb_basin) .GE. 1 .AND. basin_bxout(1:nb_basin) .LE. 8 )
       WRITE(numout,*) "Outlet to other grid box: ", ip
       ip = COUNT(basin_bxout(1:nb_basin) .EQ. -4)
       WRITE(numout,*) "Outlet in the same grid box: ", ip
       ip = COUNT(basin_bbout(1:nb_basin) .NE. undef_int)
       WRITE(numout,*) "Should be the same value as above: ", ip
    ENDIF
    !
    ! 6.0 Make simple verification
    ! What is the size of the region behind each outflow point ?
    ! We can only check if we have at least as many outflows as basins
    !
    checksz = 0
    DO ip=1,nbb
       checksz = checksz + tsz(ip)
    ENDDO
    IF ( checksz .NE. totsz) THEN
       WRITE(numout,*) 'Water got lost while I tried to find basins'
       WRITE(numout,*) checksz, ' /= ', totsz
       CALL ipslerr_p(3,'routing_reg_findbasins','Water got lost while I tried to find basins','','')
    ENDIF
    !
    ip = COUNT(trip(1:nbi,1:nbj) .GE. 97 .AND. trip(1:nbi,1:nbj) .LT. undef_int)
    ip = ip + COUNT(trip(1:nbi,1:nbj) .EQ. -4)
    IF ( ip .LT. nb_basin ) THEN
       WRITE(numout,*) 'We found some coastal point here :', ip
       WRITE(numout,*) 'nb_basin :', nb_basin
       WRITE(numout,*) 'Basin sized :', basin_sz(1:nb_basin)
    ENDIF
    !
    ! 7.0 If we calculate topoindex with option 3
    !     we need to accumulate the topoind_bx along the flow
    !
1009 1010 1011 1012 1013 1014 1015
    DO ij=1,nb_basin
       DO iz=1,basin_sz(ij)
          ip = basin_pts(ij,iz,1)
          jp = basin_pts(ij,iz,2)
          color(ip,jp) = ij
       ENDDO
    ENDDO
1016
    !
1017 1018 1019
    ! Add current point to the weight calculation.
    rweight(:,:) = 1.0
    !
1020 1021
    ! Work only for topo_option number 3 or 4
    !
1022
    IF ( topo_option .EQ. 3 .OR. topo_option .EQ. 4) THEN
1023
       rivpas(:,:) = 0
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
       ! Loop for all sub-basins and each point belongs to that sub-basin
       DO ij=1,nb_basin
          DO iz=1,basin_sz(ij)
             ! Get the coordinate of this point
             ip = basin_pts(ij,iz,1)
             jp = basin_pts(ij,iz,2)
             ! Start to accumulate "topoind" if this is not a outlet point
             IF ( trip(ip,jp) .GT. 0 .AND. trip(ip,jp) .LT. 97 ) THEN
                p = trip(ip,jp)
                cnt = 0
                il = ip ; jl = jp
1035 1036
                ! Only follow the river witin the current HTU
                DO WHILE ( ij == color(il,jl) .AND. p .GT. 0 .AND. p .LT. 9 .AND. cnt .LT. nbi*nbj )
1037 1038 1039 1040 1041 1042 1043
                   cnt = cnt + 1
                   ill = il + inc(p,1)
                   jll = jl + inc(p,2)
                   ! Of course, if you are careful, you will want to check if
                   ! this point still belongs to current sub-basin. Here I
                   ! assume that the sub-routine routing_reg_divbas worked well.
                   ! So we don't need to check.
1044 1045 1046
                   topoind(ip,jp) = topoind(ip,jp)+topoind(ill,jll)
                   rlen(ip,jp) = rlen(ip,jp)+rlen(ill,jll)
                   rdz(ip,jp) = rdz(ip,jp)+rdz(ill,jll)
1047
                   rivpas(ill,jll) = rivpas(ill,jll)+1
1048
                   rweight(ip,jp) = rweight(ip,jp)+1.0
1049 1050 1051 1052 1053 1054 1055
                   !
                   il = ill ; jl = jll
                   p = trip(il,jl)
                ENDDO
             ENDIF
             !
          ENDDO
1056 1057 1058 1059 1060 1061 1062
          ! Second pass through all points of the HTU to keep only the topoindex of full rivers.
          ! These are those throug which we did not pass when following the rivers.
          cnt = 0
          DO iz=1,basin_sz(ij)
             ip = basin_pts(ij,iz,1)
             jp = basin_pts(ij,iz,2)
             IF ( rivpas(ip,jp) == 0 ) THEN
1063
                cnt = cnt + rweight(ip,jp) 
1064
             ELSE
1065 1066 1067 1068
                topoind(ip,jp) = zero
                rlen(ip,jp) = zero
                rdz(ip,jp) = zero
                rweight(ip,jp) = zero
1069 1070 1071 1072 1073 1074 1075
             ENDIF
          ENDDO
          ! Finish the weight computation of the rivers followed
          IF ( cnt > 0 ) THEN
             DO iz=1,basin_sz(ij)
                ip = basin_pts(ij,iz,1)
                jp = basin_pts(ij,iz,2)
1076
                rweight(ip,jp) = rweight(ip,jp)/cnt
1077 1078
             ENDDO
          ENDIF
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
       ENDDO
    ENDIF
    !
  END SUBROUTINE routing_reg_findbasins
  !
!! ================================================================================================================================
!! SUBROUTINE : routing_reg_divbas
!!
!>\BRIEF This subroutine divide the large sub-grid basins to smaller ones. It is
!! based on The Pfafstetter Coding System for Watershed Identification. You can
!! find information here (for example):
!! http://ponce.sdsu.edu/pfafstetter_system_revised_presentation.html
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES : None
!!
!! FLOWCHART : None
!! \n
!_ ================================================================================================================================

1104
  SUBROUTINE routing_reg_divbas(nb_htu, nbv, nbi, nbj, ibas, iloc, jloc, tsz, tout, toutd, headd, &
1105 1106 1107 1108 1109 1110
                & tpts, trip, basin, fac, lon, lat,      &
                & new_nb, oic, new_bname, new_outdir, new_head, new_outbas, new_lat, new_lon, new_outloc, new_sz, new_pts)
    !
    IMPLICIT NONE
    !
!! INPUT VARIABLES
1111
    INTEGER(i_std), INTENT(in) :: nb_htu, nbv
1112 1113
    INTEGER(i_std), INTENT(in) :: nbi !! Number of point in x within the grid (unitless)
    INTEGER(i_std), INTENT(in) :: nbj !! Number of point in y within the grid (unitless)
1114
    INTEGER(i_std), INTENT(in) :: ibas !! Order of the basin will be divided
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    INTEGER(i_std), INTENT(in) :: iloc, jloc !! Outlet location
    !
    INTEGER(i_std), INTENT(in) :: tsz !! Size of sub-basin
    INTEGER(i_std), INTENT(in) :: tout !! Outlet type
    INTEGER(i_std), INTENT(in) :: toutd !! Outlet direction
    REAL(r_std), INTENT(in)    :: headd
    INTEGER(i_std), INTENT(in) :: tpts(:,:,:) !!
    INTEGER(i_std), INTENT(in) :: basin(:,:) !!
    REAL(r_std), INTENT(in) :: fac(:,:) !!
    REAL(r_std), INTENT(in) :: lon(:,:), lat(:,:) !!
    !
!! MODIFIED VARIABLES
    INTEGER(i_std), INTENT(inout) :: trip(:,:) !!
    !
!! OUTPUT VARIABLES
    INTEGER(i_std), INTENT(out) :: new_nb !! Number of sub-basins (unitless)
    INTEGER(i_std), INTENT(out) :: oic
1132 1133 1134 1135 1136 1137 1138 1139 1140
    INTEGER(i_std), INTENT(out) :: new_bname(nb_htu) !!
    INTEGER(i_std), INTENT(out) :: new_outdir(nb_htu) !!
    REAL(r_std), INTENT(out)    :: new_head(nb_htu) !!
    INTEGER(i_std), INTENT(out) :: new_outbas(nb_htu) !!
    INTEGER(i_std), INTENT(out) :: new_outloc(nb_htu,2) !!
    REAL(r_std), INTENT(out) :: new_lon(nb_htu) !!
    REAL(r_std), INTENT(out) :: new_lat(nb_htu) !!
    INTEGER(i_std), INTENT(out) :: new_sz(nb_htu) !!
    INTEGER(i_std), INTENT(out) :: new_pts(nb_htu, nbv, 2) !!
1141 1142 1143
    !
!! LOCAL VARIABLES
    REAL(r_std), PARAMETER :: flag=-9999. !!
1144
    LOGICAL, PARAMETER :: debug=.FALSE.
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
    LOGICAL, PARAMETER :: checkgrid=.FALSE.
    CHARACTER(LEN=7) :: fmt !!
    CHARACTER(LEN=9) :: fmtr !!
    CHARACTER(LEN=11) :: afmt !!
    CHARACTER(LEN=13) :: afmtr !!
    !
    !
    REAL(r_std), DIMENSION(nbi,nbj) :: factmp !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: triptmp !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: triptemp !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: basintmp !!
    REAL(r_std), DIMENSION(nbi,nbj) :: lontmp, lattmp !!
    !
1158
    INTEGER(i_std) :: il, jl, ill, jll, jp !!
1159
    INTEGER(i_std) :: ie, je !!
1160
    INTEGER(i_std) :: p, cnt, k, l, ic, ik, cut !!
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    INTEGER(i_std) :: ip, isz, checksz !!
    INTEGER(i_std) :: ff(1) !!
    !
    LOGICAL :: okpoint=.TRUE.
    !
    ! Number of neighbours on the HydroShed grid (regular Lat/Lon)
    !
    INTEGER(i_std), PARAMETER :: nbne=8
    INTEGER(i_std), DIMENSION(nbne,2) :: inc !!
    !
    ! Explanation for dimension of below arrays:
    !
    ! + Firstly, I suggest that you should read about the Pfafstetter Coding
    ! System, here for example:
    ! http://ponce.sdsu.edu/pfafstetter_system_revised_presentation.html
    !
    !    * Note: It will be easier if you keep in mind that the original
    !    information given in grid box of nbi*nbj. But here, to deal with main
    !    stem and tributaries, I need to store them to cnt*nbne (exactly,
    !    cnt*[nbne-2]). Where, cnt is the length of main stem and nbne is number
    !    of neighbour points, and usually 2 neighbour points will belongs to
    !    main stem.
    !
    ! + You will see steps for coding the sub-basin are:
    !
    !    - From the sub-basin outlet, trace upstream along the main stem of the
    !    river, and get the tributaries. To store location and flow accumulation
    !    of points belongs to main stream and tributaries:
    !
1190 1191
    INTEGER(i_std) :: main_loc(nbv,2), tri_loc(nbne,nbv,2)
    REAL(r_std) :: main_fac(nbv), tri_fac(nbne,nbv)
1192 1193
    REAL(r_std) :: diff_main_fac(nbv)
    REAL(r_std) :: half_output_fac
1194
    REAL(r_std) :: tmptri_fac(nbne)  ! Flow accumulation of all neighbour points
1195
    INTEGER(i_std) :: sortedtrifac(nbne) ! And sort of tmptri_fac(nbne)
1196 1197 1198
    REAL(r_std) :: alltri_fac(nbv) ! Sort flow accumulation of all tributaries
    INTEGER(i_std) :: alltri_loc1(nbv), alltri_loc2(nbv) ! And their location
    INTEGER(i_std) :: sortedallfac(nbv) ! Sort alltri_fac(nbv)
1199
    !
1200 1201 1202 1203 1204 1205
    !     *  Note: again, there are few dimensions should be exactly [nbne-1]
    !     or [nbne-2]. Because when you follow upstream the mainstream, there are
    !     always at least ONE neighbour points will not belong to TRIBUTARY.
    !     But to make your life easier, I put all "nbne" here.
    !
    !    - Identify the 4 greatest tributaries:
1206
    !
1207 1208 1209 1210 1211 1212 1213 1214
    REAL(r_std) :: tmpmain_fac(4) ! Flow accumulations of 4 greatest tributaries
    INTEGER(i_std) :: tmpmain_loc(4,2), sortedmainfac(4) ! And their locations and sorted values
    INTEGER(i_std) :: numtri(4), usetri_loc(4,4,2) ! Counting and store location when processing these 4 points
    !
    !    - Inter-basins are the watersheds that contribute flow to the main
    !    stem: there can be 5 inter-basins. So we need 9 dividing points:
    !
    INTEGER(i_std) :: divloc(9,2) ! Location of dividing points (maximum is 9)
1215
    !
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

!_ ================================================================================================================================

    !
    ! The routing code (i=1, j=2)
    !
    inc(1,1) = 0
    inc(1,2) = -1
    inc(2,1) = 1
    inc(2,2) = -1
    inc(3,1) = 1
    inc(3,2) = 0
    inc(4,1) = 1
    inc(4,2) = 1
    inc(5,1) = 0
    inc(5,2) = 1
    inc(6,1) = -1
    inc(6,2) = 1
    inc(7,1) = -1
    inc(7,2) = 0
    inc(8,1) = -1
    inc(8,2) = -1
    !
    ! 0.0 Get the information of all the points belongs to the subbasin
    ! which need to divide. Flag for flow accumulation is -9999 (the value of
    ! flow accumulation should be always non negative).
    !
    factmp(:,:) = flag
    basintmp(:,:) = 0
    lontmp(:,:) = 0
    lattmp(:,:) = 0
    triptmp(:,:) = -1
    triptemp(:,:) = -1
    !
    DO isz = 1, tsz
       il = tpts(ibas, isz, 1)
       jl = tpts(ibas, isz, 2)
       !
       factmp(il,jl) = fac(il,jl)
       triptmp(il,jl) = trip(il,jl)
       triptemp(il,jl) = trip(il,jl)
       basintmp(il,jl) = basin(il,jl)
       lontmp(il,jl) = lon(il,jl)
       lattmp(il,jl) = lat(il,jl)
    ENDDO
    !
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    ! Calculation of local flow accumulation
    factmp(:,:) = 0
    DO isz = 1, tsz
       ip = tpts(ibas, isz, 1)
       jp = tpts(ibas, isz, 2)
       IF ( trip(ip,jp) .GT. 0 .AND. trip(ip,jp) .LT. 109 ) THEN
         p = trip(ip,jp)
         il = ip ; jl = jp
         DO WHILE ( p .GT. 0 .AND. p .LT. 9 .AND. cnt .LT. nbi*nbj)
           ill = il + inc(p,1)
           jll = jl + inc(p,2)
           il = ill ; jl = jll
           factmp(il, jl) = factmp(il, jl) + 1
           p = trip(il,jl)