Python Examples


Examples:


Sample 1: This is an example of the go code used on the backend for the Nation Water Prediction Service (NWPS) application. It uses the Go version 1.26.0 on the backend and is primarily a database-driven application.

        
        #!/usr/bin/env python3
        #
        #
        # https://nomads.ncep.noaa.gov/pub/data/nccf/nonoperational/nwm/WMS/
        #  * analysis_assim     [ channel_rt, fe, land ]    alaska, conus, hawaii, puertorico   nwm.t2023032514z.analysis_assim.channel_rt.tm00.alaska.nc
        #                                                                                       nwm.t2023032514z.analysis_assim.forcing.tm00.conus.nc
        #                                                                                       nwm.t2023032514z.analysis_assim.forcing.tm00.conus.nc
        #                                                                                       nwm.t2023032400z.analysis_assim.land.tm00.alaska.nc
        #
        #  * long_range         [ channel_rt, land ]        conus                               nwm.t20230317z.long_range.channel_rt_1.conus.nc
        #  * medium_range       [ channel_rt, fe, land ]    conus                               nwm.t20230317z.medium_range.channel_rt_4.conus.nc
        #                                                                                       nwm.t2023032512z.medium_range.forcing.day1.conus.nc
        #
        #  * medium_range_blend [ channel_rt, fe, land ]
        #  * short_range        [ channel_rt, fe, land ]    conus, hawaii                       nwm.t20230317z.short_range.channel_rt.conus.nc
        #                                                                                       nwm.t2023032512z.short_range.forcing.48hour.hawaii.nc
        #                                                                                       nwm.t2023032400z.short_range.land.f001.alaska.nc
        #
        import urllib.request, logging
        import datetime, argparse
        import requests, re, sys, os, shutil

        from urllib.request import urlretrieve
        from bs4 import BeautifulSoup


        CURRENT_DATETIME = datetime.datetime.now()
        EXT = 'nc'

        def check_nolinks(links):
            if len(links) == 0:
                print('No links found for the given url(s)')
                sys.exit(1)

        def get_url_paths(url, EXT='', params={}):
            response = requests.get(url, params=params)
            if not response.ok:
                print("url could not be reached")
                sys.exit()
            response_text = response.text
            soup = BeautifulSoup(response_text, 'html.parser')
            if not soup:
                print("no links found")
                sys.exit()
            parent = [url + node.get('href') for node in soup.find_all('a') if node.get('href').endswith(EXT)]
            return parent

        def get_results(results, SAVEDIR, TEST, DISPLAY, REGEX):
            check_nolinks(results)
            for result in results:
                if REGEX:
                    if not re.search(REGEX, result):
                        continue
                if TEST:
                    print(result)
                    if DISPLAY: print(f"saving to fullpath: {SAVEDIR}")
                else:
                    try:
                        req = requests.get(result, timeout=15, stream=True)
                        if req:
                            savefilepath = os.path.join(SAVEDIR, os.path.basename(result))
                            if not os.path.exists(savefilepath):
                                if DISPLAY: print(result)
                                req.raw.decode_content = True
                                newfile = open(savefilepath, "wb")
                                shutil.copyfileobj(req.raw, newfile)
                                newfile.close()
                            else:
                                print(f"FILE EXISTS: {savefilepath}")
                        else:
                            raise Exception(f"bad request for {result}")
                    except Exception as e:
                        logging.warning(f"could not download and write {result}: {e}")


        # run it
        parser = argparse.ArgumentParser(description='Downloads netcdf files from remote site using a URL.')
        parser.add_argument('urls', metavar='URLs', type=str, nargs='+', help='URL arguments.')
        parser.add_argument('-t', '--test', dest='TEST', action='store_true', help='Just test the pull but not actually pull the information.')
        parser.add_argument('-d', '--display', dest='DISPLAY', action='store_true', help='Display the links.')
        parser.add_argument('-s', '--savedir', dest='SAVEDIR', action='store', default=os.path.curdir, help='Absolute fullpath directory to save to.')
        parser.add_argument('-r', '--regex', dest='REGEX', action='store', default='', help='Regular expression rule for each link.')
        args = parser.parse_args()

        # Get the info
        links = []

        if len(args.urls) > 1:
            for url in args.urls:
                get_results(get_url_paths(url, EXT), args.SAVEDIR, args.TEST, args.DISPLAY, args.REGEX)
        else:
            get_results(get_url_paths(args.urls[0], EXT), args.SAVEDIR, args.TEST, args.DISPLAY, args.REGEX)
        
    

