Skip to content
Extraits de code Groupes Projets
download_ereefs_wind.py 4,57 ko
Newer Older
  • Learn to ignore specific revisions
  • """
    
    Script to download eReefs data.
    
    More info on source dataset : https://research.csiro.au/ereefs/models/
    
    Author : Antoine Saint-Amand
    antoine.saint-amand@uclouvain.be
    
    """
    
    import datetime
    import os
    import sys
    import urllib.request
    from builtins import input  # To get a python 2 and 3 compatible input
    
    import numpy as np
    
    import param
    
    p = param.parameters()
    
    lat_min = p.lat_min
    lat_max = p.lat_max
    lon_min = p.lon_min
    lon_max = p.lon_max
    
    fmt = "%Y-%m-%d %H:%M:%S"
    initial_time = datetime.datetime.strptime(p.initial_time, fmt)
    final_time = datetime.datetime.strptime(p.final_time, fmt)
    
    path_output = p.nc_data_dir + "/"
    
    
    print("\n=========================")
    print("STEP 1 : Downloading data")
    print("=========================\n")
    
    duration = (final_time - initial_time).days
    
    
    def convertDate(classicDate):
        """Convert date to string with format 'YYYY-MM-DDTHH%3Amm%3AssZ'."""
        convDate = classicDate.strftime("%Y-%m-%dT%H%%3A%M%%3A%SZ")
        return convDate
    
    
    sys.stderr.write("Geographical extent of data :\n")
    sys.stderr.write("- North boundary : " + str(lat_max) + "\n")
    sys.stderr.write("- South boundary : " + str(lat_min) + "\n")
    sys.stderr.write("- West boundary  : " + str(lon_min) + "\n")
    sys.stderr.write("- East boundary  : " + str(lon_max) + "\n\n")
    
    sys.stderr.write(
        "First record : "
        + initial_time.strftime("%Y-%m-%d")
        + " // Last record : "
        + final_time.strftime("%Y-%m-%d")
        + "\n\n"
    )
    
    startDlTime = initial_time - datetime.timedelta(hours=10)
    
    sys.stderr.write("Download progress :\n")
    
    for i in range(1, duration + 1):
        endDlTime = startDlTime + datetime.timedelta(days=1)
    
        filename = "tmp_eReefs%06d.nc" % i
        path_file = path_output + filename
    
        if os.path.isfile(path_file):
            pass
        else:
            url = (
                "http://dapds00.nci.org.au/thredds/ncss/fx3/gbr4_v2/"
                + "gbr4_simple_"
                + endDlTime.strftime("%Y")
                + "-"
                + endDlTime.strftime("%m")
                + ".nc?"
                + "&var=wspeed_u&var=wspeed_v"
                + "&north="
                + str(lat_max)
                + "&west="
                + str(lon_min)
                + "&east="
                + str(lon_max)
                + "&south="
                + str(lat_min)
                + "&time_start="
                + convertDate(startDlTime)
                + "&time_end="
                + convertDate(endDlTime)
                + "&horizStride=1&timeStride=1&vertCoord=&addLatLon=true"
            )
    
            sys.stderr.write("\r")
            sys.stderr.write(
                "[%-20s] %d%%  (Now downloading : %s in file %s)"
                % (
                    "*" * int(20 * (i - 1) / duration),
                    np.ceil(100.0 / duration * (i - 1)),
                    startDlTime.strftime("%Y-%m-%d"),
                    filename,
                )
            )
            sys.stderr.flush()
    
            urllib.request.urlretrieve(url, path_file)
    
        startDlTime = endDlTime
    
    sys.stderr.write("\r")
    sys.stderr.write(
        "[%-20s] %d%% %-100s\n"
        % ("*" * int(20 * i / duration), np.floor(100.0 / duration * i), "(done)")
    )
    sys.stderr.flush()
    
    print("\nData downloaded")
    
    print("\n============================================")
    print("STEP 2 : Combining data in a single .nc file")
    print("============================================\n")
    
    mergedFilename = (
        "eReefs_wind."
        + initial_time.strftime("%Y%m%d")
        + "."
        + final_time.strftime("%Y%m%d")
        + ".nc"
    )
    pathToMergedFile = path_output + mergedFilename
    
    if os.path.isfile(pathToMergedFile):
        deleteOld = input(
            "A previous combined file "
            + mergedFilename
            + " already exists. Do you want to delete it? [y/n] "
        )
        if deleteOld == "y":
            os.remove(pathToMergedFile)
            print("File deleted.\n")
        else:
            print(
                "ERROR : File was not deleted but can"
                "t be overwritten. Please try again !"
            )
            exit(-1)
    
    for i in range(1, duration + 1):
        sys.stdout.write("\r")
        sys.stdout.write(
            "Making time variable a record dimension in each .nc file ("
            + str(i)
            + "/"
            + str(duration)
            + ")"
        )
        tmpFilename = path_output + "tmp_eReefs%06d.nc" % i
        tmpRecFilename = path_output + "tmp_eReefs_rec_%06d.nc" % i
        os.system("ncks -O --mk_rec_dmn time " + tmpFilename + " " + tmpRecFilename)
    
    sys.stdout.flush()
    
    print("\nNow combining .nc files (This could take a few minutes)\n")
    os.system(
        "ncrcat -n "
        + str(duration)
        + ",6,1 "
        + path_output
        + "tmp_eReefs_rec_000001.nc "
        + pathToMergedFile
    )
    
    print("Data combined\n")
    
    print("Now cleaning folder...\n")
    os.system("rm " + path_output + "tmp_eReefs*.nc")
    
    print("ALL GOOD!\n")