We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Theta model does not preserve item IDs
## Description

When using the `RForecastPredictor` with `method_name = "thetaf"`, the item IDs returned by the predictor's forecasts do not align with the actual item IDs. Instead, it returns `None` for the item IDs.

## To Reproduce

```python
from gluonts.dataset.repository.datasets import get_dataset
from gluonts.model.r_forecast import RForecastPredictor
from gluonts.evaluation.backtest import make_evaluation_predictions

dataset = get_dataset("m3_yearly")
predictor = RForecastPredictor(
    freq=dataset.metadata.freq,
    prediction_length=dataset.metadata.prediction_length,
    method_name="thetaf",
)
forecast_pred, forecast_true = make_evaluation_predictions(dataset.test, predictor)

forecast_pred, _ = make_evaluation_predictions(dataset.test, predictor)

for pred in forecast_pred:
    print(pred.item_id)
```

You'll see that only `None` is printed.

## Environment

- Operating system: Debian Buster
- Python version: `3.8.9`
- GluonTS version: Master, Post 0.7.0 (commit 645d551a2190b9b749528917cdf1c5e897c861d2)
- MXNet version: `1.8.0.post0`

Full list of dependencies:

```
PyYAML = "^5.4.1"
click = "^7.1.2"
fastparquet = "^0.6.1"
fbprophet = "^0.7.1"
gluonts = {git = "https://github.com/awslabs/gluon-ts.git", rev = "f6948bacb7a038df3374e768ad4939455c74b49d"}
holidays = "^0.11.1"
mxnet = "^1.8.0"
numpy = "^1.20.3"
pandas = "^1.2.4"
pyarrow = "^4.0.0"
pydantic = "^1.8.2"
pystan = "^2.0.0"
python = ">=3.8,<3.10"
rpy2 = ">=2.9.*,<3.*"
sagemaker = "^2.40.0"
sagemaker-training = "^3.9.2"
scikit-learn = "^0.24.2"
scipy = "^1.6.3"
toolz = "^0.11.1"
tqdm = "^4.60.0"
ujson = "^4.0.2"
xgboost = "^1.4.1"
```



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/gluonts/model/r_forecast/_predictor.py`
Content:
```
1 # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License").
4 # You may not use this file except in compliance with the License.
5 # A copy of the License is located at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # or in the "license" file accompanying this file. This file is distributed
10 # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 # express or implied. See the License for the specific language governing
12 # permissions and limitations under the License.
13 
14 import os
15 from pathlib import Path
16 from typing import Dict, Iterator, Optional
17 
18 import numpy as np
19 
20 from gluonts.core.component import validated
21 from gluonts.dataset.common import Dataset
22 from gluonts.model.forecast import SampleForecast
23 from gluonts.model.predictor import RepresentablePredictor
24 from gluonts.support.pandas import forecast_start
25 from gluonts.time_feature import get_seasonality
26 
27 USAGE_MESSAGE = """
28 The RForecastPredictor is a thin wrapper for calling the R forecast package.
29 In order to use it you need to install R and run
30 
31 pip install 'rpy2>=2.9.*,<3.*'
32 
33 R -e 'install.packages(c("forecast", "nnfor"), repos="https://cloud.r-project.org")'
34 """
35 
36 
37 class RForecastPredictor(RepresentablePredictor):
38     """
39     Wrapper for calling the `R forecast package
40     <http://pkg.robjhyndman.com/forecast/>`_.
41 
42     The `RForecastPredictor` is a thin wrapper for calling the R forecast
43     package.  In order to use it you need to install R and run::
44 
45         pip install 'rpy2>=2.9.*,<3.*'
46         R -e 'install.packages(c("forecast", "nnfor"), repos="https://cloud.r-project.org")'
47 
48     Parameters
49     ----------
50     freq
51         The granularity of the time series (e.g. '1H')
52     prediction_length
53         Number of time points to be predicted.
54     method
55         The method from rforecast to be used one of
56         "ets", "arima", "tbats", "croston", "mlp", "thetaf".
57     period
58         The period to be used (this is called `frequency` in the R forecast
59         package), result to a tentative reasonable default if not specified
60         (for instance 24 for hourly freq '1H')
61     trunc_length
62         Maximum history length to feed to the model (some models become slow
63         with very long series).
64     params
65         Parameters to be used when calling the forecast method default.
66         Note that currently only `output_type = 'samples'` is supported.
67     """
68 
69     @validated()
70     def __init__(
71         self,
72         freq: str,
73         prediction_length: int,
74         method_name: str = "ets",
75         period: int = None,
76         trunc_length: Optional[int] = None,
77         params: Optional[Dict] = None,
78     ) -> None:
79         super().__init__(freq=freq, prediction_length=prediction_length)
80 
81         try:
82             import rpy2.robjects.packages as rpackages
83             from rpy2 import rinterface, robjects
84             from rpy2.rinterface import RRuntimeError
85         except ImportError as e:
86             raise ImportError(str(e) + USAGE_MESSAGE) from e
87 
88         self._robjects = robjects
89         self._rinterface = rinterface
90         self._rinterface.initr()
91         self._rpackages = rpackages
92 
93         this_dir = os.path.dirname(os.path.realpath(__file__))
94         this_dir = this_dir.replace("\\", "/")  # for windows
95         r_files = [
96             n[:-2] for n in os.listdir(f"{this_dir}/R/") if n[-2:] == ".R"
97         ]
98 
99         for n in r_files:
100             try:
101                 path = Path(this_dir, "R", f"{n}.R")
102                 robjects.r(f'source("{path}")'.replace("\\", "\\\\"))
103             except RRuntimeError as er:
104                 raise RRuntimeError(str(er) + USAGE_MESSAGE) from er
105 
106         supported_methods = [
107             "ets",
108             "arima",
109             "tbats",
110             "croston",
111             "mlp",
112             "thetaf",
113         ]
114         assert (
115             method_name in supported_methods
116         ), f"method {method_name} is not supported please use one of {supported_methods}"
117 
118         self.method_name = method_name
119 
120         self._stats_pkg = rpackages.importr("stats")
121         self._r_method = robjects.r[method_name]
122 
123         self.prediction_length = prediction_length
124         self.freq = freq
125         self.period = period if period is not None else get_seasonality(freq)
126         self.trunc_length = trunc_length
127 
128         self.params = {
129             "prediction_length": self.prediction_length,
130             "output_types": ["samples"],
131             "frequency": self.period,
132         }
133         if params is not None:
134             self.params.update(params)
135 
136     def _unlist(self, l):
137         if type(l).__name__.endswith("Vector"):
138             return [self._unlist(x) for x in l]
139         else:
140             return l
141 
142     def _run_r_forecast(self, d, params, save_info):
143         buf = []
144 
145         def save_to_buf(x):
146             buf.append(x)
147 
148         def dont_save(x):
149             pass
150 
151         f = save_to_buf if save_info else dont_save
152 
153         # save output from the R console in buf
154         self._rinterface.set_writeconsole_regular(f)
155         self._rinterface.set_writeconsole_warnerror(f)
156 
157         make_ts = self._stats_pkg.ts
158         r_params = self._robjects.vectors.ListVector(params)
159         vec = self._robjects.FloatVector(d["target"])
160         ts = make_ts(vec, frequency=self.period)
161         forecast = self._r_method(ts, r_params)
162         forecast_dict = dict(
163             zip(forecast.names, map(self._unlist, list(forecast)))
164         )
165         # FOR NOW ONLY SAMPLES...
166         # if "quantiles" in forecast_dict:
167         #     forecast_dict["quantiles"] = dict(zip(params["quantiles"], forecast_dict["quantiles"]))
168 
169         self._rinterface.set_writeconsole_regular(
170             self._rinterface.consolePrint
171         )
172         self._rinterface.set_writeconsole_warnerror(
173             self._rinterface.consolePrint
174         )
175         return forecast_dict, buf
176 
177     def predict(
178         self,
179         dataset: Dataset,
180         num_samples: int = 100,
181         save_info: bool = False,
182         **kwargs,
183     ) -> Iterator[SampleForecast]:
184         for entry in dataset:
185             if isinstance(entry, dict):
186                 data = entry
187             else:
188                 data = entry.data
189                 if self.trunc_length:
190                     data = data[-self.trunc_length :]
191 
192             params = self.params.copy()
193             params["num_samples"] = num_samples
194 
195             forecast_dict, console_output = self._run_r_forecast(
196                 data, params, save_info=save_info
197             )
198 
199             samples = np.array(forecast_dict["samples"])
200             expected_shape = (params["num_samples"], self.prediction_length)
201             assert (
202                 samples.shape == expected_shape
203             ), f"Expected shape {expected_shape} but found {samples.shape}"
204             info = (
205                 {"console_output": "\n".join(console_output)}
206                 if save_info
207                 else None
208             )
209             yield SampleForecast(
210                 samples, forecast_start(data), self.freq, info=info
211             )
212
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/gluonts/model/r_forecast/_predictor.py b/src/gluonts/model/r_forecast/_predictor.py
--- a/src/gluonts/model/r_forecast/_predictor.py
+++ b/src/gluonts/model/r_forecast/_predictor.py
@@ -207,5 +207,9 @@
                 else None
             )
             yield SampleForecast(
-                samples, forecast_start(data), self.freq, info=info
+                samples,
+                forecast_start(data),
+                self.freq,
+                info=info,
+                item_id=entry.get("item_id", None),
             )

