aglinxinyuan commented on code in PR #9646:
URL: https://github.com/apache/texera/pull/9646#discussion_r4689104575


##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala:
##########
@@ -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)}

Review Comment:
   Done in a234e15d0d: `RuntimeStandaloneParitySpec`, tagged 
`NeedsPythonPackages`, runs the operator code and the exported script of all 
four charts over the same tables, with the pytexera stub from 
`TreePlotOpDescSpec` and the placeholder scope from `GaugeChartOpDescSpec`. 
Each of its 10 cases expects the same figures, or the same refusal, from both 
paths and pins what they draw, and every typed-in setting carries a quote. It 
passes unchanged against main's four operators. It fails when `dest_col` is 
unbound in the operator, when `edge_col` is unbound in the exported script, and 
when the band bounds are swapped in both.
   



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala:
##########
@@ -137,81 +142,24 @@ 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()}
          |"""
     finalCode.encode
   }
 
   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", s => { val lit: String = pyStringLiteral(s); 
pyb"$lit" }, indent = 4).plain}

Review Comment:
   Done in a234e15d0d: `buildFigure` is now an `s"..."` template with an 
`EncodableString => String` callback, `value => pyb"$value".encode` for the 
operator and `pyStringLiteral` for the export, so the `.plain` render is gone. 
The operator code and the exported script are byte-identical to before, also 
with quotes, `|`, newlines and backslashes in the settings, and 
`PythonCodeRawInvalidTextSpec` passes 118/118. One side effect: 
`createPlotlyFigure()` returns the figure already in the operator's dialect, so 
its `.plain` shows decode expressions too. `ContinuousErrorBandsOpDescSpec` 
reads it through `carries`, which accepts either form.
   



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala:
##########
@@ -360,3 +250,73 @@ 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 = {
+    val (selfParam, errorsVar, cmp, retStmt) =
+      if (isMethod) ("self, ", "self.step_errors", "≥", "return valid_steps")

Review Comment:
   Done in a234e15d0d: a comment above the tuple now says the step error reads 
≥ in the operator and >= in the exported script, as each always has, and that 
the two stay apart on purpose. The parity spec pins both messages.
   



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala:
##########
@@ -94,20 +94,24 @@ 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.
+  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("[", ", ", "]")
 
-    // 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("[", ", ", "]")
+  override def generatePythonCode(): String = {
+    val deltaReferenceExpr: PythonLiteral = deltaReferenceLiteral
+    val thresholdExpr: PythonLiteral = thresholdLiteral
+    val stepsExpr: PythonLiteral = stepsLiteral

Review Comment:
   Done in a234e15d0d: the three vals are gone, and the operator template 
splices `$deltaReferenceLiteral`, `$thresholdLiteral` and `$stepsLiteral` 
directly, as the exported script does. The generated code is byte-identical.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to