Forked from HYCAR-Hydro / airGR
Source project has a limited visibility.
s1process.py 43.89 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 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 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 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 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 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 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
#import argparse
import glob, os, sys, warnings
import subprocess
from itertools import groupby
import gdal, ogr, osr
import otbApplication as otb

from mtdUtils import getBufferedGeographicExtent, getRasterEPSG, getGeoJSONExtent_WGS84, getRasterExtentAsGeometry
import xml.etree.ElementTree as ET
import multiprocessing as mp

from path import Path
import tempfile
import zipfile
from shutil import unpack_archive
import elevation

# TODO:
#  - rasterize vector on
#   - check possibilities to update filter outcore to make filtering on a temporal moving window

def download_srtm1(roi_vector, outfile, cache_dir=Path('~/.moringa/cache').expanduser(), max_download_tiles=9,
                   overwrite=False):
    """
    Download SRTM1 (i.e. at ~30m) from AWS

    Parameters
    ----------
    roi_vector
    outfile
    cache_dir
    max_download_tiles: int
        For more than 9 it may be blocked, see https://github.com/bopen/elevation

    Returns
    -------

    """
    # TODO:
    # another possibility would be:
    #   1. use elevation to specify the tiles
    #   2. download from https://urs.earthdata.nasa.gov as specified by https://dwtkns.com/srtm30m/
    #   3. unzip file and convert to tiff
    #   but an account on https://urs.earthdata.nasa.gov is needed
    #   see https://wiki.earthdata.nasa.gov/display/EL/How+To+Access+Data+With+Python
    #   More simple with curl (tested and working): https://wiki.earthdata.nasa.gov/display/EL/How+To+Access+Data+With+cURL+And+Wget
    #   see also https://ec.haxx.se/usingcurl/usingcurl-netrc
    #   tile example: http://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/2000.02.11/N45E003.SRTMGL1.hgt.zip
    #
    # Get the tiles names :
    # use https://dwtkns.com/srtm30m/srtm30m_bounding_boxes.json
    # or the following code with elevation :
    # datasource_root, spec = elevation.datasource.ensure_setup(cache_dir, 'SRTM1')
    # bounds = elevation.datasource.build_bounds(bounds, margin='0')
    # tiles_names = spec['tile_names'](*bounds)
    outfile = Path(outfile)
    if outfile.exists():
        print('SRTM download skipped, SRTM file already exists: {}'.format(outfile))
        return outfile
    # bounds = gpd.read_file(roi_vector).to_crs('+init=epsg:4326').bounds.values[0, :]
    # bounds = gpd.read_file(roi_vector).to_crs(4326).bounds.values[0, :]
    # bounds = getSQLiteExtent_WGS84(roi_vector)
    bounds = getGeoJSONExtent_WGS84(roi_vector)
    #bounds = [bounds[i] for i in [1,0,3,2]]
    elevation.clip(bounds, outfile, cache_dir=cache_dir, max_download_tiles=max_download_tiles)
    return outfile


def download_srtm3(roi_vector, outdir, verbose=True):
    # 2 solutions are available at the moment:
    # https://github.com/bopen/elevation downloads from AWS tiles in a cache dir and clip to given latlon bounds
    # https://www.orfeo-toolbox.org/CookBook/Applications/app_DownloadSRTMTiles.html downloads tiles from USGS in zip for given vector, raster or tile name

    if verbose:
        print('Downloading SRTM3...')

    outdir = Path(outdir)
    app = otb.Registry.CreateApplication('DownloadSRTMTiles')
    app.SetParameterString('vl', roi_vector)
    app.SetParameterString('tiledir', outdir)
    app.ExecuteAndWriteOutput()

    zipfiles = outdir.glob('*.zip')
    if verbose:
        print('Unzipping tiles:')
    outfiles = []
    with tempfile.TemporaryDirectory() as tmpdir:
        tmpdir_path = Path(tmpdir)
        for zf in zipfiles:
            if verbose:
                print('\t{}'.format(zf))
            with zipfile.ZipFile(zf, "r") as j:
                tmpfile = tmpdir_path / j.namelist()[0].replace('/', '')
                outfile = outdir / tmpfile.name

            unpack_archive(zf, tmpdir_path)
            tmpfile.move(outfile)
            outfiles.append(outfile)
            zf.remove()
    return outfiles

def download_geoid(cache_dir=Path('~/.moringa/cache').expanduser(), verbose=True):
    geoid_link = 'https://gitlab.orfeo-toolbox.org/orfeotoolbox/otb-data/-/raw/master/Input/DEM/egm96.grd'
    geoid_file = Path(cache_dir) / 'emg96.grd'
    if not geoid_file.exists():
        cmd = 'curl -o {} {}'.format(geoid_file, geoid_link)
        if not verbose:
            cmd + '-s -S'
        subprocess.check_call(cmd, shell=True)
    else:
        print('Geoid file download skipped, already exists: {}'.format(geoid_file))
    return geoid_file


def S1CalibOrtho(fld, epsg=None, demfld=None, geoid=None, overwrite=False):
    lst = glob.glob(fld + os.sep + 'measurement' + os.sep + '*.tiff')
    sarcal = []
    ortho = []
    out = []
    for l in lst:
        sarcal.append(otb.Registry.CreateApplication('SARCalibration'))
        ortho.append(otb.Registry.CreateApplication('OrthoRectification'))
        sarcal[-1].SetParameterString('in', l)
        sarcal[-1].SetParameterString('lut', 'sigma')
        sarcal[-1].Execute()
        ortho[-1].SetParameterString('elev.dem', demfld)
        ortho[-1].SetParameterString('elev.geoid', geoid)
        ortho[-1].SetParameterString('map', 'epsg')
        ortho[-1].SetParameterString('map.epsg.code', str(epsg))
        ortho[-1].SetParameterInt('opt.gridspacing', 40)
        ortho[-1].SetParameterInputImage('io.in', sarcal[-1].GetParameterOutputImage('out'))
        out.append(l.replace('.tiff', '_calsigma_ortho.tiff'))
        ortho[-1].SetParameterString('io.out', out[-1])
        if (os.path.exists(out[-1]) and not overwrite):
            print('Calibration and Orthorectification process skipped, file already exists:\n\t{}'.format(out[-1]))
        else:
            ortho[-1].ExecuteAndWriteOutput()

    return out

