|
| 1 | +from functools import partial, wraps |
| 2 | +from itertools import izip |
| 3 | + |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +import pandas as pd |
| 7 | +import pandas.core.common as com |
| 8 | +from pandas.computation.ops import is_const |
| 9 | +from pandas.computation.common import flatten |
| 10 | + |
| 11 | + |
| 12 | +def _align_core_single_unary_op(term): |
| 13 | + if isinstance(term.value, np.ndarray) and not com.is_series(term.value): |
| 14 | + typ = partial(np.asanyarray, dtype=term.value.dtype) |
| 15 | + else: |
| 16 | + typ = type(term.value) |
| 17 | + ret = typ, |
| 18 | + |
| 19 | + if not hasattr(term.value, 'axes'): |
| 20 | + ret += None, |
| 21 | + else: |
| 22 | + ret += _zip_axes_from_type(typ, term.value.axes), |
| 23 | + return ret |
| 24 | + |
| 25 | + |
| 26 | +def _zip_axes_from_type(typ, new_axes): |
| 27 | + axes = {} |
| 28 | + for ax_ind, ax_name in typ._AXIS_NAMES.iteritems(): |
| 29 | + axes[ax_name] = new_axes[ax_ind] |
| 30 | + return axes |
| 31 | + |
| 32 | + |
| 33 | +def _maybe_promote_shape(values, naxes): |
| 34 | + # test to see if we have an array else leave since must be a number |
| 35 | + if not isinstance(values, np.ndarray): |
| 36 | + return values |
| 37 | + |
| 38 | + ndims = values.ndim |
| 39 | + if ndims > naxes: |
| 40 | + raise AssertionError('cannot have more dims than axes, ' |
| 41 | + '{0} > {1}'.format(ndims, naxes)) |
| 42 | + if ndims == naxes: |
| 43 | + return values |
| 44 | + |
| 45 | + ndim = set(xrange(ndims)) |
| 46 | + nax = set(xrange(naxes)) |
| 47 | + |
| 48 | + axes_slice = [slice(None)] * naxes |
| 49 | + |
| 50 | + # symmetric difference of numaxes and ndims |
| 51 | + slices = nax - ndim |
| 52 | + |
| 53 | + if ndims == naxes: |
| 54 | + if slices: |
| 55 | + raise AssertionError('slices should be empty if ndims == naxes ' |
| 56 | + '{0}'.format(slices)) |
| 57 | + else: |
| 58 | + if not slices: |
| 59 | + raise AssertionError('slices should NOT be empty if ndim != naxes ' |
| 60 | + '{0}'.format(slices)) |
| 61 | + |
| 62 | + for sl in slices: |
| 63 | + axes_slice[sl] = np.newaxis |
| 64 | + |
| 65 | + return values[tuple(axes_slice)] |
| 66 | + |
| 67 | + |
| 68 | +def _any_pandas_objects(terms): |
| 69 | + """Check a sequence of terms for instances of PandasObject.""" |
| 70 | + return any(com.is_pd_obj(term.value) for term in terms) |
| 71 | + |
| 72 | + |
| 73 | +def _filter_special_cases(f): |
| 74 | + @wraps(f) |
| 75 | + def wrapper(terms): |
| 76 | + # single unary operand |
| 77 | + if len(terms) == 1: |
| 78 | + return _align_core_single_unary_op(terms[0]) |
| 79 | + |
| 80 | + # only scalars |
| 81 | + elif all(term.isscalar for term in terms): |
| 82 | + return np.result_type(*(term.value for term in terms)), None |
| 83 | + |
| 84 | + # single element ndarrays |
| 85 | + all_has_size = all(hasattr(term.value, 'size') for term in terms) |
| 86 | + if (all_has_size and all(term.value.size == 1 for term in terms)): |
| 87 | + return np.result_type(*(term.value for term in terms)), None |
| 88 | + |
| 89 | + # no pandas so just punt to the evaluator |
| 90 | + if not _any_pandas_objects(terms): |
| 91 | + return np.result_type(*(term.value for term in terms)), None |
| 92 | + |
| 93 | + return f(terms) |
| 94 | + return wrapper |
| 95 | + |
| 96 | + |
| 97 | +@_filter_special_cases |
| 98 | +def _align_core(terms): |
| 99 | + term_index = [i for i, term in enumerate(terms) if hasattr(term.value, |
| 100 | + 'axes')] |
| 101 | + term_dims = [terms[i].value.ndim for i in term_index] |
| 102 | + ndims = pd.Series(dict(zip(term_index, term_dims))) |
| 103 | + |
| 104 | + # initial axes are the axes of the largest-axis'd term |
| 105 | + biggest = terms[ndims.idxmax()].value |
| 106 | + typ = biggest._constructor |
| 107 | + axes = biggest.axes |
| 108 | + naxes = len(axes) |
| 109 | + |
| 110 | + for term in (terms[i] for i in term_index): |
| 111 | + for axis, items in enumerate(term.value.axes): |
| 112 | + if com.is_series(term.value) and naxes > 1: |
| 113 | + ax, itm = naxes - 1, term.value.index |
| 114 | + else: |
| 115 | + ax, itm = axis, items |
| 116 | + axes[ax] = axes[ax].join(itm, how='outer') |
| 117 | + |
| 118 | + for i, ndim in ndims.iteritems(): |
| 119 | + for axis, items in izip(xrange(ndim), axes): |
| 120 | + ti = terms[i].value |
| 121 | + |
| 122 | + if hasattr(ti, 'reindex_axis'): |
| 123 | + transpose = com.is_series(ti) and naxes > 1 |
| 124 | + |
| 125 | + if transpose: |
| 126 | + f = partial(ti.reindex, index=axes[naxes - 1], copy=False) |
| 127 | + else: |
| 128 | + f = partial(ti.reindex_axis, items, axis=axis, copy=False) |
| 129 | + |
| 130 | + if pd.lib.is_bool_array(ti.values): |
| 131 | + r = f(fill_value=True) |
| 132 | + else: |
| 133 | + r = f() |
| 134 | + |
| 135 | + terms[i].update(r) |
| 136 | + |
| 137 | + res = _maybe_promote_shape(terms[i].value.T if transpose else |
| 138 | + terms[i].value, naxes) |
| 139 | + res = res.T if transpose else res |
| 140 | + |
| 141 | + try: |
| 142 | + v = res.values |
| 143 | + except AttributeError: |
| 144 | + v = res |
| 145 | + terms[i].update(v) |
| 146 | + |
| 147 | + return typ, _zip_axes_from_type(typ, axes) |
| 148 | + |
| 149 | + |
| 150 | +def _filter_terms(flat): |
| 151 | + # numeric literals |
| 152 | + literals = set(filter(is_const, flat)) |
| 153 | + |
| 154 | + # these are strings which are variable names |
| 155 | + names = set(flat) - literals |
| 156 | + |
| 157 | + # literals are not names and names are not literals, so intersection should |
| 158 | + # be empty |
| 159 | + if literals & names: |
| 160 | + raise ValueError('literals cannot be names and names cannot be ' |
| 161 | + 'literals') |
| 162 | + return names, literals |
| 163 | + |
| 164 | + |
| 165 | +def _align(terms, env): |
| 166 | + # flatten the parse tree (a nested list) |
| 167 | + terms = list(flatten(terms)) |
| 168 | + |
| 169 | + # separate names and literals |
| 170 | + names, literals = _filter_terms(terms) |
| 171 | + |
| 172 | + if not names: # only literals so just promote to a common type |
| 173 | + return np.result_type(*literals).type, None |
| 174 | + |
| 175 | + # if all resolved variables are numeric scalars |
| 176 | + if all(term.isscalar for term in terms): |
| 177 | + return np.result_type(*(term.value for term in terms)).type, None |
| 178 | + |
| 179 | + # perform the main alignment |
| 180 | + typ, axes = _align_core(terms) |
| 181 | + return typ, axes |
| 182 | + |
| 183 | + |
| 184 | +def _reconstruct_object(typ, obj, axes): |
| 185 | + """Reconstruct an object given its type, raw value, and possibly empty |
| 186 | + (None) axes. |
| 187 | +
|
| 188 | + Parameters |
| 189 | + ---------- |
| 190 | + typ : object |
| 191 | + A type |
| 192 | + obj : object |
| 193 | + The value to use in the type constructor |
| 194 | + axes : dict |
| 195 | + The axes to use to construct the resulting pandas object |
| 196 | +
|
| 197 | + Returns |
| 198 | + ------- |
| 199 | + reconst : typ |
| 200 | + An object of type ``typ`` with the value `obj` and possible axes |
| 201 | + `axes`. |
| 202 | + """ |
| 203 | + try: |
| 204 | + # handle numpy dtypes |
| 205 | + typ = typ.type |
| 206 | + except AttributeError: |
| 207 | + pass |
| 208 | + |
| 209 | + if (not isinstance(typ, partial) and |
| 210 | + issubclass(typ, pd.core.generic.PandasObject)): |
| 211 | + return typ(obj, **axes) |
| 212 | + |
| 213 | + ret_value = typ(obj) |
| 214 | + |
| 215 | + try: |
| 216 | + return ret_value.item() |
| 217 | + except (AttributeError, ValueError): |
| 218 | + return ret_value |
| 219 | + |
0 commit comments