API reference

This page provides an auto-generated summary of metsim’s API. For more details and examples, refer to the relevant chapters in the main part of the documentation.

MetSim

The main object of the MetSim package. The MetSim object is used to set up and launch forcing generation and/or disaggregation routines.

The MetSim object uses a class dictionary to refer to the model setup, which can be modified after instantiation if necessary. Before calling run or launch on the instance it is required to call the load function to ensure that all of the required parameters have been set and that the input data is sufficient to provide the output specified.

class metsim.metsim.DummyLock[source]

DummyLock provides the lock API without any actual locking.

class metsim.metsim.MetSim(params: dict, domain_slice={})[source]

MetSim handles the distribution of jobs that write to a common file by launching muliple processes and queueing up their writeback so that work can be done while IO is happening.

run_slice()[source]

Run a single slice of

setup_netcdf_output(filename, times)[source]

setup a single netcdf file

write_chunk(locks=None)[source]

write data from a single chunk

metsim.metsim.add_prec_tri_vars(domain)[source]

Check that variables for triangle precipitation method exist and have values that are within allowable ranges. Return these variables.

Parameters:domain – Dataset of domain variables for given location.
Returns:
  • dur – Array of climatological monthly storm durations. [minutes]
  • t_pk – Array of climatological monthly times to storm peaks. [minutes]
metsim.metsim.chunk_domain(chunks, dims)[source]

Return a dictionary of chunk slices that can be used to decompose a grid

metsim.metsim.wrap_run_cell(func: callable, params: dict, ds: xarray.core.dataset.Dataset, state: xarray.core.dataset.Dataset, disagg: bool, out_times: pandas.core.indexes.datetimes.DatetimeIndex)[source]

Iterate over a chunk of the domain. This is wrapped so we can return a tuple of locs and df.

Parameters:
  • func (callable) – The function to call to do the work
  • params (dict) – Parameters from a MetSim object
  • ds (xr.Dataset) – Input forcings and domain
  • state (xr.Dataset) – State variables at the point of interest
  • disagg (bool) – Whether or not we should run a disagg routine
  • out_times (pd.DatetimeIndex) – Times to return (should be trimmed 1 day at each end from the given index)
Returns:

  • df_complete (pd.DataFrame) – A dataframe with the disaggregated data in it
  • df_base (pd.DataFrame) – A dataframe with the state data in it

Physics

physics

metsim.physics.atm_pres(elev: float, lr: float) → float[source]

Atmospheric pressure (Pa) as a function of elevation (m)

[1]Iribane, J.V., and W.L. Godson, 1981. Atmospheric Thermodynamics, 2nd Edition. D. Reidel Publishing Company, Dordrecht, The Netherlands (p. 168)
Parameters:
  • elev – Elevation in meters
  • lr – Lapse rate (K/m)
Returns:

Atmospheric pressure (Pa)

Return type:

pressure

metsim.physics.calc_pet(rad: numpy.array, ta: numpy.array, dayl: numpy.array, pa: float, dt: float = 0.2) → numpy.array[source]

Calculates the potential evapotranspiration for aridity corrections in calc_vpd(), according to Kimball et al., 1997

Parameters:
  • rad – daylight average incident shortwave radiation (W/m2)
  • ta – daylight average air temperature (deg C)
  • dayl – daylength (s)
  • pa – air pressure (Pa)
  • dt – offset for saturation vapor pressure calculation
Returns:

Potential evapotranspiration (cm/day)

Return type:

pet

metsim.physics.solar_geom[source]

Flat earth assumption

Parameters:
  • elev – Elevation in meters
  • lat – Latitude in decimal format
  • lr – Lapse rate in K/m
Returns:

(tiny_rad_fract, daylength, flat_potrad, tt_max0)

Return type:

sg

metsim.physics.svp(temp: numpy.array, a: float = 0.61078, b: float = 17.269, c: float = 237.3)[source]

Compute the saturated vapor pressure.

[2]Maidment, David R. Handbook of hydrology. McGraw-Hill Inc., 1992 Equation 4.2.2.
Parameters:
  • temp – Temperature (degrees Celsius)
  • a – (optional) parameter
  • b – (optional) parameter
  • c – (optional) parameter
