We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
How to perform all tensor on np.array packages
Example：
```
import mars.tensor as mt
import numpy as np

def test_x():
    X1 = mt.tensor([0, 1])
    X2 = mt.tensor([2, 3])
    X = np.array([X1,X2])
    print(X.execute())
```
How to calculate X？
How to perform all tensor on np.array packages
Example：
```
import mars.tensor as mt
import numpy as np

def test_x():
    X1 = mt.tensor([0, 1])
    X2 = mt.tensor([2, 3])
    X = np.array([X1,X2])
    print(X.execute())
```
How to calculate X？

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mars/tensor/expressions/datasource/array.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Copyright 1999-2018 Alibaba Group Holding Ltd.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #      http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 import numpy as np
18 
19 from .... import opcodes as OperandDef
20 from ....lib.sparse.core import issparse, get_array_module, cp, cps, sps
21 from ....utils import on_serialize_shape, on_deserialize_shape
22 from ....serialize import ValueType, NDArrayField, TupleField
23 from ...core import TENSOR_TYPE, Tensor
24 from ..utils import get_chunk_slices
25 from .core import TensorNoInput
26 from .scalar import scalar
27 
28 
29 class ArrayDataSource(TensorNoInput):
30     """
31     Represents data from numpy or cupy array
32     """
33 
34     _op_type_ = OperandDef.TENSOR_DATA_SOURCE
35 
36     _data = NDArrayField('data')
37 
38     def __init__(self, data=None, dtype=None, gpu=None, **kw):
39         if dtype is not None:
40             dtype = np.dtype(dtype)
41         elif data is not None:
42             dtype = np.dtype(data.dtype)
43         super(ArrayDataSource, self).__init__(_data=data, _dtype=dtype, _gpu=gpu, **kw)
44 
45     @property
46     def data(self):
47         return self._data
48 
49     def to_chunk_op(self, *args):
50         _, idx, chunk_size = args
51         chunk_op = self.copy().reset_key()
52         chunk_op._data = self.data[get_chunk_slices(chunk_size, idx)]
53 
54         return chunk_op
55 
56 
57 class CSRMatrixDataSource(TensorNoInput):
58     """
59     Represents data from sparse array include scipy sparse or cupy sparse matrix.
60     """
61 
62     _op_type_ = OperandDef.SPARSE_MATRIX_DATA_SOURCE
63 
64     _indices = NDArrayField('indices')
65     _indptr = NDArrayField('indptr')
66     _data = NDArrayField('data')
67     _shape = TupleField('shape', ValueType.int64,
68                         on_serialize=on_serialize_shape, on_deserialize=on_deserialize_shape)
69 
70     def __init__(self, indices=None, indptr=None, data=None, shape=None,
71                  dtype=None, gpu=None, **kw):
72         super(CSRMatrixDataSource, self).__init__(_indices=indices, _indptr=indptr,
73                                                   _data=data, _shape=shape, _dtype=dtype,
74                                                   _gpu=gpu, _sparse=True, **kw)
75 
76     def to_chunk_op(self, *args):
77         _, idx, chunk_size = args
78 
79         xps = cps if self._gpu else sps
80         if len(self._shape) == 1:
81             shape = (1, self._shape[0])
82         else:
83             shape = self._shape
84         data = xps.csr_matrix(
85             (self._data, self._indices, self._indptr), shape)
86         chunk_data = data[get_chunk_slices(chunk_size, idx)]
87 
88         chunk_op = self.copy().reset_key()
89         chunk_op._data = chunk_data.data
90         chunk_op._indices = chunk_data.indices
91         chunk_op._indptr = chunk_data.indptr
92         chunk_shape = chunk_data.shape[1:] \
93             if len(self._shape) == 1 else chunk_data.shape
94         chunk_op._shape = chunk_shape
95 
96         return chunk_op
97 
98     @property
99     def indices(self):
100         return self._indices
101 
102     @property
103     def indptr(self):
104         return self._indptr
105 
106     @property
107     def data(self):
108         return self._data
109 
110     @property
111     def shape(self):
112         return self._shape
113 
114 
115 def _from_spmatrix(spmatrix, dtype=None, chunk_size=None, gpu=None):
116     if gpu is None and cp is not None and get_array_module(spmatrix) is cp:
117         gpu = True
118     if dtype and spmatrix.dtype != dtype:
119         spmatrix = spmatrix.astype(dtype)
120     spmatrix = spmatrix.tocsr()
121     op = CSRMatrixDataSource(indices=spmatrix.indices, indptr=spmatrix.indptr,
122                              data=spmatrix.data, shape=spmatrix.shape,
123                              dtype=spmatrix.dtype, gpu=gpu)
124     return op(spmatrix.shape, chunk_size=chunk_size)
125 
126 
127 def tensor(data, dtype=None, chunk_size=None, gpu=None, sparse=False):
128     if isinstance(data, TENSOR_TYPE):
129         if dtype is not None and data.dtype != dtype:
130             return data.astype(dtype)
131         return data
132     elif isinstance(data, tuple) and all(isinstance(d, TENSOR_TYPE) for d in data):
133         from ..merge import stack
134 
135         data = stack(data)
136         if dtype is not None:
137             data = data.astype(dtype)
138         return data
139     elif np.isscalar(data):
140         return scalar(data, dtype=dtype)
141     elif issparse(data):
142         return _from_spmatrix(data, dtype=dtype, chunk_size=chunk_size, gpu=gpu)
143     else:
144         m = get_array_module(data)
145         data = m.asarray(data, dtype=dtype)
146         if gpu is None and cp is not None and m is cp:
147             gpu = True
148 
149     if isinstance(data, np.ndarray):
150         if data.ndim == 0:
151             return scalar(data.item(), dtype=dtype)
152         op = ArrayDataSource(data, dtype=dtype, gpu=gpu)
153         t = op(data.shape, chunk_size=chunk_size)
154         if sparse and not t.issparse():
155             return t.tosparse()
156         return t
157     else:
158         raise ValueError('Cannot create tensor by given data: {0}'.format(data))
159 
160 
161 def array(x, dtype=None, copy=True, ndmin=None, chunk_size=None):
162     """
163     Create a tensor.
164 
165     Parameters
166     ----------
167     object : array_like
168         An array, any object exposing the array interface, an object whose
169         __array__ method returns an array, or any (nested) sequence.
170     dtype : data-type, optional
171         The desired data-type for the array.  If not given, then the type will
172         be determined as the minimum type required to hold the objects in the
173         sequence.  This argument can only be used to 'upcast' the array.  For
174         downcasting, use the .astype(t) method.
175     copy : bool, optional
176         If true (default), then the object is copied.  Otherwise, a copy will
177         only be made if __array__ returns a copy, if obj is a nested sequence,
178         or if a copy is needed to satisfy any of the other requirements
179         (`dtype`, `order`, etc.).
180     ndmin : int, optional
181         Specifies the minimum number of dimensions that the resulting
182         array should have.  Ones will be pre-pended to the shape as
183         needed to meet this requirement.
184     chunk_size: int, tuple, optional
185         Specifies chunk size for each dimension.
186 
187     Returns
188     -------
189     out : Tensor
190         An tensor object satisfying the specified requirements.
191 
192     See Also
193     --------
194     empty, empty_like, zeros, zeros_like, ones, ones_like, full, full_like
195 
196     Examples
197     --------
198     >>> import mars.tensor as mt
199 
200     >>> mt.array([1, 2, 3]).execute()
201     array([1, 2, 3])
202 
203     Upcasting:
204 
205     >>> mt.array([1, 2, 3.0]).execute()
206     array([ 1.,  2.,  3.])
207 
208     More than one dimension:
209 
210     >>> mt.array([[1, 2], [3, 4]]).execute()
211     array([[1, 2],
212            [3, 4]])
213 
214     Minimum dimensions 2:
215 
216     >>> mt.array([1, 2, 3], ndmin=2).execute()
217     array([[1, 2, 3]])
218 
219     Type provided:
220 
221     >>> mt.array([1, 2, 3], dtype=complex).execute()
222     array([ 1.+0.j,  2.+0.j,  3.+0.j])
223 
224     """
225     raw_x = x
226     x = tensor(x, chunk_size=chunk_size)
227     if copy and x is raw_x:
228         x = Tensor(x.data)
229     while ndmin is not None and x.ndim < ndmin:
230         x = x[np.newaxis, :]
231     if dtype is not None and x.dtype != dtype:
232         x = x.astype(dtype)
233     return x
234 
235 
236 def asarray(x, dtype=None):
237     """Convert the input to an array.
238 
239     Parameters
240     ----------
241     a : array_like
242         Input data, in any form that can be converted to a tensor.  This
243         includes lists, lists of tuples, tuples, tuples of tuples, tuples
244         of lists and tensors.
245     dtype : data-type, optional
246         By default, the data-type is inferred from the input data.
247 
248     Returns
249     -------
250     out : Tensor
251         Tensor interpretation of `a`.  No copy is performed if the input
252         is already an ndarray with matching dtype and order.  If `a` is a
253         subclass of ndarray, a base class ndarray is returned.
254 
255     Examples
256     --------
257     Convert a list into an array:
258 
259     >>> import mars.tensor as mt
260 
261     >>> a = [1, 2]
262     >>> mt.asarray(a).execute()
263     array([1, 2])
264 
265     Existing arrays are not copied:
266 
267     >>> a = mt.array([1, 2])
268     >>> mt.asarray(a) is a
269     True
270 
271     If `dtype` is set, array is copied only if dtype does not match:
272 
273     >>> a = mt.array([1, 2], dtype=mt.float32)
274     >>> mt.asarray(a, dtype=mt.float32) is a
275     True
276     >>> mt.asarray(a, dtype=mt.float64) is a
277     False
278     """
279     return array(x, dtype=dtype, copy=False)
280
```
--- 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/mars/tensor/expressions/datasource/array.py b/mars/tensor/expressions/datasource/array.py
--- a/mars/tensor/expressions/datasource/array.py
+++ b/mars/tensor/expressions/datasource/array.py
@@ -129,7 +129,7 @@
         if dtype is not None and data.dtype != dtype:
             return data.astype(dtype)
         return data
-    elif isinstance(data, tuple) and all(isinstance(d, TENSOR_TYPE) for d in data):
+    elif isinstance(data, (tuple, list)) and all(isinstance(d, TENSOR_TYPE) for d in data):
         from ..merge import stack
 
         data = stack(data)

{"golden_diff": "diff --git a/mars/tensor/expressions/datasource/array.py b/mars/tensor/expressions/datasource/array.py\n--- a/mars/tensor/expressions/datasource/array.py\n+++ b/mars/tensor/expressions/datasource/array.py\n@@ -129,7 +129,7 @@\n         if dtype is not None and data.dtype != dtype:\n             return data.astype(dtype)\n         return data\n-    elif isinstance(data, tuple) and all(isinstance(d, TENSOR_TYPE) for d in data):\n+    elif isinstance(data, (tuple, list)) and all(isinstance(d, TENSOR_TYPE) for d in data):\n         from ..merge import stack\n \n         data = stack(data)\n", "issue": "How to perform all tensor on np.array packages\nExample\uff1a\r\n```\r\nimport mars.tensor as mt\r\nimport numpy as np\r\n\r\ndef test_x():\r\n    X1 = mt.tensor([0, 1])\r\n    X2 = mt.tensor([2, 3])\r\n    X = np.array([X1,X2])\r\n    print(X.execute())\r\n```\r\nHow to calculate X\uff1f\nHow to perform all tensor on np.array packages\nExample\uff1a\r\n```\r\nimport mars.tensor as mt\r\nimport numpy as np\r\n\r\ndef test_x():\r\n    X1 = mt.tensor([0, 1])\r\n    X2 = mt.tensor([2, 3])\r\n    X = np.array([X1,X2])\r\n    print(X.execute())\r\n```\r\nHow to calculate X\uff1f\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2018 Alibaba Group Holding Ltd.\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# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nfrom .... import opcodes as OperandDef\nfrom ....lib.sparse.core import issparse, get_array_module, cp, cps, sps\nfrom ....utils import on_serialize_shape, on_deserialize_shape\nfrom ....serialize import ValueType, NDArrayField, TupleField\nfrom ...core import TENSOR_TYPE, Tensor\nfrom ..utils import get_chunk_slices\nfrom .core import TensorNoInput\nfrom .scalar import scalar\n\n\nclass ArrayDataSource(TensorNoInput):\n    \"\"\"\n    Represents data from numpy or cupy array\n    \"\"\"\n\n    _op_type_ = OperandDef.TENSOR_DATA_SOURCE\n\n    _data = NDArrayField('data')\n\n    def __init__(self, data=None, dtype=None, gpu=None, **kw):\n        if dtype is not None:\n            dtype = np.dtype(dtype)\n        elif data is not None:\n            dtype = np.dtype(data.dtype)\n        super(ArrayDataSource, self).__init__(_data=data, _dtype=dtype, _gpu=gpu, **kw)\n\n    @property\n    def data(self):\n        return self._data\n\n    def to_chunk_op(self, *args):\n        _, idx, chunk_size = args\n        chunk_op = self.copy().reset_key()\n        chunk_op._data = self.data[get_chunk_slices(chunk_size, idx)]\n\n        return chunk_op\n\n\nclass CSRMatrixDataSource(TensorNoInput):\n    \"\"\"\n    Represents data from sparse array include scipy sparse or cupy sparse matrix.\n    \"\"\"\n\n    _op_type_ = OperandDef.SPARSE_MATRIX_DATA_SOURCE\n\n    _indices = NDArrayField('indices')\n    _indptr = NDArrayField('indptr')\n    _data = NDArrayField('data')\n    _shape = TupleField('shape', ValueType.int64,\n                        on_serialize=on_serialize_shape, on_deserialize=on_deserialize_shape)\n\n    def __init__(self, indices=None, indptr=None, data=None, shape=None,\n                 dtype=None, gpu=None, **kw):\n        super(CSRMatrixDataSource, self).__init__(_indices=indices, _indptr=indptr,\n                                                  _data=data, _shape=shape, _dtype=dtype,\n                                                  _gpu=gpu, _sparse=True, **kw)\n\n    def to_chunk_op(self, *args):\n        _, idx, chunk_size = args\n\n        xps = cps if self._gpu else sps\n        if len(self._shape) == 1:\n            shape = (1, self._shape[0])\n        else:\n            shape = self._shape\n        data = xps.csr_matrix(\n            (self._data, self._indices, self._indptr), shape)\n        chunk_data = data[get_chunk_slices(chunk_size, idx)]\n\n        chunk_op = self.copy().reset_key()\n        chunk_op._data = chunk_data.data\n        chunk_op._indices = chunk_data.indices\n        chunk_op._indptr = chunk_data.indptr\n        chunk_shape = chunk_data.shape[1:] \\\n            if len(self._shape) == 1 else chunk_data.shape\n        chunk_op._shape = chunk_shape\n\n        return chunk_op\n\n    @property\n    def indices(self):\n        return self._indices\n\n    @property\n    def indptr(self):\n        return self._indptr\n\n    @property\n    def data(self):\n        return self._data\n\n    @property\n    def shape(self):\n        return self._shape\n\n\ndef _from_spmatrix(spmatrix, dtype=None, chunk_size=None, gpu=None):\n    if gpu is None and cp is not None and get_array_module(spmatrix) is cp:\n        gpu = True\n    if dtype and spmatrix.dtype != dtype:\n        spmatrix = spmatrix.astype(dtype)\n    spmatrix = spmatrix.tocsr()\n    op = CSRMatrixDataSource(indices=spmatrix.indices, indptr=spmatrix.indptr,\n                             data=spmatrix.data, shape=spmatrix.shape,\n                             dtype=spmatrix.dtype, gpu=gpu)\n    return op(spmatrix.shape, chunk_size=chunk_size)\n\n\ndef tensor(data, dtype=None, chunk_size=None, gpu=None, sparse=False):\n    if isinstance(data, TENSOR_TYPE):\n        if dtype is not None and data.dtype != dtype:\n            return data.astype(dtype)\n        return data\n    elif isinstance(data, tuple) and all(isinstance(d, TENSOR_TYPE) for d in data):\n        from ..merge import stack\n\n        data = stack(data)\n        if dtype is not None:\n            data = data.astype(dtype)\n        return data\n    elif np.isscalar(data):\n        return scalar(data, dtype=dtype)\n    elif issparse(data):\n        return _from_spmatrix(data, dtype=dtype, chunk_size=chunk_size, gpu=gpu)\n    else:\n        m = get_array_module(data)\n        data = m.asarray(data, dtype=dtype)\n        if gpu is None and cp is not None and m is cp:\n            gpu = True\n\n    if isinstance(data, np.ndarray):\n        if data.ndim == 0:\n            return scalar(data.item(), dtype=dtype)\n        op = ArrayDataSource(data, dtype=dtype, gpu=gpu)\n        t = op(data.shape, chunk_size=chunk_size)\n        if sparse and not t.issparse():\n            return t.tosparse()\n        return t\n    else:\n        raise ValueError('Cannot create tensor by given data: {0}'.format(data))\n\n\ndef array(x, dtype=None, copy=True, ndmin=None, chunk_size=None):\n    \"\"\"\n    Create a tensor.\n\n    Parameters\n    ----------\n    object : array_like\n        An array, any object exposing the array interface, an object whose\n        __array__ method returns an array, or any (nested) sequence.\n    dtype : data-type, optional\n        The desired data-type for the array.  If not given, then the type will\n        be determined as the minimum type required to hold the objects in the\n        sequence.  This argument can only be used to 'upcast' the array.  For\n        downcasting, use the .astype(t) method.\n    copy : bool, optional\n        If true (default), then the object is copied.  Otherwise, a copy will\n        only be made if __array__ returns a copy, if obj is a nested sequence,\n        or if a copy is needed to satisfy any of the other requirements\n        (`dtype`, `order`, etc.).\n    ndmin : int, optional\n        Specifies the minimum number of dimensions that the resulting\n        array should have.  Ones will be pre-pended to the shape as\n        needed to meet this requirement.\n    chunk_size: int, tuple, optional\n        Specifies chunk size for each dimension.\n\n    Returns\n    -------\n    out : Tensor\n        An tensor object satisfying the specified requirements.\n\n    See Also\n    --------\n    empty, empty_like, zeros, zeros_like, ones, ones_like, full, full_like\n\n    Examples\n    --------\n    >>> import mars.tensor as mt\n\n    >>> mt.array([1, 2, 3]).execute()\n    array([1, 2, 3])\n\n    Upcasting:\n\n    >>> mt.array([1, 2, 3.0]).execute()\n    array([ 1.,  2.,  3.])\n\n    More than one dimension:\n\n    >>> mt.array([[1, 2], [3, 4]]).execute()\n    array([[1, 2],\n           [3, 4]])\n\n    Minimum dimensions 2:\n\n    >>> mt.array([1, 2, 3], ndmin=2).execute()\n    array([[1, 2, 3]])\n\n    Type provided:\n\n    >>> mt.array([1, 2, 3], dtype=complex).execute()\n    array([ 1.+0.j,  2.+0.j,  3.+0.j])\n\n    \"\"\"\n    raw_x = x\n    x = tensor(x, chunk_size=chunk_size)\n    if copy and x is raw_x:\n        x = Tensor(x.data)\n    while ndmin is not None and x.ndim < ndmin:\n        x = x[np.newaxis, :]\n    if dtype is not None and x.dtype != dtype:\n        x = x.astype(dtype)\n    return x\n\n\ndef asarray(x, dtype=None):\n    \"\"\"Convert the input to an array.\n\n    Parameters\n    ----------\n    a : array_like\n        Input data, in any form that can be converted to a tensor.  This\n        includes lists, lists of tuples, tuples, tuples of tuples, tuples\n        of lists and tensors.\n    dtype : data-type, optional\n        By default, the data-type is inferred from the input data.\n\n    Returns\n    -------\n    out : Tensor\n        Tensor interpretation of `a`.  No copy is performed if the input\n        is already an ndarray with matching dtype and order.  If `a` is a\n        subclass of ndarray, a base class ndarray is returned.\n\n    Examples\n    --------\n    Convert a list into an array:\n\n    >>> import mars.tensor as mt\n\n    >>> a = [1, 2]\n    >>> mt.asarray(a).execute()\n    array([1, 2])\n\n    Existing arrays are not copied:\n\n    >>> a = mt.array([1, 2])\n    >>> mt.asarray(a) is a\n    True\n\n    If `dtype` is set, array is copied only if dtype does not match:\n\n    >>> a = mt.array([1, 2], dtype=mt.float32)\n    >>> mt.asarray(a, dtype=mt.float32) is a\n    True\n    >>> mt.asarray(a, dtype=mt.float64) is a\n    False\n    \"\"\"\n    return array(x, dtype=dtype, copy=False)\n", "path": "mars/tensor/expressions/datasource/array.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2018 Alibaba Group Holding Ltd.\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# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nfrom .... import opcodes as OperandDef\nfrom ....lib.sparse.core import issparse, get_array_module, cp, cps, sps\nfrom ....utils import on_serialize_shape, on_deserialize_shape\nfrom ....serialize import ValueType, NDArrayField, TupleField\nfrom ...core import TENSOR_TYPE, Tensor\nfrom ..utils import get_chunk_slices\nfrom .core import TensorNoInput\nfrom .scalar import scalar\n\n\nclass ArrayDataSource(TensorNoInput):\n    \"\"\"\n    Represents data from numpy or cupy array\n    \"\"\"\n\n    _op_type_ = OperandDef.TENSOR_DATA_SOURCE\n\n    _data = NDArrayField('data')\n\n    def __init__(self, data=None, dtype=None, gpu=None, **kw):\n        if dtype is not None:\n            dtype = np.dtype(dtype)\n        elif data is not None:\n            dtype = np.dtype(data.dtype)\n        super(ArrayDataSource, self).__init__(_data=data, _dtype=dtype, _gpu=gpu, **kw)\n\n    @property\n    def data(self):\n        return self._data\n\n    def to_chunk_op(self, *args):\n        _, idx, chunk_size = args\n        chunk_op = self.copy().reset_key()\n        chunk_op._data = self.data[get_chunk_slices(chunk_size, idx)]\n\n        return chunk_op\n\n\nclass CSRMatrixDataSource(TensorNoInput):\n    \"\"\"\n    Represents data from sparse array include scipy sparse or cupy sparse matrix.\n    \"\"\"\n\n    _op_type_ = OperandDef.SPARSE_MATRIX_DATA_SOURCE\n\n    _indices = NDArrayField('indices')\n    _indptr = NDArrayField('indptr')\n    _data = NDArrayField('data')\n    _shape = TupleField('shape', ValueType.int64,\n                        on_serialize=on_serialize_shape, on_deserialize=on_deserialize_shape)\n\n    def __init__(self, indices=None, indptr=None, data=None, shape=None,\n                 dtype=None, gpu=None, **kw):\n        super(CSRMatrixDataSource, self).__init__(_indices=indices, _indptr=indptr,\n                                                  _data=data, _shape=shape, _dtype=dtype,\n                                                  _gpu=gpu, _sparse=True, **kw)\n\n    def to_chunk_op(self, *args):\n        _, idx, chunk_size = args\n\n        xps = cps if self._gpu else sps\n        if len(self._shape) == 1:\n            shape = (1, self._shape[0])\n        else:\n            shape = self._shape\n        data = xps.csr_matrix(\n            (self._data, self._indices, self._indptr), shape)\n        chunk_data = data[get_chunk_slices(chunk_size, idx)]\n\n        chunk_op = self.copy().reset_key()\n        chunk_op._data = chunk_data.data\n        chunk_op._indices = chunk_data.indices\n        chunk_op._indptr = chunk_data.indptr\n        chunk_shape = chunk_data.shape[1:] \\\n            if len(self._shape) == 1 else chunk_data.shape\n        chunk_op._shape = chunk_shape\n\n        return chunk_op\n\n    @property\n    def indices(self):\n        return self._indices\n\n    @property\n    def indptr(self):\n        return self._indptr\n\n    @property\n    def data(self):\n        return self._data\n\n    @property\n    def shape(self):\n        return self._shape\n\n\ndef _from_spmatrix(spmatrix, dtype=None, chunk_size=None, gpu=None):\n    if gpu is None and cp is not None and get_array_module(spmatrix) is cp:\n        gpu = True\n    if dtype and spmatrix.dtype != dtype:\n        spmatrix = spmatrix.astype(dtype)\n    spmatrix = spmatrix.tocsr()\n    op = CSRMatrixDataSource(indices=spmatrix.indices, indptr=spmatrix.indptr,\n                             data=spmatrix.data, shape=spmatrix.shape,\n                             dtype=spmatrix.dtype, gpu=gpu)\n    return op(spmatrix.shape, chunk_size=chunk_size)\n\n\ndef tensor(data, dtype=None, chunk_size=None, gpu=None, sparse=False):\n    if isinstance(data, TENSOR_TYPE):\n        if dtype is not None and data.dtype != dtype:\n            return data.astype(dtype)\n        return data\n    elif isinstance(data, (tuple, list)) and all(isinstance(d, TENSOR_TYPE) for d in data):\n        from ..merge import stack\n\n        data = stack(data)\n        if dtype is not None:\n            data = data.astype(dtype)\n        return data\n    elif np.isscalar(data):\n        return scalar(data, dtype=dtype)\n    elif issparse(data):\n        return _from_spmatrix(data, dtype=dtype, chunk_size=chunk_size, gpu=gpu)\n    else:\n        m = get_array_module(data)\n        data = m.asarray(data, dtype=dtype)\n        if gpu is None and cp is not None and m is cp:\n            gpu = True\n\n    if isinstance(data, np.ndarray):\n        if data.ndim == 0:\n            return scalar(data.item(), dtype=dtype)\n        op = ArrayDataSource(data, dtype=dtype, gpu=gpu)\n        t = op(data.shape, chunk_size=chunk_size)\n        if sparse and not t.issparse():\n            return t.tosparse()\n        return t\n    else:\n        raise ValueError('Cannot create tensor by given data: {0}'.format(data))\n\n\ndef array(x, dtype=None, copy=True, ndmin=None, chunk_size=None):\n    \"\"\"\n    Create a tensor.\n\n    Parameters\n    ----------\n    object : array_like\n        An array, any object exposing the array interface, an object whose\n        __array__ method returns an array, or any (nested) sequence.\n    dtype : data-type, optional\n        The desired data-type for the array.  If not given, then the type will\n        be determined as the minimum type required to hold the objects in the\n        sequence.  This argument can only be used to 'upcast' the array.  For\n        downcasting, use the .astype(t) method.\n    copy : bool, optional\n        If true (default), then the object is copied.  Otherwise, a copy will\n        only be made if __array__ returns a copy, if obj is a nested sequence,\n        or if a copy is needed to satisfy any of the other requirements\n        (`dtype`, `order`, etc.).\n    ndmin : int, optional\n        Specifies the minimum number of dimensions that the resulting\n        array should have.  Ones will be pre-pended to the shape as\n        needed to meet this requirement.\n    chunk_size: int, tuple, optional\n        Specifies chunk size for each dimension.\n\n    Returns\n    -------\n    out : Tensor\n        An tensor object satisfying the specified requirements.\n\n    See Also\n    --------\n    empty, empty_like, zeros, zeros_like, ones, ones_like, full, full_like\n\n    Examples\n    --------\n    >>> import mars.tensor as mt\n\n    >>> mt.array([1, 2, 3]).execute()\n    array([1, 2, 3])\n\n    Upcasting:\n\n    >>> mt.array([1, 2, 3.0]).execute()\n    array([ 1.,  2.,  3.])\n\n    More than one dimension:\n\n    >>> mt.array([[1, 2], [3, 4]]).execute()\n    array([[1, 2],\n           [3, 4]])\n\n    Minimum dimensions 2:\n\n    >>> mt.array([1, 2, 3], ndmin=2).execute()\n    array([[1, 2, 3]])\n\n    Type provided:\n\n    >>> mt.array([1, 2, 3], dtype=complex).execute()\n    array([ 1.+0.j,  2.+0.j,  3.+0.j])\n\n    \"\"\"\n    raw_x = x\n    x = tensor(x, chunk_size=chunk_size)\n    if copy and x is raw_x:\n        x = Tensor(x.data)\n    while ndmin is not None and x.ndim < ndmin:\n        x = x[np.newaxis, :]\n    if dtype is not None and x.dtype != dtype:\n        x = x.astype(dtype)\n    return x\n\n\ndef asarray(x, dtype=None):\n    \"\"\"Convert the input to an array.\n\n    Parameters\n    ----------\n    a : array_like\n        Input data, in any form that can be converted to a tensor.  This\n        includes lists, lists of tuples, tuples, tuples of tuples, tuples\n        of lists and tensors.\n    dtype : data-type, optional\n        By default, the data-type is inferred from the input data.\n\n    Returns\n    -------\n    out : Tensor\n        Tensor interpretation of `a`.  No copy is performed if the input\n        is already an ndarray with matching dtype and order.  If `a` is a\n        subclass of ndarray, a base class ndarray is returned.\n\n    Examples\n    --------\n    Convert a list into an array:\n\n    >>> import mars.tensor as mt\n\n    >>> a = [1, 2]\n    >>> mt.asarray(a).execute()\n    array([1, 2])\n\n    Existing arrays are not copied:\n\n    >>> a = mt.array([1, 2])\n    >>> mt.asarray(a) is a\n    True\n\n    If `dtype` is set, array is copied only if dtype does not match:\n\n    >>> a = mt.array([1, 2], dtype=mt.float32)\n    >>> mt.asarray(a, dtype=mt.float32) is a\n    True\n    >>> mt.asarray(a, dtype=mt.float64) is a\n    False\n    \"\"\"\n    return array(x, dtype=dtype, copy=False)\n", "path": "mars/tensor/expressions/datasource/array.py"}]}