We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
dshape of nunique not the same as the resulting object
``` python
In [14]: fx.date.nunique()
Out[14]: 5825.0

In [15]: fx.date.nunique().dshape
Out[15]: dshape("int32")
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `blaze/compute/numpy.py`
Content:
```
1 from __future__ import absolute_import, division, print_function
2 
3 import datetime
4 
5 import numpy as np
6 from pandas import DataFrame, Series
7 from datashape import to_numpy
8 
9 from ..expr import Reduction, Field, Projection, Broadcast, Selection, ndim
10 from ..expr import Distinct, Sort, Head, Label, ReLabel, Expr, Slice
11 from ..expr import std, var, count, nunique, Summary
12 from ..expr import BinOp, UnaryOp, USub, Not, nelements
13 from ..expr import UTCFromTimestamp, DateTimeTruncate
14 
15 from .core import base, compute
16 from ..dispatch import dispatch
17 from into import into
18 import pandas as pd
19 
20 __all__ = ['np']
21 
22 
23 @dispatch(Field, np.ndarray)
24 def compute_up(c, x, **kwargs):
25     if x.dtype.names and c._name in x.dtype.names:
26         return x[c._name]
27     if not x.dtype.names and x.shape[1] == len(c._child.fields):
28         return x[:, c._child.fields.index(c._name)]
29     raise NotImplementedError() # pragma: no cover
30 
31 
32 @dispatch(Projection, np.ndarray)
33 def compute_up(t, x, **kwargs):
34     if x.dtype.names and all(col in x.dtype.names for col in t.fields):
35         return x[t.fields]
36     if not x.dtype.names and x.shape[1] == len(t._child.fields):
37         return x[:, [t._child.fields.index(col) for col in t.fields]]
38     raise NotImplementedError() # pragma: no cover
39 
40 
41 @dispatch(Broadcast, np.ndarray)
42 def compute_up(t, x, **kwargs):
43     d = dict((t._child[c]._expr, x[c]) for c in t._child.fields)
44     return compute(t._expr, d)
45 
46 
47 @dispatch(BinOp, np.ndarray, (np.ndarray, base))
48 def compute_up(t, lhs, rhs, **kwargs):
49     return t.op(lhs, rhs)
50 
51 
52 @dispatch(BinOp, np.ndarray)
53 def compute_up(t, data, **kwargs):
54     if isinstance(t.lhs, Expr):
55         return t.op(data, t.rhs)
56     else:
57         return t.op(t.lhs, data)
58 
59 
60 @dispatch(BinOp, base, np.ndarray)
61 def compute_up(t, lhs, rhs, **kwargs):
62     return t.op(lhs, rhs)
63 
64 
65 @dispatch(UnaryOp, np.ndarray)
66 def compute_up(t, x, **kwargs):
67     return getattr(np, t.symbol)(x)
68 
69 
70 @dispatch(Not, np.ndarray)
71 def compute_up(t, x, **kwargs):
72     return ~x
73 
74 
75 @dispatch(USub, np.ndarray)
76 def compute_up(t, x, **kwargs):
77     return -x
78 
79 
80 @dispatch(count, np.ndarray)
81 def compute_up(t, x, **kwargs):
82     if np.issubdtype(x.dtype, np.float): # scalar dtype
83         return pd.notnull(x).sum(keepdims=t.keepdims, axis=t.axis)
84     else:
85         return np.ones(x.shape).sum(keepdims=t.keepdims, axis=t.axis)
86 
87 
88 @dispatch(nunique, np.ndarray)
89 def compute_up(t, x, **kwargs):
90     assert t.axis == tuple(range(ndim(t._child)))
91     result = len(np.unique(x))
92     if t.keepdims:
93         result = np.array([result])
94     return result
95 
96 
97 @dispatch(Reduction, np.ndarray)
98 def compute_up(t, x, **kwargs):
99     return getattr(x, t.symbol)(axis=t.axis, keepdims=t.keepdims)
100 
101 
102 def axify(expr, axis):
103     """ inject axis argument into expression
104 
105     Helper function for compute_up(Summary, np.ndarray)
106 
107     >>> from blaze import symbol
108     >>> s = symbol('s', '10 * 10 * int')
109     >>> expr = s.sum()
110     >>> axify(expr, axis=0)
111     sum(s, axis=(0,))
112     """
113     return type(expr)(expr._child, axis=axis)
114 
115 
116 @dispatch(Summary, np.ndarray)
117 def compute_up(expr, data, **kwargs):
118     shape, dtype = to_numpy(expr.dshape)
119     if shape:
120         result = np.empty(shape=shape, dtype=dtype)
121         for n, v in zip(expr.names, expr.values):
122             result[n] = compute(axify(v, expr.axis), data)
123         return result
124     else:
125         return tuple(compute(axify(v, expr.axis), data) for v in expr.values)
126 
127 
128 @dispatch((std, var), np.ndarray)
129 def compute_up(t, x, **kwargs):
130     return getattr(x, t.symbol)(ddof=t.unbiased)
131 
132 
133 @dispatch(Distinct, np.ndarray)
134 def compute_up(t, x, **kwargs):
135     return np.unique(x)
136 
137 
138 @dispatch(Sort, np.ndarray)
139 def compute_up(t, x, **kwargs):
140     if x.dtype.names is None:  # not a struct array
141         result = np.sort(x)
142     elif (t.key in x.dtype.names or  # struct array
143         isinstance(t.key, list) and all(k in x.dtype.names for k in t.key)):
144         result = np.sort(x, order=t.key)
145     elif t.key:
146         raise NotImplementedError("Sort key %s not supported" % t.key)
147 
148     if not t.ascending:
149         result = result[::-1]
150 
151     return result
152 
153 
154 @dispatch(Head, np.ndarray)
155 def compute_up(t, x, **kwargs):
156     return x[:t.n]
157 
158 
159 @dispatch(Label, np.ndarray)
160 def compute_up(t, x, **kwargs):
161     return np.array(x, dtype=[(t.label, x.dtype.type)])
162 
163 
164 @dispatch(ReLabel, np.ndarray)
165 def compute_up(t, x, **kwargs):
166     types = [x.dtype[i] for i in range(len(x.dtype))]
167     return np.array(x, dtype=list(zip(t.fields, types)))
168 
169 
170 @dispatch(Selection, np.ndarray)
171 def compute_up(sel, x, **kwargs):
172     return x[compute(sel.predicate, {sel._child: x})]
173 
174 
175 @dispatch(UTCFromTimestamp, np.ndarray)
176 def compute_up(expr, data, **kwargs):
177     return (data * 1e6).astype('M8[us]')
178 
179 
180 @dispatch(Slice, np.ndarray)
181 def compute_up(expr, x, **kwargs):
182     return x[expr.index]
183 
184 
185 @dispatch(Expr, np.ndarray)
186 def compute_up(t, x, **kwargs):
187     ds = t._child.dshape
188     if x.ndim > 1 or isinstance(x, np.recarray) or x.dtype.fields is not None:
189         return compute_up(t, into(DataFrame, x, dshape=ds), **kwargs)
190     else:
191         return compute_up(t, into(Series, x, dshape=ds), **kwargs)
192 
193 
194 @dispatch(nelements, np.ndarray)
195 def compute_up(expr, data, **kwargs):
196     axis = expr.axis
197     if expr.keepdims:
198         shape = tuple(data.shape[i] if i not in axis else 1
199                                     for i in range(ndim(expr._child)))
200     else:
201         shape = tuple(data.shape[i] for i in range(ndim(expr._child))
202                       if i not in axis)
203     value = np.prod([data.shape[i] for i in axis])
204     result = np.empty(shape)
205     result.fill(value)
206     result = result.astype('int64')
207 
208     return result
209 
210 
211 
212 # Note the use of 'week': 'M8[D]' here.
213 
214 # We truncate week offsets "manually" in the compute_up implementation by first
215 # converting to days then multiplying our measure by 7 this simplifies our code
216 # by only requiring us to calculate the week offset relative to the day of week.
217 
218 precision_map = {'year': 'M8[Y]',
219                  'month': 'M8[M]',
220                  'week': 'M8[D]',
221                  'day': 'M8[D]',
222                  'hour': 'M8[h]',
223                  'minute': 'M8[m]',
224                  'second': 'M8[s]',
225                  'millisecond': 'M8[ms]',
226                  'microsecond': 'M8[us]',
227                  'nanosecond': 'M8[ns]'}
228 
229 
230 # these offsets are integers in units of their representation
231 
232 epoch = datetime.datetime(1970, 1, 1)
233 offsets = {
234     'week': epoch.isoweekday(),
235     'day': epoch.toordinal() # number of days since *Python's* epoch (01/01/01)
236 }
237 
238 
239 @dispatch(DateTimeTruncate, (np.ndarray, np.datetime64))
240 def compute_up(expr, data, **kwargs):
241     np_dtype = precision_map[expr.unit]
242     offset = offsets.get(expr.unit, 0)
243     measure = expr.measure * 7 if expr.unit == 'week' else expr.measure
244     result = (((data.astype(np_dtype)
245                     .view('int64')
246                     + offset)
247                     // measure
248                     * measure
249                     - offset)
250                     .astype(np_dtype))
251     return result
252 
253 
254 @dispatch(np.ndarray)
255 def chunks(x, chunksize=1024):
256     start = 0
257     n = len(x)
258     while start < n:
259         yield x[start:start + chunksize]
260         start += chunksize
261
```
--- 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/blaze/compute/numpy.py b/blaze/compute/numpy.py
--- a/blaze/compute/numpy.py
+++ b/blaze/compute/numpy.py
@@ -4,7 +4,7 @@
 
 import numpy as np
 from pandas import DataFrame, Series
-from datashape import to_numpy
+from datashape import to_numpy, to_numpy_dtype
 
 from ..expr import Reduction, Field, Projection, Broadcast, Selection, ndim
 from ..expr import Distinct, Sort, Head, Label, ReLabel, Expr, Slice
@@ -77,12 +77,19 @@
     return -x
 
 
+inat = np.datetime64('NaT').view('int64')
+
+
 @dispatch(count, np.ndarray)
 def compute_up(t, x, **kwargs):
-    if np.issubdtype(x.dtype, np.float): # scalar dtype
+    if issubclass(x.dtype.type, (np.floating, np.object_)):
         return pd.notnull(x).sum(keepdims=t.keepdims, axis=t.axis)
+    elif issubclass(x.dtype.type, np.datetime64):
+        return (x.view('int64') != inat).sum(keepdims=t.keepdims, axis=t.axis)
     else:
-        return np.ones(x.shape).sum(keepdims=t.keepdims, axis=t.axis)
+        return np.ones(x.shape,
+                       dtype=to_numpy_dtype(t.dshape)).sum(keepdims=t.keepdims,
+                                                           axis=t.axis)
 
 
 @dispatch(nunique, np.ndarray)

{"golden_diff": "diff --git a/blaze/compute/numpy.py b/blaze/compute/numpy.py\n--- a/blaze/compute/numpy.py\n+++ b/blaze/compute/numpy.py\n@@ -4,7 +4,7 @@\n \n import numpy as np\n from pandas import DataFrame, Series\n-from datashape import to_numpy\n+from datashape import to_numpy, to_numpy_dtype\n \n from ..expr import Reduction, Field, Projection, Broadcast, Selection, ndim\n from ..expr import Distinct, Sort, Head, Label, ReLabel, Expr, Slice\n@@ -77,12 +77,19 @@\n     return -x\n \n \n+inat = np.datetime64('NaT').view('int64')\n+\n+\n @dispatch(count, np.ndarray)\n def compute_up(t, x, **kwargs):\n-    if np.issubdtype(x.dtype, np.float): # scalar dtype\n+    if issubclass(x.dtype.type, (np.floating, np.object_)):\n         return pd.notnull(x).sum(keepdims=t.keepdims, axis=t.axis)\n+    elif issubclass(x.dtype.type, np.datetime64):\n+        return (x.view('int64') != inat).sum(keepdims=t.keepdims, axis=t.axis)\n     else:\n-        return np.ones(x.shape).sum(keepdims=t.keepdims, axis=t.axis)\n+        return np.ones(x.shape,\n+                       dtype=to_numpy_dtype(t.dshape)).sum(keepdims=t.keepdims,\n+                                                           axis=t.axis)\n \n \n @dispatch(nunique, np.ndarray)\n", "issue": "dshape of nunique not the same as the resulting object\n``` python\nIn [14]: fx.date.nunique()\nOut[14]: 5825.0\n\nIn [15]: fx.date.nunique().dshape\nOut[15]: dshape(\"int32\")\n```\n\n", "before_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport datetime\n\nimport numpy as np\nfrom pandas import DataFrame, Series\nfrom datashape import to_numpy\n\nfrom ..expr import Reduction, Field, Projection, Broadcast, Selection, ndim\nfrom ..expr import Distinct, Sort, Head, Label, ReLabel, Expr, Slice\nfrom ..expr import std, var, count, nunique, Summary\nfrom ..expr import BinOp, UnaryOp, USub, Not, nelements\nfrom ..expr import UTCFromTimestamp, DateTimeTruncate\n\nfrom .core import base, compute\nfrom ..dispatch import dispatch\nfrom into import into\nimport pandas as pd\n\n__all__ = ['np']\n\n\n@dispatch(Field, np.ndarray)\ndef compute_up(c, x, **kwargs):\n    if x.dtype.names and c._name in x.dtype.names:\n        return x[c._name]\n    if not x.dtype.names and x.shape[1] == len(c._child.fields):\n        return x[:, c._child.fields.index(c._name)]\n    raise NotImplementedError() # pragma: no cover\n\n\n@dispatch(Projection, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    if x.dtype.names and all(col in x.dtype.names for col in t.fields):\n        return x[t.fields]\n    if not x.dtype.names and x.shape[1] == len(t._child.fields):\n        return x[:, [t._child.fields.index(col) for col in t.fields]]\n    raise NotImplementedError() # pragma: no cover\n\n\n@dispatch(Broadcast, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    d = dict((t._child[c]._expr, x[c]) for c in t._child.fields)\n    return compute(t._expr, d)\n\n\n@dispatch(BinOp, np.ndarray, (np.ndarray, base))\ndef compute_up(t, lhs, rhs, **kwargs):\n    return t.op(lhs, rhs)\n\n\n@dispatch(BinOp, np.ndarray)\ndef compute_up(t, data, **kwargs):\n    if isinstance(t.lhs, Expr):\n        return t.op(data, t.rhs)\n    else:\n        return t.op(t.lhs, data)\n\n\n@dispatch(BinOp, base, np.ndarray)\ndef compute_up(t, lhs, rhs, **kwargs):\n    return t.op(lhs, rhs)\n\n\n@dispatch(UnaryOp, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return getattr(np, t.symbol)(x)\n\n\n@dispatch(Not, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return ~x\n\n\n@dispatch(USub, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return -x\n\n\n@dispatch(count, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    if np.issubdtype(x.dtype, np.float): # scalar dtype\n        return pd.notnull(x).sum(keepdims=t.keepdims, axis=t.axis)\n    else:\n        return np.ones(x.shape).sum(keepdims=t.keepdims, axis=t.axis)\n\n\n@dispatch(nunique, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    assert t.axis == tuple(range(ndim(t._child)))\n    result = len(np.unique(x))\n    if t.keepdims:\n        result = np.array([result])\n    return result\n\n\n@dispatch(Reduction, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return getattr(x, t.symbol)(axis=t.axis, keepdims=t.keepdims)\n\n\ndef axify(expr, axis):\n    \"\"\" inject axis argument into expression\n\n    Helper function for compute_up(Summary, np.ndarray)\n\n    >>> from blaze import symbol\n    >>> s = symbol('s', '10 * 10 * int')\n    >>> expr = s.sum()\n    >>> axify(expr, axis=0)\n    sum(s, axis=(0,))\n    \"\"\"\n    return type(expr)(expr._child, axis=axis)\n\n\n@dispatch(Summary, np.ndarray)\ndef compute_up(expr, data, **kwargs):\n    shape, dtype = to_numpy(expr.dshape)\n    if shape:\n        result = np.empty(shape=shape, dtype=dtype)\n        for n, v in zip(expr.names, expr.values):\n            result[n] = compute(axify(v, expr.axis), data)\n        return result\n    else:\n        return tuple(compute(axify(v, expr.axis), data) for v in expr.values)\n\n\n@dispatch((std, var), np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return getattr(x, t.symbol)(ddof=t.unbiased)\n\n\n@dispatch(Distinct, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return np.unique(x)\n\n\n@dispatch(Sort, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    if x.dtype.names is None:  # not a struct array\n        result = np.sort(x)\n    elif (t.key in x.dtype.names or  # struct array\n        isinstance(t.key, list) and all(k in x.dtype.names for k in t.key)):\n        result = np.sort(x, order=t.key)\n    elif t.key:\n        raise NotImplementedError(\"Sort key %s not supported\" % t.key)\n\n    if not t.ascending:\n        result = result[::-1]\n\n    return result\n\n\n@dispatch(Head, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return x[:t.n]\n\n\n@dispatch(Label, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return np.array(x, dtype=[(t.label, x.dtype.type)])\n\n\n@dispatch(ReLabel, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    types = [x.dtype[i] for i in range(len(x.dtype))]\n    return np.array(x, dtype=list(zip(t.fields, types)))\n\n\n@dispatch(Selection, np.ndarray)\ndef compute_up(sel, x, **kwargs):\n    return x[compute(sel.predicate, {sel._child: x})]\n\n\n@dispatch(UTCFromTimestamp, np.ndarray)\ndef compute_up(expr, data, **kwargs):\n    return (data * 1e6).astype('M8[us]')\n\n\n@dispatch(Slice, np.ndarray)\ndef compute_up(expr, x, **kwargs):\n    return x[expr.index]\n\n\n@dispatch(Expr, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    ds = t._child.dshape\n    if x.ndim > 1 or isinstance(x, np.recarray) or x.dtype.fields is not None:\n        return compute_up(t, into(DataFrame, x, dshape=ds), **kwargs)\n    else:\n        return compute_up(t, into(Series, x, dshape=ds), **kwargs)\n\n\n@dispatch(nelements, np.ndarray)\ndef compute_up(expr, data, **kwargs):\n    axis = expr.axis\n    if expr.keepdims:\n        shape = tuple(data.shape[i] if i not in axis else 1\n                                    for i in range(ndim(expr._child)))\n    else:\n        shape = tuple(data.shape[i] for i in range(ndim(expr._child))\n                      if i not in axis)\n    value = np.prod([data.shape[i] for i in axis])\n    result = np.empty(shape)\n    result.fill(value)\n    result = result.astype('int64')\n\n    return result\n\n\n\n# Note the use of 'week': 'M8[D]' here.\n\n# We truncate week offsets \"manually\" in the compute_up implementation by first\n# converting to days then multiplying our measure by 7 this simplifies our code\n# by only requiring us to calculate the week offset relative to the day of week.\n\nprecision_map = {'year': 'M8[Y]',\n                 'month': 'M8[M]',\n                 'week': 'M8[D]',\n                 'day': 'M8[D]',\n                 'hour': 'M8[h]',\n                 'minute': 'M8[m]',\n                 'second': 'M8[s]',\n                 'millisecond': 'M8[ms]',\n                 'microsecond': 'M8[us]',\n                 'nanosecond': 'M8[ns]'}\n\n\n# these offsets are integers in units of their representation\n\nepoch = datetime.datetime(1970, 1, 1)\noffsets = {\n    'week': epoch.isoweekday(),\n    'day': epoch.toordinal() # number of days since *Python's* epoch (01/01/01)\n}\n\n\n@dispatch(DateTimeTruncate, (np.ndarray, np.datetime64))\ndef compute_up(expr, data, **kwargs):\n    np_dtype = precision_map[expr.unit]\n    offset = offsets.get(expr.unit, 0)\n    measure = expr.measure * 7 if expr.unit == 'week' else expr.measure\n    result = (((data.astype(np_dtype)\n                    .view('int64')\n                    + offset)\n                    // measure\n                    * measure\n                    - offset)\n                    .astype(np_dtype))\n    return result\n\n\n@dispatch(np.ndarray)\ndef chunks(x, chunksize=1024):\n    start = 0\n    n = len(x)\n    while start < n:\n        yield x[start:start + chunksize]\n        start += chunksize\n", "path": "blaze/compute/numpy.py"}], "after_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport datetime\n\nimport numpy as np\nfrom pandas import DataFrame, Series\nfrom datashape import to_numpy, to_numpy_dtype\n\nfrom ..expr import Reduction, Field, Projection, Broadcast, Selection, ndim\nfrom ..expr import Distinct, Sort, Head, Label, ReLabel, Expr, Slice\nfrom ..expr import std, var, count, nunique, Summary\nfrom ..expr import BinOp, UnaryOp, USub, Not, nelements\nfrom ..expr import UTCFromTimestamp, DateTimeTruncate\n\nfrom .core import base, compute\nfrom ..dispatch import dispatch\nfrom into import into\nimport pandas as pd\n\n__all__ = ['np']\n\n\n@dispatch(Field, np.ndarray)\ndef compute_up(c, x, **kwargs):\n    if x.dtype.names and c._name in x.dtype.names:\n        return x[c._name]\n    if not x.dtype.names and x.shape[1] == len(c._child.fields):\n        return x[:, c._child.fields.index(c._name)]\n    raise NotImplementedError() # pragma: no cover\n\n\n@dispatch(Projection, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    if x.dtype.names and all(col in x.dtype.names for col in t.fields):\n        return x[t.fields]\n    if not x.dtype.names and x.shape[1] == len(t._child.fields):\n        return x[:, [t._child.fields.index(col) for col in t.fields]]\n    raise NotImplementedError() # pragma: no cover\n\n\n@dispatch(Broadcast, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    d = dict((t._child[c]._expr, x[c]) for c in t._child.fields)\n    return compute(t._expr, d)\n\n\n@dispatch(BinOp, np.ndarray, (np.ndarray, base))\ndef compute_up(t, lhs, rhs, **kwargs):\n    return t.op(lhs, rhs)\n\n\n@dispatch(BinOp, np.ndarray)\ndef compute_up(t, data, **kwargs):\n    if isinstance(t.lhs, Expr):\n        return t.op(data, t.rhs)\n    else:\n        return t.op(t.lhs, data)\n\n\n@dispatch(BinOp, base, np.ndarray)\ndef compute_up(t, lhs, rhs, **kwargs):\n    return t.op(lhs, rhs)\n\n\n@dispatch(UnaryOp, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return getattr(np, t.symbol)(x)\n\n\n@dispatch(Not, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return ~x\n\n\n@dispatch(USub, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return -x\n\n\ninat = np.datetime64('NaT').view('int64')\n\n\n@dispatch(count, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    if issubclass(x.dtype.type, (np.floating, np.object_)):\n        return pd.notnull(x).sum(keepdims=t.keepdims, axis=t.axis)\n    elif issubclass(x.dtype.type, np.datetime64):\n        return (x.view('int64') != inat).sum(keepdims=t.keepdims, axis=t.axis)\n    else:\n        return np.ones(x.shape,\n                       dtype=to_numpy_dtype(t.dshape)).sum(keepdims=t.keepdims,\n                                                           axis=t.axis)\n\n\n@dispatch(nunique, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    assert t.axis == tuple(range(ndim(t._child)))\n    result = len(np.unique(x))\n    if t.keepdims:\n        result = np.array([result])\n    return result\n\n\n@dispatch(Reduction, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return getattr(x, t.symbol)(axis=t.axis, keepdims=t.keepdims)\n\n\ndef axify(expr, axis):\n    \"\"\" inject axis argument into expression\n\n    Helper function for compute_up(Summary, np.ndarray)\n\n    >>> from blaze import symbol\n    >>> s = symbol('s', '10 * 10 * int')\n    >>> expr = s.sum()\n    >>> axify(expr, axis=0)\n    sum(s, axis=(0,))\n    \"\"\"\n    return type(expr)(expr._child, axis=axis)\n\n\n@dispatch(Summary, np.ndarray)\ndef compute_up(expr, data, **kwargs):\n    shape, dtype = to_numpy(expr.dshape)\n    if shape:\n        result = np.empty(shape=shape, dtype=dtype)\n        for n, v in zip(expr.names, expr.values):\n            result[n] = compute(axify(v, expr.axis), data)\n        return result\n    else:\n        return tuple(compute(axify(v, expr.axis), data) for v in expr.values)\n\n\n@dispatch((std, var), np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return getattr(x, t.symbol)(ddof=t.unbiased)\n\n\n@dispatch(Distinct, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return np.unique(x)\n\n\n@dispatch(Sort, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    if x.dtype.names is None:  # not a struct array\n        result = np.sort(x)\n    elif (t.key in x.dtype.names or  # struct array\n        isinstance(t.key, list) and all(k in x.dtype.names for k in t.key)):\n        result = np.sort(x, order=t.key)\n    elif t.key:\n        raise NotImplementedError(\"Sort key %s not supported\" % t.key)\n\n    if not t.ascending:\n        result = result[::-1]\n\n    return result\n\n\n@dispatch(Head, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return x[:t.n]\n\n\n@dispatch(Label, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    return np.array(x, dtype=[(t.label, x.dtype.type)])\n\n\n@dispatch(ReLabel, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    types = [x.dtype[i] for i in range(len(x.dtype))]\n    return np.array(x, dtype=list(zip(t.fields, types)))\n\n\n@dispatch(Selection, np.ndarray)\ndef compute_up(sel, x, **kwargs):\n    return x[compute(sel.predicate, {sel._child: x})]\n\n\n@dispatch(UTCFromTimestamp, np.ndarray)\ndef compute_up(expr, data, **kwargs):\n    return (data * 1e6).astype('M8[us]')\n\n\n@dispatch(Slice, np.ndarray)\ndef compute_up(expr, x, **kwargs):\n    return x[expr.index]\n\n\n@dispatch(Expr, np.ndarray)\ndef compute_up(t, x, **kwargs):\n    ds = t._child.dshape\n    if x.ndim > 1 or isinstance(x, np.recarray) or x.dtype.fields is not None:\n        return compute_up(t, into(DataFrame, x, dshape=ds), **kwargs)\n    else:\n        return compute_up(t, into(Series, x, dshape=ds), **kwargs)\n\n\n@dispatch(nelements, np.ndarray)\ndef compute_up(expr, data, **kwargs):\n    axis = expr.axis\n    if expr.keepdims:\n        shape = tuple(data.shape[i] if i not in axis else 1\n                                    for i in range(ndim(expr._child)))\n    else:\n        shape = tuple(data.shape[i] for i in range(ndim(expr._child))\n                      if i not in axis)\n    value = np.prod([data.shape[i] for i in axis])\n    result = np.empty(shape)\n    result.fill(value)\n    result = result.astype('int64')\n\n    return result\n\n\n\n# Note the use of 'week': 'M8[D]' here.\n\n# We truncate week offsets \"manually\" in the compute_up implementation by first\n# converting to days then multiplying our measure by 7 this simplifies our code\n# by only requiring us to calculate the week offset relative to the day of week.\n\nprecision_map = {'year': 'M8[Y]',\n                 'month': 'M8[M]',\n                 'week': 'M8[D]',\n                 'day': 'M8[D]',\n                 'hour': 'M8[h]',\n                 'minute': 'M8[m]',\n                 'second': 'M8[s]',\n                 'millisecond': 'M8[ms]',\n                 'microsecond': 'M8[us]',\n                 'nanosecond': 'M8[ns]'}\n\n\n# these offsets are integers in units of their representation\n\nepoch = datetime.datetime(1970, 1, 1)\noffsets = {\n    'week': epoch.isoweekday(),\n    'day': epoch.toordinal() # number of days since *Python's* epoch (01/01/01)\n}\n\n\n@dispatch(DateTimeTruncate, (np.ndarray, np.datetime64))\ndef compute_up(expr, data, **kwargs):\n    np_dtype = precision_map[expr.unit]\n    offset = offsets.get(expr.unit, 0)\n    measure = expr.measure * 7 if expr.unit == 'week' else expr.measure\n    result = (((data.astype(np_dtype)\n                    .view('int64')\n                    + offset)\n                    // measure\n                    * measure\n                    - offset)\n                    .astype(np_dtype))\n    return result\n\n\n@dispatch(np.ndarray)\ndef chunks(x, chunksize=1024):\n    start = 0\n    n = len(x)\n    while start < n:\n        yield x[start:start + chunksize]\n        start += chunksize\n", "path": "blaze/compute/numpy.py"}]}