Skip to content
Extraits de code Groupes Projets
prepro2D.py 16,4 ko
Newer Older
  • Learn to ignore specific revisions
  • 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
    import getopt
    import sys
    from datetime import datetime
    
    import gdal
    from gdalconst import *
    import numpy as np
    import pandas as pd
    import pyresample
    import slimPre
    from netCDF4 import Dataset, num2date
    from scipy.spatial import cKDTree
    
    import param
    import prepro_private
    
    if slimPre.partition_id() == "0":
        print("  ___________   ____ _____________  ____")
        print("\____ \_  __ \_/ __ \ \___ \_  __ \/  _ \ ")
        print("|  |_| |  | \/\  ___/|  |_| |  | \(  |_| )")
        print("|   __/|__|    \_____|   __/|__|   \____/ ")
        print("|__|                 |__|                 ")
        print()
    
    # --------- LOAD COMMAND LINE OPTIONS  -----------------------------------------
    opts = None
    args = None
    try:
        opts, args = getopt.getopt(sys.argv[1:], "m:")
    except getopt.GetoptError:
        print("Argument error!")
        sys.exit(1)
    
    mesh_setup = "gbr_styx"
    
    for opt, arg in opts:
        if opt == "-m":
            mesh_setup = arg
    
    p = param.parameters(mesh_setup)
    if slimPre.partition_id() == "0":
        p.print_info()
    # ------------------------------------------------------------------------------
    
    pre_data_dir = p.prepro_dir
    if slimPre.partition_nb() != "1":
        pre_data_dir = pre_data_dir + "/%s" % slimPre.partition_id()
    slimPre.make_directory(pre_data_dir)
    
    # --- useful variables
    fmt = "%Y-%m-%d %H:%M:%S"
    d0 = datetime.strptime(p.initial_time, fmt)
    d1 = datetime.strptime(p.final_time, fmt)
    if d0 > d1:
        raise ValueError(
            "initial time (%s) must be before final time (%s) !"
            % (p.initial_time, p.final_time)
        )
    
    if slimPre.partition_nb() == "1":
        mesh_file_name = p.mesh_file
    else:
        mesh_file_name = p.mesh_file[:-4] + "_" + slimPre.partition_nb() + ".msh"
    
    mesh = slimPre.Mesh(mesh_file_name, mesh_proj=p.mesh_proj)
    region_global = slimPre.Region(mesh)
    lonlat_global = slimPre.Coordinate_system(
        region_global, data_proj="+proj=latlong +ellps=WGS84"
    )
    lonlat_global_degrees = lonlat_global.coordinates[:, :2] * 180.0 / np.pi
    nElements = len(lonlat_global.coordinates)
    
    time_tpxo = slimPre.Time(
        initial_time=p.initial_time, final_time=p.final_time, time_step=900.0
    )
    time_wind = slimPre.Time(
        initial_time=p.initial_time, final_time=p.final_time, time_step=3600.0
    )
    
    # export_xdmf = True if int(slimPre.partition_nb()) < 10 and nElements < 30_000 else False
    export_xdmf = False
    
    #################################
    # 1. TIME INDEPENDENT VARIABLES #
    #################################
    if slimPre.partition_nb() == "1":
        # --- bathymetry
        if "bathymetry" in p.vec_prepro2D:
            print("=== preprocessing bathymetry ===")
            bath = prepro_private.interpolate_on_mesh(
                lonlat_global_degrees,
                None,
                p.slimGBR_data_dir + "source/bathymetry/gbr100_10nov_v6.grd",
                "z",
            )
            bath[:] = np.maximum(p.min_depth, -bath[:])
    
            slimPre.write_file(
                pre_data_dir + "/bathymetry.nc",
                region=region_global,
                time=None,
                data=[("bathymetry", bath)],
            )
            slimPre.smooth_bathymetry(
                mesh,
                (pre_data_dir + "/bathymetry.nc", "bathymetry"),
                output_file_name=pre_data_dir + "/bathymetry_smooth.nc",
                coefficient=0.5,
                transform_p0=False,
            )
            if export_xdmf:
                slimPre.netcdf_to_xdmf(
                    mesh_file_name,
                    pre_data_dir + "/bathymetry_smooth.nc",
                    pre_data_dir + "/bathymetry.h5",
                    "bathymetry",
                )
    
        # --- coriolis
        if "coriolis" in p.vec_prepro2D:
            print("=== preprocessing Coriolis coefficient ===")
            corio = 2 * 7.292e-5 * np.sin(lonlat_global.coordinates[:, 1])
            slimPre.write_file(
                pre_data_dir + "/coriolis.nc",
                region=region_global,
                time=None,
                data=[("coriolis", corio)],
            )
            del corio
    
        # --- manning
        if "manning" in p.vec_prepro2D:
            print("=== preprocessing Manning coefficient ===")
    
            # Loading .tif file and structuring as a workable array
            reefs_tiff = gdal.Open(
                p.slimGBR_data_dir + "source/reef_map/reefs_as_raster.tif", GA_ReadOnly
            )
    
            nxReefs = reefs_tiff.RasterXSize
            nyReefs = reefs_tiff.RasterYSize
    
            (
                oxReefs,
                dxReefs,
                t1Reefs,
                oyReefs,
                t2Reefs,
                dyReefs,
            ) = reefs_tiff.GetGeoTransform()
    
            reefs = np.array(reefs_tiff.GetRasterBand(1).ReadAsArray())
    
            c = np.empty((nElements))
    
            for i in range(nElements):
                c[i] = slimPre.interpolate_from_structured_grid(
                    lonlat_global_degrees[i, 0],
                    lonlat_global_degrees[i, 1],
                    oxReefs,
                    oyReefs,
                    dxReefs,
                    dyReefs,
                    reefs,
                )
    
            def bottom_coef(off_reef, on_reef):
                coef = np.ones(nElements) * off_reef
                coef[c > 0.25] = on_reef
                return coef
    
            manning_025_25 = bottom_coef(0.025, 0.25)
            manning_reduced = bottom_coef(0.025, 0.025 * np.sqrt(10))
            bulk_0025_05 = bottom_coef(2.5e-3, 5e-2)
    
            slimPre.write_file(
                pre_data_dir + "/reef.nc",
                region=region_global,
                time=None,
                data=[
                    ("manning_025_25", manning_025_25),
                    ("manning_reduced", manning_reduced),
                    ("bulk_0025_05", bulk_0025_05),
                ],
            )
            if export_xdmf:
                slimPre.netcdf_to_xdmf(
                    mesh_file_name,
                    pre_data_dir + "/reef.nc",
                    pre_data_dir + "/reef.h5",
                    ["manning_025_25", "manning_reduced", "bulk_0025_05"],
                )
    
            del reefs_tiff, reefs
    
        if "river_discharge" in p.vec_prepro2D:
            print("=== preprocessing River discharge ===")
    
            river_discharge_dir = pre_data_dir + "/discharge/"
            slimPre.make_directory(river_discharge_dir)
    
            streamflow_df = pd.read_csv(
                f"{p.local_base_dir}source/streamflow.csv",
                index_col="datetime",
                parse_dates=True,
            )
            ts_streamflow = [t.timestamp() for t in streamflow_df.index]
            time_streamflow = slimPre.Time(time_vector=ts_streamflow)
            for c in streamflow_df.columns:
                slimPre.write_file(
                    river_discharge_dir + "river_discharge_" + str(c) + ".nc",
                    region=None,
                    time=time_streamflow,
                    data=[("river_discharge", streamflow_df[c].values)],
                )
    
    ###############################
    # 2. TIME DEPENDENT VARIABLES #
    ###############################
    if int(slimPre.partition_nb()) > 1:
        # --- mercator and tides
        if "mercator" in p.vec_prepro2D:
            print("[%s] preprocessing mercator and tides" % slimPre.partition_id())
            # mercator
            print("[%s] read merc files" % slimPre.partition_id())
            h_file = (
                p.nc_data_dir
                + "/mercator_zos_"
                + d0.strftime("%Y%m%d")
                + "_"
                + d1.strftime("%Y%m%d")
                + ".nc"
            )
            u_file = (
                p.nc_data_dir
                + "/mercator_uo_"
                + d0.strftime("%Y%m%d")
                + "_"
                + d1.strftime("%Y%m%d")
                + "_DA.nc"
            )
            v_file = (
                p.nc_data_dir
                + "/mercator_vo_"
                + d0.strftime("%Y%m%d")
                + "_"
                + d1.strftime("%Y%m%d")
                + "_DA.nc"
            )
            print("[%s] interp merc on mesh: H" % slimPre.partition_id())
            h_merc = prepro_private.interpolate_on_mesh(
                lonlat_global_degrees, time_tpxo, h_file, "zos"
            )
            print("[%s] interp merc on mesh: U" % slimPre.partition_id())
            u_merc = prepro_private.interpolate_on_mesh(
                lonlat_global_degrees, time_tpxo, u_file, "uo"
            )
            print("[%s] interp merc on mesh: V" % slimPre.partition_id())
            v_merc = prepro_private.interpolate_on_mesh(
                lonlat_global_degrees, time_tpxo, v_file, "vo"
            )
            print("[%s] rotate merc" % slimPre.partition_id())
            u_merc[:], v_merc[:] = lonlat_global.rotate(u_merc, v_merc)
    
            # tides
            print("[%s] preprocessing tides" % slimPre.partition_id())
            h_tides, u_tides, v_tides = slimPre.tpxo_tide(
                region_global,
                time_tpxo,
                h_file=p.nc_data_dir + "/h_tpxo9_zone.nc",
                u_file=p.nc_data_dir + "/u_tpxo9_zone.nc",
                export_as_transport=False,
            )
    
            # sum the two components
            print("[%s] sum mercator and tides" % slimPre.partition_id())
            h = h_merc[:] + h_tides[:]
            u = u_merc[:] + u_tides[:]
            v = v_merc[:] + v_tides[:]
    
            print("[%s] merc+tides: write files" % slimPre.partition_id())
            slimPre.write_file(
                pre_data_dir + "/mercator_and_tides.nc",
                region=region_global,
                time=time_tpxo,
                data=[("h", h), ("u", u), ("v", v)],
            )
    
            if export_xdmf:
    
                print("[%s] export merc+tides to xdmf" % slimPre.partition_id())
                slimPre.netcdf_to_xdmf(
                    mesh_file_name,
                    pre_data_dir + "/mercator_and_tides.nc",
                    p.prepro_dir + "/mercator_and_tides.h5",
                    ["h", ("u", "v")],
                    time_tpxo._time[0],
                    time_tpxo._time[-1],
                    len(time_tpxo._time) // 4,
                )
    
            del h, u, v
            del h_tides, u_tides, v_tides
            del h_merc, u_merc, v_merc
    
        # --- eReefs wind
        if "wind_ereefs" in p.vec_prepro2D:
            print("[%s] preprocessing eReefs wind" % slimPre.partition_id())
    
            eReefs_file = (
                p.nc_data_dir
                + "/eReefs_wind."
                + d0.strftime("%Y%m%d")
                + "."
                + d1.strftime("%Y%m%d")
                + ".nc"
            )
    
            print("[%s] reading eReefs data" % slimPre.partition_id())
            eReefs = Dataset(eReefs_file)
    
            tSource = np.ma.array(eReefs.variables["time"][:])
            tSourceUnits = eReefs.variables["time"].units
            tSourceDatetime = num2date(tSource, units=tSourceUnits, calendar="gregorian")
            tSourceDelta = tSourceDatetime - datetime(1970, 1, 1)
            tSourceSeconds = [elt.total_seconds() for elt in tSourceDelta]
            tEReefs = slimPre.Time(np.float64(tSourceSeconds), "1970-01-01 00:00:00")
    
            lonSource = np.ma.array(eReefs.variables["longitude"][:])
            latSource = np.ma.array(eReefs.variables["latitude"][:])
            uWindSource = np.ma.array(eReefs.variables["wspeed_u"][:])
            vWindSource = np.ma.array(eReefs.variables["wspeed_v"][:])
            nTimeSource = len(tSourceSeconds)
    
            uWindSource = prepro_private.fill_mask(uWindSource)
            vWindSource = prepro_private.fill_mask(vWindSource)
    
            lonSource.mask = uWindSource[0, :, :].mask
            latSource.mask = uWindSource[0, :, :].mask
    
            lonTarget = lonlat_global_degrees[:, 0]
            latTarget = lonlat_global_degrees[:, 1]
    
            print("[%s] ereefs wind: building cKDTree" % slimPre.partition_id())
            tree = cKDTree(np.c_[lonSource.ravel(), latSource.ravel()])
    
            print("[%s] ereefs wind: queering cKDTree" % slimPre.partition_id())
            dd, ii = tree.query(np.c_[lonTarget, latTarget], k=4)
    
            print("[%s] ereefs wind: resampling" % slimPre.partition_id())
            # get indexes
            r, c = np.unravel_index(ii, np.shape(lonSource))
    
            # mask distances corresponding to masked values
            dd = np.ma.array(dd, mask=lonSource.mask[r, c])
    
            # compute weights (inverse distance weighting)
            weights = 1.0 / dd
            weights = weights / np.sum(weights, axis=-1)[:, np.newaxis]
    
            # compute resampled data
            def resamp_idw(data):
                data_resamp = np.reshape(
                    np.sum(data[:, r, c] * weights, axis=-1),
                    # [nTimeSource, len(y), len(x)],
                    [nTimeSource, len(lonTarget)],
                )
                return data_resamp
    
            uWindResamp = resamp_idw(uWindSource)
            vWindResamp = resamp_idw(vWindSource)
    
            uWindResamp[:], vWindResamp[:] = lonlat_global.rotate(uWindResamp, vWindResamp)
    
            print("[%s] eReefs wind: write files" % slimPre.partition_id())
            slimPre.write_file(
                pre_data_dir + "/eReefs_wind.nc",
                region=region_global,
                time=tEReefs,
                data=[("u", uWindResamp), ("v", vWindResamp)],
            )
            if export_xdmf:
                print("[%s] eReefs wind: export to xdmf" % slimPre.partition_id())
                slimPre.netcdf_to_xdmf(
                    mesh_file_name,
                    pre_data_dir + "/eReefs_wind.nc",
                    p.prepro_dir + "/eReefs_wind.h5",
                    ["u", "v", ("u", "v")],
                    tEReefs._time[0],
                    tEReefs._time[-1],
                    len(tEReefs._time),
                )
    
            del uWindSource, vWindSource
            del uWindResamp, vWindResamp
    
        # --- wind
        if "wind" in p.vec_prepro2D:
            print("[%s] preprocessing wind" % slimPre.partition_id())
            wind_file = (
                p.nc_data_dir
                + "/wind_"
                + d0.strftime("%Y%m%d")
                + "_"
                + d1.strftime("%Y%m%d")
                + ".nc"
            )
            print("[%s] interp wind on mesh: msl" % slimPre.partition_id())
            pa = prepro_private.interpolate_on_mesh(
                lonlat_global_degrees, time_wind, wind_file, "msl"
            )
            print("[%s] interp wind on mesh: u" % slimPre.partition_id())
            u = prepro_private.interpolate_on_mesh(
                lonlat_global_degrees, time_wind, wind_file, "u10"
            )
            print("[%s] interp wind on mesh: v" % slimPre.partition_id())
            v = prepro_private.interpolate_on_mesh(
                lonlat_global_degrees, time_wind, wind_file, "v10"
            )
            print("[%s] rotate wind" % slimPre.partition_id())
            u[:], v[:] = lonlat_global.rotate(u, v)
    
            print("[%s] wind: write files" % slimPre.partition_id())
            slimPre.write_file(
                pre_data_dir + "/wind.nc",
                region=region_global,
                time=time_wind,
                data=[("windx", u), ("windy", v), ("pa", pa)],
            )
            if export_xdmf:
                slimPre.netcdf_to_xdmf(
                    mesh_file_name,
                    pre_data_dir + "/wind.nc",
                    p.prepro_dir + "/wind.h5",
                    ["pa", ("windx", "windy")],
                    time_wind._time[0],
                    time_wind._time[-1],
                    len(time_wind._time),
                )
            del pa, u, v
    
        # --- barocline gradient
        if "baroclinic_gradient" in p.vec_prepro2D:
            print("[%s] preprocessing barocline gradient" % slimPre.partition_id())
            th_file = (
                p.nc_data_dir
                + "/mercator_thetao_"
                + d0.strftime("%Y%m%d")
                + "_"
                + d1.strftime("%Y%m%d")
                + ".nc"
            )
            s_file = (
                p.nc_data_dir
                + "/mercator_so_"
                + d0.strftime("%Y%m%d")
                + "_"
                + d1.strftime("%Y%m%d")
                + ".nc"
            )
    
            with Dataset(th_file, "r") as f:
                Th = prepro_private.fill_mask3(np.ma.array(f.variables["thetao"][:]))
                lon = np.array(f.variables["longitude"][:], dtype=np.float)
                lat = np.array(f.variables["latitude"][:], dtype=np.float)
                time = prepro_private.convert_time(
                    np.array(f.variables["time"][:]), f.variables["time"].units
                )
                depth = np.array(f.variables["depth"][:])
            with Dataset(s_file, "r") as f:
                S = prepro_private.fill_mask3(np.ma.array(f.variables["so"][:]))
    
            rho = prepro_private.jackett(Th, S, p.rho_mean)
            del Th, S
            grad_x, grad_y = prepro_private.compuWindResampe_baroclinic_gradient(
                lonlat_global_degrees, p.mesh_proj, rho, time, depth, lon, lat
            )
    
            f = slimPre.slim_private._load_function(
                (p.prepro_dir + "/bathymetry_smooth.nc", "bathymetry"), mesh._groups
            )
            bath = region_global._evaluateFunctor(f, 1)[None, :, 0]
    
            f_x = -(p.g / p.rho_mean) * grad_x / bath
            f_y = -(p.g / p.rho_mean) * grad_y / bath
            del grad_x, grad_y
    
            time_grad = slimPre.Time(time_vector=time)
            slimPre.write_file(
                pre_data_dir + "/baroclinic_forcing.nc",
                region=region_global,
                time=time_grad,
                data=[("fx", f_x), ("fy", f_y)],
            )
    
    print("[%s] DONE!" % slimPre.partition_id())
    slimPre.exit(0)