This is an automated email from the ASF dual-hosted git repository.

aicam pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git


The following commit(s) were added to refs/heads/main by this push:
     new bda608431a feat: add a new ternary contour plot operator (#4193)
bda608431a is described below

commit bda608431ac943a442f3eabaa3b4eb7eeb7f749e
Author: Elliot Lin <[email protected]>
AuthorDate: Wed Apr 22 08:46:37 2026 -0700

    feat: add a new ternary contour plot operator (#4193)
    
    <!--
    Thanks for sending a pull request (PR)! Here are some tips for you:
    1. If this is your first time, please read our contributor guidelines:
    [Contributing to
    Texera](https://github.com/apache/texera/blob/main/CONTRIBUTING.md)
      2. Ensure you have added or run the appropriate tests for your PR
      3. If the PR is work in progress, mark it a draft on GitHub.
      4. Please write your PR title to summarize what this PR proposes, we
        are following Conventional Commits style for PR titles as well.
      5. Be sure to keep the PR description updated to reflect all changes.
    -->
    
    ### What changes were proposed in this PR?
    <!--
    Please clarify what changes you are proposing. The purpose of this
    section
    is to outline the changes. Here are some tips for you:
      1. If you propose a new API, clarify the use case for a new API.
      2. If you fix a bug, you can clarify why it is a bug.
      3. If it is a refactoring, clarify what has been changed.
      3. It would be helpful to include a before-and-after comparison using
         screenshots or GIFs.
      4. Please consider writing useful notes for better and faster reviews.
    -->
    <img width="1912" height="1027" alt="image"
    
src="https://github.com/user-attachments/assets/536262ea-7541-4aeb-8b10-33dcfd73e72c";
    />
    
    This change relates to the addition of a ternary contour plot operator,
    which visualizes how a scalar value varies as a function of three
    normalized components that sum to a constant (typically 1 or 100%).
    
    In a ternary contour plot:
    - Each vertex of the triangular plot represents 100% of one component.
    - Any interior point represents a mixture of the three components.
    - Contour lines or color gradients indicate equal values of the measured
    quantity across different mixtures.
    
    This visualization is useful for identifying regions where the output is
    optimized or insensitive to changes in the component proportions, as
    well as for understanding trade-offs between the three variables.
    
    The operator takes in 4 inputs. The first three variables are the
    components, and the fourth variable is the output that corresponds to
    the proportion of the the three components.
    
    
    ### Any related issues, documentation, discussions?
    <!--
    Please use this section to link other resources if not mentioned
    already.
    1. If this PR fixes an issue, please include `Fixes #1234`, `Resolves
    #1234`
    or `Closes #1234`. If it is only related, simply mention the issue
    number.
      2. If there is design documentation, please add the link.
      3. If there is a discussion in the mailing list, please add the link.
    -->
    Needs python library scikit-image
    Can be installed using: pip install scikit-image
    
    ### How was this PR tested?
    <!--
    If tests were added, say they were added here. Or simply mention that if
    the PR
    is tested with existing test cases. Make sure to include/update test
    cases that
    check the changes thoroughly including negative and positive cases if
    possible.
    If it was tested in a way different from regular unit tests, please
    clarify how
    you tested step by step, ideally copy and paste-able, so that other
    reviewers can
    test and check, and descendants can verify in the future. If tests were
    not added,
    please describe why they were not added and/or why it was difficult to
    add.
    -->
    Tested with existing test cases
    
    ### Was this PR authored or co-authored using generative AI tooling?
    <!--
    If generative AI tooling has been used in the process of authoring this
    PR,
    please include the phrase: 'Generated-by: ' followed by the name of the
    tool
    and its version. If no, write 'No'.
    Please refer to the [ASF Generative Tooling
    Guidance](https://www.apache.org/legal/generative-tooling.html) for
    details.
    -->
    No
    
    ---------
    
    Co-authored-by: Elliot <[email protected]>
    Co-authored-by: Yicong Huang 
<[email protected]>
    Co-authored-by: Chen Li <[email protected]>
---
 amber/operator-requirements.txt                    |   1 +
 .../apache/texera/amber/operator/LogicalOp.scala   |   2 +
 .../ternaryContour/TernaryContourOpDesc.scala      | 151 +++++++++++++++++++++
 .../src/assets/operator_images/TernaryContour.png  | Bin 0 -> 167675 bytes
 4 files changed, 154 insertions(+)

diff --git a/amber/operator-requirements.txt b/amber/operator-requirements.txt
index f76f3bc014..2554373e0e 100644
--- a/amber/operator-requirements.txt
+++ b/amber/operator-requirements.txt
@@ -24,3 +24,4 @@ torch==2.8.0
 scikit-learn==1.5.0
 transformers==4.57.3
 boto3==1.40.53
+scikit-image==0.25.2
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala
index d9a8a97407..4e9d6c6e2c 100644
--- 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/LogicalOp.scala
@@ -132,6 +132,7 @@ import 
org.apache.texera.amber.operator.visualization.sankeyDiagram.SankeyDiagra
 import 
org.apache.texera.amber.operator.visualization.scatter3DChart.Scatter3dChartOpDesc
 import 
org.apache.texera.amber.operator.visualization.scatterplot.ScatterplotOpDesc
 import 
org.apache.texera.amber.operator.visualization.tablesChart.TablesPlotOpDesc
+import 
org.apache.texera.amber.operator.visualization.ternaryContour.TernaryContourOpDesc
 import 
org.apache.texera.amber.operator.visualization.ternaryPlot.TernaryPlotOpDesc
 import 
org.apache.texera.amber.operator.visualization.parallelCoordinatesPlot.ParallelCoordinatesPlotOpDesc
 import 
org.apache.texera.amber.operator.visualization.polarChart.PolarChartOpDesc
@@ -260,6 +261,7 @@ trait StateTransferFunc
     new Type(value = classOf[TablesPlotOpDesc], name = "TablesPlot"),
     new Type(value = classOf[ContinuousErrorBandsOpDesc], name = 
"ContinuousErrorBands"),
     new Type(value = classOf[FigureFactoryTableOpDesc], name = 
"FigureFactoryTable"),
+    new Type(value = classOf[TernaryContourOpDesc], name = "TernaryContour"),
     new Type(value = classOf[TernaryPlotOpDesc], name = "TernaryPlot"),
     new Type(value = classOf[DendrogramOpDesc], name = "Dendrogram"),
     new Type(value = classOf[NestedTableOpDesc], name = "NestedTable"),
diff --git 
a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDesc.scala
 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDesc.scala
new file mode 100644
index 0000000000..215e9ce0c9
--- /dev/null
+++ 
b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDesc.scala
@@ -0,0 +1,151 @@
+/*
+ * 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.ternaryContour
+
+import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
+import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
+import org.apache.texera.amber.core.tuple.{AttributeType, Schema}
+import org.apache.texera.amber.core.workflow.OutputPort.OutputMode
+import 
org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
+import org.apache.texera.amber.pybuilder.PyStringTypes.EncodableString
+import org.apache.texera.amber.core.workflow.{InputPort, OutputPort, 
PortIdentity}
+import org.apache.texera.amber.operator.PythonOperatorDescriptor
+import 
org.apache.texera.amber.operator.metadata.annotations.AutofillAttributeName
+import org.apache.texera.amber.operator.metadata.{OperatorGroupConstants, 
OperatorInfo}
+import org.apache.texera.amber.pybuilder.PythonTemplateBuilder
+
+/**
+  * Visualization Operator for Ternary Plots.
+  *
+  * This operator uses three data fields to construct a ternary plot.
+  * The points can optionally be color coded using a data field.
+  */
+
+class TernaryContourOpDesc extends PythonOperatorDescriptor {
+
+  // Add annotations for the first variable
+  @JsonProperty(value = "firstVariable", required = true)
+  @JsonSchemaTitle("Variable 1")
+  @JsonPropertyDescription("First variable data field")
+  @AutofillAttributeName var firstVariable: EncodableString = ""
+
+  // Add annotations for the second variable
+  @JsonProperty(value = "secondVariable", required = true)
+  @JsonSchemaTitle("Variable 2")
+  @JsonPropertyDescription("Second variable data field")
+  @AutofillAttributeName var secondVariable: EncodableString = ""
+
+  // Add annotations for the third variable
+  @JsonProperty(value = "thirdVariable", required = true)
+  @JsonSchemaTitle("Variable 3")
+  @JsonPropertyDescription("Third variable data field")
+  @AutofillAttributeName var thirdVariable: EncodableString = ""
+
+  // Add annotations for the fourth variable
+  @JsonProperty(value = "fourthVariable", required = true)
+  @JsonSchemaTitle("Measured Value")
+  @JsonPropertyDescription("Measured value data field")
+  @AutofillAttributeName var fourthVariable: EncodableString = ""
+
+  // OperatorInfo instance describing ternary plot
+  override def operatorInfo: OperatorInfo =
+    OperatorInfo(
+      userFriendlyName = "Ternary Contour",
+      operatorDescription =
+        "Shows how a measured value changes across all mixtures of three 
components that sum to a constant",
+      operatorGroupName = 
OperatorGroupConstants.VISUALIZATION_SCIENTIFIC_GROUP,
+      inputPorts = List(InputPort()),
+      outputPorts = List(OutputPort(mode = OutputMode.SINGLE_SNAPSHOT))
+    )
+
+  override def getOutputSchemas(
+      inputSchemas: Map[PortIdentity, Schema]
+  ): Map[PortIdentity, Schema] = {
+    val outputSchema = Schema()
+      .add("html-content", AttributeType.STRING)
+    Map(operatorInfo.outputPorts.head.id -> outputSchema)
+  }
+
+  /** Returns a Python string that drops any tuples with missing values */
+  def manipulateTable(): PythonTemplateBuilder = {
+    // Check for any empty data field names
+    assert(
+      firstVariable.nonEmpty && secondVariable.nonEmpty && 
thirdVariable.nonEmpty && fourthVariable.nonEmpty
+    )
+    pyb"""
+       |        # Remove any tuples that contain missing values
+       |        table.dropna(subset=[$firstVariable, $secondVariable, 
$thirdVariable, $fourthVariable], inplace = True)
+       |
+       |        #Remove rows where any of the first three variables are 
negative
+       |        table = table[(table[[$firstVariable, $secondVariable, 
$thirdVariable]] >= 0).all(axis=1)]
+       |
+       |        #Remove zero-sum rows
+       |        s = table[$firstVariable] + table[$secondVariable] + 
table[$thirdVariable]
+       |        table = table[s > 0]
+       |"""
+  }
+
+  /** Returns a Python string that creates the ternary contour plot figure */
+  def createPlotlyFigure(): PythonTemplateBuilder = {
+    pyb"""
+         |        A = table[$firstVariable].to_numpy()
+         |        B = table[$secondVariable].to_numpy()
+         |        C = table[$thirdVariable].to_numpy()
+         |        Z = table[$fourthVariable].to_numpy()
+         |        fig = ff.create_ternary_contour(np.array([A,B,C]), Z, 
pole_labels=[$firstVariable, $secondVariable, $thirdVariable], 
interp_mode='cartesian')
+         |"""
+  }
+
+  /** Returns a Python string that yields the html content of the ternary 
contour plot */
+  override def generatePythonCode(): String = {
+    val finalCode =
+      pyb"""
+         |from pytexera import *
+         |
+         |import plotly.io
+         |import plotly.figure_factory as ff
+         |import numpy as np
+         |
+         |class ProcessTableOperator(UDFTableOperator):
+         |
+         |    # Generate custom error message as html string
+         |    def render_error(self, error_msg):
+         |        return '''<h1>TernaryContour is not available.</h1>
+         |                  <p>Reasons are: {} </p>
+         |               '''.format(error_msg)
+         |
+         |    @overrides
+         |    def process_table(self, table: Table, port: int) -> 
Iterator[Optional[TableLike]]:
+         |        if table.empty:
+         |            yield {'html-content': self.render_error("Input table is 
empty.")}
+         |            return
+         |        ${manipulateTable()}
+         |        if table.empty:
+         |            yield {'html-content': self.render_error("No valid rows 
left (every row has at least 1 missing value).")}
+         |            return
+         |        ${createPlotlyFigure()}
+         |        # Convert fig to html content
+         |        html = plotly.io.to_html(fig, include_plotlyjs = 'cdn', 
auto_play = False)
+         |        yield {'html-content':html}
+         |"""
+    finalCode.encode
+  }
+
+}
diff --git a/frontend/src/assets/operator_images/TernaryContour.png 
b/frontend/src/assets/operator_images/TernaryContour.png
new file mode 100644
index 0000000000..6526cb3bbd
Binary files /dev/null and 
b/frontend/src/assets/operator_images/TernaryContour.png differ

Reply via email to