def S1CalibOrthoWithROI(infile, outfile, roi, demfld, geoid, lut='sigma', overwrite=False, ram=1024):
    if (os.path.exists(outfile) and not overwrite):
        print('Calibration and Orthorectification process skipped, file already exists:\n\t{}'.format(outfile))
        return outfile
    else:
        if checkRoiInS1Acquisition(infile, roi):
            pipe = []
            pipe.append(otb.Registry.CreateApplication('SARCalibration'))
            pipe[-1].SetParameterString('in', infile)
            pipe[-1].SetParameterString('lut', lut)
            pipe[-1].SetParameterString('ram', str(ram))
            pipe[-1].Execute()
            pipe.append(otb.Registry.CreateApplication('OrthoRectification'))
            pipe[-1].SetParameterInputImage('io.in', pipe[-2].GetParameterOutputImage('out'))
            pipe[-1].SetParameterString('elev.dem', demfld)
            pipe[-1].SetParameterString('elev.geoid', geoid)
            pipe[-1].SetParameterString('map', 'epsg')
            pipe[-1].SetParameterString('map.epsg.code', getRasterEPSG(roi))
            pipe[-1].SetParameterInt('opt.gridspacing', 40)
            pipe[-1].SetParameterString('opt.ram', str(ram))
            pipe[-1].Execute()

            pipe.append(otb.Registry.CreateApplication('Superimpose'))
            pipe[-1].SetParameterInputImage('inm', pipe[-2].GetParameterOutputImage('io.out'))
            pipe[-1].SetParameterString('inr', roi)
            pipe[-1].SetParameterString('ram', str(ram))
            pipe[-1].SetParameterString('out', outfile)
            pipe[-1].ExecuteAndWriteOutput()

            return outfile
        else:
            print('ROI not overlapping with S1 acquisition :\n\t{}'.format(infile))
            return None

def checkRoiInS1Acquisition(s1file, roifile):
    isIntersecting = False
    dsv = gdal.Open(roifile)
    roi_geom = getRasterExtentAsGeometry(dsv, to_wgs84=True)
    dsi = ogr.Open(os.path.dirname(s1file) + os.sep + os.pardir + os.sep + 'preview' + os.sep + 'map-overlay.kml')
    lyi = dsi.GetLayer()
    for g in lyi:
        in_geom = g.GetGeometryRef()
    isIntersecting = in_geom.Intersects(roi_geom)
    dsv = None
    dsi = None
    return isIntersecting

def preClip(infile, outfile, roi_buffered_vector, overwrite=False, verbose=True, ram=1024):
    if Path(outfile).exists() and (not overwrite):
        if verbose:
            print('Pre-clip process skipped, file already exists:\n\t{}'.format(outfile))
        return outfile

    isIntersecting = False
    dsv = ogr.Open(roi_buffered_vector)
    lyv = dsv.GetLayer()
    for f in lyv:
        roi_geom = f.GetGeometryRef()
    dsi = ogr.Open(os.path.dirname(infile) + os.sep + os.pardir + os.sep + 'preview' + os.sep + 'map-overlay.kml')
    lyi = dsi.GetLayer()
    for g in lyi:
        in_geom = g.GetGeometryRef()
    isIntersecting = in_geom.Intersects(roi_geom)
    dsv = None
    dsi = None

    if (isIntersecting):
        extroi = otb.Registry.CreateApplication('ExtractROI')
        extroi.SetParameterString('in', infile)
        extroi.SetParameterString('mode', 'fit')
        extroi.SetParameterString('mode.fit.vect', roi_buffered_vector)
        extroi.SetParameterString('out', outfile)
        extroi.SetParameterString('ram', str(ram))
        extroi.ExecuteAndWriteOutput()
        return outfile
    else:
        if verbose:
            print('Pre-clip process skipped, image outside ROI.')
        return None

    # cmd = ['obtcli_ExtractROI', '-in', infile, '-out', outfile,
    #        '-mode', 'fit', '-mode.fit.vect', roi_buffered_vector,
    #        '-ram', str(ram)]
    # subprocess.check_call(cmd, shell=False)


def S1Calibration(infile, outfile, lut='sigma', overwrite=False, verbose=True, ram=1024):
    if Path(outfile).exists() and (not overwrite):
        if verbose:
            print('Calibration process skipped, file already exists:\n\t{}'.format(outfile))
        return outfile

    print(lut)
    sarcal = otb.Registry.CreateApplication('SARCalibration')
    sarcal.SetParameterString('in', infile)
    sarcal.SetParameterString('lut', lut)
    sarcal.SetParameterString('out', outfile)
    sarcal.SetParameterString('ram', str(ram))
    sarcal.ExecuteAndWriteOutput()

    return outfile


def S1Ortho(infile, outfile, epsg, demfld, geoid, roi=None, orthofit=False, overwrite=False, verbose=True, ram=1024):
    if Path(outfile).exists() and (not overwrite):
        if verbose:
            print('Orthorectification process skipped, file already exists:\n\t{}'.format(outfile))
        return outfile
    if verbose:
        print('DEM folder: '.format(demfld))
    ortho = otb.Registry.CreateApplication('OrthoRectification')
    ortho.SetParameterString('elev.dem', demfld)
    ortho.SetParameterString('elev.geoid', geoid)
    ortho.SetParameterString('io.in', infile)
    ortho.SetParameterString('io.out', outfile)
    ortho.SetParameterString('opt.ram', str(ram))
    ortho.SetParameterInt('opt.gridspacing', 40)
    if orthofit and (roi is not None):
        print('Using mode "orthofit" for ortho-rectification')
        ortho.SetParameterString('outputs.mode', 'orthofit')
        ortho.SetParameterString('outputs.ortho', roi)
    else:
        ortho.SetParameterString('map', 'epsg')
        ortho.SetParameterString('map.epsg.code', str(epsg))
    ortho.ExecuteAndWriteOutput()

    return outfile


