|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2023 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Formatter for the formula.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import enum |
| 9 | + |
| 10 | +from ._formula_steps import ( |
| 11 | + Adder, |
| 12 | + Averager, |
| 13 | + Clipper, |
| 14 | + ConstantValue, |
| 15 | + Divider, |
| 16 | + FormulaStep, |
| 17 | + Maximizer, |
| 18 | + MetricFetcher, |
| 19 | + Minimizer, |
| 20 | + Multiplier, |
| 21 | + OpenParen, |
| 22 | + Subtractor, |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +class OperatorPrecedence(enum.Enum): |
| 27 | + """The precedence of an operator.""" |
| 28 | + |
| 29 | + SUBTRACTION = 1 |
| 30 | + ADDITION = 2 |
| 31 | + DIVISION = 3 |
| 32 | + MULTIPLICATION = 4 |
| 33 | + PRIMARY = 9 |
| 34 | + |
| 35 | + def __lt__(self, other: OperatorPrecedence) -> bool: |
| 36 | + """Test the precedence of this operator is less than the precedence of the other operator. |
| 37 | +
|
| 38 | + Args: |
| 39 | + other: The other operator (on the right-hand side). |
| 40 | +
|
| 41 | + Returns: |
| 42 | + Whether the precedence of this operator is less than the other operator. |
| 43 | + """ |
| 44 | + return self.value < other.value |
| 45 | + |
| 46 | + def __str__(self) -> str: |
| 47 | + """Return the string representation of the operator precedence. |
| 48 | +
|
| 49 | + Returns: |
| 50 | + The string representation of the operator precedence. |
| 51 | + """ |
| 52 | + match self: |
| 53 | + case OperatorPrecedence.SUBTRACTION: |
| 54 | + return "-" |
| 55 | + case OperatorPrecedence.ADDITION: |
| 56 | + return "+" |
| 57 | + case OperatorPrecedence.DIVISION: |
| 58 | + return "/" |
| 59 | + case OperatorPrecedence.MULTIPLICATION: |
| 60 | + return "*" |
| 61 | + case OperatorPrecedence.PRIMARY: |
| 62 | + return "primary" |
| 63 | + |
| 64 | + |
| 65 | +class StackItem: |
| 66 | + """Stack item for the formula formatter.""" |
| 67 | + |
| 68 | + def __init__(self, value: str, precedence: OperatorPrecedence): |
| 69 | + """Initialize the StackItem. |
| 70 | +
|
| 71 | + Args: |
| 72 | + value: The value of the stack item. |
| 73 | + precedence: The precedence of the stack item. |
| 74 | + """ |
| 75 | + self.value = value |
| 76 | + self.precedence = precedence |
| 77 | + |
| 78 | + def __str__(self) -> str: |
| 79 | + """Return the string representation of the stack item. |
| 80 | +
|
| 81 | + This is used for debugging purposes. |
| 82 | +
|
| 83 | + Returns: |
| 84 | + str: The string representation of the stack item. |
| 85 | + """ |
| 86 | + return f'("{self.value}", {self.precedence})' |
| 87 | + |
| 88 | + def as_left_value(self, outer_precedence: OperatorPrecedence) -> str: |
| 89 | + """Return the value of the stack item with parentheses if necessary. |
| 90 | +
|
| 91 | + Args: |
| 92 | + outer_precedence: The precedence of the outer stack item. |
| 93 | +
|
| 94 | + Returns: |
| 95 | + str: The value of the stack item with parentheses if necessary. |
| 96 | + """ |
| 97 | + return f"({self.value})" if self.precedence < outer_precedence else self.value |
| 98 | + |
| 99 | + def as_right_value(self, outer_precedence: OperatorPrecedence) -> str: |
| 100 | + """Return the value of the stack item with parentheses if necessary. |
| 101 | +
|
| 102 | + Args: |
| 103 | + outer_precedence: The precedence of the outer stack item. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + str: The value of the stack item with parentheses if necessary. |
| 107 | + """ |
| 108 | + return f"({self.value})" if self.precedence < outer_precedence else self.value |
| 109 | + |
| 110 | + @staticmethod |
| 111 | + def create_binary( |
| 112 | + lhs: StackItem, operator: OperatorPrecedence, rhs: StackItem |
| 113 | + ) -> StackItem: |
| 114 | + """Create a binary stack item. |
| 115 | +
|
| 116 | + Args: |
| 117 | + lhs: The left-hand side of the binary operation. |
| 118 | + operator: The operator of the binary operation. |
| 119 | + rhs: The right-hand side of the binary operation. |
| 120 | +
|
| 121 | + Returns: |
| 122 | + StackItem: The binary stack item. |
| 123 | + """ |
| 124 | + pred = OperatorPrecedence(operator) |
| 125 | + return StackItem( |
| 126 | + f"{lhs.as_left_value(pred)} {operator} {rhs.as_right_value(pred)}", |
| 127 | + pred, |
| 128 | + ) |
| 129 | + |
| 130 | + @staticmethod |
| 131 | + def create_primary(value: float) -> StackItem: |
| 132 | + """Create a stack item for literal values or function calls (primary expressions). |
| 133 | +
|
| 134 | + Args: |
| 135 | + value: The value of the literal. |
| 136 | +
|
| 137 | + Returns: |
| 138 | + StackItem: The literal stack item. |
| 139 | + """ |
| 140 | + return StackItem(str(value), OperatorPrecedence.PRIMARY) |
| 141 | + |
| 142 | + |
| 143 | +class FormulaFormatter: |
| 144 | + """Formats a formula into a human readable string in infix-notation.""" |
| 145 | + |
| 146 | + def __init__(self) -> None: |
| 147 | + """Initialize the FormulaFormatter.""" |
| 148 | + self._stack = list[StackItem]() |
| 149 | + |
| 150 | + @classmethod |
| 151 | + def format(cls, postfix_expr: list[FormulaStep]) -> str: |
| 152 | + """Return the formula as a string in infix notation. |
| 153 | +
|
| 154 | + Args: |
| 155 | + postfix_expr: The steps of the formula in postfix notation order. |
| 156 | +
|
| 157 | + Returns: |
| 158 | + str: The formula in infix notation. |
| 159 | + """ |
| 160 | + formatter = FormulaFormatter() |
| 161 | + return formatter._format(postfix_expr) |
| 162 | + |
| 163 | + def _format(self, postfix_expr: list[FormulaStep]) -> str: |
| 164 | + """Format the postfix expression to infix notation. |
| 165 | +
|
| 166 | + Args: |
| 167 | + postfix_expr: The steps of the formula in postfix notation order. |
| 168 | +
|
| 169 | + Returns: |
| 170 | + str: The formula in infix notation. |
| 171 | + """ |
| 172 | + for step in postfix_expr: |
| 173 | + match step: |
| 174 | + case ConstantValue(): |
| 175 | + self._stack.append(StackItem.create_primary(step.value)) |
| 176 | + case Adder(): |
| 177 | + self._format_binary(OperatorPrecedence.ADDITION) |
| 178 | + case Subtractor(): |
| 179 | + self._format_binary(OperatorPrecedence.SUBTRACTION) |
| 180 | + case Multiplier(): |
| 181 | + self._format_binary(OperatorPrecedence.MULTIPLICATION) |
| 182 | + case Divider(): |
| 183 | + self._format_binary(OperatorPrecedence.DIVISION) |
| 184 | + case Averager(): |
| 185 | + value = ( |
| 186 | + # pylint: disable=protected-access |
| 187 | + f"avg({', '.join(self._format([f]) for f in step.fetchers)})" |
| 188 | + ) |
| 189 | + self._stack.append(StackItem(value, OperatorPrecedence.PRIMARY)) |
| 190 | + case Clipper(): |
| 191 | + the_value = self._stack.pop() |
| 192 | + min_value = step.min_value if step.min_value is not None else "-inf" |
| 193 | + max_value = step.max_value if step.max_value is not None else "inf" |
| 194 | + value = f"clip({min_value}, {the_value.value}, {max_value})" |
| 195 | + self._stack.append(StackItem(value, OperatorPrecedence.PRIMARY)) |
| 196 | + case Maximizer(): |
| 197 | + left, right = self._pop_two_from_stack() |
| 198 | + value = f"max({left.value}, {right.value})" |
| 199 | + self._stack.append(StackItem(value, OperatorPrecedence.PRIMARY)) |
| 200 | + case Minimizer(): |
| 201 | + left, right = self._pop_two_from_stack() |
| 202 | + value = f"min({left.value}, {right.value})" |
| 203 | + self._stack.append(StackItem(value, OperatorPrecedence.PRIMARY)) |
| 204 | + case MetricFetcher(): |
| 205 | + metric_fetcher = step |
| 206 | + if engine_reference := getattr( |
| 207 | + metric_fetcher.stream, "_engine_reference", None |
| 208 | + ): |
| 209 | + value = str(engine_reference) |
| 210 | + else: |
| 211 | + value = metric_fetcher._name # pylint: disable=protected-access |
| 212 | + self._stack.append(StackItem(value, OperatorPrecedence.PRIMARY)) |
| 213 | + case OpenParen(): |
| 214 | + pass # We gently ignore this one. |
| 215 | + |
| 216 | + assert len(self._stack) == 1 |
| 217 | + return self._stack[0].value |
| 218 | + |
| 219 | + def _format_binary(self, operator: OperatorPrecedence) -> None: |
| 220 | + """Format a binary operation. |
| 221 | +
|
| 222 | + Pops the arguments of the binary expression from the stack |
| 223 | + and pushes the string representation of the binary operation to the stack. |
| 224 | +
|
| 225 | + Args: |
| 226 | + operator: The operator of the binary operation. |
| 227 | + """ |
| 228 | + left, right = self._pop_two_from_stack() |
| 229 | + self._stack.append(StackItem.create_binary(left, operator, right)) |
| 230 | + |
| 231 | + def _pop_two_from_stack(self) -> tuple[StackItem, StackItem]: |
| 232 | + """Pop two items from the stack. |
| 233 | +
|
| 234 | + Returns: |
| 235 | + The two items popped from the stack. |
| 236 | + """ |
| 237 | + right = self._stack.pop() |
| 238 | + left = self._stack.pop() |
| 239 | + return left, right |
0 commit comments