This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9646-6eab74829f6074da64ca36bc45db050d4b434597 in repository https://gitbox.apache.org/repos/asf/texera.git
commit e5192c16fbb7d45fb6fbc8ce92c862fbf0902d27 Author: Xinyuan Lin <[email protected]> AuthorDate: Wed Nov 25 08:58:16 2026 +0000 refactor(workflow-operator): share chart Python codegen (#9646) ### What changes were proposed in this PR? Share duplicated runtime (`generatePythonCode`) and standalone (`generateStandaloneCode`) Plotly Python code generation across four visualization operators in `common/workflow-operator` (`4` files, `+370/-574`, `-204` net lines): | File | Shared codegen | Net LOC | | --- | --- | ---: | | `NetworkGraphOpDesc.scala` | Extracts `NetworkGraphPython.body(indent)` for graph construction, seeded `spring_layout`, edge/node traces, and figure layout | `+107/-181` (-74) | | `BulletChartOpDesc.scala` | Extracts `deltaReferenceLiteral`, `thresholdLiteral`, `stepsLiteral`, and `BulletChartPython` (`helperDefs`, `stepsListBody`, `figureBody`) | `+97/-139` (-42) | | `TreePlotOpDesc.scala` | Extracts `TreePlotPython.annotationsBody`, `parseEdges`, and `figureBody` (reusing `PythonCodeFragment.render`) | `+94/-135` (-41) | | `ContinuousErrorBandsOpDesc.scala` | Extracts `buildFigure(tableVar, render, indent)`, a plain `s"..."` template whose `EncodableString => String` callback writes each typed-in value as a decode expression in the operator and a `pyStringLiteral` in the exported script | `+72/-119` (-47) | It also adds `RuntimeStandaloneParitySpec` (`+481`), tagged `NeedsPythonPackages`, which runs both paths of all four charts over the same tables (see below). Notes for reviewers: - Runtime `pyb` base64 encoding (`self.decode_python_template(...)`) and standalone `pyStringLiteral` escaping are preserved unchanged. - No existing operator tests were modified; all user-facing behavior and error messages remain identical. That includes the step error `BulletChartPython.helperDefs` writes, which reads `≥` in the operator and `>=` in the exported script, as on `main`. - `ContinuousErrorBandsOpDesc.createPlotlyFigure()` returns the figure already rendered in the operator's dialect, so its `.plain` now shows decode expressions too. Only `ContinuousErrorBandsOpDescSpec` reads that `.plain`, through `carries`, which accepts either form. ### Any related issues, documentation, discussions? Closes #9645 ### How was this PR tested? Verified on `a234e15d0d` (based on `origin/main` `95e2748b97`) with JDK 17 (Corretto 17.0.20.1), `sbt 1.12.9`, and Python 3.12.7 (`pandas 2.2.3`, `plotly 5.24.1`, `networkx 3.5`): ```bash sbt "WorkflowOperator/scalafixAll --check" "WorkflowOperator/scalafmtCheckAll" UDF_PYTHON_PATH=/path/to/python3.12 sbt \ "WorkflowOperator/testOnly *RuntimeStandaloneParitySpec *NetworkGraphOpDescSpec *BulletChartOpDescSpec *TreePlotOpDescSpec *ContinuousErrorBandsOpDescSpec *ColorPatternSpec *GaugeChartOpDescSpec *PythonCodeRawInvalidTextSpec" \ "WorkflowCompilingService/testOnly *WorkflowToPythonTranslatorSpec" ``` - **Lint / format:** `WorkflowOperator/scalafixAll --check` and `WorkflowOperator/scalafmtCheckAll` exit `0`. - **Unit tests:** - `WorkflowOperator`: `8` suites, `122` cases (`121` passed, `1` pre-existing `pendingUntilFixed` in `BulletChartOpDescSpec`, `0` failed, `0` canceled). `PythonCodeRawInvalidTextSpec` reports raw-invalid `118/118` and py-compile `118/118`. - `WorkflowCompilingService`: `WorkflowToPythonTranslatorSpec` `19/19` passed. - **Runtime/standalone parity:** `RuntimeStandaloneParitySpec` runs the operator code (pytexera stubbed, as in `TreePlotOpDescSpec`) and the exported script (placeholders bound, as in `GaugeChartOpDescSpec`) of all four charts. Each of its `10` cases expects the same figures, or the same refusal reason, from both paths and pins what they draw. Each chart has settings whose text carries a quote. - It passes unchanged with `main`'s four operator sources swapped in, so it pins the behavior this refactor preserves. - It fails when `dest_col` is left unbound in the Network Graph operator, when `edge_col` is left unbound in the Tree Plot export, and when the error band's upper and lower bounds are swapped in both paths. - After the second review, `662837bff4` gates the run on pandas and plotly only, since only the Network Graph code imports networkx, inside each path's `try`. With networkx hidden, the two Network Graph cases fail on the `ImportError` and the other eight pass. Its `source` now carries a quote too, and a `sourceLit` built without escaping fails the same two cases. `Test/scalafmtCheck` and `Test/scalafix --check` pass, and the spec passes 10/10 with none canceled. - **Generated code:** the review-round changes to `BulletChartOpDesc` and `ContinuousErrorBandsOpDesc` leave the operator code and the exported script byte-identical to `cd3fc253ee`, including settings with quotes, `|`, newlines and backslashes. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Antigravity Generated-by: Claude Code (Opus 5.5) --------- Co-authored-by: Claude Opus 5.5 <[email protected]> --- .../bulletChart/BulletChartOpDesc.scala | 236 +++++----- .../ContinuousErrorBandsOpDesc.scala | 191 +++----- .../networkGraph/NetworkGraphOpDesc.scala | 288 +++++------- .../visualization/treeplot/TreePlotOpDesc.scala | 229 ++++------ .../RuntimeStandaloneParitySpec.scala | 483 +++++++++++++++++++++ 5 files changed, 853 insertions(+), 574 deletions(-) diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala index cdc26d952b..e877c00faf 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala @@ -94,21 +94,21 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC assert(deltaReference.nonEmpty) } - override def generatePythonCode(): String = { - // The reference keeps the 0 the generated code used to fall back to; an unset - // threshold stays absent as None. - val deltaReferenceExpr: PythonLiteral = deltaReference.getOrElse(0.0).toString - val thresholdExpr: PythonLiteral = thresholdValue.map(_.toString).getOrElse("None") + // The reference keeps the 0 the generated code used to fall back to; an unset + // threshold stays absent as None. + private def deltaReferenceLiteral: PythonLiteral = deltaReference.getOrElse(0.0).toString + private def thresholdLiteral: PythonLiteral = thresholdValue.map(_.toString).getOrElse("None") - // The steps whose bounds are both filled in, as a list literal of numbers. - val stepsExpr: PythonLiteral = - Option(steps) - .map(_.asScala.toSeq) - .getOrElse(Seq.empty) - .flatMap(step => step.start.zip(step.end)) - .map { case (start, end) => s"""{"start": $start, "end": $end}""" } - .mkString("[", ", ", "]") + // The steps whose bounds are both filled in, as a list literal of numbers. + private def stepsLiteral: PythonLiteral = + Option(steps) + .map(_.asScala.toSeq) + .getOrElse(Seq.empty) + .flatMap(step => step.start.zip(step.end)) + .map { case (start, end) => s"""{"start": $start, "end": $end}""" } + .mkString("[", ", ", "]") + override def generatePythonCode(): String = { val finalCode = pyb""" |from pytexera import * @@ -127,26 +127,7 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC )} | | # Generate a list of grayscale HSL colors with decreasing brightness - | def generate_gray_gradient(self, step_count): - | colors = [] - | for i in range(step_count): - | lightness = 90 - (i * (60 / max(1, step_count - 1))) - | colors.append(f"hsl(0, 0%, {lightness}%)") - | return colors - | - | # Validate user-provided step definitions - | def generate_valid_steps(self, steps_data): - | valid_steps = [] - | self.step_errors = [] - | - | for index, step in enumerate(steps_data): - | s_val = step["start"] - | e_val = step["end"] - | if s_val < e_val: - | valid_steps.append({"start": s_val, "end": e_val}) - | else: - | self.step_errors.append(f"Step {index + 1}: start ≥ end ({s_val} ≥ {e_val})") - | return valid_steps + |${BulletChartPython.helperDefs(4, isMethod = true)} | | @overrides | def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: @@ -154,7 +135,7 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC | | try: | value_col = $value - | delta_ref = $deltaReferenceExpr + | delta_ref = $deltaReferenceLiteral | | if value_col not in table.columns: | yield {'html-content': self.render_error(f"Column '{value_col}' not found in input table.")} @@ -167,17 +148,11 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC bodyIndent = 4 )} | - | threshold_val = $thresholdExpr + | threshold_val = $thresholdLiteral | - | valid_steps = self.generate_valid_steps($stepsExpr) + | valid_steps = self.generate_valid_steps($stepsLiteral) | step_colors = self.generate_gray_gradient(len(valid_steps)) - | steps_list = [] - | for index, step_data in enumerate(valid_steps): - | color = step_colors[index] - | steps_list.append({ - | "range": [step_data["start"], step_data["end"]], - | "color": color - | }) + |${BulletChartPython.stepsListBody(12)} | | # Iterate through up to 10 rows of the input table | count = 0 @@ -186,41 +161,7 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC | if count >= 10: # Limit to 10 charts | break | try: - | actual = float(row[value_col]) - | ref = delta_ref - | - | # Construct gauge configuration - | gauge_config = {'shape': 'bullet'} - | if steps_list: - | gauge_config['steps'] = steps_list - | - | max_range_values = [actual, ref] - | if threshold_val is not None: - | max_range_values.append(threshold_val) - | - | if steps_list: - | for r in steps_list: - | max_range_values.append(r["range"][1]) - | - | gauge_config['axis'] = {"range": [0, max(max_range_values) * 1.2]} - | - | if threshold_val is not None: - | gauge_config["threshold"] = { - | "value": threshold_val, - | "line": {"color": "red", "width": 2}, - | "thickness": 1 - | } - | - | fig = go.Figure(go.Indicator( - | mode="number+gauge+delta", - | value=actual, - | delta={"reference": ref}, - | gauge=gauge_config, - | domain={"x": [0.1, 1], "y": [0.1, 0.9]}, - | title={"text": value_col} - | )) - | - | fig.update_layout(margin=dict(l=80, r=20, b=40, t=40), height=150) + |${BulletChartPython.figureBody(20)} | html_chunk = pio.to_html(fig, include_plotlyjs='cdn', auto_play=False) | | # Add step error @@ -251,15 +192,6 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC // the same as the runtime path, so the two scripts agree without either of them // parsing anything. val valueLit = pyStringLiteral(value) - val deltaReferenceExpr = deltaReference.getOrElse(0.0).toString - val thresholdExpr = thresholdValue.map(_.toString).getOrElse("None") - val stepsExpr = - Option(steps) - .map(_.asScala.toSeq) - .getOrElse(Seq.empty) - .flatMap(step => step.start.zip(step.end)) - .map { case (start, end) => s"""{"start": $start, "end": $end}""" } - .mkString("[", ", ", "]") // render_error's continuation line keeps the runtime path's indentation — the // HTML is triple-quoted, so those spaces reach the browser. The JSON holds one chart @@ -268,31 +200,14 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC | return '''<h1>Bullet chart is not available.</h1> | <p>Reason: {} </p>'''.format(error_msg) | - |def generate_gray_gradient(step_count): - | colors = [] - | for i in range(step_count): - | lightness = 90 - (i * (60 / max(1, step_count - 1))) - | colors.append(f"hsl(0, 0%, {lightness}%)") - | return colors - | - |def generate_valid_steps(steps_data): - | valid_steps = [] - | step_errors = [] - | for index, step in enumerate(steps_data): - | s_val = step["start"] - | e_val = step["end"] - | if s_val < e_val: - | valid_steps.append({"start": s_val, "end": e_val}) - | else: - | step_errors.append(f"Step {index + 1}: start >= end ({s_val} >= {e_val})") - | return valid_steps, step_errors + |${BulletChartPython.helperDefs(0, isMethod = false)} | |if in1df.empty: |${standaloneErrorPage("Input table is empty.")} |else: | try: | value_col = $valueLit - | delta_ref = $deltaReferenceExpr + | delta_ref = $deltaReferenceLiteral | if value_col not in in1df.columns: | with open(outputHtml, "w", encoding="utf-8") as output: | output.write(render_error(f"Column '{value_col}' not found in input table.")) @@ -301,44 +216,15 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC | if table.empty: |${standaloneErrorPage("No valid data rows found after dropping nulls.", indent = 16)} | else: - | threshold_val = $thresholdExpr - | valid_steps, step_errors = generate_valid_steps($stepsExpr) + | threshold_val = $thresholdLiteral + | valid_steps, step_errors = generate_valid_steps($stepsLiteral) | step_colors = generate_gray_gradient(len(valid_steps)) - | steps_list = [] - | for index, step_data in enumerate(valid_steps): - | steps_list.append({ - | "range": [step_data["start"], step_data["end"]], - | "color": step_colors[index] - | }) + |${BulletChartPython.stepsListBody(16)} | html_chunks = [] | figs = [] | for _, row in table.head(10).iterrows(): | try: - | actual = float(row[value_col]) - | gauge_config = {'shape': 'bullet'} - | if steps_list: - | gauge_config['steps'] = steps_list - | max_range_values = [actual, delta_ref] - | if threshold_val is not None: - | max_range_values.append(threshold_val) - | for r in steps_list: - | max_range_values.append(r["range"][1]) - | gauge_config['axis'] = {"range": [0, max(max_range_values) * 1.2]} - | if threshold_val is not None: - | gauge_config["threshold"] = { - | "value": threshold_val, - | "line": {"color": "red", "width": 2}, - | "thickness": 1 - | } - | fig = go.Figure(go.Indicator( - | mode="number+gauge+delta", - | value=actual, - | delta={"reference": delta_ref}, - | gauge=gauge_config, - | domain={"x": [0.1, 1], "y": [0.1, 0.9]}, - | title={"text": value_col} - | )) - | fig.update_layout(margin=dict(l=80, r=20, b=40, t=40), height=150) + |${BulletChartPython.figureBody(24)} | figs.append(fig) | html_chunk = plotly.io.to_html(fig, include_plotlyjs='cdn', auto_play=False) | if step_errors: @@ -360,3 +246,75 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneC | output.write(render_error(f"General error: {str(e)}"))""".stripMargin } } + +private object BulletChartPython { + def helperDefs(indent: Int, isMethod: Boolean): String = { + // Not only structure: the step error a user reads says ≥ in the operator and >= + // in the exported script, as each always has, and the two stay apart on purpose. + val (selfParam, errorsVar, cmp, retStmt) = + if (isMethod) ("self, ", "self.step_errors", "≥", "return valid_steps") + else ("", "step_errors", ">=", "return valid_steps, step_errors") + render( + s"""|def generate_gray_gradient(${selfParam}step_count): + | colors = [] + | for i in range(step_count): + | lightness = 90 - (i * (60 / max(1, step_count - 1))) + | colors.append(f"hsl(0, 0%, {lightness}%)") + | return colors + | + |def generate_valid_steps(${selfParam}steps_data): + | valid_steps = [] + | $errorsVar = [] + | for index, step in enumerate(steps_data): + | s_val = step["start"] + | e_val = step["end"] + | if s_val < e_val: + | valid_steps.append({"start": s_val, "end": e_val}) + | else: + | $errorsVar.append(f"Step {index + 1}: start $cmp end ({s_val} $cmp {e_val})") + | $retStmt""", + indent + ) + } + + def stepsListBody(indent: Int): String = + render( + """|steps_list = [] + |for index, step_data in enumerate(valid_steps): + | steps_list.append({ + | "range": [step_data["start"], step_data["end"]], + | "color": step_colors[index] + | })""", + indent + ) + + def figureBody(indent: Int): String = + render( + """|actual = float(row[value_col]) + |gauge_config = {'shape': 'bullet'} + |if steps_list: + | gauge_config['steps'] = steps_list + |max_range_values = [actual, delta_ref] + |if threshold_val is not None: + | max_range_values.append(threshold_val) + |for r in steps_list: + | max_range_values.append(r["range"][1]) + |gauge_config['axis'] = {"range": [0, max(max_range_values) * 1.2]} + |if threshold_val is not None: + | gauge_config["threshold"] = { + | "value": threshold_val, + | "line": {"color": "red", "width": 2}, + | "thickness": 1 + | } + |fig = go.Figure(go.Indicator( + | mode="number+gauge+delta", + | value=actual, + | delta={"reference": delta_ref}, + | gauge=gauge_config, + | domain={"x": [0.1, 1], "y": [0.1, 0.9]}, + | title={"text": value_col} + |)) + |fig.update_layout(margin=dict(l=80, r=20, b=40, t=40), height=150)""", + indent + ) +} diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala index 2521744ece..3d82d92818 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala @@ -59,65 +59,75 @@ class ContinuousErrorBandsOpDesc extends PythonVisualizationOpDesc with PlotlySt OperatorGroupConstants.VISUALIZATION_STATISTICAL_GROUP ) - def createPlotlyFigure(): PythonTemplateBuilder = { - assert(bands != null && !bands.isEmpty, "Bands cannot be empty") - val bandsPart = bands.asScala + /** The figure both paths draw. `render` writes one value typed into a setting in + * the caller's dialect: a decode expression for the operator, an escaped literal + * for the exported script. + * + * Plain `s` text rather than `pyb`, so that a value spliced in without `render` + * reaches both paths raw, where PythonCodeRawInvalidTextSpec catches it in the + * operator. Under `pyb` it would still be encoded in the operator and pass that + * check, but reach the exported script unquoted. + */ + private def buildFigure( + tableVar: String, + render: EncodableString => String, + indent: Int + ): String = { + val pad = " " * indent + val traces = bands.asScala .map { bandConf => - val colorPart = if (bandConf.color != "") { - pyb"line={'color':${bandConf.color}}, marker={'color':${bandConf.color}}, " - } else { - "" - } - - val fillColorPart = if (bandConf.fillColor != "") { - pyb"fillcolor=${bandConf.fillColor}, " - } else { - "" - } - - val namePart = if (bandConf.name != "") { - pyb"name=${bandConf.name}" - } else { - pyb"name=${bandConf.yValue}" - } - - pyb"""fig.add_trace(go.Scatter( - x=table[${bandConf.xValue}], - y=table[${bandConf.yUpper}], - mode='lines', - marker=dict(color="#444"), - line=dict(width=0), - showlegend=False, - $namePart - )) - fig.add_trace(go.Scatter( - x=table[${bandConf.xValue}], - y=table[${bandConf.yLower}], - mode='lines', - marker=dict(color="#444"), - line=dict(width=0), - fill='tonexty', - showlegend=False, - $fillColorPart - $namePart - )) - fig.add_trace(go.Scatter( - x=table[${bandConf.xValue}], - y=table[${bandConf.yValue}], - mode='${bandConf.mode.getModeInPlotly}', - $colorPart - $namePart - ))""" + val x = render(bandConf.xValue) + val name = render(if (bandConf.name != "") bandConf.name else bandConf.yValue) + val colorPart = + if (bandConf.color != "") { + val color = render(bandConf.color) + s"line={'color': $color}, marker={'color': $color}, " + } else "" + val fillColorPart = + if (bandConf.fillColor != "") s"fillcolor=${render(bandConf.fillColor)}, " else "" + s"""${pad}fig.add_trace(go.Scatter( + |${pad} x=$tableVar[$x], + |${pad} y=$tableVar[${render(bandConf.yUpper)}], + |${pad} mode='lines', + |${pad} marker=dict(color="#444"), + |${pad} line=dict(width=0), + |${pad} showlegend=False, + |${pad} name=$name + |${pad})) + |${pad}fig.add_trace(go.Scatter( + |${pad} x=$tableVar[$x], + |${pad} y=$tableVar[${render(bandConf.yLower)}], + |${pad} mode='lines', + |${pad} marker=dict(color="#444"), + |${pad} line=dict(width=0), + |${pad} fill='tonexty', + |${pad} showlegend=False, + |${pad} $fillColorPart + |${pad} name=$name + |${pad})) + |${pad}fig.add_trace(go.Scatter( + |${pad} x=$tableVar[$x], + |${pad} y=$tableVar[${render(bandConf.yValue)}], + |${pad} mode='${bandConf.mode.getModeInPlotly}', + |${pad} $colorPart + |${pad} name=$name + |${pad}))""".stripMargin } + .mkString("\n") + s"""${pad}fig = go.Figure() + |$traces + |${pad}fig.update_layout(margin=dict(t=0, b=0, l=0, r=0), + |${pad} xaxis_title=${render(xLabel)}, + |${pad} yaxis_title=${render(yLabel)}, + |${pad} hovermode="x")""".stripMargin + } - pyb""" - | fig = go.Figure() - | ${bandsPart.mkString("\n ")} - | fig.update_layout(margin=dict(t=0, b=0, l=0, r=0), - | xaxis_title=$xLabel, - | yaxis_title=$yLabel, - | hovermode="x") - |""" + // Rendered in the operator's dialect up front, so `.plain` shows the decode + // expressions as well. + def createPlotlyFigure(): PythonTemplateBuilder = { + assert(bands != null && !bands.isEmpty, "Bands cannot be empty") + val figure = buildFigure("table", value => pyb"$value".encode, indent = 8) + pyb"$figure" } override def generatePythonCode(): String = { @@ -137,7 +147,7 @@ class ContinuousErrorBandsOpDesc extends PythonVisualizationOpDesc with PlotlySt | @overrides | def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: |${emptyTableGuard("input table is empty.")} - | ${createPlotlyFigure()} + |${createPlotlyFigure()} | # convert fig to html content |${plotlyHtmlYield()} |""" @@ -145,73 +155,16 @@ class ContinuousErrorBandsOpDesc extends PythonVisualizationOpDesc with PlotlySt } override def generateStandaloneCode(): String = { - val traces = - bands.asScala - .map { bandConf => - // Values typed into the UI become escaped Python literals: the runtime - // path splices them as decode expressions, which a standalone script has - // no decoder for, and hand-written quotes break on a value containing one. - val colorLit = pyStringLiteral(bandConf.color) - val colorPart = - if (bandConf.color != "") - s"""line={'color': $colorLit}, marker={'color': $colorLit}, """ - else "" - val fillColorPart = - if (bandConf.fillColor != "") - s"""fillcolor=${pyStringLiteral(bandConf.fillColor)}, """ - else "" - val nameLit = - pyStringLiteral(if (bandConf.name != "") bandConf.name else bandConf.yValue) - val xLit = pyStringLiteral(bandConf.xValue) - - s"""fig.add_trace(go.Scatter( - | x=in1df[$xLit], - | y=in1df[${pyStringLiteral(bandConf.yUpper)}], - | mode='lines', - | marker=dict(color="#444"), - | line=dict(width=0), - | showlegend=False, - | name=$nameLit - |)) - |fig.add_trace(go.Scatter( - | x=in1df[$xLit], - | y=in1df[${pyStringLiteral(bandConf.yLower)}], - | mode='lines', - | marker=dict(color="#444"), - | line=dict(width=0), - | fill='tonexty', - | showlegend=False, - | $fillColorPart - | name=$nameLit - |)) - |fig.add_trace(go.Scatter( - | x=in1df[$xLit], - | y=in1df[${pyStringLiteral(bandConf.yValue)}], - | mode='${bandConf.mode.getModeInPlotly}', - | $colorPart - | name=$nameLit - |))""".stripMargin - } - .mkString("\n") - - // Nested under the `else` below, so every trace line needs the extra level. - val indentedTraces = - traces.linesIterator.map(line => if (line.isEmpty) line else s" $line").mkString("\n") - - // The empty-input branch mirrors generatePythonCode's `if table.empty` - // guard: without it the traces index columns of a frame that has none, and - // an empty input silently renders a blank chart instead of saying why. + // Values typed into the UI become escaped Python literals: the runtime + // path splices them as decode expressions, which a standalone script has + // no decoder for, and hand-written quotes break on a value containing one. + // The empty-input branch mirrors generatePythonCode's `if table.empty` guard. s"""${standaloneError("Continuous Error Bands is not available.")} | |if in1df.empty: |${standaloneErrorPage("input table is empty.")} |else: - | fig = go.Figure() - |$indentedTraces - | fig.update_layout(margin=dict(t=0, b=0, l=0, r=0), - | xaxis_title=${pyStringLiteral(xLabel)}, - | yaxis_title=${pyStringLiteral(yLabel)}, - | hovermode="x") + |${buildFigure("in1df", value => pyStringLiteral(value), indent = 4)} |${standaloneFigure("Continuous error bands", indent = 4, bothOutputs = true)}""".stripMargin } } diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala index ed07a2a797..0300122ef5 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala @@ -92,99 +92,10 @@ class NetworkGraphOpDesc extends PythonVisualizationOpDesc with PlotlyStandalone | def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: |${manipulateTable()} | if not table.empty: - | sources = table[$source] - | destinations = table[$destination] - | # Union of the two columns, in first-appearance order. Adding the - | # Series pairs them off element-wise; a set reorders per run. - | nodes = list(dict.fromkeys(pd.concat([sources, destinations]).tolist())) - | G = nx.Graph() - | for node in nodes: - | G.add_node(node) - | for i, j in table.iterrows(): - | G.add_edges_from([(j[$source], j[$destination])]) - | # Seeded so the same graph draws the same picture every run; - | # spring_layout starts from random positions otherwise. - | pos = nx.spring_layout(G, k=0.5, iterations=50, seed=0) - | for n, p in pos.items(): - | G.nodes[n]['pos'] = p - | - | edge_trace = go.Scatter( - | x=[], - | y=[], - | name='Edges', - | line=dict(width=0.5, color='#888'), - | hoverinfo='none', - | mode='lines', - | visible=True - | ) - | - | for edge in G.edges(): - | x0, y0 = G.nodes[edge[0]]['pos'] - | x1, y1 = G.nodes[edge[1]]['pos'] - | edge_trace['x'] += tuple([x0, x1, None]) - | edge_trace['y'] += tuple([y0, y1, None]) - | - | node_trace = go.Scatter( - | x=[], - | y=[], - | name='Nodes', - | text=[], - | mode='markers', - | hoverinfo='text', - | visible=True, - | marker=dict( - | showscale=True, - | colorscale='plasma', - | reversescale=True, - | color=[], - | size=15, - | colorbar=dict( - | thickness=10, - | title='Node Connections', - | xanchor='left', - | titleside='right' - | ), - | line=dict(width=0) - | ) - | ) - | - | for node in G.nodes(): - | x, y = G.nodes[node]['pos'] - | node_trace['x'] += tuple([x]) - | node_trace['y'] += tuple([y]) - | - | for node, adjacencies in enumerate(G.adjacency()): - | node_trace['marker']['color'] += tuple([len(adjacencies[1])]) - | node_info = str(adjacencies[0]) + ': ' + str(len(adjacencies[1])) + ' connections.' - | node_trace['text'] += tuple([node_info]) - | - | fig = go.Figure( - | data=[edge_trace, node_trace], - | layout=go.Layout( - | title='<br>'+$title, - | hovermode='closest', - | showlegend=False, - | margin=dict(b=20, l=5, r=5, t=40), - | annotations=[ - | dict( - | text='', - | showarrow=False, - | xref="paper", - | yref="paper" - | ) - | ], - | xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), - | yaxis=dict(showgrid=False, zeroline=False, showticklabels=False) - | ) - | ) - | fig.update_layout( - | margin=dict(l=0, r=0, t=0, b=0), - | legend=dict( - | itemclick=False, - | itemdoubleclick=False - | ) - | ) - | + | source_col = $source + | dest_col = $destination + | graph_title = '<br>'+$title + |${NetworkGraphPython.body(12)} | html = plotly.io.to_html(fig, include_plotlyjs='cdn', auto_play=False) | else: | html = self.render_error('Table should not have any empty/null values or fields.') @@ -212,95 +123,110 @@ class NetworkGraphOpDesc extends PythonVisualizationOpDesc with PlotlyStandalone | if table.empty: |${standaloneErrorPage("Table should not have any empty/null values or fields.", indent = 8)} | else: - | sources = table[$sourceLit] - | destinations = table[$destinationLit] - | nodes = list(dict.fromkeys(pd.concat([sources, destinations]).tolist())) - | G = nx.Graph() - | for node in nodes: - | G.add_node(node) - | for _, row in table.iterrows(): - | G.add_edges_from([(row[$sourceLit], row[$destinationLit])]) - | pos = nx.spring_layout(G, k=0.5, iterations=50, seed=0) - | for n, p in pos.items(): - | G.nodes[n]["pos"] = p - | - | edge_trace = go.Scatter( - | x=[], - | y=[], - | name="Edges", - | line=dict(width=0.5, color="#888"), - | hoverinfo="none", - | mode="lines", - | visible=True - | ) - | - | for edge in G.edges(): - | x0, y0 = G.nodes[edge[0]]["pos"] - | x1, y1 = G.nodes[edge[1]]["pos"] - | edge_trace["x"] += tuple([x0, x1, None]) - | edge_trace["y"] += tuple([y0, y1, None]) - | - | node_trace = go.Scatter( - | x=[], - | y=[], - | name="Nodes", - | text=[], - | mode="markers", - | hoverinfo="text", - | visible=True, - | marker=dict( - | showscale=True, - | colorscale="plasma", - | reversescale=True, - | color=[], - | size=15, - | colorbar=dict( - | thickness=10, - | title="Node Connections", - | xanchor="left", - | titleside="right" - | ), - | line=dict(width=0) - | ) - | ) - | - | for node in G.nodes(): - | x, y = G.nodes[node]["pos"] - | node_trace["x"] += tuple([x]) - | node_trace["y"] += tuple([y]) - | - | for _, adjacencies in enumerate(G.adjacency()): - | node_trace["marker"]["color"] += tuple([len(adjacencies[1])]) - | node_info = str(adjacencies[0]) + ": " + str(len(adjacencies[1])) + " connections." - | node_trace["text"] += tuple([node_info]) - | - | fig = go.Figure( - | data=[edge_trace, node_trace], - | layout=go.Layout( - | title=$titleLit, - | hovermode="closest", - | showlegend=False, - | margin=dict(b=20, l=5, r=5, t=40), - | annotations=[ - | dict( - | text="", - | showarrow=False, - | xref="paper", - | yref="paper" - | ) - | ], - | xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), - | yaxis=dict(showgrid=False, zeroline=False, showticklabels=False) - | ) - | ) - | fig.update_layout( - | margin=dict(l=0, r=0, t=0, b=0), - | legend=dict( - | itemclick=False, - | itemdoubleclick=False - | ) - | ) + | source_col = $sourceLit + | dest_col = $destinationLit + | graph_title = $titleLit + |${NetworkGraphPython.body(8)} |${standaloneFigure("Network graph")}""".stripMargin } } + +private object NetworkGraphPython { + def body(indent: Int): String = + render( + """|sources = table[source_col] + |destinations = table[dest_col] + |# Union of the two columns, in first-appearance order. Adding the + |# Series pairs them off element-wise; a set reorders per run. + |nodes = list(dict.fromkeys(pd.concat([sources, destinations]).tolist())) + |G = nx.Graph() + |for node in nodes: + | G.add_node(node) + |for _, row in table.iterrows(): + | G.add_edges_from([(row[source_col], row[dest_col])]) + |# Seeded so the same graph draws the same picture every run; + |# spring_layout starts from random positions otherwise. + |pos = nx.spring_layout(G, k=0.5, iterations=50, seed=0) + |for n, p in pos.items(): + | G.nodes[n]['pos'] = p + | + |edge_trace = go.Scatter( + | x=[], + | y=[], + | name='Edges', + | line=dict(width=0.5, color='#888'), + | hoverinfo='none', + | mode='lines', + | visible=True + |) + | + |for edge in G.edges(): + | x0, y0 = G.nodes[edge[0]]['pos'] + | x1, y1 = G.nodes[edge[1]]['pos'] + | edge_trace['x'] += tuple([x0, x1, None]) + | edge_trace['y'] += tuple([y0, y1, None]) + | + |node_trace = go.Scatter( + | x=[], + | y=[], + | name='Nodes', + | text=[], + | mode='markers', + | hoverinfo='text', + | visible=True, + | marker=dict( + | showscale=True, + | colorscale='plasma', + | reversescale=True, + | color=[], + | size=15, + | colorbar=dict( + | thickness=10, + | title='Node Connections', + | xanchor='left', + | titleside='right' + | ), + | line=dict(width=0) + | ) + |) + | + |for node in G.nodes(): + | x, y = G.nodes[node]['pos'] + | node_trace['x'] += tuple([x]) + | node_trace['y'] += tuple([y]) + | + |for _, adjacencies in enumerate(G.adjacency()): + | node_trace['marker']['color'] += tuple([len(adjacencies[1])]) + | node_info = str(adjacencies[0]) + ': ' + str(len(adjacencies[1])) + ' connections.' + | node_trace['text'] += tuple([node_info]) + | + |fig = go.Figure( + | data=[edge_trace, node_trace], + | layout=go.Layout( + | title=graph_title, + | hovermode='closest', + | showlegend=False, + | margin=dict(b=20, l=5, r=5, t=40), + | annotations=[ + | dict( + | text='', + | showarrow=False, + | xref="paper", + | yref="paper" + | ) + | ], + | xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), + | yaxis=dict(showgrid=False, zeroline=False, showticklabels=False) + | ) + |) + |fig.update_layout( + | margin=dict(l=0, r=0, t=0, b=0), + | legend=dict( + | itemclick=False, + | itemdoubleclick=False + | ) + |)""", + indent + ) +} diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala index f5397cea54..3a22a2705c 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDesc.scala @@ -76,29 +76,11 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneCode | <p>Reason: {error_msg} </p>''' | | def make_annotations(self, pos, text): - | font_color = 'rgb(250,250,250)' - | node_color = '#6175c1' - | font_size = 10 - | - | annotations = [] - | for k, (node_name, coords) in enumerate(pos.items()): - | annotations.append( - | dict( - | text=text[k], - | x=coords[0], - | y=coords[1], - | xref='x1', yref='y1', - | font=dict(color=font_color, size=font_size), - | showarrow=False, - | align='center', - | bordercolor='rgb(50,50,50)', - | borderwidth=1, - | borderpad=5, - | bgcolor=node_color, - | opacity=0.8 - | ) - | ) - | return annotations + |${TreePlotPython.annotationsBody( + 8, + "for k, (node_name, coords) in enumerate(pos.items()):", + "text[k]" + )} | | def build_tree_layout(self, edges): |${TreePlotPython.body(8)} @@ -107,17 +89,11 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneCode | def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: |${emptyTableGuard("Input table is empty.", bodyIndent = 4)} | - | edges = [] - | for item in table[$edgeListColumn].dropna(): - | try: - | edge = ast.literal_eval(str(item)) - | if isinstance(edge, (list, tuple)) and len(edge) == 2: - | edges.append(list(edge)) - | except (ValueError, SyntaxError): - | pass + | edge_col = $edgeListColumn + |${TreePlotPython.parseEdges("table", 8)} | | if not edges: - | yield {'html-content': self.render_error("No valid [parent, child] pairs found in column " + $edgeListColumn + ".")} + | yield {'html-content': self.render_error("No valid [parent, child] pairs found in column " + edge_col + ".")} | return | | try: @@ -126,22 +102,6 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneCode | yield {'html-content': self.render_error(f"Tree layout failed: {e}")} | return | - | HORIZONTAL_DENSITY = 120 - | VERTICAL_DENSITY = 120 - | PADDING = 200 - | MIN_WIDTH = 800 - | MIN_HEIGHT = 600 - | - | if len(coords) > 1: - | x_coords, y_coords = zip(*coords) - | x_range = max(x_coords) - min(x_coords) - | y_range = max(y_coords) - min(y_coords) - | plot_width = max(MIN_WIDTH, x_range * HORIZONTAL_DENSITY + PADDING) - | plot_height = max(MIN_HEIGHT, y_range * VERTICAL_DENSITY + PADDING) - | else: - | plot_width = MIN_WIDTH - | plot_height = MIN_HEIGHT - | | position = {k: coords[k] for k in range(len(labels))} | index_of = {label: k for k, label in enumerate(labels)} | @@ -152,26 +112,7 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneCode | Xe += [position[edge[0]][0], position[edge[1]][0], None] | Ye += [position[edge[0]][1], position[edge[1]][1], None] | - | fig = go.Figure() - | - | fig.add_trace(go.Scatter(x=Xe, y=Ye, mode='lines', - | line=dict(color='rgb(210,210,210)', width=1), - | hoverinfo='none')) - | - | axis = dict(showline=False, zeroline=False, showgrid=False, showticklabels=False) - | - | fig.update_layout(title='Tree Plot', - | width=int(plot_width), - | height=int(plot_height), - | annotations=self.make_annotations(position, labels), - | font_size=12, - | showlegend=False, - | xaxis=axis, - | yaxis=axis, - | margin=dict(l=40, r=40, b=85, t=100), - | dragmode='pan', - | hovermode='closest', - | plot_bgcolor='rgb(248,248,248)') + |${TreePlotPython.figureBody(8, "coords", "self.make_annotations(position, labels)")} | |${plotlyHtmlYield()} | @@ -191,28 +132,7 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneCode | <p>Reason: {error_msg} </p>''' | |def make_annotations(pos): - | font_color = 'rgb(250,250,250)' - | node_color = '#6175c1' - | font_size = 10 - | annotations = [] - | for node_name, coords in pos.items(): - | annotations.append( - | dict( - | text=node_name, - | x=coords[0], - | y=coords[1], - | xref='x1', yref='y1', - | font=dict(color=font_color, size=font_size), - | showarrow=False, - | align='center', - | bordercolor='rgb(50,50,50)', - | borderwidth=1, - | borderpad=5, - | bgcolor=node_color, - | opacity=0.8 - | ) - | ) - | return annotations + |${TreePlotPython.annotationsBody(4, "for node_name, coords in pos.items():", "node_name")} | |def build_tree_layout(edges): |${TreePlotPython.body(4)} @@ -227,63 +147,23 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneCode |if in1df.empty: |${standaloneErrorPage("Input table is empty.")} |else: - | edges = [] - | for item in in1df[${pyStringLiteral(edgeListColumn)}].dropna(): - | try: - | edge = ast.literal_eval(str(item)) - | if isinstance(edge, (list, tuple)) and len(edge) == 2: - | edges.append(list(edge)) - | except (ValueError, SyntaxError): - | pass + | edge_col = ${pyStringLiteral(edgeListColumn)} + |${TreePlotPython.parseEdges("in1df", 4)} | | if not edges: | with open(outputHtml, "w", encoding="utf-8") as output: - | output.write(render_error("No valid [parent, child] pairs found in column " + ${pyStringLiteral( - edgeListColumn - )} + ".")) + | output.write(render_error("No valid [parent, child] pairs found in column " + edge_col + ".")) | else: | try: | position = compute_tree_layout(edges) | - | HORIZONTAL_DENSITY = 120 - | VERTICAL_DENSITY = 120 - | PADDING = 200 - | MIN_WIDTH = 800 - | MIN_HEIGHT = 600 - | - | if len(position) > 1: - | x_coords, y_coords = zip(*position.values()) - | x_range = max(x_coords) - min(x_coords) - | y_range = max(y_coords) - min(y_coords) - | plot_width = max(MIN_WIDTH, x_range * HORIZONTAL_DENSITY + PADDING) - | plot_height = max(MIN_HEIGHT, y_range * VERTICAL_DENSITY + PADDING) - | else: - | plot_width = MIN_WIDTH - | plot_height = MIN_HEIGHT - | | Xe = [] | Ye = [] | for parent, child in edges: | Xe += [position[parent][0], position[child][0], None] | Ye += [position[parent][1], position[child][1], None] | - | fig = go.Figure() - | fig.add_trace(go.Scatter(x=Xe, y=Ye, mode='lines', - | line=dict(color='rgb(210,210,210)', width=1), - | hoverinfo='none')) - | axis = dict(showline=False, zeroline=False, showgrid=False, showticklabels=False) - | fig.update_layout(title='Tree Plot', - | width=int(plot_width), - | height=int(plot_height), - | annotations=make_annotations(position), - | font_size=12, - | showlegend=False, - | xaxis=axis, - | yaxis=axis, - | margin=dict(l=40, r=40, b=85, t=100), - | dragmode='pan', - | hovermode='closest', - | plot_bgcolor='rgb(248,248,248)') + |${TreePlotPython.figureBody(12, "list(position.values())", "make_annotations(position)")} |${standaloneFigure("Tree plot", indent = 12)} | except TreeLayoutError as e: | with open(outputHtml, "w", encoding="utf-8") as output: @@ -293,8 +173,87 @@ class TreePlotOpDesc extends PythonVisualizationOpDesc with PlotlyStandaloneCode } private object TreePlotPython { + def annotationsBody(indent: Int, loopHeader: String, textExpr: String): String = + render( + s"""|font_color = 'rgb(250,250,250)' + |node_color = '#6175c1' + |font_size = 10 + |annotations = [] + |$loopHeader + | annotations.append( + | dict( + | text=$textExpr, + | x=coords[0], + | y=coords[1], + | xref='x1', yref='y1', + | font=dict(color=font_color, size=font_size), + | showarrow=False, + | align='center', + | bordercolor='rgb(50,50,50)', + | borderwidth=1, + | borderpad=5, + | bgcolor=node_color, + | opacity=0.8 + | ) + | ) + |return annotations""", + indent + ) + + def parseEdges(tableVar: String, indent: Int): String = + render( + s"""|edges = [] + |for item in $tableVar[edge_col].dropna(): + | try: + | edge = ast.literal_eval(str(item)) + | if isinstance(edge, (list, tuple)) and len(edge) == 2: + | edges.append(list(edge)) + | except (ValueError, SyntaxError): + | pass""", + indent + ) + + def figureBody(indent: Int, coordsExpr: String, annotationsCall: String): String = + render( + s"""|HORIZONTAL_DENSITY = 120 + |VERTICAL_DENSITY = 120 + |PADDING = 200 + |MIN_WIDTH = 800 + |MIN_HEIGHT = 600 + | + |_coords = $coordsExpr + |if len(_coords) > 1: + | x_coords, y_coords = zip(*_coords) + | x_range = max(x_coords) - min(x_coords) + | y_range = max(y_coords) - min(y_coords) + | plot_width = max(MIN_WIDTH, x_range * HORIZONTAL_DENSITY + PADDING) + | plot_height = max(MIN_HEIGHT, y_range * VERTICAL_DENSITY + PADDING) + |else: + | plot_width = MIN_WIDTH + | plot_height = MIN_HEIGHT + | + |fig = go.Figure() + |fig.add_trace(go.Scatter(x=Xe, y=Ye, mode='lines', + | line=dict(color='rgb(210,210,210)', width=1), + | hoverinfo='none')) + |axis = dict(showline=False, zeroline=False, showgrid=False, showticklabels=False) + |fig.update_layout(title='Tree Plot', + | width=int(plot_width), + | height=int(plot_height), + | annotations=$annotationsCall, + | font_size=12, + | showlegend=False, + | xaxis=axis, + | yaxis=axis, + | margin=dict(l=40, r=40, b=85, t=100), + | dragmode='pan', + | hovermode='closest', + | plot_bgcolor='rgb(248,248,248)')""", + indent + ) + def body(indent: Int): String = - org.apache.texera.amber.operator.visualization.PythonCodeFragment.render( + render( """|# Tidy top-down tree: depth picks the row, a leaf takes the next |# free column and a parent sits centred over its own children. |labels = [] diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/RuntimeStandaloneParitySpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/RuntimeStandaloneParitySpec.scala new file mode 100644 index 0000000000..6f7991534b --- /dev/null +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/RuntimeStandaloneParitySpec.scala @@ -0,0 +1,483 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.amber.operator.visualization + +import com.fasterxml.jackson.databind.JsonNode +import org.apache.texera.amber.operator.visualization.bulletChart.{ + BulletChartOpDesc, + BulletChartStepDefinition +} +import org.apache.texera.amber.operator.visualization.continuousErrorBands.{ + BandConfig, + ContinuousErrorBandsOpDesc +} +import org.apache.texera.amber.operator.visualization.lineChart.LineMode +import org.apache.texera.amber.operator.visualization.networkGraph.NetworkGraphOpDesc +import org.apache.texera.amber.operator.visualization.treeplot.TreePlotOpDesc +import org.apache.texera.amber.util.JSONUtils.objectMapper +import org.apache.texera.amber.util.PythonTestSupport.{ + NeedsPythonPackages, + canImport, + configuredPython, + withDriver +} +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import scala.jdk.CollectionConverters._ + +/** + * Runs the Python four charts generate for the operator, and the script each one + * exports, over the same tables. + * + * Both paths of these charts are assembled from shared Python fragments, and a + * fragment that reads a name its caller never bound still compiles: only running + * it fails. Each case runs both paths and expects the same figures, or the same + * refusal; the values pinned below keep the two from drifting together. Each + * chart has settings whose text carries a quote, which the operator decodes at + * runtime and the exported script has to spell as an escaped literal. + */ +class RuntimeStandaloneParitySpec extends AnyFlatSpec with Matchers { + + private def networkGraph: NetworkGraphOpDesc = { + val op = new NetworkGraphOpDesc + op.source = "from's \"node\"" + op.destination = "to's \"node\"" + op.title = "Friends \"graph\"" + op + } + + private def bulletChart: BulletChartOpDesc = { + val op = new BulletChartOpDesc + op.value = "it's \"score\"" + op.deltaReference = Some(50) + op.thresholdValue = Some(80) + // The second step runs backwards, so it is reported rather than drawn; the last + // has no end, so it reaches neither script. + op.steps = Seq( + new BulletChartStepDefinition(Some(0), Some(40)), + new BulletChartStepDefinition(Some(60), Some(40)), + new BulletChartStepDefinition(Some(40), Some(100)), + new BulletChartStepDefinition(Some(100), None) + ).asJava + op + } + + private def treePlot: TreePlotOpDesc = { + val op = new TreePlotOpDesc + op.edgeListColumn = "edge \"pairs\"" + op + } + + private def errorBands: ContinuousErrorBandsOpDesc = { + val named = new BandConfig + named.xValue = "t" + named.yValue = "mean \"v\"" + named.yUpper = "hi" + named.yLower = "lo" + named.name = "band's one" + named.color = "#ff0000" + named.fillColor = "rgba(255, 0, 0, 0.2)" + named.mode = LineMode.LINE + // Left unnamed and uncoloured: named after its y column, in plotly's own colours. + val unnamed = new BandConfig + unnamed.xValue = "t" + unnamed.yValue = "other" + unnamed.yUpper = "other_hi" + unnamed.yLower = "other_lo" + val op = new ContinuousErrorBandsOpDesc + op.xLabel = "Time \"s\"" + op.yLabel = "it's y" + op.bands = Seq(named, unnamed).asJava + op + } + + /** Both paths of every chart, keyed by the names the driver's tables use. The + * exported script gets the imports the translator writes above it. + */ + private def jobs: String = { + val charts: Seq[(String, PythonVisualizationOpDesc)] = Seq( + "network_graph" -> networkGraph, + "bullet_chart" -> bulletChart, + "tree_plot" -> treePlot, + "error_bands" -> errorBands + ) + val root = objectMapper.createObjectNode() + charts.foreach { + case (name, op) => + val imports = "import pandas as pd" +: op.standaloneImports() + root + .putObject(name) + .put("operator", op.generatePythonCode()) + .put("script", (imports :+ op.generateStandaloneCode()).mkString("\n")) + } + objectMapper.writeValueAsString(root) + } + + /** What one path left for one table: the figures it drew, the reason on any error + * page, the step errors listed under its charts, and the traceback if it raised. + */ + private case class Drawn( + figures: Seq[JsonNode], + reasons: Seq[String], + stepErrors: Seq[String], + failure: Option[String] + ) + + private case class Outcome(operator: Drawn, script: Drawn) + + private def drawn(node: JsonNode): Drawn = + Drawn( + node.get("figures").asScala.toSeq, + node.get("reasons").asScala.map(_.asText).toSeq, + node.get("stepErrors").asScala.map(_.asText).toSeq, + Option(node.get("failure")).filterNot(_.isNull).map(_.asText) + ) + + /** Every case's outcome by `chart/case`. One run for the whole suite, so pandas, + * plotly and networkx are imported once. + */ + private lazy val outcomes: Map[String, Outcome] = { + val python = configuredPython().getOrElse( + cancel("No runnable python executable (udf.conf python.path, python3, python, py)") + ) + // networkx stays out of the gate: only the network graph imports it, inside each + // path's try, so without it those two cases fail instead of all ten cancelling. + if (!canImport(python, "pandas", "plotly")) { + cancel(s"'$python' cannot import pandas and plotly; skipping runtime verification") + } + + withDriver( + python, + "chart_parity_jobs_", + "chart_parity_driver_", + jobs, + driverScript, + "Parity driver timed out after 120s" + ) { (exitCode, output) => + withClue(s"Driver output:\n$output\n") { + exitCode shouldBe 0 + } + "(?m)^CASE (\\S+) (.*)$".r + .findAllMatchIn(output) + .map { m => + val outcome = objectMapper.readTree(m.group(2)) + m.group(1) -> Outcome(drawn(outcome.get("operator")), drawn(outcome.get("script"))) + } + .toMap + } + } + + /** The case's outcome, once both paths are known to have run to the end. */ + private def outcome(name: String): Outcome = { + val result = outcomes.getOrElse(name, fail(s"The driver reported nothing for $name")) + withClue(s"$name, operator: ") { result.operator.failure shouldBe None } + withClue(s"$name, exported script: ") { result.script.failure shouldBe None } + result + } + + /** Both paths drew nothing for the case and gave this reason instead. */ + private def refusedAlike(name: String, reason: String): Unit = { + val refused = outcome(name) + Seq("operator" -> refused.operator, "exported script" -> refused.script).foreach { + case (path, result) => + withClue(s"$name, $path: ") { + result.figures shouldBe empty + result.reasons shouldBe Seq(reason) + } + } + } + + private def texts(node: JsonNode): Seq[String] = node.asScala.map(_.asText).toSeq + + // A gap between line segments is a null. + private def numbers(node: JsonNode): Seq[Option[Double]] = + node.asScala.map(n => Option.when(!n.isNull)(n.asDouble)).toSeq + + "NetworkGraphOpDesc" should + "draw the same graph in the operator and the exported script" taggedAs NeedsPythonPackages in { + val drawn = outcome("network_graph/drawn") + drawn.script.figures shouldBe drawn.operator.figures + drawn.operator.figures should have size 1 + val graph = drawn.operator.figures.head + graph.at("/layout/title/text").asText shouldBe "<br>Friends \"graph\"" + // The row without a source names no edge, so d never becomes a node and the + // other three close a triangle. + texts(graph.at("/data/1/text")) shouldBe + Seq("a: 2 connections.", "b: 2 connections.", "c: 2 connections.") + numbers(graph.at("/data/1/marker/color")) shouldBe Seq(Some(2.0), Some(2.0), Some(2.0)) + numbers(graph.at("/data/0/x")).grouped(3).map(_.last).toSeq shouldBe Seq(None, None, None) + } + + it should "refuse a table with no complete edge the same way in both" taggedAs NeedsPythonPackages in { + refusedAlike( + "network_graph/no_complete_edge", + "Table should not have any empty/null values or fields." + ) + } + + "BulletChartOpDesc" should + "draw the same first ten charts in the operator and the exported script" taggedAs NeedsPythonPackages in { + val drawn = outcome("bullet_chart/drawn") + drawn.script.figures shouldBe drawn.operator.figures + val indicators = drawn.operator.figures.map(_.at("/data/0")) + // Twelve values survive the dropped hole, and only the first ten are drawn. + indicators.map(_.get("value").asDouble) shouldBe + Seq(50.0, 150.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0) + indicators.foreach { indicator => + indicator.at("/title/text").asText shouldBe "it's \"score\"" + indicator.at("/delta/reference").asDouble shouldBe 50.0 + indicator.at("/gauge/threshold/value").asDouble shouldBe 80.0 + // The backwards step is left out, so two remain, shaded light to dark. + indicator + .at("/gauge/steps") + .asScala + .map(step => (numbers(step.get("range")), step.get("color").asText)) + .toSeq shouldBe Seq( + (Seq(Some(0.0), Some(40.0)), "hsl(0, 0%, 90.0%)"), + (Seq(Some(40.0), Some(100.0)), "hsl(0, 0%, 30.0%)") + ) + } + // The axis runs a fifth past the largest of the value, the reference, the + // threshold and the step ends. + indicators.head.at("/gauge/axis/range/1").asDouble shouldBe 120.0 +- 1e-9 + indicators(1).at("/gauge/axis/range/1").asDouble shouldBe 180.0 +- 1e-9 + } + + // The operator's message has always said ≥ and the exported script's >=. + it should "list the backwards step under every chart, each path in its own glyph" taggedAs NeedsPythonPackages in { + val drawn = outcome("bullet_chart/drawn") + drawn.operator.stepErrors shouldBe Seq.fill(10)("Step 2: start ≥ end (60.0 ≥ 40.0)") + drawn.script.stepErrors shouldBe Seq.fill(10)("Step 2: start >= end (60.0 >= 40.0)") + } + + it should "refuse a table without the value column the same way in both" taggedAs NeedsPythonPackages in { + refusedAlike( + "bullet_chart/missing_column", + "Column 'it's \"score\"' not found in input table." + ) + } + + it should "refuse a table whose values are all missing the same way in both" taggedAs NeedsPythonPackages in { + refusedAlike("bullet_chart/all_null", "No valid data rows found after dropping nulls.") + } + + "TreePlotOpDesc" should + "draw the same tree in the operator and the exported script" taggedAs NeedsPythonPackages in { + val drawn = outcome("tree_plot/drawn") + drawn.script.figures shouldBe drawn.operator.figures + drawn.operator.figures should have size 1 + val tree = drawn.operator.figures.head + // Three rows hold a pair; the missing cell, the text and the triple are skipped. + tree + .at("/layout/annotations") + .asScala + .map(node => (node.get("text").asText, node.get("x").asDouble, node.get("y").asDouble)) + .toSeq shouldBe Seq( + ("root", 0.5, 0.0), + ("left", 0.0, -1.0), + ("right", 1.0, -1.0), + ("leaf", 0.0, -2.0) + ) + numbers(tree.at("/data/0/x")) shouldBe + Seq(Some(0.5), Some(0.0), None, Some(0.5), Some(1.0), None, Some(0.0), Some(0.0), None) + numbers(tree.at("/data/0/y")) shouldBe + Seq(Some(0.0), Some(-1.0), None, Some(0.0), Some(-1.0), None, Some(-1.0), Some(-2.0), None) + // Too small a tree to grow past the minimum size. + tree.at("/layout/width").asInt shouldBe 800 + tree.at("/layout/height").asInt shouldBe 600 + } + + it should "refuse a column without a single pair the same way in both" taggedAs NeedsPythonPackages in { + refusedAlike( + "tree_plot/no_pairs", + "No valid [parent, child] pairs found in column edge \"pairs\"." + ) + } + + "ContinuousErrorBandsOpDesc" should + "draw the same bands in the operator and the exported script" taggedAs NeedsPythonPackages in { + val drawn = outcome("error_bands/drawn") + drawn.script.figures shouldBe drawn.operator.figures + drawn.operator.figures should have size 1 + val figure = drawn.operator.figures.head + val traces = figure.get("data").asScala.toSeq + // Each band is its upper bound, its lower bound filled up to it, then the line. + traces.map(trace => numbers(trace.get("y")).flatten) shouldBe Seq( + Seq(1.5, 2.5, 3.5), + Seq(0.5, 1.5, 2.5), + Seq(1.0, 2.0, 3.0), + Seq(3.25, 2.25, 1.25), + Seq(2.75, 1.75, 0.75), + Seq(3.0, 2.0, 1.0) + ) + traces.foreach(trace => numbers(trace.get("x")).flatten shouldBe Seq(1.0, 2.0, 3.0)) + traces.map(_.get("name").asText) shouldBe Seq.fill(3)("band's one") ++ Seq.fill(3)("other") + traces.map(_.path("fill").asText) shouldBe Seq("", "tonexty", "", "", "tonexty", "") + traces(1).get("fillcolor").asText shouldBe "rgba(255, 0, 0, 0.2)" + traces(4).has("fillcolor") shouldBe false + traces(2).get("mode").asText shouldBe "lines" + traces(2).at("/line/color").asText shouldBe "#ff0000" + traces(2).at("/marker/color").asText shouldBe "#ff0000" + traces(5).get("mode").asText shouldBe "lines+markers" + traces(5).has("line") shouldBe false + figure.at("/layout/xaxis/title/text").asText shouldBe "Time \"s\"" + figure.at("/layout/yaxis/title/text").asText shouldBe "it's y" + } + + it should "refuse an empty table the same way in both" taggedAs NeedsPythonPackages in { + refusedAlike("error_bands/empty", "input table is empty.") + } + + // Runs both paths of every chart over each of its tables and prints what each + // left behind. Only the pytexera import seam is stubbed, as in the operator + // specs, so the generated module runs unmodified; the exported script runs with + // its placeholders bound, as in GaugeChartOpDescSpec. + private val driverScript: String = + """import base64 + |import json + |import pathlib + |import re + |import sys + |import tempfile + |import traceback + |import types + |from typing import Iterator, Optional + | + |import pandas as pd + |import plotly.io + | + |class UDFTableOperator: + | def decode_python_template(self, data): + | return base64.b64decode(data).decode("utf-8") + | + |stub = types.ModuleType("pytexera") + |stub.UDFTableOperator = UDFTableOperator + |stub.overrides = lambda fn: fn + |stub.Table = pd.DataFrame + |stub.TableLike = object + |stub.Iterator = Iterator + |stub.Optional = Optional + |sys.modules["pytexera"] = stub + | + |def report(figures, page, failure=None): + | for figure in figures: + | # plotly's default theme: the same in both paths, and most of the bytes. + | figure.get("layout", {}).pop("template", None) + | return { + | "figures": figures, + | "reasons": re.findall(r"<p>Reason[^:]*: (.*?) </p>", page, re.S), + | "stepErrors": [ + | item + | for notes in re.findall(r"<b>Step Errors:</b><ul>(.*?)</ul>", page, re.S) + | for item in re.findall(r"<li>(.*?)</li>", notes, re.S) + | ], + | "failure": failure, + | } + | + |def run_operator(source, table): + | # Every chart the operator draws goes through plotly.io.to_html, so the + | # figure is read there rather than out of the page around it. + | figures = [] + | def record(fig, *args, **kwargs): + | figures.append(json.loads(fig.to_json())) + | return "" + | to_html = plotly.io.to_html + | plotly.io.to_html = record + | try: + | ns = {"__name__": "generated_operator"} + | exec(compile(source, "operator", "exec"), ns) + | outputs = ns["ProcessTableOperator"]().process_table(table.copy(), 0) + | return report(figures, "".join(output["html-content"] for output in outputs)) + | except Exception: + | return report([], "", traceback.format_exc()) + | finally: + | plotly.io.to_html = to_html + | + |def run_script(source, table): + | with tempfile.TemporaryDirectory() as directory: + | scope = { + | "in1df": table.copy(), + | "outputHtml": directory + "/chart.html", + | "outputJson": directory + "/chart.json", + | } + | try: + | exec(compile(source, "script", "exec"), scope) + | page = pathlib.Path(scope["outputHtml"]).read_text(encoding="utf-8") + | written = pathlib.Path(scope["outputJson"]) + | figures = json.loads(written.read_text(encoding="utf-8")) if written.exists() else [] + | except Exception: + | return report([], "", traceback.format_exc()) + | # One chart is written as an object, several as a list. + | return report(figures if isinstance(figures, list) else [figures], page) + | + |CASES = { + | "network_graph": { + | "drawn": pd.DataFrame({ + | 'from\'s "node"': ["a", "a", "b", None], + | 'to\'s "node"': ["b", "c", "c", "d"], + | }), + | "no_complete_edge": pd.DataFrame({ + | 'from\'s "node"': ["a", None], + | 'to\'s "node"': [None, "b"], + | }), + | }, + | "bullet_chart": { + | "drawn": pd.DataFrame({ + | 'it\'s "score"': [50.0, None, 150.0, 60.0, 70.0, 80.0, 90.0, + | 100.0, 110.0, 120.0, 130.0, 140.0, 160.0], + | }), + | "missing_column": pd.DataFrame({"other": [1.0]}), + | "all_null": pd.DataFrame({'it\'s "score"': [None, None]}), + | }, + | "tree_plot": { + | "drawn": pd.DataFrame({ + | 'edge "pairs"': ["['root', 'left']", None, "not a pair", "[1, 2, 3]", + | "['root', 'right']", "['left', 'leaf']"], + | }), + | "no_pairs": pd.DataFrame({'edge "pairs"': [None, "not a pair", "[1, 2, 3]"]}), + | }, + | "error_bands": { + | "drawn": pd.DataFrame({ + | "t": [1, 2, 3], + | 'mean "v"': [1.0, 2.0, 3.0], + | "hi": [1.5, 2.5, 3.5], + | "lo": [0.5, 1.5, 2.5], + | "other": [3.0, 2.0, 1.0], + | "other_hi": [3.25, 2.25, 1.25], + | "other_lo": [2.75, 1.75, 0.75], + | }), + | "empty": pd.DataFrame({ + | column: [] + | for column in ["t", 'mean "v"', "hi", "lo", "other", "other_hi", "other_lo"] + | }), + | }, + |} + | + |jobs = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) + |for chart, tables in CASES.items(): + | for case, table in tables.items(): + | outcome = { + | "operator": run_operator(jobs[chart]["operator"], table), + | "script": run_script(jobs[chart]["script"], table), + | } + | print("CASE %s/%s %s" % (chart, case, json.dumps(outcome))) + |""".stripMargin +}