def Superimpose(infile, roi, outfile, overwrite=False, verbose=True, ram=1024):
    if Path(outfile).exists() and (not overwrite):
        if verbose:
            print('Superimpose process skipped, file already exists:\n\t{}'.format(outfile))
        return outfile

    app = otb.Registry.CreateApplication('Superimpose')
    app.SetParameterString('inr', roi)
    app.SetParameterString('inm', infile)
    app.SetParameterString('out', outfile)
    app.SetParameterString('ram', str(ram))
    app.ExecuteAndWriteOutput()

    return outfile


def MultitempFilteringOutcore(infiles, outfile, window_radius=3, overwrite=False, verbose=True, ram=1024):
    if len(infiles)==0:
        return None

    if Path(outfile).exists() and (not overwrite):
        if verbose:
            print('MultitempFilteringOutcore process skipped, file already exists:\n\t{}'.format(outfile))
        return outfile

    app = otb.Registry.CreateApplication('MultitempFilteringOutcore')
    app.SetParameterStringList('inl', infiles)
    app.SetParameterString('wr', str(window_radius))
    app.SetParameterString('oc', outfile)
    app.SetParameterString('ram', str(ram))
    app.ExecuteAndWriteOutput()
    # (infiles[0].parent / 'filtered').mkdir_p()
    # otb_path / 'bin' /
    # cmd = ['otbcli_MultitempFilteringOutcore', '-inl'] + infiles + \
    #       ['-wr', str(window_radius), '-oc', outfile, '-ram', str(ram)]
    # if verbose:
    #     print(' '.join(cmd))
    # subprocess.check_call(cmd, shell=False)

    return outfile


# cmd = ['otbcli_MultitempFilteringOutcore', '-inl'] + files + ['-wr', str(window_radius), '-oc',
#                                                               outcore_file]

def MultitempFilteringFilter(infiles, outdir, window_radius, outcore_file, enl_file, overwrite=False, verbose=True, ram=1024):
    infiles = [Path(f) for f in infiles]
    outdir = Path(outdir)

    outfiles = [enl_file] + [outdir / f.name.stripext() + '_filtered.tiff' for f in infiles]
    existing = [f for f in outfiles if f.exists()]

    if (len(existing) > 0) and (not overwrite):
        if len(existing) != len(outfiles):
            raise IOError('Some outputs of MultitempFilteringFilter already exist but not all,'
                          'set overwrite argument to overwrite:\n\t{}'.format(existing))
        if verbose:
            print('MultitempFilteringFilter process skipped, files already exists:\n\t{}'.format(existing))
        return outfiles

    """
    app = otb.Registry.CreateApplication('MultitempFilteringFilter')
    app.SetParameterStringList('inl', infiles) # list parameter not accpeted
    app.SetParameterString('wr', str(window_radius))
    app.SetParameterString('oc', outcore_file)
    app.SetParameterString('enl', enl_file)
    app.SetParameterString('filtpath', outdir)
    app.SetParameterString('ram', str(10*ram))
    app.ExecuteAndWriteOutput()
    # infiles[0].parent.mkdir_p()
    # cmd = ['otbcli_MultitempFilteringFilter', '-inl'] + infiles + ['-wr', str(window_radius), '-oc',
    #                                                              outcore_file, '-enl', enl_file,
    #                                                              '-filtpath', outdir, '-ram', str(ram)]
    # if verbose:
    #     print(cmd)
    # subprocess.check_call(cmd, shell=False)
    """
    i = 1
    for f in infiles:
        pipe = []
        pipe.append(otb.Registry.CreateApplication('Smoothing'))
        pipe[-1].SetParameterString('in', f)
        pipe[-1].SetParameterString('type', 'mean')
        pipe[-1].SetParameterString('type.mean.radius', str(window_radius))
        pipe[-1].SetParameterString('ram', str(ram))
        pipe[-1].Execute()
        pipe.append(otb.Registry.CreateApplication('BandMath'))
        pipe[-1].SetParameterStringList('il', [outcore_file])
        pipe[-1].AddImageToParameterInputImageList('il', pipe[-2].GetParameterOutputImage('out'))
        pipe[-1].SetParameterString('exp', 'im2b1*im1b1/im1b2')
        pipe[-1].SetParameterString('ram', str(ram))
        pipe[-1].SetParameterString('out', outfiles[i])
        pipe[-1].ExecuteAndWriteOutput()
        i += 1

    return outfiles



def extractROI(infiles, outdir, roi, roiname=None, ncores=12, overwrite=False, verbose=True, ram=1024):
    """
    Merge same date images with average (through gdalbuildvrt) and extracts roi

    Parameters
    ----------
    infiles: list
        List S1 tiff files to process
    outdir: str
        Output directory where are stored generated files
    roi: str
        Region of interest raster
    roiname: str
        name used as suffix of generated files: xxx_roiname.tiff
    ncores: int
        Number of cores used in multiprocessing
    overwrite: bool
        If True, overwrites existing files.
    verbose: bool

    Returns
    -------
    list
        Ouput files
    """
    if verbose:
        print('Mosaic and ROI extraction process...')

    infiles = [Path(infile) for infile in infiles]
    outdir = Path(outdir)
    roi = Path(roi)

    # roi must be a raster over the ROI, outputs will be superimposed over this reference.
    if roiname is None:
        roiname = roi.name.splitext()[0]

    infiles = sorted(infiles, key=lambda x: x.name[11:29])
    slst = [list(i) for j, i in groupby(infiles, lambda x: x.name[11:22])]

    #### build virtual rasters of same date --> layer average when loaded
    vrtfiles = []
    outfiles = []
    proc_files = []
    for l in slst:
        oldd = l[0].name[14:45]
        newd = l[0].name[14:29] + '-' + l[-1].name[30:45]
        outfile = outdir / l[0].name.replace(oldd, newd).replace('.tiff', '_' + roiname + '.tiff')
        outfiles.append(outfile)
        if (not outfile.exists()) or overwrite:
            vrt = outfile.replace('.tiff', '.vrt')
            vrtfiles.append(vrt)
            proc_files.append(outfile)
            vrtcmd = ['gdalbuildvrt', vrt] + l
            subprocess.call(vrtcmd, shell=False)
            tiffcmd = ['gdal_translate', vrt, outfile]
            subprocess.call(tiffcmd, shell=False)

    return outfiles