Returns:

Saturated vapor pressure (Pa)

Return type:

svp

metsim.physics.svp_slope(temp: pandas.core.series.Series, a: float = 0.61078, b: float = 17.269, c: float = 237.3)[source]

Compute the gradient of the saturated vapor pressure as a function of temperature.

[3]Maidment, David R. Handbook of hydrology. McGraw-Hill Inc., 1992. Equation 4.2.3.
Parameters:temp – Temperature (degrees Celsius)
Returns:Gradient of d(svp)/dT.
Return type:dsvp_dT

MtClim

MTCLIM

metsim.methods.mtclim.pet(shortwave, t_day, daylength, params)[source]

Computes potential evapotranspiration Note this should be jointly computed iteratively with tdew, vapor_pressure, and shortwave as used in the main run function.

Parameters:
  • shortwave – Daily estimated shortwave radiation
  • t_day – Daylight average temperature
  • daylength – Daily length of daylight
  • params – Dictionary of class parameters from the MetSim object Note this must contain the keys ‘sw_prec_thresh’ and ‘rain_scalar’
Returns:

Estimated potential evapotranspiration

Return type:

pet

metsim.methods.mtclim.run(df: pandas.core.frame.DataFrame, params: dict) → pandas.core.frame.DataFrame[source]

Runs the entire mtclim set of estimation routines. This will take a set of daily t_min, t_max, and prec to return a set of estimated variables. See the documentation for the other mtclim functions for more information about which variables are estimated.

Note: this function modifies the input dictionary and returns it

Parameters:
  • df – Dataframe containing daily inputs.
  • params – A dictionary containing the class parameters of the MetSim object.
Returns:

The same dataframe with estimated variables added

Return type:

df

metsim.methods.mtclim.shortwave(tfmax, vapor_pressure, tt_max, potrad)[source]

Computes shortwave radiation Note this should be jointly computed iteratively with pet, tdew, and vapor_pressure as used in the main run function.

Parameters:tfmax – Daily maximum cloudy-sky transmittance
Returns:Estimated vapor pressure
Return type:vapor_pressure
metsim.methods.mtclim.t_day(t_min: numpy.ndarray, t_max: numpy.ndarray, params: dict) → numpy.ndarray[source]

Computes the daylight average temperature, based on a weighted parameterization.

Parameters:
  • t_min – Timeseries of daily minimum temperature
  • t_max – Timeseries of daily maximum temperature
  • params – Dictionary of class parameters from the MetSim object Note this must contain the key ‘tday_coef’
Returns:

Daily average temperature during daylight hours

Return type:

tday

metsim.methods.mtclim.tdew(pet, t_min, seasonal_prec, dtr)[source]

Computes dewpoint temperature Note this should be jointly computed iteratively with pet, vapor_pressure, and shortwave as used in the main run function.

Parameters:
  • pet – Estimated potential evapotranspiration
  • t_min – Daily minimum temperature
  • seasonal_prec – 90 running total precipitation
  • dtr – Daily temperature range
Returns:

Estimated dewpoint temperature

Return type:

tdew

metsim.methods.mtclim.tfmax(dtr, sm_dtr, prec, params)[source]

Computes the maximum daily transmittance of the amtosphere under cloudy conditions

Parameters:
  • dtr – Daily temperature range
  • sm_dtr – Smoothed daily temperature range using 30 moving window
  • prec – Daily total precipitation
  • params – Dictionary of class parameters from the MetSim object Note this must contain the keys ‘sw_prec_thresh’ and ‘rain_scalar’
Returns:

Daily maximum cloudy-sky transmittance

Return type:

tfmax

metsim.methods.mtclim.tskc(tfmax, params)[source]

Computes cloud cover fraction

Parameters:
  • tfmax – Daily maximum cloudy-sky transmittance
  • params – Dictionary of class parameters from the MetSim object
Returns:

Daily estimated cloud cover fraction

Return type:

tskc

