hrudelin_1_init.py 25.76 KiB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 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 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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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 266 267 268 269 270 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 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 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


############################################################################
#
# MODULE:       hrudelin_1_init.py
# AUTHOR(S):    adapted from GRASS-HRU (ILMS) - JENA University
#               by IRSTEA - Christine Barachet,
#               Julien Veyssier
# PURPOSE:      Prepare files for the next steps of HRU Delineation
#               shapefile : selected gauges
#               rasters :   bounded DEM and others (geology, soils, landuse)
#                           DEM, slope and aspect with values of reclassification
#                           calculates oriented flows and subbasins
#
# COPYRIGHT:    (C) 2020 UR RIVERLY - INRAE
#
#               This program is free software under the GNU General Public
#               License (>=v2). Read the file LICENSE that comes with 
#                HRU-DELIN for details.
#
#############################################################################



# to keep python2 compatibility
from __future__ import print_function
import string, os, shutil, sys, glob, types
import math
import json
try:
    import ConfigParser
except Exception as e:
    import configparser as ConfigParser
# use wrappers now !
#import grass.script as grass
from grass.script.utils import decode, encode

from osgeo import ogr

from utils import cutting_raster, get_raster_bounds, get_polygon_bounds 
from utils import isfloat, isint, get_coords, is_valid_shp, is_valid_geometry
from utils import is_column_exist, is_column_valid, is_column_value_unique
from utils import are_columns_value_unique

MY_ABS_PATH=os.path.abspath(__file__)
MY_DIR=os.path.dirname(MY_ABS_PATH)
DATA_PATH=os.path.join(MY_DIR, '..', 'data')



try:
    # Python 3
    from subprocess import DEVNULL
except ImportError:
    #DEVNULL = open('cbtrace_step1', 'wb')
    DEVNULL = open(os.devnull, 'wb')





