Ejemplo n.º 1
0
def test_code():

    @pytest.mark.mpl_image_compare(tolerance=.03, remove_text=False, style='default')
    def test_plot(methodToRun, proj, use_ax, positional_arguments, keyword_arguments, use_figsize=(14,9), use_dpi=200, ax_in_dict=False):
        
        if use_ax == True:
            fig = plt.figure(figsize=use_figsize,dpi=use_dpi)
            ax = plt.axes(projection=proj)
            ax = methodToRun(*positional_arguments, ax=ax, **keyword_arguments)
        else:
            fig = plt.figure(figsize=use_figsize,dpi=use_dpi)
            ax = methodToRun(*positional_arguments, **keyword_arguments)
        
        if ax_in_dict == True:
            ax = ax['ax']
        
        return fig

    #method2(storm.plot, ['spam'], {'ham': 'ham'})
    
    #Retrieve HURDAT2 reanalysis dataset for North Atlantic
    hurdat_atl = tracks.TrackDataset()

        
    #Assign all tornadoes to storm
    hurdat_atl.assign_storm_tornadoes()
    
    #------------------------------------------------------------
    
    #Search name
    hurdat_atl.search_name('michael')
    
    #Test getting storm ID
    storm_id = hurdat_atl.get_storm_id(('michael', 2018))
    if storm_id != 'AL142018':
        raise AssertionError("Incorrect type")
    
    #Test retrieving hurricane Michael (2018)
    storm = hurdat_atl.get_storm(('michael', 2018))
    
    #Cartopy proj
    proj = ccrs.PlateCarree(central_longitude=0.0)
    
    #Make plot of storm track
    test_plot(storm.plot, proj, True, [], {'return_ax': True}, use_figsize=(14,9))
    
    #Get NHC discussion
    disco = storm.get_nhc_discussion(forecast=1)
    
    #Plot NHC forecast
    test_plot(storm.plot_nhc_forecast, proj, True, [], {'forecast': 1, 'return_ax': True}, use_figsize=(14,9))
    #ax = storm.plot_nhc_forecast(forecast=1,return_ax=True)
    
    #Plot storm tornadoes
    #test_plot(storm.plot_tors, proj, [], {'return_ax': True})
    #ax = storm.plot_tors(return_ax=True)
    
    #Plot rotated tornadoes
    test_plot(storm.plot_TCtors_rotated, proj, False, [], {'return_ax': True}, use_figsize=(9,9), use_dpi=150)
    #ax = storm.plot_TCtors_rotated(return_ax=True)
    
    #Convert to datatypes
    storm.to_dict()
    storm.to_xarray()
    storm.to_dataframe()
    
    #------------------------------------------------------------
    
    #Test retrieving season
    season = hurdat_atl.get_season(2017)
    
    #Make plot of season
    test_plot(season.plot, proj, True, [], {'return_ax': True}, use_figsize=(14,9))
    #ax = season.plot(return_ax=True)
    
    #Annual summary
    season.summary()
    
    #Dataframe
    season.to_dataframe()
    
    #------------------------------------------------------------
    
    #Rank storms
    hurdat_atl.rank_storm('ace')
    
    #Gridded stats
    test_plot(hurdat_atl.gridded_stats, proj, True, ['maximum wind'], {}, use_figsize=(14,9))
    #hurdat_atl.gridded_stats('maximum wind',return_ax=True)
    
Ejemplo n.º 2
0
            rng = 5
            val = (75 - value)
            colors.append(getColor(val, rng, [178, 0, 255], [99, 0, 214]))

        else:
            colors.append(rgb(99, 0, 214))

    return colors


#==============================================================================
# Retrieve storm data from Tropycal
#==============================================================================

#Retrieve HURDATv2 dataset, including Best Track for current year data
basin = tracks.TrackDataset(include_btk=True)

#Retrieve data for the requested storm
storm = basin.get_storm(storm_tuple)

#==============================================================================
# Interpolate HURDATv2 or best track data to every 10 minutes
#==============================================================================

#Determine loop start and end dates
try:
    start_date
except:
    start_date = storm.date[0]

try:
Ejemplo n.º 3
0
import tropycal.tracks as tracks

import datetime as dt
import sys

import matplotlib.pyplot as plt

hurdat_atl = tracks.TrackDataset(basin='north_indian',
                                 source='ibtracs',
                                 ibtracs_mode="jtwc")

# Let's retrieve an instance of Hurricane Kyarr from 2019:

storm = hurdat_atl.get_storm(('vardah', 2016))

###########################################
# This instance of Storm contains several methods that return the storm data back in different data types. The following examples will show # how to retrieve 3 different data types.
#

print(storm.to_dict())

print(storm.to_xarray())

print(storm.to_dataframe())

