Trim

class auglib.transform.Trim(*, start_pos=0, end_pos=None, duration=None, fill='none', fill_pos='right', unit='seconds', preserve_level=False, bypass_prob=None)[source]

Trim, zero pad, and/or repeat signal.

If duration is None the signal will be trimmed to the range [start_pos, end_pos], whereas the start or end of the signal is used if start_pos and/or end_pos are None.

If duration is provided and fill is 'none' it will calculate start_pos or end_pos to match the given duration if the incoming signal is long enough. If duration is provided, but neither start_pos or end_pos it will trim a signal with given duration from the center of the signal.

If duration is provided and fill is 'zeros' or 'loop' it will return a signal of length duration filling missing values with zeros or the trimmed signal. fill_pos defines if the signal is filled on the right, left, or both ends.

The following table shows a few combinations of the arguments and the resulting augmented signal for an ingoing signal of [1, 2, 3, 4]. All time values are given in samples.

start_pos

end_pos

duration

fill

fill_pos

outcome

1

None

None

none

right

[2, 3, 4]

None

1

None

none

right

[1, 2, 3]

None

None

2

none

right

[2, 3]

2

None

4

loop

right

[3, 4, 3, 4]

1

1

4

zeros

right

[2, 3, 0, 0]

3

None

4

zeros

both

[0, 4, 0, 0]

Parameters:
  • start_pos (int | float | auglib.core.observe.Base | auglib.core.time.Time) – starting point of the trimmed region, relative to the start of the input signal (see unit)

  • end_pos (int | float | auglib.core.observe.Base | auglib.core.time.Time) – end point of the trimmed region, relative to the end of the input signal (see unit). The end point is counted backwards from the end of the signal. If end_pos=512 samples, it will remove the last 512 samples of the input

  • duration (int | float | auglib.core.observe.Base | auglib.core.time.Time) – target duration of the resulting signal (see unit). If set to None or 0, the selected section extends until the end or the beginning of the original signal

  • fill (str) – fill strategy if the end and/or start point of the trimmed region exceeds the signal. Three strategies are available: 'none' the signal is not extended, 'zeros' the signal is filled up with zeros, 'loop' the trimmed signal is repeated

  • fill_pos (str) – position at which the selected fill strategy applies. 'right' adds samples to the right, 'left' adds samples to the left, or 'both' adds samples on both sides, equally distributed starting at the right

  • unit (str) – literal specifying the format of start_pos, end_pos, and duration (see auglib.utils.to_samples())

  • preserve_level (bool | auglib.core.observe.Base) – if True the root mean square value of the augmented signal will be the same as before augmentation

  • bypass_prob (float | auglib.core.observe.Base) – Probability to bypass the transformation

Raises:
  • ValueError – if fill contains a non-supported value

  • ValueError – if fill_pos contains a non-supported value

Examples

Remove first 0.2 s and last 0.2 s of a speech signal.

>>> import audb
>>> import audiofile
>>> import audplot
>>> import auglib
>>> transform = auglib.transform.Trim(start_pos=0.2, end_pos=0.2)
>>> files = audb.load_media("emodb", "wav/03a01Fa.wav", version="1.4.1")
>>> signal, sampling_rate = audiofile.read(files[0])
>>> augmented_signal = transform(signal, sampling_rate)
>>> audplot.waveform(augmented_signal)
../_images/auglib-transform-Trim-1.png

Trim speech signal to half its current length.

>>> transform = auglib.transform.Trim(duration=0.5, unit="relative")
>>> augmented_signal = transform(signal, sampling_rate)
>>> audplot.waveform(augmented_signal)
../_images/auglib-transform-Trim-3.png

Trim beginning and end of a speech signal, and request a fixed duration. If the trimmed signal is shorter than the requested duration, it is looped.

>>> transform = auglib.transform.Trim(
...     start_pos=0.5,
...     end_pos=0.5,
...     duration=2.0,
...     fill="loop",
... )
>>> augmented_signal = transform(signal, sampling_rate)
>>> audplot.waveform(augmented_signal)
../_images/auglib-transform-Trim-5.png

__call__()

Trim.__call__(signal, sampling_rate=None)

Apply transform to signal.

Parameters:
  • signal (numpy.ndarray) – signal to be transformed

  • sampling_rate (int) – sampling rate in Hz

Return type:

numpy.ndarray

Returns:

augmented signal

Raises:
  • ValueError – if the signal shape is not support by chosen transform parameters

  • ValueError – if sampling_rate is None, but the transform requires a sampling rate

  • RuntimeError – if the given sampling rate is incompatible with the transform