metsim.methods.mtclim.vapor_pressure(tdew)[source]

Computes vapor pressure Note this should be jointly computed iteratively with pet, tdew, and shortwave as used in the main run function.

Parameters:tdew – Daily dewpoint temperature
Returns:Estimated vapor pressure
Return type:vapor_pressure

Disagg

Disaggregates daily data down to finer grained data using some heuristics

metsim.disaggregate.disaggregate(df_daily: pandas.core.frame.DataFrame, params: dict, solar_geom: dict, t_begin: list = None, t_end: list = None) → pandas.core.frame.DataFrame[source]

Take a daily timeseries and scale it down to a finer time scale.

Parameters:
  • df_daily – Dataframe containing daily timeseries. Should be the result of one of the methods provided in the methods directory.
  • params – A dictionary containing the class parameters of the MetSim object.
  • solar_geom – A dictionary of solar geometry variables
  • t_begin – List of t_min and t_max for day previous to the start of df_daily. None indicates no extension of the record.
  • t_end – List of t_min and t_max for day after the end of df_daily. None indicates no extension of the record.
Returns:

A dataframe with sub-daily timeseries.

Return type:

df_disagg

metsim.disaggregate.longwave(air_temp: numpy.array, vapor_pressure: numpy.array, tskc: numpy.array, params: dict) → numpy.array[source]

Calculate longwave. This calculation can be performed using a variety of parameterizations for both the clear sky and cloud covered emissivity. Options for choosing these parameterizations should be passed in via the params argument.

For more information about the options provided in this function see:

[1]Bohn, T.J., Livneh, B., Oyler, J.W., Running, S.W., Nijssen, B. and Lettenmaier, D.P., 2013. Global evaluation of MTCLIM and related algorithms for forcing of ecological and hydrological models. Agricultural and forest meteorology, 176, pp.38-49, doi:10.1016/j.agrformet.2013.03.003.
Parameters:
  • air_temp – Sub-daily temperature
  • vapor_pressure – Sub-daily vapor pressure
  • tskc – Daily cloud fraction
  • params – A dictionary of parameters, which contains information about which emissivity and cloud fraction methods to use.
Returns:

A sub-daily timeseries of the longwave radiation

Return type:

lwrad

metsim.disaggregate.prec(prec: pandas.core.series.Series, t_min: pandas.core.series.Series, ts: float, params: dict, month_of_year: int)[source]

Distributes sub-daily precipitation either evenly (uniform) or with a triangular (triangle) distribution, depending upon the chosen method.

Note: The uniform disaggregation returns only through to the beginning of
the last day. Final values are filled in using a forward fill in the top level disaggregate function
Parameters:
  • prec – Daily timeseries of precipitation. [mm]
  • t_min – Daily timeseries of minimum daily temperature. [C]
  • ts – Timestep length to disaggregate down to. [minutes]
  • params – A dictionary of parameters, which contains information about which precipitation disaggregation method to use.
  • month_of_year – Timeseries of index of month of year
Returns:

A sub-daily timeseries of precipitation. [mm]

Return type:

prec

metsim.disaggregate.pressure(temp: numpy.array, elev: float, lr: float) → numpy.array[source]

Calculates air pressure.

Parameters:
  • temp – A sub-daily timeseries of temperature
  • elev – Elevation
  • lr – Lapse rate
Returns:

A sub-daily timeseries of air pressure (kPa)

Return type:

pressure

metsim.disaggregate.relative_humidity(vapor_pressure: numpy.array, temp: numpy.array) → numpy.array[source]

Calculate relative humidity from vapor pressure and temperature.

Parameters:
  • vapor_pressure – A sub-daily timeseries of vapor pressure
  • temp – A sub-daily timeseries of temperature
Returns:

A sub-daily timeseries of relative humidity

Return type:

rh

metsim.disaggregate.set_min_max_hour(tiny_rad_fract: numpy.ndarray, yday: numpy.ndarray, daylength: numpy.ndarray, n_days: int, ts: int, params: dict) → Tuple[numpy.ndarray][source]

Determine the time at which min and max temp is reached for each day.

