Optical Flow

metintos.flow_tuning.add_steps_to_times_sources_targets(times_sources_targets, steps_list=(numpy.timedelta64(0, 'ns'),))[source]

Given a dict mapping (source step, source step) -> (target step), return a dict replacing step keys and values with analogous TimeSelector values that also include time information.

param times_sources_targets:

type times_sources_targets:

param steps_list:

default 0

type steps_list:

returns:

None

metintos.flow_tuning.add_times_to_steps_sources_targets(steps_sources_targets, dataset)[source]

Given a dict mapping (source step, source step) -> (target step), return a dict replacing step keys and values with analogous TimeSelector values that also include time information.

param steps_sources_targets:

type steps_sources_targets:

param dataset:

type dataset:

returns:

None

metintos.flow_tuning.evaluate_flow_on_dataset(flow_calc, dataset, variables, sources_and_targets, array_norm=None, aggregation_norm=None, cut_evaluation_array=None, aggregate=True)[source]
Parameters:
  • flow_calc

  • dataset (xarray.Dataset) –

  • variables

  • sources_and_targets

  • array_norms

  • aggregation_norm

  • cut_evaluation_array

  • aggregate

Returns:

None

metintos.flow_tuning.evaluate_flow_on_dataset_norms(flow_calc, dataset, variables, sources_and_targets, array_norms=None, aggregation_norm=None, cut_evaluation_array=None, aggregate=False)[source]
Parameters:
  • flow_calc

  • dataset (xarray.Dataset) –

  • variables

  • sources_and_targets

  • array_norms

  • aggregation_norm

  • cut_evaluation_array

  • aggregate

Returns:

None

metintos.flow_tuning.filter_dims(d, dims)[source]

Returns d filtered so that only key-value pairs where the key is in dims are kept

Parameters:
  • d

  • dims

Returns:

None

metintos.flow_tuning.optimize_flow(parameter_space, flow_generator, dataset, sources_and_targets, var_weights=None, max_evals=100, cut_evaluation_array=None)[source]

Optimizes the parameters of the algorithm for performance on the dataset

Parameters:
  • parameter_space

  • flow_generator

  • dataset

  • sources_and_targets

  • var_weights

  • max_evals

  • cut_evaluation_array

Returns:

None

metintos.flow_tuning.TimeSelector = <class 'metintos.flow_tuning.TimeSelector'>

tuple : TimeSelector = namedtuple(“TimeSelector”, [‘time’, ‘step’])

class metintos.optiflow.FarnebackFlow(**kwargs)[source]

Optical flow calculator using the algorithm of Farneback (2003)

Variables:

parameters – arguments passed to the Farneback algorithm

__call__(start_frame, end_frame, initial_flow=None, check_nans=True)[source]

Returns the computed optical flow

Parameters:
  • start_frame (array_like) – 2D array (N x M) representing the start frame

  • end_frame (array_like) – 2D array (N x M) representing the end frame

  • initial_flow (array_like or None) – (optional) N x M x 2 array to initialize the flow

  • start_frame – 2D array (N x M) representing the start frame

  • check_nans (bool) – (optional) if True, replace any nans in the input with zeros

Returns:

optical flow between the frames

Return type:

array_like

__init__(**kwargs)[source]

Optical flow calculator using the algorithm of Farneback (2003)

Parameters:

kwargs (dict) – arguments passed to the Farneback algorithm

Returns:

None

class metintos.optiflow.MultiFrameInterpolant(frames, flow_calculator=None, spatial_interp=None, t_axis=None, initial_flows=None)[source]

Performs optical flow or linear interpolation between several consecutive, equally spaced frames

Variables:

interpolants – List of pairwise interpolants

__call__(t)[source]
Parameters:

t (float) – Fraction of the time domain between the start and the end frame. Must fulfill 0 <= t <= n_frames

Returns:

Flow-interpolated array at t

Return type:

