smrf.utils package

Submodules

smrf.utils.gitinfo module

smrf.utils.gradient module

smrf.utils.gradient.aspect(dz_dx, dz_dy)[source]

Calculate the aspect from the finite difference. Aspect is degrees clockwise from North (0/360 degrees)

See below for a referance to how ArcGIS calculates slope http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/How_Aspect_works/00q900000023000000/

Parameters
  • dz_dx – finite difference in the x direction

  • dz_dy – finite difference in the y direction

Returns

aspect in degrees

smrf.utils.gradient.aspect_to_ipw_radians(a)[source]

IPW defines aspect differently than most GIS programs so convert an aspect in degrees from due North (0/360) to the IPW definition.

Aspect is radians from south (aspect 0 is toward the south) with range from -pi to pi, with negative values to the west and positive values to the east

Parameters

a – aspect in degrees from due North

Returns

a: aspect in radians from due South

smrf.utils.gradient.gradient_d4(dem, dx, dy, aspect_rad=False)[source]

Calculate the slope and aspect for provided dem, this will mimic the original IPW gradient method that does a finite difference in the x/y direction

Given a center cell e and it’s neighbors:

a | b | c |
d | e | f |
g | h | i |

The rate of change in the x direction is [dz/dx] = (f - d ) / (2 * dx)

The rate of change in the y direction is [dz/dy] = (h - b ) / (2 * dy)

The slope is calculated as slope_radians = arctan ( sqrt ([dz/dx]^2 + [dz/dy]^2) )

Parameters
  • dem – array of elevation values

  • dx – cell size along the x axis

  • dy – cell size along the y axis

  • aspect_rad – turn the aspect from degrees to IPW radians

Returns

slope in radians aspect in degrees or IPW radians

smrf.utils.gradient.gradient_d8(dem, dx, dy, aspect_rad=False)[source]

Calculate the slope and aspect for provided dem, using a 3x3 cell around the center

Given a center cell e and it’s neighbors:

a | b | c |
d | e | f |
g | h | i |