def multitempSpeckleFilt(infiles, outdir, window_radius=3, overwrite=False, verbose=True, ram=1024):
    print('Multi-temporal speckle filtering...')

    infiles = [Path(f) for f in infiles]
    outdir = Path(outdir)

    polars = ['vh', 'vv']
    sensors = ['s1a', 's1b']
    outfiles = []
    for polar in polars:
        polar_files = [f for f in infiles if f.name.split('-')[3] == polar]
        for sensor in sensors:
            files = [f for f in polar_files if f.name.startswith(sensor)]
            outcore_file = outdir / 'outcore_{}_{}.tiff'.format(sensor, polar)
            enl_file = outdir / 'enl_{}_{}.tiff'.format(sensor, polar)

            if len(files) > 0:

                #### generate outcore file
                if verbose:
                    print('\tComputing speckle filter file: {}'.format(outcore_file))
                MultitempFilteringOutcore(files, outcore_file, window_radius=window_radius, overwrite=overwrite, verbose=verbose, ram=ram)

                #### apply filtering: outputs are enl_file and outdir/files.name
                if verbose:
                    print('\tFiltering images {} {} ...'.format(sensor, polar))

                psoutfiles = MultitempFilteringFilter(files, outdir, window_radius,
                                                      outcore_file, enl_file , overwrite, verbose, ram=ram)

                outfiles.extend([outcore_file] + psoutfiles)

    return outfiles

    #
    # lstvh = sorted(glob.glob(fld + os.sep + '*vh*_calsigma_ortho_*.tiff'), key=lambda x: os.path.basename(x)[14:22])
    # if len(lstvh) == 0:
    #     lstvh = sorted(glob.glob(fld + os.sep + '*.SAFE' + os.sep + 'measurement' + os.sep + '*vh*_calsigma_ortho.tiff'), key=lambda x: os.path.basename(x)[17:25])
    # lstvv = sorted(glob.glob(fld + os.sep + '*vv*_calsigma_ortho_*.tiff'), key=lambda x: os.path.basename(x)[14:22])
    # if len(lstvv) == 0:
    #     lstvv = sorted(glob.glob(fld + os.sep + '*.SAFE' + os.sep + 'measurement' + os.sep + '*vv*_calsigma_ortho.tiff'), key=lambda x: os.path.basename(x)[17:25])
    #
    # ofld = fld + os.sep + 'specklefilter'
    # if not os.path.exists(ofld):
    #     os.mkdir(ofld)
    # if not os.path.exists(ofld + os.sep + 'filtered'):
    #     os.mkdir(ofld + os.sep + 'filtered')
    #
    # slinksvh = [ofld + os.sep + os.path.basename(x) for x in lstvh]
    # slinksvv = [ofld + os.sep + os.path.basename(x) for x in lstvv]
    # [os.symlink(lstvh[i], slinksvh[i]) for i in range(len(lstvh)) if not os.path.exists(slinksvh[i])]
    # [os.symlink(lstvv[i], slinksvv[i]) for i in range(len(lstvv)) if not os.path.exists(slinksvv[i])]
    #
    # if len(slinksvh) > 0:
    #     cmd = ['otbcli_MultitempFilteringOutcore', '-inl'] + slinksvh + ['-wr',str(window_radius),'-oc',fld + os.sep + 'outcore_vh.tiff']
    #     subprocess.call(cmd, shell=False)
    #     cmd = ['otbcli_MultitempFilteringFilter', '-inl'] + slinksvh + ['-wr', str(window_radius), '-oc', fld + os.sep + 'outcore_vh.tiff', '-enl', fld + os.sep + 'enl_vh.tiff']
    #     subprocess.call(cmd, shell=False)
    #     #cmd = ['otbcli_MultitempFiltering', '-inl'] + slinksvh + ['-wr', str(window_radius)]
    #     #subprocess.call(cmd,shell=False)
    # if len(lstvv) > 0:
    #     cmd = ['otbcli_MultitempFilteringOutcore', '-inl'] + slinksvv + ['-wr',str(window_radius),'-oc',fld + os.sep + 'outcore_vv.tiff']
    #     subprocess.call(cmd, shell=False)
    #     cmd = ['otbcli_MultitempFilteringFilter', '-inl'] + slinksvv + ['-wr', str(window_radius), '-oc',fld + os.sep + 'outcore_vv.tiff', '-enl', fld + os.sep + 'enl_vv.tiff']
    #     subprocess.call(cmd, shell=False)


def separateS1AS1B(safe_files):
    safe_files_s1a = []
    safe_files_s1b = []

    for l in safe_files:
        if os.path.basename(l).startswith('S1A'):
            safe_files_s1a.append(l)
        elif os.path.basename(l).startswith('S1B'):
            safe_files_s1b.append(l)

    return safe_files_s1a,safe_files_s1b