ax = storm.plot(return_ax=True)
hurdat_atl.ace_climo(plot_year=2019,
                     compare_years=2018,
                     save_path="ace_climo.png")

hurdat_atl.wind_pres_relationship(storm=('kyarr', 2019),
Ejemplo n.º 4
0
# Lets you view the operational cone data for a particular tropical cyclone. #
#   Or, you can view the CARQ data instead.                                  #
#                                                                            #
# Code by Stephen Mullens. April 2020.                                       #
##############################################################################
import tropycal.tracks as tracks

# Which storm do you want to see?
# ALXXYYYY
# AL = Atlantic, XX = storm number, YYYY = year
tc_id = "AL031981"

# Download the dataset for the North Atlantic basin.
# include_btk includes the current year.
print("get hurdat_atl")
hurdat_atl = tracks.TrackDataset(basin='north_atlantic',include_btk=True)

# Get the data for the tc_id.
print("get storm_raw")
storm_raw = hurdat_atl.get_storm(tc_id)

# Get the operational forecasts for the tc_id.
print("get op_storm")
op_storm = storm_raw.get_operational_forecasts()

# Output the storm's name and the year it occurred.
print(f"\n{storm_raw['name']} - {storm_raw['year']}")

# Output all the 4-character model codes for this storm. 
keys = [k for k in op_storm.keys()]
print(keys)
Ejemplo n.º 5
0
This sample script illustrates how to retrieve a single storm from the HURDAT2 dataset, and make plots and analyses of this storm.

For documentation generation purposes, return_ax must be set True for plotting functions. You don't need to have this extra argument in every plotting function call (e.g., "storm.plot(return_ax=True)" will produce the same output as "storm.plot()").
"""

import tropycal.tracks as tracks
import datetime as dt

###########################################
# HURTDAT2 Dataset
# ----------------
# Let's start by creating an instance of a TrackDataset object. By default, this reads in the HURDAT2 dataset from the National Hurricane  Center (NHC) website. For this example we'll be using the HURDAT2 dataset over the North Atlantic basin.
# 
# HURDAT data is not available for the most recent hurricane seasons. To include the latest data up through today, the "include_btk" flag  would need to be set to True, which reads in preliminary best track data from the NHC website.

hurdat_atl = tracks.TrackDataset(basin='north_atlantic',source='hurdat',include_btk=False)

###########################################
# Individual storm analysis
# -------------------------
# Individual storms can be retrieved from the dataset by calling the ``get_storm()`` function, which returns an instance of a Storm object. This can be done by either entering a tuple containing the storm name and year, or by the standard tropical cyclone ID (e.g., "AL012019").
# 
# Let's retrieve an instance of Hurricane Michael from 2018:

storm = hurdat_atl.get_storm(('michael',2018))

###########################################
# This instance of Storm contains several methods that return the storm data back in different data types. The following examples will show # how to retrieve 3 different data types.
# 
# Retrieve a dictionary of Michael's data:
Ejemplo n.º 6
0
# Let's start by creating an instance of a TornadoDataset object. By default, this reads in the SPC tornado database from their website.

tor_data = tornado.TornadoDataset()
    
###########################################
# We can use a TornadoDataset object to analyze both tornadoes associated with tropical cyclones and non-TC tornadoes. As an example of the latter, we can make a plot of all tornadoes during the 27 April 2011 tornado outbreak, along with the Practically Perfect Forecast (PPH) in filled contours:

tor_ax,domain,leg_tor = tor_data.plot_tors(dt.datetime(2011,4,27),plotPPH=True,return_ax=True)
tor_ax

###########################################
# Using TrackDataset
# ------------------
# We can also use TornadoDataset to assess tornadoes associated with tropical cyclones. First off let's get an instance of TrackDataset for the North Atlantic HURDAT2 basin:

hurdat_atl = tracks.TrackDataset(basin='north_atlantic',source='hurdat',include_btk=False)

###########################################
# This instance of Storm contains several methods that return the storm data back in different data types. The following examples will show how to retrieve 3 different data types.
# 
# Now we want to attribute tornadoes from the SPC database to all tropical cyclones which produced tornadoes. We do so using the ``assign_storm_tornadoes()`` method of TrackDataset. The main input parameter is "dist_thresh", which controls the distance from the tropical cyclone center over which to attribute tornadoes to. For this example we'll use 750 kilometers as the threshold.
# 
# This code block will take a while to run, as it will iterate over every storm in HURDAT2 and match tornadoes to those that produced them.

hurdat_atl.assign_storm_tornadoes(dist_thresh=750)

###########################################
# Once the above block is done running, we can now look at a climatology of tornadoes associated with North Atlantic tropical cyclones. The current method of analysis is via the ``plot_TCtors_rotated()`` method, which rotates tropical cyclones to a storm motion relative framework.
# 
# Most tornadoes associated with tropical cyclones occur in the front right quadrant (i.e., forward and right of the storm track). We can visualize this by plotting all tornadoes associated with tropical cyclones in a motion relative framework:
Ejemplo n.º 7
0
def plot_forecast_cone(in_fp, out_fp, storm_label=None):
    """
    Repopulate tropycal storm dict with local model data; then
    invoke plot_nhc_forecast and outputs a TC track cone forecast figure.

    Args:
        in_fp (str) - input filepath
        out_fp (str) - output filepath
        storm_label (str) - storm label; if not provided, use default tech
    """
    try:
        with open(CACHED_FP, 'rb') as f:
            storm = pickle.load(f)
    except Exception as e:
        print(e)
        # read nhc data for prepopulation
        hurdat_atl = tracks.TrackDataset(basin='north_atlantic',
                                         source='hurdat',
                                         include_btk=False)
        storm = hurdat_atl.get_storm(('michael', 2018))
        with open(CACHED_FP, 'wb') as f:
            pickle.dump(storm, f)

    # read local data, rename, and create cols
    df = pd.read_csv(in_fp, header=None, names=COLUMNS)
    df = df.loc[df['tech'] == ' C00Z']
    df = df.drop_duplicates(['tau'], keep='first')
    df['ace'] = df['vmax']**2 / 10000
    df['date'] = (pd.to_datetime(df['init'], format='%Y%m%d%H') +
                  pd.to_timedelta(df['tau'], unit='H'))
    df['season'] = df['date'].dt.year
    df['year'] = df['date'].dt.year
    df['source'] = 'model'
    df['source_info'] = 'FNMOC'
    df['special'] = ''
    df['type'] = 'TS'
    df['extra_obs'] = 0
    df['wmo_basin'] = df['basin']
    latlon_dirs = [('lat', 'N'), ('lat', 'S'), ('lon', 'E'), ('lon', 'W')]
    for latlon, endswith in latlon_dirs:
        df = _scale_lat_lon(df, latlon, endswith)
    df = df.rename(
        columns={
            'stormname': 'name',
            'tech': 'id',
            'technum': 'operational_id',
            'tau': 'fhr'
        })
    if storm_label is not None:
        df['name'] = storm_label
    else:
        df['name'] = df['id']
    print(storm.dict)

    # replace values
    for key in storm.dict:
        if isinstance(storm.dict[key], (str, int, float)):
            storm.dict[key] = df[key].unique()[0]
        elif key == 'date':
            storm.dict[key] = [pd_dt.to_pydatetime() for pd_dt in df[key]]
        elif isinstance(storm.dict[key], list):
            storm.dict[key] = df[key].values.tolist()
        else:
            storm.dict[key] = df[key].values

    sub_df = df[['init', 'fhr', 'lat', 'lon', 'vmax', 'mslp', 'type']]
    storm.forecast_dict = {}
    # not really official forecast
    # tropycal only uses OFCL for cone forecast
    storm.forecast_dict['OFCL'] = {}
    for init, group in sub_df.groupby('init'):
        storm.forecast_dict['OFCL'][init] = (group.drop(
            columns='init').to_dict('list'))
        storm.forecast_dict['OFCL'][init]['init'] = pd.to_datetime(
            init, format='%Y%m%d%H').to_pydatetime()

    # to use plot_nhc_forecast CARQ is expected
    storm.forecast_dict['CARQ'] = storm.forecast_dict['OFCL']

    try:
        ax = storm.plot_nhc_forecast(0, return_ax=True)
    except Exception as e:
        ax = storm.plot(return_ax=True)
    plt.savefig(out_fp)
Ejemplo n.º 8
0
    if binGenMap == 1:
        #   Get Labels for Counties
        shapeMap['labelPoint'] = shapeMap['geometry'].apply(
            lambda x: x.representative_point().coords[:])
        shapeMap['labelPoint'] = [
            coords[0] for coords in shapeMap['labelPoint']
        ]
        #   Get Map Bounds
        fltX = intMapScale * (listMapX[1] - listMapX[0]) / (listMapY[1] -
                                                            listMapY[0])
        fltY = intMapScale * (listMapY[1] - listMapY[0]) / (listMapX[1] -
                                                            listMapX[0])
    #   endif

    #   Get Basin
    basinNA = tracks.TrackDataset(basin='north_atlantic')

    #   Get Log String
    strLog = '\nHurricanes without US Landfall:\n'

    #   Start Hurricane List Read
    for hurricane in listHurr:
        #   Get Hurricane+CAT DF
        dfStorm = gen_storm_df(hurricane)
        dfStorm = dfStorm[[
            'year', 'month', 'hour', 'type', 'lat', 'lon', 'vmax', 'mslp'
        ]]

        #   Get Storm Points
        dfPoints = storm_to_points(dfStorm)
        dfPoints = dfPoints[[