Sample 2: This is an example of the python code I wrote to update the LRO test data for local development and Docker with NWPS.

        
        #!/usr/bin/env python3.11
        #
        # 1. Download lro file from: https://water.noaa.gov/resources/downloads/lro/
        # 2. Run command in same directory: python convert_lro.py
        # 3. You should see a dated sql file like this: long_range_river_flood_risk_data.20260220.sql
        # 4. Move the file to the directory ~/nwps-core/storage/postgres/data/
        # 5. Run the docker import: docker exec -it nwps_postgres_1 sh -c $'psql -f /data/long_range_river_flood_risk_data.20260220.sql -U wps_website owp_water_website'
        # 6. Check frontend

        import os, sys, csv
        import datetime

        sql = ["TRUNCATE ahps_lro ;"]
        coj = datetime.date.today()
        currentdate = coj.strftime("%Y%m%d")
        lines = None
        currentdir = os.getcwd()
        write = None
        outputfile = None

        # Open file to write to.
        try:
            outputfile = open(os.path.join(currentdir, f"long_range_river_flood_risk_data.{currentdate}.sql"), 'w')
        except Exception as e:
            print(e)

        with open(os.path.join(currentdir, "long_range_river_flood_risk_data.csv"), 'r', newline='', encoding='utf-8') as inputfile:
            reader = csv.DictReader(inputfile)
            header_list = reader.fieldnames

            #print(header_list)
            # ['lid', ' name', ' lat', ' lon', ' wfo', ' rfc', ' wrr', ' state', ' minor', ' moderate', ' major', ' date_produced', ' obj_or_subj', ' interval', ' ']

            for row in reader:
                #print(f"{header_list[3]}: {row[header_list[3]]}")

                obj_subj = row[header_list[12]]

                if obj_subj == 'OBJ':
                    # lid
                    lid = row[header_list[0]]

                    # create minorcs
                    minorcs = row[header_list[8]][1:]

                    # create moderate
                    moderatecs = row[header_list[9]]

                    # create majorcs
                    majorcs = row[header_list[10]]

                    # create produced_time
                    produced_time = datetime.datetime.fromisoformat(row[header_list[11]].replace('Z', '+00:00'))

                    # create obj_subj
                    #obj_subj = row[header_list[12]]

                    # create interval
                    interval = row[header_list[13]]

                    sql.append(f"INSERT INTO ahps_lro (lid, minorcs, moderatecs, majorcs, produced_time, interval, obj_subj) VALUES ('{lid}', '{minorcs}', '{moderatecs}', '{majorcs}', '{produced_time}', '{interval}', '{obj_subj}') ;")

            # write to sql file
            for s in sql:
                outputfile.write(f"{s}\n")

            outputfile.close()
        
    

Sample 3: This python code was used to update a number of netcdfs with our work on the old AHPS system with the Office of Water Prediction.

        
        def set_missing_compliance_data_conus(netcdf_file):
            netcdf_file.setncattr('Conventions', 'CF-1.6')
            netcdf_file.setncattr('title', os.path.basename(netcdf_file.filepath()).split('.')[0])
            netcdf_file.setncattr('history', netcdf_file.variables['amountofprecip'].dateofdata)

            netcdf_file.variables['lat'].units = "Degree_North"
            netcdf_file.variables['lon'].units = "Degree_East"
            netcdf_file.variables['lon'].long_name = "longitude"
            netcdf_file.variables['lon'].standard_name = "longitude"
            netcdf_file.variables['lat'].long_name = "latitude"
            netcdf_file.variables['lat'].standard_name = "latitude"
            netcdf_file.variables['true_lat'].long_name = "True_Latitude"
            netcdf_file.variables['true_lon'].long_name = "True_Longitude"
            netcdf_file.variables['timeofdata'].long_name = "Time_of_Data"
            netcdf_file.variables['timeofcreation'].long_name = "Time_of_Creation"
            netcdf_file.variables['hrap_xor'].long_name = "Harp_Xor"
            netcdf_file.variables['hrap_yor'].long_name = "Harp_Yor"


        def set_missing_compliance_data_ak(netcdf_file):
            netcdf_file.variables['reftime'].units = "seconds"
            netcdf_file.variables['reftime'].comments = "seconds since (1970-1-1 00:00:00.0)"
            netcdf_file.variables['valtimeMINUSreftime'].long_name = "Valid_Time_Minus_Reference_Time"


        rootdir = r"D:\precip\water.weather.gov\precip\archive"

        for subdir, dirs, files in os.walk(rootdir):
            for file in files:
                if file.endswith("nc"):
                    # print(file)
                    #Add crs
                    try:
                        netcdf_file = netCDF4.Dataset(os.path.join(subdir, file), mode='a')
                        netcdf_file.createVariable('crs', int, )
                        netcdf_file.variables['crs'].straight_vertical_longitude_from_pole = -105.
                        netcdf_file.variables['crs'].false_easting = 0.
                        netcdf_file.variables['crs'].standard_parallel = 60.
                        netcdf_file.variables['crs'].false_northing = 0.
                        netcdf_file.variables['crs'].grid_mapping_name = "polar_stereographic"
                        netcdf_file.variables['crs'].latitude_of_projection_origin = 90.
                        netcdf_file.variables['crs'].earth_radius = 6371200.

                    try:
                        netcdf_file.variables['amountofprecip'].units = "mm"
                        netcdf_file.variables['amountofprecip'].scale_factor = "100"
                    except:
                        print(file)
                        # print ("amountofprecip not found")


        print ('Finished')