Parameters:
  • tiny_rad_fract – Array of fraction of shortwave radiation received at a shortened timestep. This should be calculated by metsim.physics.solar_geom.
  • yday – Array of day of year for each simulated day.
  • n_days – Number of days in run.
  • ts – Timestep of run.
  • params – Dictionary of parameters to use. Must contain utc_offset and tmax_daylength_fraction.
Returns:

A tuple containing 2 timeseries, corresponding to time of min and max temp, respectively

Return type:

(t_t_min, t_t_max)

metsim.disaggregate.shortwave(sw_rad: numpy.array, daylength: numpy.array, day_of_year: numpy.array, tiny_rad_fract: numpy.array, params: dict) → numpy.array[source]

Disaggregate shortwave radiation down to a subdaily timeseries.

Parameters:
  • sw_rad – Daily incoming shortwave radiation
  • daylength – List of daylength time for each day of year
  • day_of_year – Timeseries of index of days since Jan-1
  • tiny_rad_fract – Fraction of the daily potential radiation during a radiation time step defined by SW_RAD_DT
  • params – Dictionary of parameters from the MetSim object
Returns:

A sub-daily timeseries of shortwave radiation.

Return type:

disaggrad

metsim.disaggregate.specific_humidity(vapor_pressure: numpy.array, air_pressure: numpy.array) → numpy.array[source]

Calculates specific humidity

Parameters:
  • vapor_pressure – A sub-daily timeseries of vapor pressure (kPa)
  • air_pressure – A sub-daily timeseries of air pressure (kPa)
Returns:

A sub-daily timeseries of specific humidity

Return type:

spec_humid

metsim.disaggregate.temp(t_min: numpy.array, t_max: numpy.array, out_len: int, t_t_min: numpy.array, t_t_max: numpy.array, ts: int, t_begin: list = None, t_end: list = None) → numpy.array[source]

Disaggregate temperature using a Hermite polynomial interpolation scheme.

Parameters:
  • t_min – Timeseries of daily minimum temperatures.
  • t_max – Timeseries of daily maximum temperatures.
  • out_len – Length of the required output vector.
  • t_t_min – Times at which minimum daily temperatures are reached.
  • t_t_max – Times at which maximum daily temperatures are reached.
  • ts – Timestep for disaggregation
  • t_begin – List of t_min and t_max for day previous to the start of df_daily. None indicates no extension of the record.
  • t_end – List of t_min and t_max for day after the end of df_daily. None indicates no extension of the record.
Returns:

A sub-daily timeseries of temperature.

Return type:

temps

metsim.disaggregate.tskc(tskc: numpy.array, ts: int, params: dict) → numpy.array[source]

Disaggregate cloud fraction with uniform interpolation

Parameters:
  • tskc – Daily cloud fraction
  • ts – Time step to disaggregate to (in minutes)
Returns:

Sub-daily timeseries of cloud fraction

Return type:

tskc

metsim.disaggregate.vapor_pressure(vp_daily: numpy.array, temp: numpy.array, t_t_min: numpy.array, n_out: int, ts: int) → numpy.array[source]

Calculate vapor pressure. First a linear interpolation of the daily values is calculated. Then this is compared to the saturated vapor pressure calculated using the disaggregated temperature. When the interpolated vapor pressure is greater than the calculated saturated vapor pressure, the interpolation is replaced with the saturation value.

Parameters:
  • vp_daily – Daily vapor pressure
  • temp – Sub-daily temperature
  • t_t_min – Timeseries of minimum daily temperature
  • n_out – Number of output observations
  • ts – Timestep to disaggregate down to
Returns:

A sub-daily timeseries of the vapor pressure

Return type:

vp

metsim.disaggregate.wind(wind: numpy.array, ts: int, params: dict) → numpy.array[source]

Wind is assumed constant throughout the day Note: this returns only through to the beginning of the

last day. Final values are filled in using a forward fill in the top level disaggregate function
Parameters:
  • wind – Daily timeseries of wind
  • ts – Timestep to disaggregate down to
Returns:

A sub-daily timeseries of wind

Return type:

wind