We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
cupy.array(cupy_array, oder=None) raises error
When I do this:
```python
>>> x = cupy.ones(3)
>>> xx = cupy.array(x, order=None)
```
I get this traceback:
```

  File "[...]/cupy/cupy/creation/from_data.py", line 41, in array
    return core.array(obj, dtype, copy, order, subok, ndmin)

  File "cupy/core/core.pyx", line 2026, in cupy.core.core.array
    cpdef ndarray array(obj, dtype=None, bint copy=True, str order='K',

  File "cupy/core/core.pyx", line 2039, in cupy.core.core.array
    a = src.astype(dtype, order=order, copy=copy)

  File "cupy/core/core.pyx", line 276, in cupy.core.core.ndarray.astype
    cpdef ndarray astype(

  File "cupy/core/core.pyx", line 313, in cupy.core.core.ndarray.astype
    raise TypeError('order not understood')

TypeError: order not understood
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `cupy/indexing/generate.py`
Content:
```
1 # flake8: NOQA
2 # "flake8: NOQA" to suppress warning "H104  File contains nothing but comments"
3 
4 # class s_(object):
5 
6 import numpy
7 import six
8 
9 import cupy
10 from cupy import core
11 from cupy.creation import from_data
12 from cupy.manipulation import join
13 
14 
15 class AxisConcatenator(object):
16     """Translates slice objects to concatenation along an axis.
17 
18     For detailed documentation on usage, see :func:`cupy.r_`.
19     This implementation is partially borrowed from NumPy's one.
20 
21     """
22 
23     def _output_obj(self, obj, ndim, ndmin, trans1d):
24         k2 = ndmin - ndim
25         if trans1d < 0:
26             trans1d += k2 + 1
27         defaxes = list(six.moves.range(ndmin))
28         k1 = trans1d
29         axes = defaxes[:k1] + defaxes[k2:] + \
30             defaxes[k1:k2]
31         return obj.transpose(axes)
32 
33     def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):
34         self.axis = axis
35         self.trans1d = trans1d
36         self.matrix = matrix
37         self.ndmin = ndmin
38 
39     def __getitem__(self, key):
40         trans1d = self.trans1d
41         ndmin = self.ndmin
42         objs = []
43         scalars = []
44         arraytypes = []
45         scalartypes = []
46         if isinstance(key, six.string_types):
47             raise NotImplementedError
48         if not isinstance(key, tuple):
49             key = (key,)
50 
51         for i, k in enumerate(key):
52             scalar = False
53             if isinstance(k, slice):
54                 raise NotImplementedError
55             elif isinstance(k, six.string_types):
56                 if i != 0:
57                     raise ValueError(
58                         'special directives must be the first entry.')
59                 raise NotImplementedError
60             elif type(k) in numpy.ScalarType:
61                 newobj = from_data.array(k, ndmin=ndmin)
62                 scalars.append(i)
63                 scalar = True
64                 scalartypes.append(newobj.dtype)
65             else:
66                 newobj = from_data.array(k, copy=False, ndmin=ndmin)
67                 if ndmin > 1:
68                     ndim = from_data.array(k, copy=False).ndim
69                     if trans1d != -1 and ndim < ndmin:
70                         newobj = self._output_obj(newobj, ndim, ndmin, trans1d)
71 
72             objs.append(newobj)
73             if not scalar and isinstance(newobj, core.ndarray):
74                 arraytypes.append(newobj.dtype)
75 
76         final_dtype = numpy.find_common_type(arraytypes, scalartypes)
77         if final_dtype is not None:
78             for k in scalars:
79                 objs[k] = objs[k].astype(final_dtype)
80 
81         return join.concatenate(tuple(objs), axis=self.axis)
82 
83     def __len__(self):
84         return 0
85 
86 
87 class CClass(AxisConcatenator):
88 
89     def __init__(self):
90         super(CClass, self).__init__(-1, ndmin=2, trans1d=0)
91 
92 
93 c_ = CClass()
94 """Translates slice objects to concatenation along the second axis.
95 
96 This is a CuPy object that corresponds to :func:`cupy.r_`, which is
97 useful because of its common occurrence. In particular, arrays will be
98 stacked along their last axis after being upgraded to at least 2-D with
99 1's post-pended to the shape (column vectors made out of 1-D arrays).
100 
101 For detailed documentation, see :func:`r_`.
102 
103 This implementation is partially borrowed from NumPy's one.
104 
105 Args:
106     Not a function, so takes no parameters
107 
108 Returns:
109     cupy.ndarray: Joined array.
110 
111 .. seealso:: :func:`numpy.c_`
112 
113 Examples
114 --------
115 >>> a = cupy.array([[1, 2, 3]], dtype=np.int32)
116 >>> b = cupy.array([[4, 5, 6]], dtype=np.int32)
117 >>> cupy.c_[a, 0, 0, b]
118 array([[1, 2, 3, 0, 0, 4, 5, 6]], dtype=int32)
119 
120 """
121 
122 
123 class RClass(AxisConcatenator):
124 
125     def __init__(self):
126         super(RClass, self).__init__()
127 
128 
129 r_ = RClass()
130 """Translates slice objects to concatenation along the first axis.
131 
132 This is a simple way to build up arrays quickly.
133 If the index expression contains comma separated arrays, then stack
134 them along their first axis.
135 
136 This object can build up from normal CuPy arrays.
137 Therefore, the other objects (e.g. writing strings like '2,3,4',
138 or using imaginary numbers like [1,2,3j],
139 or using string integers like '-1') are not implemented yet
140 compared with NumPy.
141 
142 This implementation is partially borrowed from NumPy's one.
143 
144 Args:
145     Not a function, so takes no parameters
146 
147 Returns:
148     cupy.ndarray: Joined array.
149 
150 .. seealso:: :func:`numpy.r_`
151 
152 Examples
153 --------
154 >>> a = cupy.array([1, 2, 3], dtype=np.int32)
155 >>> b = cupy.array([4, 5, 6], dtype=np.int32)
156 >>> cupy.r_[a, 0, 0, b]
157 array([1, 2, 3, 0, 0, 4, 5, 6], dtype=int32)
158 
159 """
160 
161 
162 def indices(dimensions, dtype=int):
163     """Returns an array representing the indices of a grid.
164 
165     Computes an array where the subarrays contain index values 0,1,...
166     varying only along the corresponding axis.
167 
168     Args:
169         dimensions: The shape of the grid.
170         dtype: Data type specifier. It is int by default.
171 
172     Returns:
173         ndarray:
174         The array of grid indices,
175         ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
176 
177     Examples
178     --------
179     >>> grid = cupy.indices((2, 3))
180     >>> grid.shape
181     (2, 2, 3)
182     >>> grid[0]        # row indices
183     array([[0, 0, 0],
184            [1, 1, 1]])
185     >>> grid[1]        # column indices
186     array([[0, 1, 2],
187            [0, 1, 2]])
188 
189     .. seealso:: :func:`numpy.indices`
190 
191     """
192     dimensions = tuple(dimensions)
193     N = len(dimensions)
194     shape = (1,) * N
195     res = cupy.empty((N,) + dimensions, dtype=dtype)
196     for i, dim in enumerate(dimensions):
197         res[i] = cupy.arange(dim, dtype=dtype).reshape(
198             shape[:i] + (dim,) + shape[i + 1:]
199         )
200     return res
201 
202 
203 def ix_(*args):
204     """Construct an open mesh from multiple sequences.
205 
206     This function takes N 1-D sequences and returns N outputs with N
207     dimensions each, such that the shape is 1 in all but one dimension
208     and the dimension with the non-unit shape value cycles through all
209     N dimensions.
210 
211     Using `ix_` one can quickly construct index arrays that will index
212     the cross product. ``a[cupy.ix_([1,3],[2,5])]`` returns the array
213     ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
214 
215     Args:
216         *args: 1-D sequences
217 
218     Returns:
219         tuple of ndarrays:
220         N arrays with N dimensions each, with N the number of input sequences.
221         Together these arrays form an open mesh.
222 
223     Examples
224     --------
225     >>> a = cupy.arange(10).reshape(2, 5)
226     >>> a
227     array([[0, 1, 2, 3, 4],
228            [5, 6, 7, 8, 9]])
229     >>> ixgrid = cupy.ix_([0,1], [2,4])
230     >>> ixgrid
231     (array([[0],
232            [1]]), array([[2, 4]]))
233 
234      .. seealso:: :func:`numpy.ix_`
235 
236     """
237     out = []
238     nd = len(args)
239     for k, new in enumerate(args):
240         new = from_data.asarray(new)
241         if new.ndim != 1:
242             raise ValueError('Cross index must be 1 dimensional')
243         if new.size == 0:
244             # Explicitly type empty arrays to avoid float default
245             new = new.astype(numpy.intp)
246         if cupy.issubdtype(new.dtype, cupy.bool_):
247             new, = new.nonzero()
248         new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))
249         out.append(new)
250     return tuple(out)
251 
252 # TODO(okuta): Implement ravel_multi_index
253 
254 
255 def unravel_index(indices, dims, order='C'):
256     """Converts a flat index or array of flat indices into a tuple of coordinate arrays.
257 
258     Args:
259         indices (cupy.ndarray): An integer array whose elements are indices
260             into the flattened version of an array of dimensions :obj:`dims`.
261         dims (tuple of ints): The shape of the array to use for unraveling indices.
262         order ('C' or 'F'): Determines whether the indices should be viewed as indexing
263             in row-major (C-style) or column-major (Fortran-style) order.
264 
265     Returns: tuple of ndarrays:
266         Each array in the tuple has the same shape as the indices array.
267 
268     Examples
269     --------
270     >>> cupy.unravel_index(cupy.array([22, 41, 37]), (7, 6))
271     (array([3, 6, 6]), array([4, 5, 1]))
272     >>> cupy.unravel_index(cupy.array([31, 41, 13]), (7, 6), order='F')
273     (array([3, 6, 6]), array([4, 5, 1]))
274 
275     .. seealso:: :func:`numpy.unravel_index`
276 
277     """
278     if order == 'C':
279         dims = reversed(dims)
280     elif order == 'F':
281         pass
282     else:
283         raise TypeError('order not understood')
284 
285     if not cupy.can_cast(indices, cupy.int64, 'same_kind'):
286         raise TypeError(
287             'Iterator operand 0 dtype could not be cast '
288             'from dtype(\'{}\') to dtype(\'{}\') '
289             'according to the rule \'same_kind\''.format(
290                 indices.dtype, cupy.int64().dtype))
291 
292     if (indices < 0).any():
293         raise ValueError('invalid entry in index array')
294 
295     unraveled_coords = []
296     for dim in dims:
297         unraveled_coords.append(indices % dim)
298         indices = indices // dim
299 
300     if (indices > 0).any():
301         raise ValueError('invalid entry in index array')
302 
303     if order == 'C':
304         unraveled_coords = reversed(unraveled_coords)
305     return tuple(unraveled_coords)
306 
307 
308 # TODO(okuta): Implement diag_indices
309 
310 
311 # TODO(okuta): Implement diag_indices_from
312 
313 
314 # TODO(okuta): Implement mask_indices
315 
316 
317 # TODO(okuta): Implement tril_indices
318 
319 
320 # TODO(okuta): Implement tril_indices_from
321 
322 
323 # TODO(okuta): Implement triu_indices
324 
325 
326 # TODO(okuta): Implement triu_indices_from
327
```
--- 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/cupy/indexing/generate.py b/cupy/indexing/generate.py
--- a/cupy/indexing/generate.py
+++ b/cupy/indexing/generate.py
@@ -275,7 +275,7 @@
     .. seealso:: :func:`numpy.unravel_index`
 
     """
-    if order == 'C':
+    if order in ('C', None):
         dims = reversed(dims)
     elif order == 'F':
         pass

{"golden_diff": "diff --git a/cupy/indexing/generate.py b/cupy/indexing/generate.py\n--- a/cupy/indexing/generate.py\n+++ b/cupy/indexing/generate.py\n@@ -275,7 +275,7 @@\n     .. seealso:: :func:`numpy.unravel_index`\n \n     \"\"\"\n-    if order == 'C':\n+    if order in ('C', None):\n         dims = reversed(dims)\n     elif order == 'F':\n         pass\n", "issue": "cupy.array(cupy_array, oder=None) raises error\nWhen I do this:\r\n```python\r\n>>> x = cupy.ones(3)\r\n>>> xx = cupy.array(x, order=None)\r\n```\r\nI get this traceback:\r\n```\r\n\r\n  File \"[...]/cupy/cupy/creation/from_data.py\", line 41, in array\r\n    return core.array(obj, dtype, copy, order, subok, ndmin)\r\n\r\n  File \"cupy/core/core.pyx\", line 2026, in cupy.core.core.array\r\n    cpdef ndarray array(obj, dtype=None, bint copy=True, str order='K',\r\n\r\n  File \"cupy/core/core.pyx\", line 2039, in cupy.core.core.array\r\n    a = src.astype(dtype, order=order, copy=copy)\r\n\r\n  File \"cupy/core/core.pyx\", line 276, in cupy.core.core.ndarray.astype\r\n    cpdef ndarray astype(\r\n\r\n  File \"cupy/core/core.pyx\", line 313, in cupy.core.core.ndarray.astype\r\n    raise TypeError('order not understood')\r\n\r\nTypeError: order not understood\r\n```\n", "before_files": [{"content": "# flake8: NOQA\n# \"flake8: NOQA\" to suppress warning \"H104  File contains nothing but comments\"\n\n# class s_(object):\n\nimport numpy\nimport six\n\nimport cupy\nfrom cupy import core\nfrom cupy.creation import from_data\nfrom cupy.manipulation import join\n\n\nclass AxisConcatenator(object):\n    \"\"\"Translates slice objects to concatenation along an axis.\n\n    For detailed documentation on usage, see :func:`cupy.r_`.\n    This implementation is partially borrowed from NumPy's one.\n\n    \"\"\"\n\n    def _output_obj(self, obj, ndim, ndmin, trans1d):\n        k2 = ndmin - ndim\n        if trans1d < 0:\n            trans1d += k2 + 1\n        defaxes = list(six.moves.range(ndmin))\n        k1 = trans1d\n        axes = defaxes[:k1] + defaxes[k2:] + \\\n            defaxes[k1:k2]\n        return obj.transpose(axes)\n\n    def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):\n        self.axis = axis\n        self.trans1d = trans1d\n        self.matrix = matrix\n        self.ndmin = ndmin\n\n    def __getitem__(self, key):\n        trans1d = self.trans1d\n        ndmin = self.ndmin\n        objs = []\n        scalars = []\n        arraytypes = []\n        scalartypes = []\n        if isinstance(key, six.string_types):\n            raise NotImplementedError\n        if not isinstance(key, tuple):\n            key = (key,)\n\n        for i, k in enumerate(key):\n            scalar = False\n            if isinstance(k, slice):\n                raise NotImplementedError\n            elif isinstance(k, six.string_types):\n                if i != 0:\n                    raise ValueError(\n                        'special directives must be the first entry.')\n                raise NotImplementedError\n            elif type(k) in numpy.ScalarType:\n                newobj = from_data.array(k, ndmin=ndmin)\n                scalars.append(i)\n                scalar = True\n                scalartypes.append(newobj.dtype)\n            else:\n                newobj = from_data.array(k, copy=False, ndmin=ndmin)\n                if ndmin > 1:\n                    ndim = from_data.array(k, copy=False).ndim\n                    if trans1d != -1 and ndim < ndmin:\n                        newobj = self._output_obj(newobj, ndim, ndmin, trans1d)\n\n            objs.append(newobj)\n            if not scalar and isinstance(newobj, core.ndarray):\n                arraytypes.append(newobj.dtype)\n\n        final_dtype = numpy.find_common_type(arraytypes, scalartypes)\n        if final_dtype is not None:\n            for k in scalars:\n                objs[k] = objs[k].astype(final_dtype)\n\n        return join.concatenate(tuple(objs), axis=self.axis)\n\n    def __len__(self):\n        return 0\n\n\nclass CClass(AxisConcatenator):\n\n    def __init__(self):\n        super(CClass, self).__init__(-1, ndmin=2, trans1d=0)\n\n\nc_ = CClass()\n\"\"\"Translates slice objects to concatenation along the second axis.\n\nThis is a CuPy object that corresponds to :func:`cupy.r_`, which is\nuseful because of its common occurrence. In particular, arrays will be\nstacked along their last axis after being upgraded to at least 2-D with\n1's post-pended to the shape (column vectors made out of 1-D arrays).\n\nFor detailed documentation, see :func:`r_`.\n\nThis implementation is partially borrowed from NumPy's one.\n\nArgs:\n    Not a function, so takes no parameters\n\nReturns:\n    cupy.ndarray: Joined array.\n\n.. seealso:: :func:`numpy.c_`\n\nExamples\n--------\n>>> a = cupy.array([[1, 2, 3]], dtype=np.int32)\n>>> b = cupy.array([[4, 5, 6]], dtype=np.int32)\n>>> cupy.c_[a, 0, 0, b]\narray([[1, 2, 3, 0, 0, 4, 5, 6]], dtype=int32)\n\n\"\"\"\n\n\nclass RClass(AxisConcatenator):\n\n    def __init__(self):\n        super(RClass, self).__init__()\n\n\nr_ = RClass()\n\"\"\"Translates slice objects to concatenation along the first axis.\n\nThis is a simple way to build up arrays quickly.\nIf the index expression contains comma separated arrays, then stack\nthem along their first axis.\n\nThis object can build up from normal CuPy arrays.\nTherefore, the other objects (e.g. writing strings like '2,3,4',\nor using imaginary numbers like [1,2,3j],\nor using string integers like '-1') are not implemented yet\ncompared with NumPy.\n\nThis implementation is partially borrowed from NumPy's one.\n\nArgs:\n    Not a function, so takes no parameters\n\nReturns:\n    cupy.ndarray: Joined array.\n\n.. seealso:: :func:`numpy.r_`\n\nExamples\n--------\n>>> a = cupy.array([1, 2, 3], dtype=np.int32)\n>>> b = cupy.array([4, 5, 6], dtype=np.int32)\n>>> cupy.r_[a, 0, 0, b]\narray([1, 2, 3, 0, 0, 4, 5, 6], dtype=int32)\n\n\"\"\"\n\n\ndef indices(dimensions, dtype=int):\n    \"\"\"Returns an array representing the indices of a grid.\n\n    Computes an array where the subarrays contain index values 0,1,...\n    varying only along the corresponding axis.\n\n    Args:\n        dimensions: The shape of the grid.\n        dtype: Data type specifier. It is int by default.\n\n    Returns:\n        ndarray:\n        The array of grid indices,\n        ``grid.shape = (len(dimensions),) + tuple(dimensions)``.\n\n    Examples\n    --------\n    >>> grid = cupy.indices((2, 3))\n    >>> grid.shape\n    (2, 2, 3)\n    >>> grid[0]        # row indices\n    array([[0, 0, 0],\n           [1, 1, 1]])\n    >>> grid[1]        # column indices\n    array([[0, 1, 2],\n           [0, 1, 2]])\n\n    .. seealso:: :func:`numpy.indices`\n\n    \"\"\"\n    dimensions = tuple(dimensions)\n    N = len(dimensions)\n    shape = (1,) * N\n    res = cupy.empty((N,) + dimensions, dtype=dtype)\n    for i, dim in enumerate(dimensions):\n        res[i] = cupy.arange(dim, dtype=dtype).reshape(\n            shape[:i] + (dim,) + shape[i + 1:]\n        )\n    return res\n\n\ndef ix_(*args):\n    \"\"\"Construct an open mesh from multiple sequences.\n\n    This function takes N 1-D sequences and returns N outputs with N\n    dimensions each, such that the shape is 1 in all but one dimension\n    and the dimension with the non-unit shape value cycles through all\n    N dimensions.\n\n    Using `ix_` one can quickly construct index arrays that will index\n    the cross product. ``a[cupy.ix_([1,3],[2,5])]`` returns the array\n    ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.\n\n    Args:\n        *args: 1-D sequences\n\n    Returns:\n        tuple of ndarrays:\n        N arrays with N dimensions each, with N the number of input sequences.\n        Together these arrays form an open mesh.\n\n    Examples\n    --------\n    >>> a = cupy.arange(10).reshape(2, 5)\n    >>> a\n    array([[0, 1, 2, 3, 4],\n           [5, 6, 7, 8, 9]])\n    >>> ixgrid = cupy.ix_([0,1], [2,4])\n    >>> ixgrid\n    (array([[0],\n           [1]]), array([[2, 4]]))\n\n     .. seealso:: :func:`numpy.ix_`\n\n    \"\"\"\n    out = []\n    nd = len(args)\n    for k, new in enumerate(args):\n        new = from_data.asarray(new)\n        if new.ndim != 1:\n            raise ValueError('Cross index must be 1 dimensional')\n        if new.size == 0:\n            # Explicitly type empty arrays to avoid float default\n            new = new.astype(numpy.intp)\n        if cupy.issubdtype(new.dtype, cupy.bool_):\n            new, = new.nonzero()\n        new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))\n        out.append(new)\n    return tuple(out)\n\n# TODO(okuta): Implement ravel_multi_index\n\n\ndef unravel_index(indices, dims, order='C'):\n    \"\"\"Converts a flat index or array of flat indices into a tuple of coordinate arrays.\n\n    Args:\n        indices (cupy.ndarray): An integer array whose elements are indices\n            into the flattened version of an array of dimensions :obj:`dims`.\n        dims (tuple of ints): The shape of the array to use for unraveling indices.\n        order ('C' or 'F'): Determines whether the indices should be viewed as indexing\n            in row-major (C-style) or column-major (Fortran-style) order.\n\n    Returns: tuple of ndarrays:\n        Each array in the tuple has the same shape as the indices array.\n\n    Examples\n    --------\n    >>> cupy.unravel_index(cupy.array([22, 41, 37]), (7, 6))\n    (array([3, 6, 6]), array([4, 5, 1]))\n    >>> cupy.unravel_index(cupy.array([31, 41, 13]), (7, 6), order='F')\n    (array([3, 6, 6]), array([4, 5, 1]))\n\n    .. seealso:: :func:`numpy.unravel_index`\n\n    \"\"\"\n    if order == 'C':\n        dims = reversed(dims)\n    elif order == 'F':\n        pass\n    else:\n        raise TypeError('order not understood')\n\n    if not cupy.can_cast(indices, cupy.int64, 'same_kind'):\n        raise TypeError(\n            'Iterator operand 0 dtype could not be cast '\n            'from dtype(\\'{}\\') to dtype(\\'{}\\') '\n            'according to the rule \\'same_kind\\''.format(\n                indices.dtype, cupy.int64().dtype))\n\n    if (indices < 0).any():\n        raise ValueError('invalid entry in index array')\n\n    unraveled_coords = []\n    for dim in dims:\n        unraveled_coords.append(indices % dim)\n        indices = indices // dim\n\n    if (indices > 0).any():\n        raise ValueError('invalid entry in index array')\n\n    if order == 'C':\n        unraveled_coords = reversed(unraveled_coords)\n    return tuple(unraveled_coords)\n\n\n# TODO(okuta): Implement diag_indices\n\n\n# TODO(okuta): Implement diag_indices_from\n\n\n# TODO(okuta): Implement mask_indices\n\n\n# TODO(okuta): Implement tril_indices\n\n\n# TODO(okuta): Implement tril_indices_from\n\n\n# TODO(okuta): Implement triu_indices\n\n\n# TODO(okuta): Implement triu_indices_from\n", "path": "cupy/indexing/generate.py"}], "after_files": [{"content": "# flake8: NOQA\n# \"flake8: NOQA\" to suppress warning \"H104  File contains nothing but comments\"\n\n# class s_(object):\n\nimport numpy\nimport six\n\nimport cupy\nfrom cupy import core\nfrom cupy.creation import from_data\nfrom cupy.manipulation import join\n\n\nclass AxisConcatenator(object):\n    \"\"\"Translates slice objects to concatenation along an axis.\n\n    For detailed documentation on usage, see :func:`cupy.r_`.\n    This implementation is partially borrowed from NumPy's one.\n\n    \"\"\"\n\n    def _output_obj(self, obj, ndim, ndmin, trans1d):\n        k2 = ndmin - ndim\n        if trans1d < 0:\n            trans1d += k2 + 1\n        defaxes = list(six.moves.range(ndmin))\n        k1 = trans1d\n        axes = defaxes[:k1] + defaxes[k2:] + \\\n            defaxes[k1:k2]\n        return obj.transpose(axes)\n\n    def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):\n        self.axis = axis\n        self.trans1d = trans1d\n        self.matrix = matrix\n        self.ndmin = ndmin\n\n    def __getitem__(self, key):\n        trans1d = self.trans1d\n        ndmin = self.ndmin\n        objs = []\n        scalars = []\n        arraytypes = []\n        scalartypes = []\n        if isinstance(key, six.string_types):\n            raise NotImplementedError\n        if not isinstance(key, tuple):\n            key = (key,)\n\n        for i, k in enumerate(key):\n            scalar = False\n            if isinstance(k, slice):\n                raise NotImplementedError\n            elif isinstance(k, six.string_types):\n                if i != 0:\n                    raise ValueError(\n                        'special directives must be the first entry.')\n                raise NotImplementedError\n            elif type(k) in numpy.ScalarType:\n                newobj = from_data.array(k, ndmin=ndmin)\n                scalars.append(i)\n                scalar = True\n                scalartypes.append(newobj.dtype)\n            else:\n                newobj = from_data.array(k, copy=False, ndmin=ndmin)\n                if ndmin > 1:\n                    ndim = from_data.array(k, copy=False).ndim\n                    if trans1d != -1 and ndim < ndmin:\n                        newobj = self._output_obj(newobj, ndim, ndmin, trans1d)\n\n            objs.append(newobj)\n            if not scalar and isinstance(newobj, core.ndarray):\n                arraytypes.append(newobj.dtype)\n\n        final_dtype = numpy.find_common_type(arraytypes, scalartypes)\n        if final_dtype is not None:\n            for k in scalars:\n                objs[k] = objs[k].astype(final_dtype)\n\n        return join.concatenate(tuple(objs), axis=self.axis)\n\n    def __len__(self):\n        return 0\n\n\nclass CClass(AxisConcatenator):\n\n    def __init__(self):\n        super(CClass, self).__init__(-1, ndmin=2, trans1d=0)\n\n\nc_ = CClass()\n\"\"\"Translates slice objects to concatenation along the second axis.\n\nThis is a CuPy object that corresponds to :func:`cupy.r_`, which is\nuseful because of its common occurrence. In particular, arrays will be\nstacked along their last axis after being upgraded to at least 2-D with\n1's post-pended to the shape (column vectors made out of 1-D arrays).\n\nFor detailed documentation, see :func:`r_`.\n\nThis implementation is partially borrowed from NumPy's one.\n\nArgs:\n    Not a function, so takes no parameters\n\nReturns:\n    cupy.ndarray: Joined array.\n\n.. seealso:: :func:`numpy.c_`\n\nExamples\n--------\n>>> a = cupy.array([[1, 2, 3]], dtype=np.int32)\n>>> b = cupy.array([[4, 5, 6]], dtype=np.int32)\n>>> cupy.c_[a, 0, 0, b]\narray([[1, 2, 3, 0, 0, 4, 5, 6]], dtype=int32)\n\n\"\"\"\n\n\nclass RClass(AxisConcatenator):\n\n    def __init__(self):\n        super(RClass, self).__init__()\n\n\nr_ = RClass()\n\"\"\"Translates slice objects to concatenation along the first axis.\n\nThis is a simple way to build up arrays quickly.\nIf the index expression contains comma separated arrays, then stack\nthem along their first axis.\n\nThis object can build up from normal CuPy arrays.\nTherefore, the other objects (e.g. writing strings like '2,3,4',\nor using imaginary numbers like [1,2,3j],\nor using string integers like '-1') are not implemented yet\ncompared with NumPy.\n\nThis implementation is partially borrowed from NumPy's one.\n\nArgs:\n    Not a function, so takes no parameters\n\nReturns:\n    cupy.ndarray: Joined array.\n\n.. seealso:: :func:`numpy.r_`\n\nExamples\n--------\n>>> a = cupy.array([1, 2, 3], dtype=np.int32)\n>>> b = cupy.array([4, 5, 6], dtype=np.int32)\n>>> cupy.r_[a, 0, 0, b]\narray([1, 2, 3, 0, 0, 4, 5, 6], dtype=int32)\n\n\"\"\"\n\n\ndef indices(dimensions, dtype=int):\n    \"\"\"Returns an array representing the indices of a grid.\n\n    Computes an array where the subarrays contain index values 0,1,...\n    varying only along the corresponding axis.\n\n    Args:\n        dimensions: The shape of the grid.\n        dtype: Data type specifier. It is int by default.\n\n    Returns:\n        ndarray:\n        The array of grid indices,\n        ``grid.shape = (len(dimensions),) + tuple(dimensions)``.\n\n    Examples\n    --------\n    >>> grid = cupy.indices((2, 3))\n    >>> grid.shape\n    (2, 2, 3)\n    >>> grid[0]        # row indices\n    array([[0, 0, 0],\n           [1, 1, 1]])\n    >>> grid[1]        # column indices\n    array([[0, 1, 2],\n           [0, 1, 2]])\n\n    .. seealso:: :func:`numpy.indices`\n\n    \"\"\"\n    dimensions = tuple(dimensions)\n    N = len(dimensions)\n    shape = (1,) * N\n    res = cupy.empty((N,) + dimensions, dtype=dtype)\n    for i, dim in enumerate(dimensions):\n        res[i] = cupy.arange(dim, dtype=dtype).reshape(\n            shape[:i] + (dim,) + shape[i + 1:]\n        )\n    return res\n\n\ndef ix_(*args):\n    \"\"\"Construct an open mesh from multiple sequences.\n\n    This function takes N 1-D sequences and returns N outputs with N\n    dimensions each, such that the shape is 1 in all but one dimension\n    and the dimension with the non-unit shape value cycles through all\n    N dimensions.\n\n    Using `ix_` one can quickly construct index arrays that will index\n    the cross product. ``a[cupy.ix_([1,3],[2,5])]`` returns the array\n    ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.\n\n    Args:\n        *args: 1-D sequences\n\n    Returns:\n        tuple of ndarrays:\n        N arrays with N dimensions each, with N the number of input sequences.\n        Together these arrays form an open mesh.\n\n    Examples\n    --------\n    >>> a = cupy.arange(10).reshape(2, 5)\n    >>> a\n    array([[0, 1, 2, 3, 4],\n           [5, 6, 7, 8, 9]])\n    >>> ixgrid = cupy.ix_([0,1], [2,4])\n    >>> ixgrid\n    (array([[0],\n           [1]]), array([[2, 4]]))\n\n     .. seealso:: :func:`numpy.ix_`\n\n    \"\"\"\n    out = []\n    nd = len(args)\n    for k, new in enumerate(args):\n        new = from_data.asarray(new)\n        if new.ndim != 1:\n            raise ValueError('Cross index must be 1 dimensional')\n        if new.size == 0:\n            # Explicitly type empty arrays to avoid float default\n            new = new.astype(numpy.intp)\n        if cupy.issubdtype(new.dtype, cupy.bool_):\n            new, = new.nonzero()\n        new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))\n        out.append(new)\n    return tuple(out)\n\n# TODO(okuta): Implement ravel_multi_index\n\n\ndef unravel_index(indices, dims, order='C'):\n    \"\"\"Converts a flat index or array of flat indices into a tuple of coordinate arrays.\n\n    Args:\n        indices (cupy.ndarray): An integer array whose elements are indices\n            into the flattened version of an array of dimensions :obj:`dims`.\n        dims (tuple of ints): The shape of the array to use for unraveling indices.\n        order ('C' or 'F'): Determines whether the indices should be viewed as indexing\n            in row-major (C-style) or column-major (Fortran-style) order.\n\n    Returns: tuple of ndarrays:\n        Each array in the tuple has the same shape as the indices array.\n\n    Examples\n    --------\n    >>> cupy.unravel_index(cupy.array([22, 41, 37]), (7, 6))\n    (array([3, 6, 6]), array([4, 5, 1]))\n    >>> cupy.unravel_index(cupy.array([31, 41, 13]), (7, 6), order='F')\n    (array([3, 6, 6]), array([4, 5, 1]))\n\n    .. seealso:: :func:`numpy.unravel_index`\n\n    \"\"\"\n    if order in ('C', None):\n        dims = reversed(dims)\n    elif order == 'F':\n        pass\n    else:\n        raise TypeError('order not understood')\n\n    if not cupy.can_cast(indices, cupy.int64, 'same_kind'):\n        raise TypeError(\n            'Iterator operand 0 dtype could not be cast '\n            'from dtype(\\'{}\\') to dtype(\\'{}\\') '\n            'according to the rule \\'same_kind\\''.format(\n                indices.dtype, cupy.int64().dtype))\n\n    if (indices < 0).any():\n        raise ValueError('invalid entry in index array')\n\n    unraveled_coords = []\n    for dim in dims:\n        unraveled_coords.append(indices % dim)\n        indices = indices // dim\n\n    if (indices > 0).any():\n        raise ValueError('invalid entry in index array')\n\n    if order == 'C':\n        unraveled_coords = reversed(unraveled_coords)\n    return tuple(unraveled_coords)\n\n\n# TODO(okuta): Implement diag_indices\n\n\n# TODO(okuta): Implement diag_indices_from\n\n\n# TODO(okuta): Implement mask_indices\n\n\n# TODO(okuta): Implement tril_indices\n\n\n# TODO(okuta): Implement tril_indices_from\n\n\n# TODO(okuta): Implement triu_indices\n\n\n# TODO(okuta): Implement triu_indices_from\n", "path": "cupy/indexing/generate.py"}]}