array_like

__init__(frames, flow_calculator=None, spatial_interp=None, t_axis=None, initial_flows=None)[source]
Parameters:
  • frames (list[array_like]) – List of 2D arrays

  • flow_calculator ((R² x R²) -> R² mapping) – Callable that computes the optical flow between two frames / arrays

  • spatial_interp (R² -> (R² -> R)) – Callable that generates a 2D interpolant of a frame array with normalized coordinates

  • t_axis (array_like(dtype='timedelta64')) – (optional) array containing the timestamps of t

  • initial_flows (list[array_like]) – List of arrays of shape N x M x 2 representing initial guesses for the optical flows

Returns:

None

eval_at_t(t, check_nans=True)[source]
Parameters:
  • t – Union[np.datetime64, np.timedelta64]

  • check_nans (bool) – if True, replace any nans in the input with zeros

Returns:

Flow-interpolated array at timestamp t

Return type:

array_like

class metintos.optiflow.NormalizedWrappedInterpolant(array, interpolant_generator=None)[source]

2D interpolant with natural index coordinates

Variables:
  • array – 2D array to interpolate

  • i – normalized coordinates along the first axis

  • j – normalized coordinates along the second axis

  • interpolant – wrapped interpolant

__call__(*args, **kwargs)[source]
Parameters:
  • args

  • kwargs

Returns:

__init__(array, interpolant_generator=None)[source]
Parameters:
  • array (array_like) – 2D array to interpolate

  • interpolant_generator (R² -> (R² -> R) mapping) – wrapped interpolant

Returns:

None

ev(*args, **kwargs)[source]
Parameters:
  • args

  • kwargs

Returns:

class metintos.optiflow.TwoFrameInterpolant(start_frame, end_frame, flow_calculator=None, spatial_interp=None, initial_flow=None)[source]

Performs optical flow or linear interpolation between two consecutive frames

Variables:
  • start_frame – Matrix representation of the variable at the start of the temporal interpolation domain

  • end_frame – Matrix representation of the variable at the end of the temporal interpolation

  • flow_calculator – Callable that computes the optical flow between two frames / arrays

  • spatial_interp – Callable that generates a 2D interpolant of a frame array with normalized coordinates

  • flow – Optical flow between the start and end frames

__call__(t)[source]
Parameters:

t (float) – Fraction of the time domain between the start and the end frame. Must fulfill 0 <= t <= 1

Returns:

Flow-interpolated array at t

Return type:

array_like

__init__(start_frame, end_frame, flow_calculator=None, spatial_interp=None, initial_flow=None)[source]
Parameters:
  • start_frame (array_like) – 2D array representation of the variable at the start of the temporal interpolation domain

  • end_frame (array_like) – 2D array representation of the variable at the end of the temporal interpolation

  • flow_calculator ((R² x R²) -> R² mapping) – Callable that computes the optical flow between two frames / arrays

  • spatial_interp (R² -> (R² -> R)) – Callable that generates a 2D interpolant of a frame array with normalized coordinates

Returns:

None

International Standard Atmosphere (ISA)

class metintos.isa.CasadiISA(deltaT=0)[source]

Casadi implementation of the ISA atmosphere (troposphere and tropopause only)

var deltaT:

Temperature differential w.r.t. ISA conditions

type deltaT:

float

__init__(deltaT=0)[source]
Parameters:

deltaT (float, optional) – Temperature differential w.r.t. ISA conditions

Returns:

None

Utilities

metintos.utils.get_bracketing_indexes(array, value)[source]

Returns consecutive indexes idx_low and idx_high such that array[idx_low] <= value < array[idx_high].

Parameters:
  • array (array_like) – Array to search. Must be 1D and monotonically sorted in ascending order. This condition is NOT checked here

  • value (Union[float, np.datetime64, np.timedelta64]) – Value to bracket

Returns:

Indexes that fulfill the condition array[idx_low] <= value < array[idx_high].

