diff --git a/pycast/common/timeseries.py b/pycast/common/timeseries.py index cbf3be6..4dca477 100644 --- a/pycast/common/timeseries.py +++ b/pycast/common/timeseries.py @@ -587,26 +587,30 @@ def apply(self, method): def sample(self, percentage): """Samples with replacement from the TimeSeries. Returns the sample and the remaining timeseries. - The original timeseries is not changed + The original timeseries is not changed. :param float percentage: How many percent of the original timeseries should be in the sample - :return: a tuple containing (sample, rest) as two timeseries objects + :return: A tuple containing (sample, rest) as two TimeSeries. + :rtype: Tuple(TimeSeries,TimeSeries) - :raise: Raises a ValueError if not 0 < percentage < 1 + :raise: Raises a ValueError if percentage is not in (0.0, 1.0). """ - if not (percentage > 0 and percentage < 1): - raise ValueError("Parameter percentage has to be in ]0,1[") + if not (0.0 < percentage < 1.0): + raise ValueError("Parameter percentage has to be in (0.0, 1.0).") - cls = self.__class__ + cls = self.__class__ value_count = int(len(self) * percentage) - values = random.sample(self, value_count) + values = random.sample(self, value_count) - sample = cls.from_twodim_list(values) + sample = cls.from_twodim_list(values) rest_values = self._timeseriesData[:] + for value in values: rest_values.remove(value) + rest = cls.from_twodim_list(rest_values) + return sample, rest class MultiDimensionalTimeSeries(TimeSeries): diff --git a/pycast/tests/timeseriesmiscellaneoustest.py b/pycast/tests/timeseriesmiscellaneoustest.py index 7532c8d..77850ad 100644 --- a/pycast/tests/timeseriesmiscellaneoustest.py +++ b/pycast/tests/timeseriesmiscellaneoustest.py @@ -391,8 +391,17 @@ def sampling_test(self): """Test if the two parts of a sampled timeSeries add up to the entire timeSeries""" data = [[0.0, 0.0], [1.0, 0.1], [2.0, 0.2], [3.0, 0.3], [4.0, 0.4]] - ts = TimeSeries.from_twodim_list(data) - sample, rest = ts.sample(.4) + ts = TimeSeries.from_twodim_list(data) + + for illegalValue in (-3.1, 0.0, 1.0, 1.3, 4.2): + try: + ts.sample(illegalValue) + except ValueError: + pass + else: + assert False, "ValueError not raised. Percentage was %s." % illegalValue # pragma: no cover + + sample, rest = ts.sample(0.4) + self.assertEquals(len(sample), 2) - self.assertEquals(sample + rest, ts) - + self.assertEquals(sample + rest, ts) \ No newline at end of file