def separateAscDesc(safe_files):
    safe_files_asc = []
    safe_files_des = []

    for l in safe_files:
        l = Path(l)
        root = ET.parse(l / 'manifest.safe').getroot()
        for item in root.iter():
            if item.tag.endswith('pass'):
                if item.text == 'ASCENDING':
                    safe_files_asc.append(l)
                elif item.text == 'DESCENDING':
                    safe_files_des.append(l)

    '''
    if len(safe_files_asc) > 0 and not os.path.exists(fld + os.sep + 'ASC'):
        os.mkdir(fld + os.sep + 'ASC')
        [shutil.move(l, fld + os.sep + 'ASC/') for l in safe_files_asc]
        safe_files_asc_out = glob.glob(fld + os.sep + 'ASC' + os.sep + '*.SAFE')

    if len(safe_files_des) > 0 and not os.path.exists(fld + os.sep + 'DES'):
        os.mkdir(fld + os.sep + 'DES')
        [shutil.move(l, fld + os.sep + 'DES/') for l in safe_files_des]
        safe_files_des_out = glob.glob(fld + os.sep + 'DES' + os.sep + '*.SAFE')
    '''

    return safe_files_asc, safe_files_des


def createS1Features(fld, base_name='S1series', out_fld=None, features=None, convert_to_db=True, by_date=False):
    if out_fld is None:
        out_fld = fld

    lst_vh = sorted(glob.glob(fld + os.sep + '*iw-grd-vh*.tiff'), key=lambda x: os.path.basename(x)[14:22])
    lst_vv = sorted(glob.glob(fld + os.sep + '*iw-grd-vv*.tiff'), key=lambda x: os.path.basename(x)[14:22])

    # Check date correspondance
    dates_vh = [os.path.basename(l)[14:22] for l in lst_vh]
    dates_vv = [os.path.basename(l)[14:22] for l in lst_vv]

    assert len(lst_vh) > 0 and len(lst_vv) > 0, "No vv/vh images found in folder."
    assert dates_vh == dates_vv, "Dates for images in folder are not aligned for vh and vv polarizations."

    vh_out = out_fld + os.sep + base_name + '_vh_series.tiff'
    vv_out = out_fld + os.sep + base_name + '_vv_series.tiff'

    with open(out_fld + os.sep + base_name + '_dates.txt', 'w') as f:
        [f.write(x + '\n') for x in dates_vh]

    if convert_to_db:
        expr = '{' + ';'.join(['1000*log10(abs(im%db1)+1e-6)' % (i + 1) for i in range(len(lst_vh))]) + '}'
    else:
        expr = '{' + ';'.join(['10000*im%db1' % (i + 1) for i in range(len(lst_vh))]) + '}'

    feat = []

    feat.append(otb.Registry.CreateApplication('BandMathX'))
    feat[-1].SetParameterStringList('il', lst_vh)
    feat[-1].SetParameterString('exp', expr)
    if by_date:
        feat[-1].Execute()
    else:
        feat[-1].SetParameterString('out', vh_out)
        feat[-1].SetParameterOutputImagePixelType('out', otb.ImagePixelType_int16)
        feat[-1].ExecuteAndWriteOutput()

    feat.append(otb.Registry.CreateApplication('BandMathX'))
    feat[-1].SetParameterStringList('il', lst_vv)
    feat[-1].SetParameterString('exp', expr)
    if by_date:
        feat[-1].Execute()
    else:
        feat[-1].SetParameterString('out', vv_out)
        feat[-1].SetParameterOutputImagePixelType('out', otb.ImagePixelType_int16)
        feat[-1].ExecuteAndWriteOutput()

    if features is not None and 'ratio' in features:
        expr = '{' + ';'.join(['1000 * im1b%d / (im2b%d + 1e-6)' % (i + 1, i + 1) for i in range(len(lst_vh))]) + '}'
        feat.append(otb.Registry.CreateApplication('BandMathX'))
        feat[-1].AddImageToParameterInputImageList('il', feat[0].GetParameterOutputImage('out'))
        feat[-1].AddImageToParameterInputImageList('il', feat[1].GetParameterOutputImage('out'))
        feat[-1].SetParameterString('exp', expr)
        if by_date:
            feat[-1].Execute()
        else:
            ratio_out = out_fld + os.sep + base_name + '_vh_vv_ratio_series.tiff'
            feat[-1].SetParameterString('out', ratio_out)
            feat[-1].SetParameterOutputImagePixelType('out', otb.ImagePixelType_int16)
            feat[-1].ExecuteAndWriteOutput()

    if by_date:
        i = 1
        cc = []
        for d in dates_vh:
            stack_out = out_fld + os.sep + base_name + '_' + d + '_feat.tif'
            cc.append(otb.Registry.CreateApplication('BandMathX'))
            [cc[-1].AddImageToParameterInputImageList('il', x.GetParameterOutputImage('out')) for x in feat]
            cc[-1].SetParameterString('exp', '{' + ';'.join(['im%db%d' % (t,i) for t in range(1,len(feat)+1)]) + '}')
            cc[-1].SetParameterString('out', stack_out)
            cc[-1].SetParameterOutputImagePixelType('out', otb.ImagePixelType_int16)
            cc[-1].ExecuteAndWriteOutput()

    return


def createS1Quicklooks(fld, scale=0.1):
    if not os.path.exists(fld + os.sep + 'QLK'):
        os.mkdir(fld + os.sep + 'QLK')

    lst = sorted(glob.glob(fld + os.sep + '*iw-grd-v*.tiff'))

    for f in lst:
        fout = fld + os.sep + 'QLK' + os.sep + 'qlk_' + os.path.basename(f)[11:]

        rig = otb.Registry.CreateApplication('RigidTransformResample')
        rig.SetParameterString('in', f)
        rig.SetParameterFloat('transform.type.id.scalex', scale)
        rig.SetParameterFloat('transform.type.id.scaley', scale)
        rig.Execute()

        dbc = otb.Registry.CreateApplication('BandMath')
        dbc.AddImageToParameterInputImageList('il', rig.GetParameterOutputImage('out'))
        dbc.SetParameterString('exp', '10*log10(abs(im1b1)+1e-6)')
        dbc.Execute()

        dcv = otb.Registry.CreateApplication('DynamicConvert')
        dcv.SetParameterInputImage('in', dbc.GetParameterOutputImage('out'))
        dcv.SetParameterFloat('quantile.high', 2.0)
        dcv.SetParameterFloat('quantile.low', 2.0)
        dcv.SetParameterInt('outmin', 1)
        dcv.SetParameterInt('outmax', 255)
        dcv.SetParameterString('out', fout)
        dcv.SetParameterOutputImagePixelType('out', otb.ImagePixelType_uint8)
        dcv.ExecuteAndWriteOutput()

    return