Return type:

tuple

Input/output

metintos.io.check_array_for_nans(arr)[source]
Parameters:

arr

Returns:

None

metintos.io.get_var_name(dataset, variable)[source]
Parameters:
  • dataset

  • variable

Returns:

None

class metintos.io.CoordinateGenerator[source]

Helper class for generating coordinates

Variables:

dict – Coordinates dictionary, mapping axis_name -> np.ndarray

__init__()[source]

This declares the axes variable as a dictionary

add_axis_lims_n_points(ax_name, lower, upper, n, dtype=None)[source]

Add an axis coordinate specifying limits and number of points in coordinate axis

Parameters:
  • ax_name (str) – Name of the coordinate axis to be set

  • lower (float) – Lower limit of the coordinate axis

  • upper (float) – Upper limit of the coordinate axis

  • n (int) – Number of points in the coordinate axis

  • dtype (dtype, optional) – The type of the coordinate array. If dtype is not given, it will be inferred by numpy.linspace()

Returns:

None

add_axis_lims_resolution(ax_name, lower, upper, resolution)[source]

Add an axis coordinate specifying limits and resolution (i.e. steps between coordinate points)

Parameters:
  • ax_name (str) – Name of the coordinate axis to be set

  • lower (float) – Lower limit of the coordinate axis

  • upper (float) – Upper limit of the coordinate axis

  • resolution (float) – Distance between axis points

Returns:

None

class metintos.io.DatasetHandler(ds, output_dtype=<class 'numpy.float32'>, time_dim='step')[source]

Wrapper for a xarray.Dataset containing meteorological information at pressure levels

Variables:

ds – The dataset

__init__(ds, output_dtype=<class 'numpy.float32'>, time_dim='step')[source]
Parameters:
  • ds (xarray.Dataset) – The dataset

  • output_dtype (data-type) – (optional)

  • time_dim (str) – (optional)

Returns:

None

complete_new_coords(**coords)[source]

Generates a coordinate set by completing the specificed new coordinates with the already existing ones

Parameters:

coords (dict) – New coordinates, as a dict mapping variable names to monotonically increasing 1D arrays

Returns:

New coordinates, completing missing dimensions with the already existing values

Return type:

dict

property data_variables_list

Return a list of variables that are not coordinates

Returns:

list of variables that are not coordinates

property default_dims

Returns the default dimensions

Returns:

tuple with the dimensions.

static get_coords_shape(dims, coords)[source]

Returns the shape of an array with the given coordinates and dimension ordering

Parameters:
  • dims – dimension

  • coords – coordinates

Returns:

The coordinates shape

Return type:

tuple

get_geographical_coordinate_slice_by_indexes(lat_idx_low, lat_idx_high, lon_idx_low, lon_idx_high)[source]

Get a CoordinateGenerator (Not implemented)

Parameters:
  • lat_idx_low

  • lat_idx_high

  • lon_idx_low

  • lon_idx_high

Returns:

None

get_optical_flow_interpolated_dataset(new_coords, variables=None, flow_calculator=None, spatial_interp=None, verbose=False, zero_out_nans=True)[source]

Reinterpolates the dataset to the new coordinates using optical flow interpolation

Parameters:
  • new_coords (dict) – A dictionary of new coordinates, mapping coordinate names to numpy arrays. If a coordinate axis is missing, the old coordinate axis is used by default

  • variables (list) – (optional) List of variables to be transported to the new dataset

  • flow_calculator ((R² x R²) -> R² mapping) – (optional) Callable that computes the optical flow between two frames / arrays

  • spatial_interp (R² -> (R² -> R)) – (optional) Callable that generates a 2D interpolant of a frame array with normalized coordinates

  • verbose (bool) – (optional) If true, display the progress of the dataset reinterpolation procedure

  • zero_out_nans (bool) – (optional) if True, replace any nans in the input with zeros

