Ejemplo n.º 1
0
    def test_total_seconds_scalar(self):
        # see gh-10939
        rng = Timedelta('1 days, 10:11:12.100123456')
        expt = 1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456. / 1e9
        tm.assert_almost_equal(rng.total_seconds(), expt)

        rng = Timedelta(np.nan)
        assert np.isnan(rng.total_seconds())
Ejemplo n.º 2
0
    def test_total_seconds_scalar(self):
        # see gh-10939
        rng = Timedelta('1 days, 10:11:12.100123456')
        expt = 1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456. / 1e9
        tm.assert_almost_equal(rng.total_seconds(), expt)

        rng = Timedelta(np.nan)
        assert np.isnan(rng.total_seconds())
Ejemplo n.º 3
0
def segment_to_indices(
    signal: np.ndarray,
    sampling_rate: int,
    start: pd.Timedelta,
    end: pd.Timedelta,
) -> typing.Tuple[int, int]:
    if pd.isna(end):
        end = pd.to_timedelta(signal.shape[-1] / sampling_rate, unit='s')
    max_i = signal.shape[-1]
    start_i = int(round(start.total_seconds() * sampling_rate))
    start_i = min(start_i, max_i)
    end_i = int(round(end.total_seconds() * sampling_rate))
    end_i = min(end_i, max_i)
    return start_i, end_i
Ejemplo n.º 4
0
 def get_shock(self, step: pd.Timedelta):
     shock = {}
     for instrument_id, instrument in self.universe.items():
         if np.random.rand() < self.rate * step.total_seconds():
             magnitude = np.random.choice(np.arange(1, self.magnitude+1))
             shock[instrument_id] = np.random.choice((1, -1)) * np.random.choice(magnitude)
     return shock
Ejemplo n.º 5
0
 def get_shock(self, step: pd.Timedelta):
     shock = {}
     for instrument_id, instrument in self.universe.items():
         if np.random.rand() < self.rate * step.total_seconds():
             log_ret = np.random.exponential(self.magnitude) * np.random.choice((1, -1))
             shock[instrument_id] = int((np.exp(log_ret)-1) * instrument.get_value())
     return shock
Ejemplo n.º 6
0
def read_audio(
    path: str,
    start: pd.Timedelta = None,
    end: pd.Timedelta = None,
    channel: int = None,
) -> typing.Tuple[np.ndarray, int]:  # pragma: no cover
    """Reads (segment of an) audio file.

    Args:
        path: path to audio file
        start: read from this position
        end: read until this position
        channel: channel number

    Returns:
        signal: array with signal values in shape ``(channels, samples)``
        sampling_rate: sampling rate in Hz

    """
    if start is None or pd.isna(start):
        offset = 0
    else:
        offset = start.total_seconds()

    if end is None or pd.isna(end):
        duration = None
    else:
        duration = end.total_seconds() - offset

    # load raw audio
    signal, sampling_rate = af.read(
        audeer.safe_path(path),
        always_2d=True,
        offset=offset,
        duration=duration,
    )

    # mix down
    if channel is not None:
        if channel < 0 or channel >= signal.shape[0]:
            raise ValueError(f'We need 0<=channel<{signal.shape[0]}, '
                             f'but we have channel={channel}.')
        signal = signal[channel, :]

    return signal, sampling_rate
Ejemplo n.º 7
0
def format_timedelta(td: pd.Timedelta, use_colons=True):
    total_secs = int(td.total_seconds())
    hrs = total_secs // 3600
    mins = (total_secs % 3600) // 60
    secs = (total_secs % 3600) % 60
    if use_colons:
        return f"{hrs:02}:{mins:02}:{secs:02}"
    else:
        return f"{hrs:02}{mins:02}{secs:02}"
Ejemplo n.º 8
0
def read_audio(
    file: str,
    *,
    start: pd.Timedelta = None,
    end: pd.Timedelta = None,
    root: str = None,
) -> typing.Tuple[np.ndarray, int]:
    """Reads (segment of an) audio file.

    Args:
        file: path to audio file
        start: read from this position
        end: read until this position
        root: root folder

    Returns:
        signal: array with signal values in shape ``(channels, samples)``
        sampling_rate: sampling rate in Hz

    """
    if root is not None and not os.path.isabs(file):
        file = os.path.join(root, file)

    if start is None or pd.isna(start):
        offset = 0
    else:
        offset = start.total_seconds()

    if end is None or pd.isna(end):
        duration = None
    else:
        duration = end.total_seconds() - offset

    signal, sampling_rate = af.read(
        audeer.safe_path(file),
        always_2d=True,
        offset=offset,
        duration=duration,
    )

    return signal, sampling_rate
Ejemplo n.º 9
0
def timedelt_to_float_h(timedeltas: pd.Timedelta) -> float:  # type:ignore
    """
    Convert timedelta to float.

    Parameters
    ----------
    timedeltas : pd.Timedelta
        Timedifference.

    Returns
    -------
    float
        Timedelta as seconds.
    """
    seconds = timedeltas.total_seconds()  # type:ignore
    return seconds / 3600
Ejemplo n.º 10
0
    def test_as_unit_non_nano(self):
        # case where we are going neither to nor from nano
        td = Timedelta(days=1)._as_unit("ms")
        assert td.days == 1
        assert td.value == 86_400_000
        assert td.components.days == 1
        assert td._d == 1
        assert td.total_seconds() == 86400

        res = td._as_unit("us")
        assert res.value == 86_400_000_000
        assert res.components.days == 1
        assert res.components.hours == 0
        assert res._d == 1
        assert res._h == 0
        assert res.total_seconds() == 86400
Ejemplo n.º 11
0
def split_time_range(time_range: tuple, duration: pd.Timedelta, ignore_error=False) -> tuple:
    """
    Takes a time range (formatted strings: '%Y-%m-%dT%H:%M:%S.%f'), and selects
    a random interval within these boundaries of the specified active_screen_time.

    :param time_range: tuple with formatted time strings
    :param duration: timedelta specifying the active_screen_time of the new interval
    :param ignore_error: (bool) if true, the function ignores durations
                         that exceed the original length of the time range
    :return: new time range
    """

    # Convert the time range strings to unix epoch format
    start = datetime.strptime(time_range[0], '%Y-%m-%dT%H:%M:%S.%f').timestamp()
    stop = datetime.strptime(time_range[1], '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    # Calculate total active_screen_time (in seconds) of original
    difference = stop - start

    # Calculate active_screen_time of new interval (in seconds)
    duration = duration.total_seconds()

    # Error handling
    if difference < duration:

        if ignore_error:
            log(
                "WARNING: New interval length exceeds original time range active_screen_time! Returning original time range.")
            return time_range

        else:
            raise Exception('ERROR: New interval length exceeds original time range active_screen_time!')

    # Pick random new start and stop
    new_start = rnd.randint(int(start), int(stop - duration))
    new_stop = new_start + duration

    # Format new time range
    new_time_range = (datetime.fromtimestamp(new_start).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3],
                      datetime.fromtimestamp(new_stop).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3])

    return new_time_range
Ejemplo n.º 12
0
def toSeconds(someTime: Timedelta) -> float:
    return someTime.total_seconds()
Ejemplo n.º 13
0
    def __init__(self, value : float = 0, time_interval : pd.Timedelta = pd.Timedelta(1, 's')):

        self._value = value / time_interval.total_seconds()