We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
flattened point dtype does not match flattened space dtype
Originally found this by using the FlattenObservationWrapper and seeing that my flattened space yielded different precision points than the original space. This is a bug that actually originates from the `spaces.utils.flatten_space` function and is caused by some missing dtype arguments. 

Simplified examples of the bug:
```
from gym.spaces import utils
from gym.spaces import MultiDiscrete, MultiBinary

original_space = MultiDiscrete([2, 2, 100])
flattened_space = utils.flatten_space(original_space)

original_sample = original_space.sample()
flattened_sample = utils.flatten(original_space, original_sample)

assert flattened_space.dtype == flattened_sample.dtype
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `gym/spaces/utils.py`
Content:
```
1 from collections import OrderedDict
2 import numpy as np
3 
4 from gym.spaces import Box
5 from gym.spaces import Discrete
6 from gym.spaces import MultiDiscrete
7 from gym.spaces import MultiBinary
8 from gym.spaces import Tuple
9 from gym.spaces import Dict
10 
11 
12 def flatdim(space):
13     """Return the number of dimensions a flattened equivalent of this space
14     would have.
15 
16     Accepts a space and returns an integer. Raises ``NotImplementedError`` if
17     the space is not defined in ``gym.spaces``.
18     """
19     if isinstance(space, Box):
20         return int(np.prod(space.shape))
21     elif isinstance(space, Discrete):
22         return int(space.n)
23     elif isinstance(space, Tuple):
24         return int(sum([flatdim(s) for s in space.spaces]))
25     elif isinstance(space, Dict):
26         return int(sum([flatdim(s) for s in space.spaces.values()]))
27     elif isinstance(space, MultiBinary):
28         return int(space.n)
29     elif isinstance(space, MultiDiscrete):
30         return int(np.prod(space.shape))
31     else:
32         raise NotImplementedError
33 
34 
35 def flatten(space, x):
36     """Flatten a data point from a space.
37 
38     This is useful when e.g. points from spaces must be passed to a neural
39     network, which only understands flat arrays of floats.
40 
41     Accepts a space and a point from that space. Always returns a 1D array.
42     Raises ``NotImplementedError`` if the space is not defined in
43     ``gym.spaces``.
44     """
45     if isinstance(space, Box):
46         return np.asarray(x, dtype=np.float32).flatten()
47     elif isinstance(space, Discrete):
48         onehot = np.zeros(space.n, dtype=np.float32)
49         onehot[x] = 1.0
50         return onehot
51     elif isinstance(space, Tuple):
52         return np.concatenate(
53             [flatten(s, x_part) for x_part, s in zip(x, space.spaces)])
54     elif isinstance(space, Dict):
55         return np.concatenate(
56             [flatten(s, x[key]) for key, s in space.spaces.items()])
57     elif isinstance(space, MultiBinary):
58         return np.asarray(x).flatten()
59     elif isinstance(space, MultiDiscrete):
60         return np.asarray(x).flatten()
61     else:
62         raise NotImplementedError
63 
64 
65 def unflatten(space, x):
66     """Unflatten a data point from a space.
67 
68     This reverses the transformation applied by ``flatten()``. You must ensure
69     that the ``space`` argument is the same as for the ``flatten()`` call.
70 
71     Accepts a space and a flattened point. Returns a point with a structure
72     that matches the space. Raises ``NotImplementedError`` if the space is not
73     defined in ``gym.spaces``.
74     """
75     if isinstance(space, Box):
76         return np.asarray(x, dtype=np.float32).reshape(space.shape)
77     elif isinstance(space, Discrete):
78         return int(np.nonzero(x)[0][0])
79     elif isinstance(space, Tuple):
80         dims = [flatdim(s) for s in space.spaces]
81         list_flattened = np.split(x, np.cumsum(dims)[:-1])
82         list_unflattened = [
83             unflatten(s, flattened)
84             for flattened, s in zip(list_flattened, space.spaces)
85         ]
86         return tuple(list_unflattened)
87     elif isinstance(space, Dict):
88         dims = [flatdim(s) for s in space.spaces.values()]
89         list_flattened = np.split(x, np.cumsum(dims)[:-1])
90         list_unflattened = [
91             (key, unflatten(s, flattened))
92             for flattened, (key,
93                             s) in zip(list_flattened, space.spaces.items())
94         ]
95         return OrderedDict(list_unflattened)
96     elif isinstance(space, MultiBinary):
97         return np.asarray(x).reshape(space.shape)
98     elif isinstance(space, MultiDiscrete):
99         return np.asarray(x).reshape(space.shape)
100     else:
101         raise NotImplementedError
102 
103 
104 def flatten_space(space):
105     """Flatten a space into a single ``Box``.
106 
107     This is equivalent to ``flatten()``, but operates on the space itself. The
108     result always is a `Box` with flat boundaries. The box has exactly
109     ``flatdim(space)`` dimensions. Flattening a sample of the original space
110     has the same effect as taking a sample of the flattenend space.
111 
112     Raises ``NotImplementedError`` if the space is not defined in
113     ``gym.spaces``.
114 
115     Example::
116 
117         >>> box = Box(0.0, 1.0, shape=(3, 4, 5))
118         >>> box
119         Box(3, 4, 5)
120         >>> flatten_space(box)
121         Box(60,)
122         >>> flatten(box, box.sample()) in flatten_space(box)
123         True
124 
125     Example that flattens a discrete space::
126 
127         >>> discrete = Discrete(5)
128         >>> flatten_space(discrete)
129         Box(5,)
130         >>> flatten(box, box.sample()) in flatten_space(box)
131         True
132 
133     Example that recursively flattens a dict::
134 
135         >>> space = Dict({"position": Discrete(2),
136         ...               "velocity": Box(0, 1, shape=(2, 2))})
137         >>> flatten_space(space)
138         Box(6,)
139         >>> flatten(space, space.sample()) in flatten_space(space)
140         True
141     """
142     if isinstance(space, Box):
143         return Box(space.low.flatten(), space.high.flatten())
144     if isinstance(space, Discrete):
145         return Box(low=0, high=1, shape=(space.n, ))
146     if isinstance(space, Tuple):
147         space = [flatten_space(s) for s in space.spaces]
148         return Box(
149             low=np.concatenate([s.low for s in space]),
150             high=np.concatenate([s.high for s in space]),
151         )
152     if isinstance(space, Dict):
153         space = [flatten_space(s) for s in space.spaces.values()]
154         return Box(
155             low=np.concatenate([s.low for s in space]),
156             high=np.concatenate([s.high for s in space]),
157         )
158     if isinstance(space, MultiBinary):
159         return Box(low=0, high=1, shape=(space.n, ))
160     if isinstance(space, MultiDiscrete):
161         return Box(
162             low=np.zeros_like(space.nvec),
163             high=space.nvec,
164         )
165     raise NotImplementedError
166
```
--- 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/gym/spaces/utils.py b/gym/spaces/utils.py
--- a/gym/spaces/utils.py
+++ b/gym/spaces/utils.py
@@ -43,10 +43,10 @@
     ``gym.spaces``.
     """
     if isinstance(space, Box):
-        return np.asarray(x, dtype=np.float32).flatten()
+        return np.asarray(x, dtype=space.dtype).flatten()
     elif isinstance(space, Discrete):
-        onehot = np.zeros(space.n, dtype=np.float32)
-        onehot[x] = 1.0
+        onehot = np.zeros(space.n, dtype=space.dtype)
+        onehot[x] = 1
         return onehot
     elif isinstance(space, Tuple):
         return np.concatenate(
@@ -55,9 +55,9 @@
         return np.concatenate(
             [flatten(s, x[key]) for key, s in space.spaces.items()])
     elif isinstance(space, MultiBinary):
-        return np.asarray(x).flatten()
+        return np.asarray(x, dtype=space.dtype).flatten()
     elif isinstance(space, MultiDiscrete):
-        return np.asarray(x).flatten()
+        return np.asarray(x, dtype=space.dtype).flatten()
     else:
         raise NotImplementedError
 
@@ -73,7 +73,7 @@
     defined in ``gym.spaces``.
     """
     if isinstance(space, Box):
-        return np.asarray(x, dtype=np.float32).reshape(space.shape)
+        return np.asarray(x, dtype=space.dtype).reshape(space.shape)
     elif isinstance(space, Discrete):
         return int(np.nonzero(x)[0][0])
     elif isinstance(space, Tuple):
@@ -94,9 +94,9 @@
         ]
         return OrderedDict(list_unflattened)
     elif isinstance(space, MultiBinary):
-        return np.asarray(x).reshape(space.shape)
+        return np.asarray(x, dtype=space.dtype).reshape(space.shape)
     elif isinstance(space, MultiDiscrete):
-        return np.asarray(x).reshape(space.shape)
+        return np.asarray(x, dtype=space.dtype).reshape(space.shape)
     else:
         raise NotImplementedError
 
@@ -140,26 +140,33 @@
         True
     """
     if isinstance(space, Box):
-        return Box(space.low.flatten(), space.high.flatten())
+        return Box(space.low.flatten(), space.high.flatten(), dtype=space.dtype)
     if isinstance(space, Discrete):
-        return Box(low=0, high=1, shape=(space.n, ))
+        return Box(low=0, high=1, shape=(space.n, ), dtype=space.dtype)
     if isinstance(space, Tuple):
         space = [flatten_space(s) for s in space.spaces]
         return Box(
             low=np.concatenate([s.low for s in space]),
             high=np.concatenate([s.high for s in space]),
+            dtype=np.result_type(*[s.dtype for s in space])
         )
     if isinstance(space, Dict):
         space = [flatten_space(s) for s in space.spaces.values()]
         return Box(
             low=np.concatenate([s.low for s in space]),
             high=np.concatenate([s.high for s in space]),
+            dtype=np.result_type(*[s.dtype for s in space])
         )
     if isinstance(space, MultiBinary):
-        return Box(low=0, high=1, shape=(space.n, ))
+        return Box(low=0,
+                   high=1,
+                   shape=(space.n, ),
+                   dtype=space.dtype
+                   )
     if isinstance(space, MultiDiscrete):
         return Box(
             low=np.zeros_like(space.nvec),
             high=space.nvec,
+            dtype=space.dtype
         )
     raise NotImplementedError

{"golden_diff": "diff --git a/gym/spaces/utils.py b/gym/spaces/utils.py\n--- a/gym/spaces/utils.py\n+++ b/gym/spaces/utils.py\n@@ -43,10 +43,10 @@\n     ``gym.spaces``.\n     \"\"\"\n     if isinstance(space, Box):\n-        return np.asarray(x, dtype=np.float32).flatten()\n+        return np.asarray(x, dtype=space.dtype).flatten()\n     elif isinstance(space, Discrete):\n-        onehot = np.zeros(space.n, dtype=np.float32)\n-        onehot[x] = 1.0\n+        onehot = np.zeros(space.n, dtype=space.dtype)\n+        onehot[x] = 1\n         return onehot\n     elif isinstance(space, Tuple):\n         return np.concatenate(\n@@ -55,9 +55,9 @@\n         return np.concatenate(\n             [flatten(s, x[key]) for key, s in space.spaces.items()])\n     elif isinstance(space, MultiBinary):\n-        return np.asarray(x).flatten()\n+        return np.asarray(x, dtype=space.dtype).flatten()\n     elif isinstance(space, MultiDiscrete):\n-        return np.asarray(x).flatten()\n+        return np.asarray(x, dtype=space.dtype).flatten()\n     else:\n         raise NotImplementedError\n \n@@ -73,7 +73,7 @@\n     defined in ``gym.spaces``.\n     \"\"\"\n     if isinstance(space, Box):\n-        return np.asarray(x, dtype=np.float32).reshape(space.shape)\n+        return np.asarray(x, dtype=space.dtype).reshape(space.shape)\n     elif isinstance(space, Discrete):\n         return int(np.nonzero(x)[0][0])\n     elif isinstance(space, Tuple):\n@@ -94,9 +94,9 @@\n         ]\n         return OrderedDict(list_unflattened)\n     elif isinstance(space, MultiBinary):\n-        return np.asarray(x).reshape(space.shape)\n+        return np.asarray(x, dtype=space.dtype).reshape(space.shape)\n     elif isinstance(space, MultiDiscrete):\n-        return np.asarray(x).reshape(space.shape)\n+        return np.asarray(x, dtype=space.dtype).reshape(space.shape)\n     else:\n         raise NotImplementedError\n \n@@ -140,26 +140,33 @@\n         True\n     \"\"\"\n     if isinstance(space, Box):\n-        return Box(space.low.flatten(), space.high.flatten())\n+        return Box(space.low.flatten(), space.high.flatten(), dtype=space.dtype)\n     if isinstance(space, Discrete):\n-        return Box(low=0, high=1, shape=(space.n, ))\n+        return Box(low=0, high=1, shape=(space.n, ), dtype=space.dtype)\n     if isinstance(space, Tuple):\n         space = [flatten_space(s) for s in space.spaces]\n         return Box(\n             low=np.concatenate([s.low for s in space]),\n             high=np.concatenate([s.high for s in space]),\n+            dtype=np.result_type(*[s.dtype for s in space])\n         )\n     if isinstance(space, Dict):\n         space = [flatten_space(s) for s in space.spaces.values()]\n         return Box(\n             low=np.concatenate([s.low for s in space]),\n             high=np.concatenate([s.high for s in space]),\n+            dtype=np.result_type(*[s.dtype for s in space])\n         )\n     if isinstance(space, MultiBinary):\n-        return Box(low=0, high=1, shape=(space.n, ))\n+        return Box(low=0,\n+                   high=1,\n+                   shape=(space.n, ),\n+                   dtype=space.dtype\n+                   )\n     if isinstance(space, MultiDiscrete):\n         return Box(\n             low=np.zeros_like(space.nvec),\n             high=space.nvec,\n+            dtype=space.dtype\n         )\n     raise NotImplementedError\n", "issue": "flattened point dtype does not match flattened space dtype\nOriginally found this by using the FlattenObservationWrapper and seeing that my flattened space yielded different precision points than the original space. This is a bug that actually originates from the `spaces.utils.flatten_space` function and is caused by some missing dtype arguments. \r\n\r\nSimplified examples of the bug:\r\n```\r\nfrom gym.spaces import utils\r\nfrom gym.spaces import MultiDiscrete, MultiBinary\r\n\r\noriginal_space = MultiDiscrete([2, 2, 100])\r\nflattened_space = utils.flatten_space(original_space)\r\n\r\noriginal_sample = original_space.sample()\r\nflattened_sample = utils.flatten(original_space, original_sample)\r\n\r\nassert flattened_space.dtype == flattened_sample.dtype\r\n```\n", "before_files": [{"content": "from collections import OrderedDict\nimport numpy as np\n\nfrom gym.spaces import Box\nfrom gym.spaces import Discrete\nfrom gym.spaces import MultiDiscrete\nfrom gym.spaces import MultiBinary\nfrom gym.spaces import Tuple\nfrom gym.spaces import Dict\n\n\ndef flatdim(space):\n    \"\"\"Return the number of dimensions a flattened equivalent of this space\n    would have.\n\n    Accepts a space and returns an integer. Raises ``NotImplementedError`` if\n    the space is not defined in ``gym.spaces``.\n    \"\"\"\n    if isinstance(space, Box):\n        return int(np.prod(space.shape))\n    elif isinstance(space, Discrete):\n        return int(space.n)\n    elif isinstance(space, Tuple):\n        return int(sum([flatdim(s) for s in space.spaces]))\n    elif isinstance(space, Dict):\n        return int(sum([flatdim(s) for s in space.spaces.values()]))\n    elif isinstance(space, MultiBinary):\n        return int(space.n)\n    elif isinstance(space, MultiDiscrete):\n        return int(np.prod(space.shape))\n    else:\n        raise NotImplementedError\n\n\ndef flatten(space, x):\n    \"\"\"Flatten a data point from a space.\n\n    This is useful when e.g. points from spaces must be passed to a neural\n    network, which only understands flat arrays of floats.\n\n    Accepts a space and a point from that space. Always returns a 1D array.\n    Raises ``NotImplementedError`` if the space is not defined in\n    ``gym.spaces``.\n    \"\"\"\n    if isinstance(space, Box):\n        return np.asarray(x, dtype=np.float32).flatten()\n    elif isinstance(space, Discrete):\n        onehot = np.zeros(space.n, dtype=np.float32)\n        onehot[x] = 1.0\n        return onehot\n    elif isinstance(space, Tuple):\n        return np.concatenate(\n            [flatten(s, x_part) for x_part, s in zip(x, space.spaces)])\n    elif isinstance(space, Dict):\n        return np.concatenate(\n            [flatten(s, x[key]) for key, s in space.spaces.items()])\n    elif isinstance(space, MultiBinary):\n        return np.asarray(x).flatten()\n    elif isinstance(space, MultiDiscrete):\n        return np.asarray(x).flatten()\n    else:\n        raise NotImplementedError\n\n\ndef unflatten(space, x):\n    \"\"\"Unflatten a data point from a space.\n\n    This reverses the transformation applied by ``flatten()``. You must ensure\n    that the ``space`` argument is the same as for the ``flatten()`` call.\n\n    Accepts a space and a flattened point. Returns a point with a structure\n    that matches the space. Raises ``NotImplementedError`` if the space is not\n    defined in ``gym.spaces``.\n    \"\"\"\n    if isinstance(space, Box):\n        return np.asarray(x, dtype=np.float32).reshape(space.shape)\n    elif isinstance(space, Discrete):\n        return int(np.nonzero(x)[0][0])\n    elif isinstance(space, Tuple):\n        dims = [flatdim(s) for s in space.spaces]\n        list_flattened = np.split(x, np.cumsum(dims)[:-1])\n        list_unflattened = [\n            unflatten(s, flattened)\n            for flattened, s in zip(list_flattened, space.spaces)\n        ]\n        return tuple(list_unflattened)\n    elif isinstance(space, Dict):\n        dims = [flatdim(s) for s in space.spaces.values()]\n        list_flattened = np.split(x, np.cumsum(dims)[:-1])\n        list_unflattened = [\n            (key, unflatten(s, flattened))\n            for flattened, (key,\n                            s) in zip(list_flattened, space.spaces.items())\n        ]\n        return OrderedDict(list_unflattened)\n    elif isinstance(space, MultiBinary):\n        return np.asarray(x).reshape(space.shape)\n    elif isinstance(space, MultiDiscrete):\n        return np.asarray(x).reshape(space.shape)\n    else:\n        raise NotImplementedError\n\n\ndef flatten_space(space):\n    \"\"\"Flatten a space into a single ``Box``.\n\n    This is equivalent to ``flatten()``, but operates on the space itself. The\n    result always is a `Box` with flat boundaries. The box has exactly\n    ``flatdim(space)`` dimensions. Flattening a sample of the original space\n    has the same effect as taking a sample of the flattenend space.\n\n    Raises ``NotImplementedError`` if the space is not defined in\n    ``gym.spaces``.\n\n    Example::\n\n        >>> box = Box(0.0, 1.0, shape=(3, 4, 5))\n        >>> box\n        Box(3, 4, 5)\n        >>> flatten_space(box)\n        Box(60,)\n        >>> flatten(box, box.sample()) in flatten_space(box)\n        True\n\n    Example that flattens a discrete space::\n\n        >>> discrete = Discrete(5)\n        >>> flatten_space(discrete)\n        Box(5,)\n        >>> flatten(box, box.sample()) in flatten_space(box)\n        True\n\n    Example that recursively flattens a dict::\n\n        >>> space = Dict({\"position\": Discrete(2),\n        ...               \"velocity\": Box(0, 1, shape=(2, 2))})\n        >>> flatten_space(space)\n        Box(6,)\n        >>> flatten(space, space.sample()) in flatten_space(space)\n        True\n    \"\"\"\n    if isinstance(space, Box):\n        return Box(space.low.flatten(), space.high.flatten())\n    if isinstance(space, Discrete):\n        return Box(low=0, high=1, shape=(space.n, ))\n    if isinstance(space, Tuple):\n        space = [flatten_space(s) for s in space.spaces]\n        return Box(\n            low=np.concatenate([s.low for s in space]),\n            high=np.concatenate([s.high for s in space]),\n        )\n    if isinstance(space, Dict):\n        space = [flatten_space(s) for s in space.spaces.values()]\n        return Box(\n            low=np.concatenate([s.low for s in space]),\n            high=np.concatenate([s.high for s in space]),\n        )\n    if isinstance(space, MultiBinary):\n        return Box(low=0, high=1, shape=(space.n, ))\n    if isinstance(space, MultiDiscrete):\n        return Box(\n            low=np.zeros_like(space.nvec),\n            high=space.nvec,\n        )\n    raise NotImplementedError\n", "path": "gym/spaces/utils.py"}], "after_files": [{"content": "from collections import OrderedDict\nimport numpy as np\n\nfrom gym.spaces import Box\nfrom gym.spaces import Discrete\nfrom gym.spaces import MultiDiscrete\nfrom gym.spaces import MultiBinary\nfrom gym.spaces import Tuple\nfrom gym.spaces import Dict\n\n\ndef flatdim(space):\n    \"\"\"Return the number of dimensions a flattened equivalent of this space\n    would have.\n\n    Accepts a space and returns an integer. Raises ``NotImplementedError`` if\n    the space is not defined in ``gym.spaces``.\n    \"\"\"\n    if isinstance(space, Box):\n        return int(np.prod(space.shape))\n    elif isinstance(space, Discrete):\n        return int(space.n)\n    elif isinstance(space, Tuple):\n        return int(sum([flatdim(s) for s in space.spaces]))\n    elif isinstance(space, Dict):\n        return int(sum([flatdim(s) for s in space.spaces.values()]))\n    elif isinstance(space, MultiBinary):\n        return int(space.n)\n    elif isinstance(space, MultiDiscrete):\n        return int(np.prod(space.shape))\n    else:\n        raise NotImplementedError\n\n\ndef flatten(space, x):\n    \"\"\"Flatten a data point from a space.\n\n    This is useful when e.g. points from spaces must be passed to a neural\n    network, which only understands flat arrays of floats.\n\n    Accepts a space and a point from that space. Always returns a 1D array.\n    Raises ``NotImplementedError`` if the space is not defined in\n    ``gym.spaces``.\n    \"\"\"\n    if isinstance(space, Box):\n        return np.asarray(x, dtype=space.dtype).flatten()\n    elif isinstance(space, Discrete):\n        onehot = np.zeros(space.n, dtype=space.dtype)\n        onehot[x] = 1\n        return onehot\n    elif isinstance(space, Tuple):\n        return np.concatenate(\n            [flatten(s, x_part) for x_part, s in zip(x, space.spaces)])\n    elif isinstance(space, Dict):\n        return np.concatenate(\n            [flatten(s, x[key]) for key, s in space.spaces.items()])\n    elif isinstance(space, MultiBinary):\n        return np.asarray(x, dtype=space.dtype).flatten()\n    elif isinstance(space, MultiDiscrete):\n        return np.asarray(x, dtype=space.dtype).flatten()\n    else:\n        raise NotImplementedError\n\n\ndef unflatten(space, x):\n    \"\"\"Unflatten a data point from a space.\n\n    This reverses the transformation applied by ``flatten()``. You must ensure\n    that the ``space`` argument is the same as for the ``flatten()`` call.\n\n    Accepts a space and a flattened point. Returns a point with a structure\n    that matches the space. Raises ``NotImplementedError`` if the space is not\n    defined in ``gym.spaces``.\n    \"\"\"\n    if isinstance(space, Box):\n        return np.asarray(x, dtype=space.dtype).reshape(space.shape)\n    elif isinstance(space, Discrete):\n        return int(np.nonzero(x)[0][0])\n    elif isinstance(space, Tuple):\n        dims = [flatdim(s) for s in space.spaces]\n        list_flattened = np.split(x, np.cumsum(dims)[:-1])\n        list_unflattened = [\n            unflatten(s, flattened)\n            for flattened, s in zip(list_flattened, space.spaces)\n        ]\n        return tuple(list_unflattened)\n    elif isinstance(space, Dict):\n        dims = [flatdim(s) for s in space.spaces.values()]\n        list_flattened = np.split(x, np.cumsum(dims)[:-1])\n        list_unflattened = [\n            (key, unflatten(s, flattened))\n            for flattened, (key,\n                            s) in zip(list_flattened, space.spaces.items())\n        ]\n        return OrderedDict(list_unflattened)\n    elif isinstance(space, MultiBinary):\n        return np.asarray(x, dtype=space.dtype).reshape(space.shape)\n    elif isinstance(space, MultiDiscrete):\n        return np.asarray(x, dtype=space.dtype).reshape(space.shape)\n    else:\n        raise NotImplementedError\n\n\ndef flatten_space(space):\n    \"\"\"Flatten a space into a single ``Box``.\n\n    This is equivalent to ``flatten()``, but operates on the space itself. The\n    result always is a `Box` with flat boundaries. The box has exactly\n    ``flatdim(space)`` dimensions. Flattening a sample of the original space\n    has the same effect as taking a sample of the flattenend space.\n\n    Raises ``NotImplementedError`` if the space is not defined in\n    ``gym.spaces``.\n\n    Example::\n\n        >>> box = Box(0.0, 1.0, shape=(3, 4, 5))\n        >>> box\n        Box(3, 4, 5)\n        >>> flatten_space(box)\n        Box(60,)\n        >>> flatten(box, box.sample()) in flatten_space(box)\n        True\n\n    Example that flattens a discrete space::\n\n        >>> discrete = Discrete(5)\n        >>> flatten_space(discrete)\n        Box(5,)\n        >>> flatten(box, box.sample()) in flatten_space(box)\n        True\n\n    Example that recursively flattens a dict::\n\n        >>> space = Dict({\"position\": Discrete(2),\n        ...               \"velocity\": Box(0, 1, shape=(2, 2))})\n        >>> flatten_space(space)\n        Box(6,)\n        >>> flatten(space, space.sample()) in flatten_space(space)\n        True\n    \"\"\"\n    if isinstance(space, Box):\n        return Box(space.low.flatten(), space.high.flatten(), dtype=space.dtype)\n    if isinstance(space, Discrete):\n        return Box(low=0, high=1, shape=(space.n, ), dtype=space.dtype)\n    if isinstance(space, Tuple):\n        space = [flatten_space(s) for s in space.spaces]\n        return Box(\n            low=np.concatenate([s.low for s in space]),\n            high=np.concatenate([s.high for s in space]),\n            dtype=np.result_type(*[s.dtype for s in space])\n        )\n    if isinstance(space, Dict):\n        space = [flatten_space(s) for s in space.spaces.values()]\n        return Box(\n            low=np.concatenate([s.low for s in space]),\n            high=np.concatenate([s.high for s in space]),\n            dtype=np.result_type(*[s.dtype for s in space])\n        )\n    if isinstance(space, MultiBinary):\n        return Box(low=0,\n                   high=1,\n                   shape=(space.n, ),\n                   dtype=space.dtype\n                   )\n    if isinstance(space, MultiDiscrete):\n        return Box(\n            low=np.zeros_like(space.nvec),\n            high=space.nvec,\n            dtype=space.dtype\n        )\n    raise NotImplementedError\n", "path": "gym/spaces/utils.py"}]}