Returns:

The reinterpolated dataset

Return type:

xarray.Dataset

get_optical_flow_interpolated_variable(new_coords, variable, flow_calculator=None, spatial_interp=None, flow_padding=0.1, verbose=False, zero_out_nans=True)[source]
Parameters:
  • new_coords (dict) – A dictionary of new coordinates, mapping coordinate names to numpy arrays. If a coordinate axis is missing, the old coordinate axis is used by default

  • variable (str) – variable to be transported to the new dataset

  • flow_calculator ((R² x R²) -> R² mapping) – (optional) Callable that computes the optical flow between two frames / arrays

  • spatial_interp (R² -> (R² -> R)) – (optional) Callable that generates a 2D interpolant of a frame array with normalized coordinates

  • flow_padding (float) – (optional)

  • verbose (bool) – (optional) If true, display the progress of the dataset reinterpolation procedure

  • zero_out_nans (bool) – (optional) if True, replace any nans in the input with zeros

Returns:

The reinterpolated dataset

Return type:

xarray.Dataset

get_resampled_dataset(**coords)[source]

Resamples the dataset to new coordinates

Parameters:

coords (dict) – A dictionary of new coordinates, mapping coordinate names to numpy arrays. If a coordinate axis is missing, the old coordinate axis is used by default

Returns:

A dataset reinterpolated to the new coordinates

Return type:

xarray.Dataset

classmethod load_from_steps(path_list, **backend_kwargs)[source]

Loads the meteo infromation from multiple grib files with consecutive forecast steps

Parameters:
  • path_list (list) – List of paths of the grib files

  • backend_kwargs

Returns:

cls(ds)

Constants

metintos.constants.P0_MSL = 101325.0

float : P0_MSL = 101325.0

metintos.constants.R_a = 6378137.0

float : R_a = 6378.137e3

metintos.constants.R_b = 6356.752

float : R_b = 6356.752

metintos.constants.R_mean = 6356800.0

float : R_mean = 6356.8e3

metintos.constants.Rg = 287.05287

float : Rg = 287.05287

metintos.constants.T0_MSL = 288.15

float : T0_MSL = 288.15

metintos.constants.T_tropopause = 216.65

float : T_tropopause = 216.65

metintos.constants.a0_MSL = 340.294

float : a0_MSL = 340.294

metintos.constants.d2r = 0.017453292519943295

float : d2r = np.pi/180

metintos.constants.first_eccentricity = 0.08181919084262149

float : first_eccentricity = (flattening*(2 - flattening))**0.5

metintos.constants.flattening = 0.0033528106647474805

float : flattening = 1/298.257223563

metintos.constants.ft = 0.3048

float : ft = 0.3048

metintos.constants.g = 9.80665

float : g0 = g = 9.80665

metintos.constants.g0 = 9.80665

float : g0 = g = 9.80665

metintos.constants.h_tropopause = 11000.0

float : h_tropopause = 11e3

metintos.constants.hour = numpy.timedelta64(3600000000000,'ns')

float : hour = np.timedelta64(1, ‘h’).astype(‘timedelta64[ns]’)

metintos.constants.kappa = 1.4

float : kappa = 1.4

metintos.constants.kt = 0.5144444444444445

float : kt = nmi/3600

metintos.constants.lapse_rate_troposphere = -0.0065

float : lapse_rate_troposphere = -0.0065

metintos.constants.m2ft = 3.280839895013123

float : m2ft = ft**-1

metintos.constants.minute = numpy.timedelta64(60000000000,'ns')

float : minute = np.timedelta64(1, ‘m’).astype(‘timedelta64[ns]’)

metintos.constants.ms2kt = 1.9438444924406046

float : ms2kt = 1/kt

metintos.constants.nmi = 1852.0

float : nmi = 1852.0

metintos.constants.rho0_MSL = 1.225

float : rho0_MSL = 1.225