The rate of change in the x direction is [dz/dx] = ((c + 2f + i) - (a + 2d + g) / (8 * dx)

The rate of change in the y direction is [dz/dy] = ((g + 2h + i) - (a + 2b + c)) / (8 * dy)

The slope is calculated as slope_radians = arctan ( sqrt ([dz/dx]^2 + [dz/dy]^2) )

Parameters
  • dem – array of elevation values

  • dx – cell size along the x axis

  • dy – cell size along the y axis

  • aspect_rad – turn the aspect from degrees to IPW radians

Returns

slope in radians aspect in degrees or IPW radians

smrf.utils.io module

Input/Output functions Adapted from the UW-Hydro tonic project

smrf.utils.io.isbool(x)[source]

Test if str is an bolean

smrf.utils.io.isfloat(x)[source]

Test if value is a float

smrf.utils.io.isint(x)[source]

Test if value is an integer

smrf.utils.io.isscalar(x)[source]

Test if a value is a scalar

smrf.utils.pycompat module

smrf.utils.pycompat.iteritems(d)[source]
smrf.utils.pycompat.itervalues(d)[source]

smrf.utils.queue module

Create classes for running on multiple threads

20160323 Scott Havens

class smrf.utils.queue.DateQueue_Threading(maxsize=0, timeout=None, name=None)[source]

Bases: queue.Queue

DateQueue extends Queue.Queue module Stores the items in a dictionary with date_time keys When values are retrieved, it will not remove them and will require cleaning at the end to not have to many values

20160323 Scott Havens

clean(index)[source]

Need to clean it out so mimic the original get

get(index, block=True, timeout=None)[source]

Remove and return an item from the queue.

If optional args ‘block’ is true and ‘timeout’ is None (the default), block if necessary until an item is available. If ‘timeout’ is a non-negative number, it blocks at most ‘timeout’ seconds and raises the Empty exception if no item was available within that time. Otherwise (‘block’ is false), return an item if one is immediately available, else raise the Empty exception (‘timeout’ is ignored in that case).

This is from queue.Queue but with modifcation for supplying what to get

Parameters
  • index – datetime object representing the date/time being processed

  • block – boolean determining whether to wait for a variable to become available

  • timeout – Number of seconds to wait before dropping error, none equates to forever.

put(item, block=True, timeout=None)[source]

Put an item into the queue.

If optional args ‘block’ is true and ‘timeout’ is None (the default), block if necessary until a free slot is available. If ‘timeout’ is a non-negative number, it blocks at most ‘timeout’ seconds and raises the Full exception if no free slot was available within that time. Otherwise (‘block’ is false), put an item on the queue if a free slot is immediately available, else raise the Full exception (‘timeout’ is ignored in that case).

class smrf.utils.queue.QueueCleaner(date_time, queue)[source]

Bases: threading.Thread

QueueCleaner that will go through all the queues and check if they all have a date in common. When this occurs, all the threads will have processed that time step and it’s not longer needed

run()[source]

Go through the date times and look for when all the queues have that date_time

class smrf.utils.queue.QueueOutput(queue, date_time, out_func, out_frequency, nx, ny)[source]

Bases: threading.Thread

Takes values from the queue and outputs using ‘out_func’

run()[source]

Output the desired variables to a file.

Go through the date times and look for when all the queues have that date_time

smrf.utils.utils module

20160104 Scott Havens

Collection of utility functions

class smrf.utils.utils.CheckStation(**kwargs)[source]

Bases: inicheck.checkers.CheckType

Custom check for ensuring our stations are always capitalized

type_func(value)[source]

Attempt to convert all the values to upper case.

Parameters

value – A single string in a a config entry representing a station name

Returns

A single station name all upper case

Return type

value

smrf.utils.utils.backup_input(data, config_obj)[source]

Backs up input data files so a user can rerun a run with the exact data used for a run.

Parameters
  • data – Pandas dataframe containing the station data

  • config_obj – The config object produced by inicheck

smrf.utils.utils.check_station_colocation(metadata_csv=None, metadata=None)[source]

Takes in a data frame representing the metadata for the weather stations as produced by smrf.framework.model_framework.SMRF.loadData and check to see if any stations have the same location.

Parameters
  • metadata_csv – CSV containing the metdata for weather stations

  • metadata – Pandas Dataframe containing the metdata for weather stations

Returns

list of station primary_id that are colocated

Return type

repeat_sta

smrf.utils.utils.find_configs(directory)[source]

Searches through a directory and returns all the .ini fulll filenames.

Parameters

directory – string path to directory.

Returns

list of paths pointing to the config file.

Return type

configs

smrf.utils.utils.getConfigHeader()[source]

Generates string for inicheck to add to config files

Returns

string for cfg headers

Return type

cfg_str

smrf.utils.utils.get_asc_stats(fp)[source]

Returns header of ascii dem file

smrf.utils.utils.get_config_doc_section_hdr()[source]

Returns the header dictionary for linking modules in smrf to the documentation generated by inicheck auto doc functions

smrf.utils.utils.getgitinfo()[source]

gitignored file that contains specific SMRF version and path

Returns

git version from ‘git describe’

Return type

str

smrf.utils.utils.getqotw()[source]
smrf.utils.utils.grid_interpolate(values, vtx, wts, shp, fill_value=nan)[source]

Broken out gridded interpolation from scipy.interpolate.griddata that takes the vertices and wts from interp_weights function

Parameters
  • values – flattened WindNinja wind speeds

  • vtx – vertices for interpolation

  • wts – weights for interpolation

  • shape – shape of SMRF grid

  • fill_value – value for extrapolated points

Returns

interpolated values

Return type

ret

smrf.utils.utils.grid_interpolate_deconstructed(tri, values, grid_points, method='linear')[source]

Underlying methods from scipy grid_data broken out to pass in the tri values returned from qhull.Delaunay. This is done to improve the speed of using grid_data

Parameters
  • tri – values returned from qhull.Delaunay

  • values – values at HRRR stations generally

  • grid_points – tuple of vectors for X,Y coords of grid stations

  • method – either linear or cubic

Returns

result of interpolation to gridded points

smrf.utils.utils.handle_run_script_options(config_option)[source]

Handle function for dealing with args in the SMRF run script

Parameters

config_option – string path to a directory or a specific config file.

Returns

Full path to an existing config file.

Return type

configFile

smrf.utils.utils.interp_weights(xy, uv, d=2)[source]

Find vertices and weights of LINEAR interpolation for gridded interp. This routine follows the methods of scipy.interpolate.griddata as outlined here: https://stackoverflow.com/questions/20915502/speedup-scipy-griddata-for-multiple-interpolations-between-two-irregular-grids This function finds the vertices and weights which is the most computationally expensive part of the routine. The interpolateion can then be done quickly.

Parameters
  • xy – n by 2 array of flattened meshgrid x and y coords of WindNinja grid

  • uv – n by 2 array of flattened meshgrid x and y coords of SMRF grid

  • d – dimensions of array (i.e. 2 for our purposes)

Returns

wts:

Return type

vertices

smrf.utils.utils.is_leap_year(year)[source]
smrf.utils.utils.nan_helper(y)[source]

Helper to handle indices and logical indices of NaNs.

Example

>>> # linear interpolation of NaNs
>>> nans, x= nan_helper(y)
>>> y[nans]= np.interp(x(nans), x(~nans), y[~nans])
Parameters

y – 1d numpy array with possible NaNs

Returns

nans - logical indices of NaNs index - a function

Return type

tuple

smrf.utils.utils.set_min_max(data, min_val, max_val)[source]

Ensure that the data is in the bounds of min and max

Parameters
  • data – numpy array of data to be min/maxed

  • min_val – minimum threshold to trim data

  • max_val – Maximum threshold to trim data

Returns

numpy array of data trimmed at min_val and max_val

Return type

data

smrf.utils.utils.water_day(indate)[source]

Determine the decimal day in the water year

Parameters

indate – datetime object

Returns

dd - decimal day from start of water year wy - Water year

Return type

tuple

20160105 Scott Havens

Module contents