|
11 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
| 14 | +from __future__ import annotations |
14 | 15 |
|
| 16 | +import dataclasses |
| 17 | +import inspect |
| 18 | +import typing |
| 19 | + |
| 20 | +import bigframes.core.expression as ex |
| 21 | +import bigframes.core.identifiers as ids |
| 22 | +import bigframes.dtypes as dtypes |
| 23 | +from bigframes._config import options |
15 | 24 | from bigframes.functions import Udf |
16 | 25 | from bigframes.functions.udf_def import BigqueryUdf, PythonUdf |
17 | | -from bigframes.operations import base_ops, remote_function_ops |
| 26 | +from bigframes.operations import remote_function_ops |
| 27 | + |
| 28 | + |
| 29 | +@dataclasses.dataclass(frozen=True) |
| 30 | +class ArgumentSpec: |
| 31 | + """ |
| 32 | + Information about a single argument to a function |
| 33 | + """ |
| 34 | + |
| 35 | + name: str |
| 36 | + default_value: typing.Any |
| 37 | + is_varargs: bool |
18 | 38 |
|
19 | 39 |
|
20 | | -def func_to_op(op) -> base_ops.NaryOp: |
| 40 | +@dataclasses.dataclass(frozen=True) |
| 41 | +class CallableExpression(ex.Expression): |
21 | 42 | """ |
22 | | - Convert various bigframes, python functions into bigframes operations. |
| 43 | + Encodes a calling convention and an expression to bind arguments to. |
| 44 | + """ |
| 45 | + |
| 46 | + expr: ex.Expression |
| 47 | + arg_specs: typing.Sequence[ArgumentSpec] |
| 48 | + |
| 49 | + @classmethod |
| 50 | + def from_callable( |
| 51 | + cls, func: typing.Callable, unpack_mode: bool = False |
| 52 | + ) -> CallableExpression: |
| 53 | + sig = inspect.signature(func) |
| 54 | + arg_specs = [] |
| 55 | + for name, param in sig.parameters.items(): |
| 56 | + is_varargs = param.kind == inspect.Parameter.VAR_POSITIONAL |
| 57 | + arg_specs.append( |
| 58 | + ArgumentSpec( |
| 59 | + name=name, |
| 60 | + default_value=param.default, |
| 61 | + is_varargs=is_varargs, |
| 62 | + ) |
| 63 | + ) |
| 64 | + |
| 65 | + from bigframes.core.bytecode import dis_to_expr |
| 66 | + |
| 67 | + expr = dis_to_expr(func, unpack_mode=unpack_mode) |
| 68 | + return cls(expr=expr, arg_specs=arg_specs) |
| 69 | + |
| 70 | + def apply(self, *args, **kwargs) -> ex.Expression: |
| 71 | + """ |
| 72 | + Apply the arguments to the expression. |
| 73 | +
|
| 74 | + All args are expected to be column references, or scalars. |
| 75 | + """ |
| 76 | + bindings = {} |
| 77 | + pos_idx = 0 |
| 78 | + |
| 79 | + def to_expr(val): |
| 80 | + if isinstance(val, ex.Expression): |
| 81 | + return val |
| 82 | + return ex.const(val) |
| 83 | + |
| 84 | + for spec in self.arg_specs: |
| 85 | + if spec.is_varargs: |
| 86 | + raise NotImplementedError( |
| 87 | + "varargs in compiled python functions is not supported" |
| 88 | + ) |
23 | 89 |
|
24 | | - This should handle anything that might be passed to eg map, combine, other pandas methods that take a function. |
| 90 | + if pos_idx < len(args): |
| 91 | + bindings[spec.name] = to_expr(args[pos_idx]) |
| 92 | + pos_idx += 1 |
| 93 | + elif spec.name in kwargs: |
| 94 | + bindings[spec.name] = to_expr(kwargs[spec.name]) |
| 95 | + elif spec.default_value is not inspect.Parameter.empty: |
| 96 | + bindings[spec.name] = to_expr(spec.default_value) |
| 97 | + else: |
| 98 | + raise TypeError(f"missing required argument: '{spec.name}'") |
25 | 99 |
|
26 | | - It should raise a TypeError if the object is not a supported type. |
| 100 | + if pos_idx < len(args): |
| 101 | + raise TypeError( |
| 102 | + f"too many positional arguments: expected {len(self.arg_specs)}, got {len(args)}" |
| 103 | + ) |
27 | 104 |
|
28 | | - Args: |
29 | | - op: The object to convert. |
| 105 | + return self.expr.bind_variables(bindings) |
30 | 106 |
|
31 | | - Returns: |
32 | | - A bigframes operations. |
| 107 | + @property |
| 108 | + def column_references(self) -> typing.Tuple[ids.ColumnId, ...]: |
| 109 | + return self.expr.column_references |
| 110 | + |
| 111 | + @property |
| 112 | + def free_variables(self) -> typing.Tuple[typing.Hashable, ...]: |
| 113 | + return self.expr.free_variables |
| 114 | + |
| 115 | + @property |
| 116 | + def is_const(self) -> bool: |
| 117 | + return self.expr.is_const |
| 118 | + |
| 119 | + @property |
| 120 | + def is_resolved(self) -> bool: |
| 121 | + return False |
| 122 | + |
| 123 | + @property |
| 124 | + def output_type(self) -> dtypes.ExpressionType: |
| 125 | + raise ValueError( |
| 126 | + "CallableExpression does not have a fixed output type until arguments are applied." |
| 127 | + ) |
| 128 | + |
| 129 | + def bind_refs( |
| 130 | + self, |
| 131 | + bindings: typing.Mapping[ids.ColumnId, ex.Expression], |
| 132 | + allow_partial_bindings: bool = False, |
| 133 | + ) -> CallableExpression: |
| 134 | + return dataclasses.replace( |
| 135 | + self, |
| 136 | + expr=self.expr.bind_refs( |
| 137 | + bindings, allow_partial_bindings=allow_partial_bindings |
| 138 | + ), |
| 139 | + ) |
| 140 | + |
| 141 | + def bind_variables( |
| 142 | + self, |
| 143 | + bindings: typing.Mapping[typing.Hashable, ex.Expression], |
| 144 | + allow_partial_bindings: bool = False, |
| 145 | + ) -> CallableExpression: |
| 146 | + arg_names = {spec.name for spec in self.arg_specs} |
| 147 | + filtered_bindings = {k: v for k, v in bindings.items() if k not in arg_names} |
| 148 | + return dataclasses.replace( |
| 149 | + self, |
| 150 | + expr=self.expr.bind_variables( |
| 151 | + filtered_bindings, allow_partial_bindings=allow_partial_bindings |
| 152 | + ), |
| 153 | + ) |
| 154 | + |
| 155 | + def transform_children( |
| 156 | + self, t: typing.Callable[[ex.Expression], ex.Expression] |
| 157 | + ) -> ex.Expression: |
| 158 | + new_expr = t(self.expr) |
| 159 | + if new_expr != self.expr: |
| 160 | + return dataclasses.replace(self, expr=new_expr) |
| 161 | + return self |
| 162 | + |
| 163 | + |
| 164 | +def func_to_expr(op, unpack_mode: bool = False) -> CallableExpression: |
| 165 | + """ |
| 166 | + Convert various bigframes, python functions into bigframes CallableExpression. |
33 | 167 | """ |
34 | | - # TODO(b/517578802): Handle numpy ufuncs, builtin functions, etc. |
35 | 168 | if isinstance(op, Udf): |
36 | 169 | if isinstance(op.udf_def, BigqueryUdf): |
37 | | - return remote_function_ops.RemoteFunctionOp(function_def=op.udf_def) |
| 170 | + bq_op = remote_function_ops.RemoteFunctionOp(function_def=op.udf_def) |
38 | 171 | elif isinstance(op.udf_def, PythonUdf): |
39 | | - return remote_function_ops.PythonUdfOp(function_def=op.udf_def) |
| 172 | + bq_op = remote_function_ops.PythonUdfOp(function_def=op.udf_def) |
| 173 | + else: |
| 174 | + raise TypeError(f"Unsupported UDF definition: {op.udf_def}") |
| 175 | + |
| 176 | + inputs_expr = tuple( |
| 177 | + ex.free_var(arg.name) for arg in op.udf_def.signature.inputs |
| 178 | + ) |
| 179 | + expr = ex.OpExpression(bq_op, inputs_expr) |
| 180 | + |
| 181 | + arg_specs = [ |
| 182 | + ArgumentSpec( |
| 183 | + name=arg.name, |
| 184 | + default_value=inspect.Parameter.empty, |
| 185 | + is_varargs=False, |
| 186 | + ) |
| 187 | + for arg in op.udf_def.signature.inputs |
| 188 | + ] |
| 189 | + return CallableExpression(expr=expr, arg_specs=arg_specs) |
| 190 | + |
| 191 | + elif options.experiments.enable_python_transpiler and callable(op): |
| 192 | + return CallableExpression.from_callable(op, unpack_mode=unpack_mode) |
| 193 | + |
40 | 194 | else: |
41 | 195 | raise TypeError(f"Unsupported function type: {op}") |
0 commit comments