snap_to_grids

emlib.misc.snap_to_grids(x, ticks, offsets=None, mode='nearest')[source]

Snap x to the nearest slot within multiple overlapping grids

A regular grid is defined as x = offset + tick*n, where n is an integer from -inf to inf.

Parameters:
  • x (Union[float, Rational]) – a number or a seq. of numbers

  • ticks (Sequence[Union[Rational, float]]) – a seq. of ticks, each tick defines a grid

  • offsets (Optional[Sequence[Union[Rational, float]]]) – a seq. of offsets, or None to set offset to 0 for each grid

  • mode – one of ‘floor’, ‘ceil’, ‘nearest’

Return type:

Union[float, Rational]

Returns:

the snapped value

Given a list of regular grids, snap the value of x to this grid

Example

snap a time to a grid of 16th notes >>> snap_to_grids(0.3, [1/4]) 0.25

snap a time to a multiple grid of 16ths, 8th note triplets, etc. >>> snap_to_grids(0.3, [1/8, 1/6, 1/5]) 0.3333333333333333