'''
def raster_bbox(img, buf=0, outfile=None, driver='GeoJSON', outcrs=4326):
    with rio.open(img) as r:
        bounds = r.bounds
        res = r.res

    geom = box(bounds[0]-buf*res[0], bounds[1]-buf*res[1], bounds[2]+buf*res[0], bounds[3]+buf*res[1])
    # df = gpd.GeoDataFrame({"id":1,"geometry":[geom]}, crs=r.crs).to_crs('+init=epsg:{}'.format(outcrs))
    df = gpd.GeoDataFrame({"id": 1, "geometry": [geom]}, crs=r.crs).to_crs(outcrs)
    if outfile is None:
        return df
    else:
        df.to_file(outfile, driver=driver)
        return outfile
'''

def raster_epsg(x):
    d = gdal.Open(x)
    proj = osr.SpatialReference(wkt=d.GetProjection())
    return int(proj.GetAttrValue('AUTHORITY', 1))

def s1process(indir, outdir, epsg=None,
              roi=None, buffer=100, dem=None, geoid=None, orthofit=False, lut='sigma',
              direction='descending', satellite='both', step='all', force_clip=False, features=None, skip_db_conversion=False,
              features_by_date=False, calib_dir=None, cache_dir=Path('~/.moringa/cache').expanduser(),
              ram=1024, ncores=1, overwrite=False, verbose=True):
    """Process Sentinel 1 data

    Process S1 SAFE images:
        (clip to ROI extent ->) calibrate -> orthorectify -> mosaic (-> superimpose) -> filter speckle
        see ortho

    Parameters
    ----------
    indir: str | list
        Directory containing .SAFE directories or list of .SAFE directories.
        Or the output directory of one of the processing step, e.g. 'myROI/calib'.
    outdir: str
        Output directory where will be stored processed data.
    epsg: int
        Input EPSG. If not given, EPSG is deduced from ROI.
    roi: str
        Region Of Interest raster file. If not specified, EPSG and DEM are expected.
    buffer: int
        Number of pixels extending ROI extent for SRTM cropping to avoid border effects during ortho-rectification process.
    dem: str
        DEM directory. Optional, if not given SRTM30m will be downloaded over ROI.
    geoid str
        Geoid file. If not given, emg96.grd from OTB repo is used.
    orthofit: bool
        If activated it will use mode orthofit with ROI in OTB OrthoRectification app.
        Otherwise image is clipped before calibration step and
        aligned (OTB Superimpose) on ROI grid after mosaic
    direction: str
        Direction of acquisition, either ascending, descending or both
    step: str | list
        Specify one or more processing steps. Available steps are ['all', 'clip', 'calib', 'ortho', 'mosaic', 'superimpose', 'filter'].
        If orthofit=True: 'all' --> ['calib', 'ortho', 'mosaic', 'filter']
        Otherwise: 'all' --> ['clip', 'calib', 'ortho', 'mosaic', 'superimpose', 'filter']
    calib_dir: str
        Specify calibration directory to avoid computation of calibration.
        This option should not be used if the processing includes pre-clip step.
    cache_dir: str
        Cache directory for elevation package, it is where are stored the SRTM tiles (<50MB/tile) before crop to ROI.
    ram: int
        RAM limit to be used in OTB applications. Warning: ncores x ram may be used, although it is around 2GB/tile usually.
    ncores: int
        Number of cores used in multithreaded processing for orthrectification step
    overwrite: bool
        If True, it will overwrite existing files.
    verbose: bool

    Returns
    -------
    list
        Processed files.

    """
    # rajouter args:
    # - outdir
    # - option directory in main sinon liste de fichier .SAFE
    #
    # avant:
    #   si dir find files
    #   download SRTM30m
    # pour chaque tiff:
    #     clip, calibrate, ortho
    # avec l'ensemble:
    #     etxractROI
    #     multi-temp filtering

    # TODO: check if temporary files are used during process, otherwise insert temporary file in processing steps

    # set environment variables
    os.environ['GDAL_NUM_THREADS'] = str(ncores)
    os.environ['OPJ_NUM_THREADS'] = str(ncores)
    os.environ['ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS'] = str(ncores)

    dem_dir = dem
    outdir = Path(outdir)

    if orthofit:
        all_steps = ['calib', 'ortho', 'mosaic', 'filter']
    else:
        all_steps = ['clip', 'calib', 'ortho', 'mosaic', 'filter']

    if isinstance(step, str):
        step = [step]
    if 'all' in step:
        step = all_steps

    # set output directories
    clip_dir = outdir / 'clipped'
    if calib_dir is None:
        calib_dir = outdir / 'calib'
    else:
        if 'clip' in step:
            warnings.warn('Argument "calib_dir" should not be used with step "clip".')
        calib_dir = Path(calib_dir)
    ortho_dir = outdir / 'ortho'
    mosaic_dir = outdir / 'mosaic'
    filtered_dir = outdir / 'filtered'

    if 'calib' in step:
        if len(indir) == 1:
            indir = indir[0]

        if isinstance(indir, str):
            if indir.endswith('.SAFE'):
                safe_files = [Path(indir)]
            else:
                indir = Path(indir)
                safe_files = indir.glob('*.SAFE')
        elif isinstance(indir, list):
            safe_files = [Path(f) for f in indir if Path(f).exists() and f.endswith('.SAFE')]
        else:
            raise IOError('Input directory should either be a .SAFE file (list) or be a directory containing .SAFE files.')
        # safe_files = safe_files[1:5]

        if direction != 'both':
            safe_files_asc, safe_files_des = separateAscDesc(safe_files)
            if direction == 'ascending':
                safe_files = safe_files_asc
            elif direction == 'descending':
                safe_files = safe_files_des
            else:
                sys.exit('Invalid direction parameter.')

        if satellite != 'both':
            safe_files_s1a, safe_files_s1b = separateS1AS1B(safe_files)
            if satellite == 's1a':
                safe_files = safe_files_s1a
            elif satellite == 's1b':
                safe_files = safe_files_s1b
            else:
                sys.exit('Invalid satellite parameter.')

        if len(safe_files) == 0:
            raise IOError('No .SAFE file found in {}'.format(indir))

        proc_files = []
        for f in safe_files:
            proc_files.extend(f.glob('measurement/*.tiff'))  # files to be processed

    else:
        indir = Path(indir)
        proc_files = indir.glob('s1*.tiff')

    if (dem_dir is None) and (roi is None):
        raise IOError('Without ROI, DEM directory must be given in arguments.')

    if epsg is None:
        if roi is None:
            raise IOError('Without ROI, EPSG must be given explicitly.')
        epsg = raster_epsg(roi)

    #### Start processing
    outdir.mkdir_p()

    if (roi is not None) and any([s in ['clip', 'ortho'] for s in step]):
        #roi_buffered_vector = outdir / 'buffered_roi.sqlite'
        roi_buffered_vector = outdir / 'buffered_roi.geojson'
        if not roi_buffered_vector.exists():
            #raster_bbox(roi, buf=buffer, outfile=roi_buffered_vector)
            getBufferedGeographicExtent(roi, buf=buffer, toFile=roi_buffered_vector, drvname='GeoJSON')

    if (roi is not None and 'clip' in step and 'calib' in step and 'ortho' in step):
        #### pipelined calibration + ortho + superimpose
        ortho_dir.mkdir_p()

        if dem_dir is None:
            dem_dir = outdir / 'dem'
            dem_dir.mkdir_p()
            srtm_file = dem_dir / 'srtm.tiff'
            download_srtm1(roi_buffered_vector, srtm_file, cache_dir)
        if geoid is None:
            geoid = download_geoid(cache_dir, verbose)

        outfiles = [ortho_dir / infile.name.replace('.tiff', '_clipped_cal' + lut + '_ortho.tiff') for infile in proc_files]
        mp_args = [(infile, outfile, roi, dem_dir, geoid, lut, overwrite, ram) for infile, outfile in
                   zip(proc_files, outfiles)]
        """
        files = []
        for arg in mp_args:
            try:
                f = S1CalibOrthoWithROI(*arg)
                if f is not None:
                    files.append(f)
            except Exception as e:
                print(e)
                print('Clip went wrong, file skipped: {}'.format(f))
        """
        with mp.Pool(ncores) as pool:
            files = pool.starmap(S1CalibOrthoWithROI, mp_args)  # 1h for 8 tiles in parallel (8 threads)
        proc_files = [x for x in files if x is not None]

    else:
        if (roi is not None and 'clip' in step):
            ### Clipping
            if verbose:
                print('Clipping process...')
            clip_dir.mkdir_p()
            # roi_buffered_vector = tempfile.NamedTemporaryFile(dir=outdir, suffix='.sqlite').name
            # getBufferedGeographicExtent(roi, buf=50, toFile=roi_buffered_vector)

            # infile, outfile, roi_buffered_vector, overwrite
            outfiles = [clip_dir / infile.name.replace('.tiff', '_clipped.tiff') for infile in proc_files]
            mp_args = [(infile, outfile, roi_buffered_vector, overwrite, verbose, ram) for infile, outfile in
                       zip(proc_files, outfiles)]
            files = []
            # if ncores > 1:
            #     with mp.Pool(ncores) as pool:
            #         proc_files = pool.starmap(preClip, mp_args)
            # else:
            for arg in mp_args:
                try:
                    f = preClip(*arg)  # 3s/S2tile
                    if f is not None:
                        files.append(f)
                except Exception as e:
                    print(e)
                    print('Clip went wrong, file skipped: {}'.format(f))
            proc_files = files

        #### calibration
        if 'calib' in step:
            if verbose:
                print('Calibration process...')

            calib_dir.mkdir_p()
            outfiles = [calib_dir / infile.name.replace('.tiff', '_cal' + lut + '.tiff') for infile in proc_files]
            mp_args = [(infile, outfile, lut, overwrite, verbose, ram) for infile, outfile in zip(proc_files, outfiles)]
            files = []
            for arg in mp_args:
                f = S1Calibration(*arg) # 6s/S2tile using 32threads
                files.append(f)
            proc_files = files
            # with mp.Pool(ncores) as pool:
            #     proc_files = pool.starmap(S1Calibration, mp_args)

        #### orthorectification
        if 'ortho' in step:
            if verbose:
                print('Orthorectification process...')

            ortho_dir.mkdir_p()

            # download SRTM

            if dem_dir is None:
                dem_dir = outdir / 'dem'
                dem_dir.mkdir_p()
                srtm_file = dem_dir / 'srtm.tiff'
                download_srtm1(roi_buffered_vector, srtm_file, cache_dir)

            if geoid is None:
                geoid = download_geoid(cache_dir, verbose)

            outfiles = [ortho_dir / infile.name.replace('.tiff', '_ortho.tiff') for infile in proc_files]
            mp_args = [(infile, outfile, epsg, dem_dir, geoid, roi, orthofit, overwrite, verbose, ram) for infile, outfile in
                       zip(proc_files, outfiles)]
            # files = []
            # for arg in mp_args:
            #     f = S1Ortho(*arg) #40 min/tile
            #     files.append(f)
            # proc_files = files
            with mp.Pool(ncores) as pool:
                proc_files = pool.starmap(S1Ortho, mp_args) # 1h for 8 tiles in parallel (8 threads)

    #### mosaic
    if 'mosaic' in step:
        mosaic_dir.mkdir_p()
        roiname = Path(roi).name.splitext()[0]
        proc_files = extractROI(proc_files, mosaic_dir, roi, roiname, ncores, overwrite, verbose, ram)

    if 'superimpose' in step:
        superimpose_dir = outdir / 'superimpose'
        superimpose_dir.mkdir()
        outfiles = [superimpose_dir / infile.name.replace('.tiff', '_superimpose.tiff') for infile in proc_files]
        mp_args = [(infile, roi, outfile, overwrite, verbose, ram) for infile, outfile in zip(proc_files, outfiles)]
        with mp.Pool(ncores) as pool:
            proc_files = pool.starmap(Superimpose, mp_args)

    #### speckle filtering
    if 'filter' in step:
        print(proc_files)
        filtered_dir.mkdir_p()
        multitempSpeckleFilt(proc_files, filtered_dir, window_radius=3, overwrite=overwrite, verbose=verbose, ram=ram)

    if features is not None:
        if 'filter' not in step:
            print('Features only enabled if filtering is performed.')
            sys.exit(-1)
        feat_list = [f for f in features if f != 'vh_vv_only']
        if len(feat_list) == 0:
            feat_list = None
        feature_dir = outdir / 'features'
        feature_dir.mkdir_p()
        createS1Features(filtered_dir.strip(), out_fld=feature_dir.strip(), features=feat_list,
                         convert_to_db=not skip_db_conversion, by_date=features_by_date)