arguments

Trim.arguments

Returns arguments that are serialized.

Returns:

Dictionary of arguments and their values.

Raises:

RuntimeError – if arguments are found that are not assigned to attributes of the same name

Examples

>>> import audobject.testing
>>> o = audobject.testing.TestObject("test", point=(1, 1))
>>> o.arguments
{'name': 'test', 'point': (1, 1)}

borrowed_arguments

Trim.borrowed_arguments

Returns borrowed arguments.

Returns:

Dictionary with borrowed arguments.

from_dict()

static Trim.from_dict(d, root=None, **kwargs)
Return type:

audobject.core.object.Object

from_yaml()

static Trim.from_yaml(path_or_stream, **kwargs)
Return type:

audobject.core.object.Object

from_yaml_s()

static Trim.from_yaml_s(yaml_string, **kwargs)
Return type:

audobject.core.object.Object

hidden_arguments

Trim.hidden_arguments

Returns hidden arguments.

Returns:

List with names of hidden arguments.

id

Trim.id

Object identifier.

The ID of an object ID is created from its non-hidden arguments.

Returns:

object identifier

Examples

>>> class Foo(Object):
...     def __init__(self, bar: str):
...         self.bar = bar
>>> foo1 = Foo("I am unique!")
>>> foo1.id
'893df240-babe-d796-cdf1-c436171b7a96'
>>> foo2 = Foo("I am different!")
>>> foo2.id
'9303f2a5-bfc9-e5ff-0ffa-a9846e2d2190'
>>> foo3 = Foo("I am unique!")
>>> foo1.id == foo3.id
True

is_loaded_from_dict

Trim.is_loaded_from_dict

Check if object was loaded from a dictionary.

Returns True if object was initialized from a dictionary, e.g. after loading it from a YAML file.

Returns:

True if object was loaded from a dictionary,

otherwise False

resolvers

Trim.resolvers

Return resolvers.

Returns:

Dictionary with resolvers.

short_id

Trim.short_id

Short object identifier.

The short ID consists of eight characters and is created from its non-hidden arguments.

Returns:

short object identifier

Examples

>>> class Foo(Object):
...     def __init__(self, bar: str):
...         self.bar = bar
>>> foo1 = Foo("I am unique!")
>>> foo1.id
'893df240-babe-d796-cdf1-c436171b7a96'
>>> foo1.short_id
'171b7a96'
>>> foo2 = Foo("I am different!")
>>> foo2.short_id
'6e2d2190'
>>> foo3 = Foo("I am unique!")
>>> foo1.short_id == foo3.short_id
True

to_dict()

Trim.to_dict(*, include_version=True, flatten=False, root=None)

Converts object to a dictionary.

Includes items from audobject.Object.arguments. If an argument has a resolver, its value is encoded. Usually, the object can be re-instantiated using audobject.Object.from_dict(). However, if flatten=True, this is not possible.

Parameters:
  • include_version (bool) – add version to class name

  • flatten (bool) – flatten the dictionary

  • root (str) – if file is written to disk, set to target directory

Return type:

collections.abc.Mapping[str, typing.Union[bool, datetime.datetime, dict, float, int, list, None, str]]

Returns:

dictionary that represent the object

Examples

>>> import audobject.testing
>>> o = audobject.testing.TestObject("test", point=(1, 1))
>>> o.to_dict(include_version=False)
{'$audobject.core.testing.TestObject': {'name': 'test', 'point': [1, 1]}}
>>> o.to_dict(flatten=True)
{'name': 'test', 'point.0': 1, 'point.1': 1}

to_samples()

Trim.to_samples(value, sampling_rate=None, *, length=None, allow_negative=True)

Convert duration value to samples.

Return type:

int

to_yaml()

Trim.to_yaml(path_or_stream, *, include_version=True)

Save object to YAML file.

Parameters:
  • path_or_stream (str | io.IOBase) – file path or stream

  • include_version (bool) – add version to class name

to_yaml_s()

Trim.to_yaml_s(*, include_version=True)

Convert object to YAML string.

Parameters:

include_version (bool) – add version to class name

Return type:

str

Returns:

YAML string

Examples

>>> import audobject.testing
>>> o = audobject.testing.TestObject("test", point=(1, 1))
>>> print(o.to_yaml_s(include_version=False))
$audobject.core.testing.TestObject:
  name: test
  point:
  - 1
  - 1