1"""
2Core eval alignment algorithms.
3"""
4from __future__ import annotations
5
6from functools import (
7 partial,
8 wraps,
9)
10from typing import (
11 TYPE_CHECKING,
12 Callable,
13 Sequence,
14)
15import warnings
16
17import numpy as np
18
19from pandas.errors import PerformanceWarning
20from pandas.util._exceptions import find_stack_level
21
22from pandas.core.dtypes.generic import (
23 ABCDataFrame,
24 ABCSeries,
25)
26
27from pandas.core.base import PandasObject
28import pandas.core.common as com
29from pandas.core.computation.common import result_type_many
30
31if TYPE_CHECKING:
32 from pandas._typing import F
33
34 from pandas.core.generic import NDFrame
35 from pandas.core.indexes.api import Index
36
37
38def _align_core_single_unary_op(
39 term,
40) -> tuple[partial | type[NDFrame], dict[str, Index] | None]:
41 typ: partial | type[NDFrame]
42 axes: dict[str, Index] | None = None
43
44 if isinstance(term.value, np.ndarray):
45 typ = partial(np.asanyarray, dtype=term.value.dtype)
46 else:
47 typ = type(term.value)
48 if hasattr(term.value, "axes"):
49 axes = _zip_axes_from_type(typ, term.value.axes)
50
51 return typ, axes
52
53
54def _zip_axes_from_type(
55 typ: type[NDFrame], new_axes: Sequence[Index]
56) -> dict[str, Index]:
57 return {name: new_axes[i] for i, name in enumerate(typ._AXIS_ORDERS)}
58
59
60def _any_pandas_objects(terms) -> bool:
61 """
62 Check a sequence of terms for instances of PandasObject.
63 """
64 return any(isinstance(term.value, PandasObject) for term in terms)
65
66
67def _filter_special_cases(f) -> Callable[[F], F]:
68 @wraps(f)
69 def wrapper(terms):
70 # single unary operand
71 if len(terms) == 1:
72 return _align_core_single_unary_op(terms[0])
73
74 term_values = (term.value for term in terms)
75
76 # we don't have any pandas objects
77 if not _any_pandas_objects(terms):
78 return result_type_many(*term_values), None
79
80 return f(terms)
81
82 return wrapper
83
84
85@_filter_special_cases
86def _align_core(terms):
87 term_index = [i for i, term in enumerate(terms) if hasattr(term.value, "axes")]
88 term_dims = [terms[i].value.ndim for i in term_index]
89
90 from pandas import Series
91
92 ndims = Series(dict(zip(term_index, term_dims)))
93
94 # initial axes are the axes of the largest-axis'd term
95 biggest = terms[ndims.idxmax()].value
96 typ = biggest._constructor
97 axes = biggest.axes
98 naxes = len(axes)
99 gt_than_one_axis = naxes > 1
100
101 for value in (terms[i].value for i in term_index):
102 is_series = isinstance(value, ABCSeries)
103 is_series_and_gt_one_axis = is_series and gt_than_one_axis
104
105 for axis, items in enumerate(value.axes):
106 if is_series_and_gt_one_axis:
107 ax, itm = naxes - 1, value.index
108 else:
109 ax, itm = axis, items
110
111 if not axes[ax].is_(itm):
112 axes[ax] = axes[ax].join(itm, how="outer")
113
114 for i, ndim in ndims.items():
115 for axis, items in zip(range(ndim), axes):
116 ti = terms[i].value
117
118 if hasattr(ti, "reindex"):
119 transpose = isinstance(ti, ABCSeries) and naxes > 1
120 reindexer = axes[naxes - 1] if transpose else items
121
122 term_axis_size = len(ti.axes[axis])
123 reindexer_size = len(reindexer)
124
125 ordm = np.log10(max(1, abs(reindexer_size - term_axis_size)))
126 if ordm >= 1 and reindexer_size >= 10000:
127 w = (
128 f"Alignment difference on axis {axis} is larger "
129 f"than an order of magnitude on term {repr(terms[i].name)}, "
130 f"by more than {ordm:.4g}; performance may suffer."
131 )
132 warnings.warn(
133 w, category=PerformanceWarning, stacklevel=find_stack_level()
134 )
135
136 f = partial(ti.reindex, reindexer, axis=axis, copy=False)
137
138 terms[i].update(f())
139
140 terms[i].update(terms[i].value.values)
141
142 return typ, _zip_axes_from_type(typ, axes)
143
144
145def align_terms(terms):
146 """
147 Align a set of terms.
148 """
149 try:
150 # flatten the parse tree (a nested list, really)
151 terms = list(com.flatten(terms))
152 except TypeError:
153 # can't iterate so it must just be a constant or single variable
154 if isinstance(terms.value, (ABCSeries, ABCDataFrame)):
155 typ = type(terms.value)
156 return typ, _zip_axes_from_type(typ, terms.value.axes)
157 return np.result_type(terms.type), None
158
159 # if all resolved variables are numeric scalars
160 if all(term.is_scalar for term in terms):
161 return result_type_many(*(term.value for term in terms)).type, None
162
163 # perform the main alignment
164 typ, axes = _align_core(terms)
165 return typ, axes
166
167
168def reconstruct_object(typ, obj, axes, dtype):
169 """
170 Reconstruct an object given its type, raw value, and possibly empty
171 (None) axes.
172
173 Parameters
174 ----------
175 typ : object
176 A type
177 obj : object
178 The value to use in the type constructor
179 axes : dict
180 The axes to use to construct the resulting pandas object
181
182 Returns
183 -------
184 ret : typ
185 An object of type ``typ`` with the value `obj` and possible axes
186 `axes`.
187 """
188 try:
189 typ = typ.type
190 except AttributeError:
191 pass
192
193 res_t = np.result_type(obj.dtype, dtype)
194
195 if not isinstance(typ, partial) and issubclass(typ, PandasObject):
196 return typ(obj, dtype=res_t, **axes)
197
198 # special case for pathological things like ~True/~False
199 if hasattr(res_t, "type") and typ == np.bool_ and res_t != np.bool_:
200 ret_value = res_t.type(obj)
201 else:
202 ret_value = typ(obj).astype(res_t)
203 # The condition is to distinguish 0-dim array (returned in case of
204 # scalar) and 1 element array
205 # e.g. np.array(0) and np.array([0])
206 if (
207 len(obj.shape) == 1
208 and len(obj) == 1
209 and not isinstance(ret_value, np.ndarray)
210 ):
211 ret_value = np.array([ret_value]).astype(res_t)
212
213 return ret_value