def parse_cmd_line(argv=sys.argv[1:]):
    import argparse
    parser = argparse.ArgumentParser(prog='s1process',
                                     description='Process S1 SAFE images: (clip to ROI extent ->) calibrate -> orthorectify -> filter speckle')
    parser.add_argument("indir", nargs='+', help="Input directory containing .SAFE directories to be processed. It can also be a list of .SAFE directories.")
    parser.add_argument('-o', '--outdir', help='Output directory where will be stored processed data.')
    parser.add_argument("--roi", help="Region Of Interest raster file. If not specified, EPSG and DEM are expected.")
    parser.add_argument("--epsg", type=int, help="Input EPSG. If not given, EPSG is deduced from ROI.")
    parser.add_argument("--dem", help="DEM directory. Optional, if not given SRTM30m will be downloaded over ROI.")
    parser.add_argument("--geoid", help="Geoid file. If not given, emg96.grd from OTB repo is used.")
    parser.add_argument("--orthofit", action='store_true', help="If activated it will use mode orthofit with ROI in OTB OrthoRectification app."
                                                                "Otherwise image is clipped before calibration step and "
                                                                "aligned (OTB Superimpose) on ROI grid after mosaic")
    parser.add_argument("--lut",
                        help='Specify lookup table to use for calibration (sigma, gamma, beta).',
                        choices=['sigma', 'gamma', 'beta'],
                        default='sigma')

    parser.add_argument("--direction",
                        help="Direction of acquisition, either ascending, descending",
                        choices=['descending', 'ascending', 'both'],
                        default='descending')

    parser.add_argument("--satellite",
                        help="Choose a single satellite (s1a or s1b).",
                        choices=['s1a', 's1b', 'both'],
                        default='both')

    parser.add_argument('--step', nargs='+', help='Specify one or more processing steps.',
                        choices=['all', 'clip', 'calib', 'ortho', 'filter'], default='all')

    parser.add_argument('--features', nargs='+', help="Enable the production of collected vh/vv + feature stack(supp. ratio).",
                        choices=['vh_vv_only', 'ratio'], default=None)

    parser.add_argument('--skip_db_conversion', action='store_true', help="When feature stack production is enabled, this allows to skip"
                                                                           "conversion of data to dB.")

    parser.add_argument('--features_by_date', action='store_true',
                        help="When feature stack production is enabled, default stack compilation is"
                             "per-feature (vh,vv,ratios). This enables per-date stack production.")

    parser.add_argument('--ncores', type=int, help='Number of cores used in multithreaded processing.', default=1)
    parser.add_argument('--ram', type=int,
                        help='RAM limit to be used in OTB applications. Warning: ncores x ram will be used.',
                        default=256)
    parser.add_argument('--overwrite', action='store_true', help='If True, it will overwrite existing files.')
    parser.add_argument('--verbose', action='store_true', help='Verbosity')
    args = parser.parse_args(argv)
    return args