'''
 MAIN
'''
def main(parms_file):
    print('---------- HRU-delin Step 1 started ---------------------------------------------')

    #test gdal version; must be at least >=3
    if int(gdal.VersionInfo('VERSION_NUM'))< 3000000:
        sys.exit('------------> ERROR : GDAL version mut be at least >= 3.0')

    
    configFileDir = os.path.dirname(parms_file)
    # create main env
    buildGrassEnv(os.path.join(configFileDir, 'grass_db'), 'hru-delin')
    os.environ['GISRC'] = os.path.join(configFileDir, 'grass_db', 'grassdata', 'hru-delin', '.grassrc')
    # Get parameters from configuration file
    parms = ConfigParser.ConfigParser(allow_no_value=True)
    parms.read(parms_file)
    directory = parms.get('dir_in', 'dir')


    # Test parameters from configuration file
        ## test if directory is valid
    
    if not os.path.isdir(directory):
        sys.exit('------------> ERROR : In Directoy is not valid')
        
        ## manage absolute and relative paths
    if not os.path.isabs(directory):
        directory = os.path.join(configFileDir, directory)
    
    directory_out = parms.get('dir_out', 'files')
    if not os.path.isabs(directory_out):
        directory_out = os.path.join(configFileDir, directory_out)

        ## Test if dem exist
    dem = os.path.join(directory, str(parms.get('dem', 'dem')))
    if not os.path.isfile(dem):
        msg="------------> ERROR : Input Dem "+ dem+" not found"
        sys.exit(msg)
        
    ## if hgeon, landuse and soil provided, test if exist
    for data in parms.items('data'):
        data = os.path.join(directory, data[1])
        if not os.path.isfile(data):
            print(data)
            sys.exit('------------> ERROR : Input data not found' )  

        
     
    ## Test if gauges exist
    gauges = os.path.join(directory, str(parms.get('gauges', 'gauges')))
    is_valid_shp(gauges)
       
    ## Test if gauges is point or multipoint
    is_valid_geometry(gauges,'Point')
            
    ## Test gauges_col_name
    gauges_col_name = parms.get('gauges', 'gauges_col_name')
    if gauges_col_name == '':
        msg="------------> ERROR : CHECK gauges_col_name PARAMETER"
        sys.exit(msg)

    ## In gauges, test if gauges_col_name exist and if no null value
    is_column_exist(gauges,gauges_col_name)
    is_column_valid(gauges,gauges_col_name)
    is_column_value_unique(gauges,gauges_col_name)

    ## Test gauges_area_col_name
    gauges_area_col_name = parms.get('gauges', 'gauges_area_col_name')
    if gauges_area_col_name == '':
        msg="------------> ERROR : CHECK gauges_area_col_name PARAMETER"
        sys.exit(msg)

    ## In gauges, test if gauges_area_col_name exist and if no null value
    is_column_exist(gauges,gauges_area_col_name)
    is_column_valid(gauges,gauges_area_col_name)

        
    gauges_file = parms.get('gauges', 'relocated_gauges')
    if gauges_file != '':
        is_valid_shp(gauges_file)
            

         

        ## if irrigation is yes, test input data
    if str(parms.get('irrigation', 'to_do')) == 'yes':
        irrig = os.path.join(directory, str(parms.get('irrigation', 'irrigation')))
        is_valid_shp(irrig) 
        
        ## Test if irrigation is point or multipoint
        is_valid_geometry(irrig,'Point')
                
        ## Test irrig_col_name
        irrig_col_name = parms.get('irrigation', 'irrig_col_name')
        if irrig_col_name == '':
            sys.exit('------------> ERROR : CHECK irrig_col_name PARAMETER in Irrigation')

        ## In irrigation, test if irrig_col_name exists and if no null value
        is_column_exist(irrig,irrig_col_name)
        is_column_valid(irrig,irrig_col_name)
        is_column_value_unique(irrig,irrig_col_name)
       
        ## Test irrig_col_type
        irrig_col_type = parms.get('irrigation', 'irrig_col_type')
        if irrig_col_type == '':
            sys.exit('------------> ERROR : CHECK irrig_col_type PARAMETER in Irrigation')

        ## In irrigation, test if irrig_col_type exists 
        is_column_exist(irrig,irrig_col_type)


        #if min_surf_GU is provided, test value:
        irrig_surf_min_GU = parms.get('irrigation', 'irrig_surf_min_GU')
        if irrig_surf_min_GU != '':
            try:
                isinstance(float(irrig_surf_min_GU),float)
            except:    
                sys.exit('------------> ERROR : irrig_surf_min_GU PARAMETER is not integer or double')

        irrig_col_min_GU = parms.get('irrigation', 'irrig_col_min_GU')
        if irrig_col_min_GU != '':
            is_column_exist(irrig,irrig_col_min_GU)

        irrig_distance_GU = parms.get('irrigation', 'irrig_distance_GU')
        try:
                isinstance(float(irrig_distance_GU),float)
        except:    
                sys.exit('------------> ERROR : irrig_distance_GU PARAMETER is not integer or double')
        if float(irrig_distance_GU)<0:
            sys.exit('------------> ERROR : irrig_distance_GU PARAMETER cannot be negative')



        irrig_sector = os.path.join(directory, str(parms.get('irrigation', 'irrigation_sector')))
        is_valid_shp(irrig_sector)
              
        ## Test if irrig_sector is polyon or multipolygon
        is_valid_geometry(irrig_sector,'Polygon')
            
        ## Test irrig_sector_col_name
        irrig_sector_col_name = parms.get('irrigation', 'irrig_sector_col_name')
        if irrig_sector_col_name == '':
            sys.exit('------------> ERROR : CHECK irrig_sector_col_name PARAMETER in Irrigation')

        ## In irrig_sector, test if irrig_sector_col_name exists  and if no null value
        is_column_exist(irrig_sector,irrig_sector_col_name)
        is_column_valid(irrig_sector,irrig_sector_col_name)
            
        ## Test irrig_sector_col_SAU_IRR
        irrig_sector_col_SAU = parms.get('irrigation', 'irrig_sector_col_sau_irr')
        if irrig_sector_col_SAU == '':
            sys.exit('------------> ERROR : CHECK irrig_sector_col_sau_irr PARAMETER in Irrigation')

        ## In irrig_sector, test if irrig_sector_col_SAU_IRR exists 
        is_column_exist(irrig_sector,irrig_sector_col_SAU)
            
        ## Test irrig_sector_col_DOM_SAU_IRR
        irrig_sector_col_DOM_SAU = parms.get('irrigation', 'irrig_sector_col_dom_sau_irr')
        if irrig_sector_col_DOM_SAU == '':
            sys.exit('------------> ERROR : CHECK irrig_sector_col_dom_sau_irr PARAMETER in Irrigation')

        ## In irrig_sector, test if irrig_sector_col_DOM_SAU_IRR exists 
        is_column_exist(irrig_sector,irrig_sector_col_DOM_SAU)

       

        irrigation_file = parms.get('irrigation', 'relocated_irrigation')
        if irrigation_file != '':
            is_valid_shp(irrigation_file) 
            

    ## if dams is yes, test input data
    if str(parms.get('dams', 'to_do')) == 'yes':
        dams = os.path.join(directory, str(parms.get('dams', 'dams')))
        is_valid_shp(dams)

        ## Test if dams is point or multipoint
        is_valid_geometry(dams,'Point')
            
        
        ## Test dams_col_name
        dams_col_name = parms.get('dams', 'dams_col_name')
        if dams_col_name == '':
            sys.exit('------------> ERROR : CHECK dams_col_name PARAMETER in Irrigation')


        ## In dams, test if dams_col_name exists and if no null value
        is_column_exist(dams,dams_col_name)
        is_column_valid(dams,dams_col_name)
        is_column_value_unique(dams,dams_col_name)
        are_columns_value_unique(gauges,gauges_col_name,dams,dams_col_name)
         
        ## Test dams_smax
        dams_smax = parms.get('dams', 'dams_smax')
        if dams_smax == '':
            sys.exit('------------> ERROR : CHECK dams_smax PARAMETER in dams')

        ## In dams, test if dams_smax exists 
        is_column_exist(dams,dams_smax)
            
        ## Test dams_s0
        dams_s0 = parms.get('dams', 'dams_s0')
        if dams_s0 == '':
            sys.exit('------------> ERROR : CHECK dams_s0 PARAMETER in dams')


        ## In dams, test if dams_s0 exists 
        is_column_exist(dams,dams_s0)

        # Test dams_area_col_name
        dams_area_col_name = parms.get('dams', 'dams_area_col_name')
        if dams_area_col_name == '':
            sys.exit('------------> ERROR : CHECK dams_area_col_name PARAMETER in dams')


        ## In dams, test if dams_area_col_name exists 
        is_column_exist(dams,dams_area_col_name)

        dams_file = parms.get('dams', 'relocated_dams')
        if dams_file != '':
            is_valid_shp(dams_file) 
            

        #test if dams_col_name and gauges_col_name have no common value


        ## if rules_auto_dem is yes, test if step_dem valid
    if (parms.get('reclass_dem', 'rules_auto_dem')) == 'yes':
        if not isint(parms.get('reclass_dem', 'step_dem')):
            sys.exit('------------> ERROR : Step dem value not provided or is not integer' ) 
        ## test if basin min size is valid
    if not isint(parms.get('basin_min_size', 'size')):
        sys.exit('------------> ERROR : Basin min size value not provided or is not integer' ) 


    # Initializing the variables for cutting up of layers
    xmin_slect = ymin_slect = 0.0
    ymax_slect = xmax_slect = 9999999999.9


   
    dem_name = os.path.basename(parms.get('dem', 'dem')).split('.')[0]

    selection = (parms.get('surface', 'selection'))
    xmin_slect, ymax_slect, xmax_slect, ymin_slect = get_raster_bounds(dem, xmin_slect, ymax_slect, xmax_slect, ymin_slect)

    ## test if selection is valid


    if selection == 'total':
        pass
    elif selection == 'polygon':
        polygon_test = os.path.join(directory, str(parms.get('surface', 'polygon')))
        if not os.path.isfile(polygon_test):
            sys.exit('------------> ERROR : Polygon layer for surface selection not found')
        xmin_slect, ymax_slect, xmax_slect, ymin_slect = get_polygon_bounds(os.path.join(directory, parms.get('surface', 'polygon')), xmin_slect, ymax_slect, xmax_slect, ymin_slect)
    elif selection == 'coords':
        xmin_slect, ymax_slect, xmax_slect, ymin_slect = get_coords(parms, xmin_slect, ymax_slect, xmax_slect, ymin_slect)
    else:
        print('==============================================================================')
        print('No surface specified in hrudelin_config or invalid parameter, full DEM applied')
        print('==============================================================================')

    print('---------- HRU-delin Step 1 : Preparing the layers')
    # Cutting up of the DEM
    dem_cut = os.path.join(directory_out, 'step1_dem_cut.tif')
    cutting_raster(dem, dem_cut, xmin_slect, ymax_slect, xmax_slect, ymin_slect)

    # Cutting up of the gauges shapefile
    gauges_shp = os.path.join(directory, parms.get('gauges', 'gauges'))
    gauges_selected = os.path.join(directory_out, 'gauges_selected.shp')
    ## this ensures intersection with DEM
    ogr2ogrMain(['', '-spat', str(xmin_slect), str(ymin_slect), str(xmax_slect), str(ymax_slect), gauges_selected, gauges_shp])

    #if irrigation, cutting irrigation and cantons vector
    if str(parms.get('irrigation', 'to_do')) == 'yes':
        irrigation_shp = os.path.join(directory, parms.get('irrigation', 'irrigation'))
        irrigation_selected = os.path.join(directory_out, 'irrigation_selected.shp')
        ## this ensures intersection with DEM
        ogr2ogrMain(['', '-spat', str(xmin_slect), str(ymin_slect), str(xmax_slect), str(ymax_slect), irrigation_selected, irrigation_shp])
        
        cantons_shp = os.path.join(directory, parms.get('irrigation', 'irrigation_sector'))
        cantons_selected = os.path.join(directory_out, 'irrig_sector_selected.shp')
        ## this ensures intersection with DEM
        ogr2ogrMain(['', '-spat', str(xmin_slect), str(ymin_slect), str(xmax_slect), str(ymax_slect), cantons_selected, cantons_shp])

    if str(parms.get('dams', 'to_do')) == 'yes':
        dams_shp = os.path.join(directory, parms.get('dams', 'dams'))
        dams_selected = os.path.join(directory_out, 'dams_selected.shp')
        ## this ensures intersection with DEM
        ogr2ogrMain(['', '-spat', str(xmin_slect), str(ymin_slect), str(xmax_slect), str(ymax_slect), dams_selected, dams_shp])

    # Cutting up and save other rasters (landuse, soils, geology, ...)
    for data in parms.items('data'):
        xmin_slect, ymax_slect, xmax_slect, ymin_slect = get_raster_bounds(os.path.join(directory, data[1]), xmin_slect, ymax_slect, xmax_slect, ymin_slect)
    for data in parms.items('data'):
        layer = os.path.join(directory, data[1])
        layer_cut = os.path.join(directory_out, 'step1_' + data[1])
        cutting_raster(layer, layer_cut, xmin_slect, ymax_slect, xmax_slect, ymin_slect)

    dem_wk = 'dem_wk'

    grass_run_command('g.proj', flags='c', georef=dem_cut, stdout=DEVNULL, stderr=DEVNULL)
    grass_run_command('r.in.gdal', flags='o', input=dem_cut, output=dem_wk, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)
    grass_run_command('g.region', flags='sp', raster=dem_wk, stdout=DEVNULL, stderr=DEVNULL)

    # Fill the DEM (depressionless)
    dem_filled = elev = dem_wk
    if (parms.get('demfill', 'demfill') == 'yes'):
        print('---------- HRU-delin Step 1 : Filling the DEM')
        dem_filled = 'dem_filled'
        dem_temp = 'dem_temp'
        dir_temp = 'dir_temp'
        unfilled_areas = 'unfilled_areas'

        areas = 1
        while (areas > 0):
            grass_run_command('r.fill.dir', input=elev, output=dem_filled, direction=dir_temp, areas=unfilled_areas,
                overwrite='True', stdout=DEVNULL, stderr=DEVNULL)
            areas = int(grass_parse_command('r.info', flags='r', map=unfilled_areas, stdout=DEVNULL, stderr=DEVNULL)['max'])
            elev = dem_filled

    # Slope and aspect derivation
    print('---------- HRU-delin Step 1 : Derivating layers from MNT')
    dem_slope = 'dem_slope'
    dem_aspect = 'dem_aspect'
    grass_run_command('r.slope.aspect', elevation=dem_filled, slope=dem_slope, aspect=dem_aspect,
        overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    # Reclassifying rasters
    # DEM
    dem_rcl = 'dem_rcl'

   

    if (parms.get('reclass_dem', 'rules_auto_dem')) == 'yes':
        pRecode = grass_feed_command('r.recode', input=dem_filled, output=dem_rcl, rules='-', quiet=True)


        step_reclass = int(parms.get('reclass_dem', 'step_dem'))

        alti_min = float(grass_parse_command('r.info', flags='r', map=dem_filled, stdout=DEVNULL, stderr=DEVNULL)['min'])
        alti_max = float(grass_parse_command('r.info', flags='r', map=dem_filled, stdout=DEVNULL, stderr=DEVNULL)['max'])

        # just a copy, still do the pipe
        recl_dem_file = os.path.join(directory_out, 'reclass_rules_dem')
        
        with open(recl_dem_file, 'w') as dem_rules:
            new_max = math.floor(alti_max / step_reclass) * step_reclass + step_reclass
            if alti_min < 0:
                x = 1
                rule = '%.1f:0:1:%d\n' % (alti_min, x)
                pRecode.stdin.write(encode(rule))
                dem_rules.write(rule)
                new_min = 0
            else:
                x = 0
                new_min = math.floor(alti_min / step_reclass) * step_reclass
            while new_min < new_max:
                x += 1
                # keep the decimal to make sure r.recode does not round things
                rule = '%.1f:%.1f:%d:%d\n' % (new_min, new_min+step_reclass, x, x)
                pRecode.stdin.write(encode(rule))
                dem_rules.write(rule)
                new_min += step_reclass
        pRecode.stdin.close()
        pRecode.wait()
    else:
        recl_dem_file = os.path.join(configFileDir, 'reclass_rules_dem')
        if not os.path.isfile(recl_dem_file):
            sys.exit('------------> File reclass_rules_dem is missing')
        # r.recode does a better job with grass7, values close to interval limits are now correctly reclassified

        grass_run_command('r.recode', input=dem_filled, output=dem_rcl, rules=recl_dem_file, stdout=DEVNULL, stderr=DEVNULL)
  
        # Save the rules to directory_out
        recl_dem_name = os.path.basename(recl_dem_file)
        shutil.copyfile(recl_dem_file, os.path.join(directory_out, recl_dem_name))

    # Slope
    slp_rcl = 'slp_rcl'

    if (parms.get('reclass_slope', 'rules_auto_slope')) == 'yes':
        pRecode = grass_feed_command('r.recode', input=dem_slope, output=slp_rcl, rules='-', quiet=True)
        recl_slope_file = os.path.join(directory_out, 'reclass_rules_slope')
       
        default_recl_slope_file = os.path.join(DATA_PATH, 'reclass_default_rules_slope')

        slp_min = float(grass_parse_command('r.info', flags='r', map=dem_slope, stdout=DEVNULL, stderr=DEVNULL)['min'])
        slp_max = float(grass_parse_command('r.info', flags='r', map=dem_slope, stdout=DEVNULL, stderr=DEVNULL)['max'])
        with open(default_recl_slope_file, 'r') as default_slp_rules:
            slp_class = default_slp_rules.read()
        max_slp = str(slp_max)
        slp_class_new = slp_class.replace('max_slp', max_slp)
        max_class = str(int(math.ceil(slp_max)))
        slp_class = slp_class_new.replace('max_class', max_class)
        # write a copy but still do the pipe
        with open(recl_slope_file, 'w') as slp_rules:
            slp_rules.write(slp_class)
        pRecode.stdin.write(encode(slp_class))
        pRecode.stdin.close()
        pRecode.wait()
    else:
        recl_slope_file = os.path.join(configFileDir, 'reclass_rules_slope')
        if not os.path.isfile(recl_slope_file):
            sys.exit('------------> file reclass_rules_slope is missing')
        # improve some subprocess.Popen => run_command with rules=FILE
        grass_run_command('r.recode', input=dem_slope, output=slp_rcl, rules=recl_slope_file, stdout=DEVNULL, stderr=DEVNULL)
        recl_slope_name = os.path.basename(recl_slope_file)
        shutil.copyfile(recl_slope_file, os.path.join(directory_out, recl_slope_name))

    # Aspect
    recl_aspect_file = os.path.join(directory_out, 'reclass_rules_aspect')
    if (parms.get('reclass_aspect', 'rules_auto_aspect')) == 'yes':
        recl_aspect = os.path.join(DATA_PATH, 'reclass_default_rules_aspect')
        shutil.copyfile(recl_aspect, recl_aspect_file)
    else:
        user_aspect = os.path.join(configFileDir, 'reclass_rules_aspect')
        if not os.path.isfile(user_aspect):
            sys.exit('------------> File %s is missing' % user_aspect)
        shutil.copyfile(user_aspect, recl_aspect_file)

    asp_rcl = 'asp_rcl'
    grass_run_command('r.recode', input=dem_aspect, output=asp_rcl, rules=recl_aspect_file, stdout=DEVNULL, stderr=DEVNULL)

    # Oriented flows generation
    print('---------- HRU-delin Step 1 : Generating Oriented Flows')
    min_size = int(parms.get('basin_min_size', 'size'))
    streams = 'streams_wk'
    subbasins = 'subbasins_wk'
    halfbasins='halfbasins'
    accum = 'accum_wk'
    drain = 'drain_wk'
    grass_run_command('r.watershed',
        flags='sb',
        elevation=dem_filled,
        stream=streams,
        basin=subbasins,
        half_basin=halfbasins,
        accumulation=accum,
        drainage=drain,
        threshold=min_size,
        overwrite='True',
        stdout=DEVNULL, stderr=DEVNULL
    )

    # Save rasters
    print('---------- HRU-delin Step 1 : Saving the rasters')
    raster_out = os.path.join(directory_out, 'step1_dem_filled.tif')
    grass_run_command('r.out.gdal', input=dem_filled, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_dem_reclass.tif')
    grass_run_command('r.out.gdal', input=dem_rcl, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_slope.tif')
    grass_run_command('r.out.gdal', input=dem_slope, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_aspect.tif')
    grass_run_command('r.out.gdal', input=dem_aspect, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_slope_reclass.tif')
    grass_run_command('r.out.gdal', input=slp_rcl, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_aspect_reclass.tif')
    grass_run_command('r.out.gdal', input=asp_rcl, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_streams.tif')
    grass_run_command('r.out.gdal', input=streams, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_drain.tif')
    grass_run_command('r.out.gdal', input=drain, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_accum.tif')
    grass_run_command('r.out.gdal', input=accum, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_subbasins.tif')
    grass_run_command('r.out.gdal', input=subbasins, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)

    raster_out = os.path.join(directory_out, 'step1_halfbasins.tif')
    grass_run_command('r.out.gdal', input=halfbasins, output=raster_out, overwrite='True', stdout=DEVNULL, stderr=DEVNULL)
    print('---------- HRU-delin Step 1 ended   ---------------------------------------------')

if __name__ == '__main__':
    from progressColors import *
    try:
        from osgeo import gdal
        from osgeo import ogr
    except Exception as e:
        print('!!! %spython3-gdal was not found on your system, did you install it?%s' % (COLOR_RED, COLOR_RESET))
        print('On Debian/Ubuntu/Linux Mint you can install it with:\n')
        print('%ssudo apt install python3-gdal%s\n' % (COLOR_GREEN, COLOR_RESET))
        print('or if you don\'t have superuser access:\n')
        print('%spip3 install GDAL%s\n' % (COLOR_GREEN, COLOR_RESET))
        sys.exit(1)

    try:
        import dbf
    except Exception as e:
        print('!!! %sdbf python3 module was not found on your system, no topology .dbf file will be generated.%s' % (COLOR_YELLOW, COLOR_RESET))
        print('On Debian/Ubuntu/Linux Mint you can install it with:\n')
        print('%ssudo apt install python3-dbf%s\n' % (COLOR_GREEN, COLOR_RESET))
        print('or if you don\'t have superuser access:\n')
        print('%spip3 install dbf%s\n' % (COLOR_GREEN, COLOR_RESET))
    from grassUtils import buildGrassEnv, grass_run_command, grass_parse_command, grass_feed_command
    from ogr2ogr import main as ogr2ogrMain
    try:
        from tqdm import tqdm
    except Exception as e:
        print('!!! %s tqdm python3 module not found !!%s\n' % (COLOR_RED, COLOR_RESET))
        print('On Debian/Ubuntu/Linux Mint you can install it with:\n')
        print('%ssudo apt install python3-tqdm%s\n' % (COLOR_GREEN, COLOR_RESET))
        print('or if you don\'t have superuser access:\n')
        print('%spip3 install tqdm%s\n' % (COLOR_GREEN, COLOR_RESET))
        sys.exit(1)

    parms_file = 'hrudelin_config.cfg'
    if len(sys.argv) > 1:
        parms_file = sys.argv[1]

    main(parms_file)

    try:
        os.system('notify-send "hru-delin step 1 complete"')
    except Exception as e:
        pass
else:
    from .progressColors import *
    try:
        from osgeo import gdal
        from osgeo import ogr
    except Exception as e:
        print('!!! python3-gdal was not found on your system, did you install it?')
        print('On Debian/Ubuntu/Linux Mint you can install it with:\n')
        print('sudo apt install python3-gdal\n')
        print('or if you don\'t have superuser access:\n')
        print('pip3 install GDAL\n')
        sys.exit(1)

    try:
        import dbf
    except Exception as e:
        print('!!! dbf python3 module was not found on your system, no topology .dbf file will be generated.')
        print('On Debian/Ubuntu/Linux Mint you can install it with:\n')
        print('sudo apt install python3-dbf\n')
        print('or if you don\'t have superuser access:\n')
        print('pip3 install dbf\n')
    from .grassUtils import buildGrassEnv, grass_run_command, grass_parse_command, grass_feed_command
    from .ogr2ogr import main as ogr2ogrMain