{"golden_diff": "diff --git a/src/gluonts/model/r_forecast/_predictor.py b/src/gluonts/model/r_forecast/_predictor.py\n--- a/src/gluonts/model/r_forecast/_predictor.py\n+++ b/src/gluonts/model/r_forecast/_predictor.py\n@@ -207,5 +207,9 @@\n                 else None\n             )\n             yield SampleForecast(\n-                samples, forecast_start(data), self.freq, info=info\n+                samples,\n+                forecast_start(data),\n+                self.freq,\n+                info=info,\n+                item_id=entry.get(\"item_id\", None),\n             )\n", "issue": "Theta model does not preserve item IDs\n## Description\r\n\r\nWhen using the `RForecastPredictor` with `method_name = \"thetaf\"`, the item IDs returned by the predictor's forecasts do not align with the actual item IDs. Instead, it returns `None` for the item IDs.\r\n\r\n## To Reproduce\r\n\r\n```python\r\nfrom gluonts.dataset.repository.datasets import get_dataset\r\nfrom gluonts.model.r_forecast import RForecastPredictor\r\nfrom gluonts.evaluation.backtest import make_evaluation_predictions\r\n\r\ndataset = get_dataset(\"m3_yearly\")\r\npredictor = RForecastPredictor(\r\n    freq=dataset.metadata.freq,\r\n    prediction_length=dataset.metadata.prediction_length,\r\n    method_name=\"thetaf\",\r\n)\r\nforecast_pred, forecast_true = make_evaluation_predictions(dataset.test, predictor)\r\n\r\nforecast_pred, _ = make_evaluation_predictions(dataset.test, predictor)\r\n\r\nfor pred in forecast_pred:\r\n    print(pred.item_id)\r\n```\r\n\r\nYou'll see that only `None` is printed.\r\n\r\n## Environment\r\n\r\n- Operating system: Debian Buster\r\n- Python version: `3.8.9`\r\n- GluonTS version: Master, Post 0.7.0 (commit 645d551a2190b9b749528917cdf1c5e897c861d2)\r\n- MXNet version: `1.8.0.post0`\r\n\r\nFull list of dependencies:\r\n\r\n```\r\nPyYAML = \"^5.4.1\"\r\nclick = \"^7.1.2\"\r\nfastparquet = \"^0.6.1\"\r\nfbprophet = \"^0.7.1\"\r\ngluonts = {git = \"https://github.com/awslabs/gluon-ts.git\", rev = \"f6948bacb7a038df3374e768ad4939455c74b49d\"}\r\nholidays = \"^0.11.1\"\r\nmxnet = \"^1.8.0\"\r\nnumpy = \"^1.20.3\"\r\npandas = \"^1.2.4\"\r\npyarrow = \"^4.0.0\"\r\npydantic = \"^1.8.2\"\r\npystan = \"^2.0.0\"\r\npython = \">=3.8,<3.10\"\r\nrpy2 = \">=2.9.*,<3.*\"\r\nsagemaker = \"^2.40.0\"\r\nsagemaker-training = \"^3.9.2\"\r\nscikit-learn = \"^0.24.2\"\r\nscipy = \"^1.6.3\"\r\ntoolz = \"^0.11.1\"\r\ntqdm = \"^4.60.0\"\r\nujson = \"^4.0.2\"\r\nxgboost = \"^1.4.1\"\r\n```\r\n\r\n\n", "before_files": [{"content": "# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport os\nfrom pathlib import Path\nfrom typing import Dict, Iterator, Optional\n\nimport numpy as np\n\nfrom gluonts.core.component import validated\nfrom gluonts.dataset.common import Dataset\nfrom gluonts.model.forecast import SampleForecast\nfrom gluonts.model.predictor import RepresentablePredictor\nfrom gluonts.support.pandas import forecast_start\nfrom gluonts.time_feature import get_seasonality\n\nUSAGE_MESSAGE = \"\"\"\nThe RForecastPredictor is a thin wrapper for calling the R forecast package.\nIn order to use it you need to install R and run\n\npip install 'rpy2>=2.9.*,<3.*'\n\nR -e 'install.packages(c(\"forecast\", \"nnfor\"), repos=\"https://cloud.r-project.org\")'\n\"\"\"\n\n\nclass RForecastPredictor(RepresentablePredictor):\n    \"\"\"\n    Wrapper for calling the `R forecast package\n    <http://pkg.robjhyndman.com/forecast/>`_.\n\n    The `RForecastPredictor` is a thin wrapper for calling the R forecast\n    package.  In order to use it you need to install R and run::\n\n        pip install 'rpy2>=2.9.*,<3.*'\n        R -e 'install.packages(c(\"forecast\", \"nnfor\"), repos=\"https://cloud.r-project.org\")'\n\n    Parameters\n    ----------\n    freq\n        The granularity of the time series (e.g. '1H')\n    prediction_length\n        Number of time points to be predicted.\n    method\n        The method from rforecast to be used one of\n        \"ets\", \"arima\", \"tbats\", \"croston\", \"mlp\", \"thetaf\".\n    period\n        The period to be used (this is called `frequency` in the R forecast\n        package), result to a tentative reasonable default if not specified\n        (for instance 24 for hourly freq '1H')\n    trunc_length\n        Maximum history length to feed to the model (some models become slow\n        with very long series).\n    params\n        Parameters to be used when calling the forecast method default.\n        Note that currently only `output_type = 'samples'` is supported.\n    \"\"\"\n\n    @validated()\n    def __init__(\n        self,\n        freq: str,\n        prediction_length: int,\n        method_name: str = \"ets\",\n        period: int = None,\n        trunc_length: Optional[int] = None,\n        params: Optional[Dict] = None,\n    ) -> None:\n        super().__init__(freq=freq, prediction_length=prediction_length)\n\n        try:\n            import rpy2.robjects.packages as rpackages\n            from rpy2 import rinterface, robjects\n            from rpy2.rinterface import RRuntimeError\n        except ImportError as e:\n            raise ImportError(str(e) + USAGE_MESSAGE) from e\n\n        self._robjects = robjects\n        self._rinterface = rinterface\n        self._rinterface.initr()\n        self._rpackages = rpackages\n\n        this_dir = os.path.dirname(os.path.realpath(__file__))\n        this_dir = this_dir.replace(\"\\\\\", \"/\")  # for windows\n        r_files = [\n            n[:-2] for n in os.listdir(f\"{this_dir}/R/\") if n[-2:] == \".R\"\n        ]\n\n        for n in r_files:\n            try:\n                path = Path(this_dir, \"R\", f\"{n}.R\")\n                robjects.r(f'source(\"{path}\")'.replace(\"\\\\\", \"\\\\\\\\\"))\n            except RRuntimeError as er:\n                raise RRuntimeError(str(er) + USAGE_MESSAGE) from er\n\n        supported_methods = [\n            \"ets\",\n            \"arima\",\n            \"tbats\",\n            \"croston\",\n            \"mlp\",\n            \"thetaf\",\n        ]\n        assert (\n            method_name in supported_methods\n        ), f\"method {method_name} is not supported please use one of {supported_methods}\"\n\n        self.method_name = method_name\n\n        self._stats_pkg = rpackages.importr(\"stats\")\n        self._r_method = robjects.r[method_name]\n\n        self.prediction_length = prediction_length\n        self.freq = freq\n        self.period = period if period is not None else get_seasonality(freq)\n        self.trunc_length = trunc_length\n\n        self.params = {\n            \"prediction_length\": self.prediction_length,\n            \"output_types\": [\"samples\"],\n            \"frequency\": self.period,\n        }\n        if params is not None:\n            self.params.update(params)\n\n    def _unlist(self, l):\n        if type(l).__name__.endswith(\"Vector\"):\n            return [self._unlist(x) for x in l]\n        else:\n            return l\n\n    def _run_r_forecast(self, d, params, save_info):\n        buf = []\n\n        def save_to_buf(x):\n            buf.append(x)\n\n        def dont_save(x):\n            pass\n\n        f = save_to_buf if save_info else dont_save\n\n        # save output from the R console in buf\n        self._rinterface.set_writeconsole_regular(f)\n        self._rinterface.set_writeconsole_warnerror(f)\n\n        make_ts = self._stats_pkg.ts\n        r_params = self._robjects.vectors.ListVector(params)\n        vec = self._robjects.FloatVector(d[\"target\"])\n        ts = make_ts(vec, frequency=self.period)\n        forecast = self._r_method(ts, r_params)\n        forecast_dict = dict(\n            zip(forecast.names, map(self._unlist, list(forecast)))\n        )\n        # FOR NOW ONLY SAMPLES...\n        # if \"quantiles\" in forecast_dict:\n        #     forecast_dict[\"quantiles\"] = dict(zip(params[\"quantiles\"], forecast_dict[\"quantiles\"]))\n\n        self._rinterface.set_writeconsole_regular(\n            self._rinterface.consolePrint\n        )\n        self._rinterface.set_writeconsole_warnerror(\n            self._rinterface.consolePrint\n        )\n        return forecast_dict, buf\n\n    def predict(\n        self,\n        dataset: Dataset,\n        num_samples: int = 100,\n        save_info: bool = False,\n        **kwargs,\n    ) -> Iterator[SampleForecast]:\n        for entry in dataset:\n            if isinstance(entry, dict):\n                data = entry\n            else:\n                data = entry.data\n                if self.trunc_length:\n                    data = data[-self.trunc_length :]\n\n            params = self.params.copy()\n            params[\"num_samples\"] = num_samples\n\n            forecast_dict, console_output = self._run_r_forecast(\n                data, params, save_info=save_info\n            )\n\n            samples = np.array(forecast_dict[\"samples\"])\n            expected_shape = (params[\"num_samples\"], self.prediction_length)\n            assert (\n                samples.shape == expected_shape\n            ), f\"Expected shape {expected_shape} but found {samples.shape}\"\n            info = (\n                {\"console_output\": \"\\n\".join(console_output)}\n                if save_info\n                else None\n            )\n            yield SampleForecast(\n                samples, forecast_start(data), self.freq, info=info\n            )\n", "path": "src/gluonts/model/r_forecast/_predictor.py"}], "after_files": [{"content": "# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport os\nfrom pathlib import Path\nfrom typing import Dict, Iterator, Optional\n\nimport numpy as np\n\nfrom gluonts.core.component import validated\nfrom gluonts.dataset.common import Dataset\nfrom gluonts.model.forecast import SampleForecast\nfrom gluonts.model.predictor import RepresentablePredictor\nfrom gluonts.support.pandas import forecast_start\nfrom gluonts.time_feature import get_seasonality\n\nUSAGE_MESSAGE = \"\"\"\nThe RForecastPredictor is a thin wrapper for calling the R forecast package.\nIn order to use it you need to install R and run\n\npip install 'rpy2>=2.9.*,<3.*'\n\nR -e 'install.packages(c(\"forecast\", \"nnfor\"), repos=\"https://cloud.r-project.org\")'\n\"\"\"\n\n\nclass RForecastPredictor(RepresentablePredictor):\n    \"\"\"\n    Wrapper for calling the `R forecast package\n    <http://pkg.robjhyndman.com/forecast/>`_.\n\n    The `RForecastPredictor` is a thin wrapper for calling the R forecast\n    package.  In order to use it you need to install R and run::\n\n        pip install 'rpy2>=2.9.*,<3.*'\n        R -e 'install.packages(c(\"forecast\", \"nnfor\"), repos=\"https://cloud.r-project.org\")'\n\n    Parameters\n    ----------\n    freq\n        The granularity of the time series (e.g. '1H')\n    prediction_length\n        Number of time points to be predicted.\n    method\n        The method from rforecast to be used one of\n        \"ets\", \"arima\", \"tbats\", \"croston\", \"mlp\", \"thetaf\".\n    period\n        The period to be used (this is called `frequency` in the R forecast\n        package), result to a tentative reasonable default if not specified\n        (for instance 24 for hourly freq '1H')\n    trunc_length\n        Maximum history length to feed to the model (some models become slow\n        with very long series).\n    params\n        Parameters to be used when calling the forecast method default.\n        Note that currently only `output_type = 'samples'` is supported.\n    \"\"\"\n\n    @validated()\n    def __init__(\n        self,\n        freq: str,\n        prediction_length: int,\n        method_name: str = \"ets\",\n        period: int = None,\n        trunc_length: Optional[int] = None,\n        params: Optional[Dict] = None,\n    ) -> None:\n        super().__init__(freq=freq, prediction_length=prediction_length)\n\n        try:\n            import rpy2.robjects.packages as rpackages\n            from rpy2 import rinterface, robjects\n            from rpy2.rinterface import RRuntimeError\n        except ImportError as e:\n            raise ImportError(str(e) + USAGE_MESSAGE) from e\n\n        self._robjects = robjects\n        self._rinterface = rinterface\n        self._rinterface.initr()\n        self._rpackages = rpackages\n\n        this_dir = os.path.dirname(os.path.realpath(__file__))\n        this_dir = this_dir.replace(\"\\\\\", \"/\")  # for windows\n        r_files = [\n            n[:-2] for n in os.listdir(f\"{this_dir}/R/\") if n[-2:] == \".R\"\n        ]\n\n        for n in r_files:\n            try:\n                path = Path(this_dir, \"R\", f\"{n}.R\")\n                robjects.r(f'source(\"{path}\")'.replace(\"\\\\\", \"\\\\\\\\\"))\n            except RRuntimeError as er:\n                raise RRuntimeError(str(er) + USAGE_MESSAGE) from er\n\n        supported_methods = [\n            \"ets\",\n            \"arima\",\n            \"tbats\",\n            \"croston\",\n            \"mlp\",\n            \"thetaf\",\n        ]\n        assert (\n            method_name in supported_methods\n        ), f\"method {method_name} is not supported please use one of {supported_methods}\"\n\n        self.method_name = method_name\n\n        self._stats_pkg = rpackages.importr(\"stats\")\n        self._r_method = robjects.r[method_name]\n\n        self.prediction_length = prediction_length\n        self.freq = freq\n        self.period = period if period is not None else get_seasonality(freq)\n        self.trunc_length = trunc_length\n\n        self.params = {\n            \"prediction_length\": self.prediction_length,\n            \"output_types\": [\"samples\"],\n            \"frequency\": self.period,\n        }\n        if params is not None:\n            self.params.update(params)\n\n    def _unlist(self, l):\n        if type(l).__name__.endswith(\"Vector\"):\n            return [self._unlist(x) for x in l]\n        else:\n            return l\n\n    def _run_r_forecast(self, d, params, save_info):\n        buf = []\n\n        def save_to_buf(x):\n            buf.append(x)\n\n        def dont_save(x):\n            pass\n\n        f = save_to_buf if save_info else dont_save\n\n        # save output from the R console in buf\n        self._rinterface.set_writeconsole_regular(f)\n        self._rinterface.set_writeconsole_warnerror(f)\n\n        make_ts = self._stats_pkg.ts\n        r_params = self._robjects.vectors.ListVector(params)\n        vec = self._robjects.FloatVector(d[\"target\"])\n        ts = make_ts(vec, frequency=self.period)\n        forecast = self._r_method(ts, r_params)\n        forecast_dict = dict(\n            zip(forecast.names, map(self._unlist, list(forecast)))\n        )\n        # FOR NOW ONLY SAMPLES...\n        # if \"quantiles\" in forecast_dict:\n        #     forecast_dict[\"quantiles\"] = dict(zip(params[\"quantiles\"], forecast_dict[\"quantiles\"]))\n\n        self._rinterface.set_writeconsole_regular(\n            self._rinterface.consolePrint\n        )\n        self._rinterface.set_writeconsole_warnerror(\n            self._rinterface.consolePrint\n        )\n        return forecast_dict, buf\n\n    def predict(\n        self,\n        dataset: Dataset,\n        num_samples: int = 100,\n        save_info: bool = False,\n        **kwargs,\n    ) -> Iterator[SampleForecast]:\n        for entry in dataset:\n            if isinstance(entry, dict):\n                data = entry\n            else:\n                data = entry.data\n                if self.trunc_length:\n                    data = data[-self.trunc_length :]\n\n            params = self.params.copy()\n            params[\"num_samples\"] = num_samples\n\n            forecast_dict, console_output = self._run_r_forecast(\n                data, params, save_info=save_info\n            )\n\n            samples = np.array(forecast_dict[\"samples\"])\n            expected_shape = (params[\"num_samples\"], self.prediction_length)\n            assert (\n                samples.shape == expected_shape\n            ), f\"Expected shape {expected_shape} but found {samples.shape}\"\n            info = (\n                {\"console_output\": \"\\n\".join(console_output)}\n                if save_info\n                else None\n            )\n            yield SampleForecast(\n                samples,\n                forecast_start(data),\n                self.freq,\n                info=info,\n                item_id=entry.get(\"item_id\", None),\n            )\n", "path": "src/gluonts/model/r_forecast/_predictor.py"}]}