if __name__ == '__main__':

    args = parse_cmd_line()
    s1process(**vars(args))
    # # to be put in option
    # nproc = 12
    # removing = False
    # step = 'ortho'
    # # Following can be ascending / descending / both
    # asc_desc = 'ascending'
    #
    # fld = sys.argv[1]
    # epsg = int(sys.argv[2])
    # demfld = sys.argv[3]
    # geoid = sys.argv[4]
    # roi = None
    # if len(sys.argv) > 5:
    #     roi = sys.argv[5]
    # if len(sys.argv) > 6:
    #     asc_desc = sys.argv[6]
    # if len(sys.argv) > 7 and sys.argv[7] == 'removing':
    #     removing = True
    #
    # test = glob.glob(fld + os.sep + 'measurement')
    # lst = glob.glob(fld + os.sep + '*.SAFE')
    #
    # if len(test) > 0:
    #     if step == 'all':
    #         done = S1CalibOrtho(fld, epsg, demfld, geoid)
    #     elif step == 'ortho':
    #         done = S1Ortho(fld, epsg, demfld, geoid, removing)
    # elif len(lst) > 0:
    #     if asc_desc != 'both':
    #         lst_asc, lst_des = separateAscDesc(fld)
    #         if asc_desc == 'ascending':
    #             lst = lst_asc
    #         elif asc_desc == 'descending':
    #             lst = lst_des
    #         else:
    #             sys.exit('Invalid asc/desc parameter.')
    #     if len(lst) > 0:
    #         for l in lst:
    #             if roi is not None:
    #                 preClip(l, roi, removing)
    #             S1Calibration(l, removing, force=False)
    #         cmdlist = []
    #         for l in lst:
    #             cmdlist.append(['python3', 's1process.py', l, str(epsg), demfld, geoid])
    #         queuedProcess(cmdlist, nproc, shell=False)
    #         roifld = extractROI(fld, roi, nproc)
    #         multitempSpeckleFilt(roifld)