From bfaedb3ab1b1ac2bd75bc408ca246da898baaa5a Mon Sep 17 00:00:00 2001 From: Shivang Jariwala <97551095+shivangj-10@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:58:25 -0500 Subject: [PATCH 1/3] merge triangle meshes example --- code-samples/geoscience-objects/README.md | 4 + .../bonus/merge-triangle-meshes/README.md | 12 + .../merge-triangle-meshes.ipynb | 345 ++++++++++++++++++ .../triangle_mesh_helpers.py | 224 ++++++++++++ 4 files changed, 585 insertions(+) create mode 100644 code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md create mode 100644 code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb create mode 100644 code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py diff --git a/code-samples/geoscience-objects/README.md b/code-samples/geoscience-objects/README.md index da9e6696c..f4288ebdf 100644 --- a/code-samples/geoscience-objects/README.md +++ b/code-samples/geoscience-objects/README.md @@ -32,6 +32,10 @@ The publishing notebooks use the lower-level `evo-schemas` interfaces. Use them - [Publish a Regular 2D Grid](publish-regular-2d-grid/publish-regular-2d-grid.ipynb) - [Publish a Triangular Mesh](publish-triangular-mesh/publish-triangular-mesh.ipynb) +## Bonus + +- [Merge Triangle Meshes](bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb) + ## Requirements Each notebook directory contains its own dependency instructions. You need a [supported Python version](../README.md#before-you-start), a Seequent account with Evo access, and Evo application credentials to authenticate in the notebooks. diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md new file mode 100644 index 000000000..0467b557d --- /dev/null +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md @@ -0,0 +1,12 @@ +# Merge Triangle Meshes +This folder contains a Jupyter notebook showing how to select any number of existing triangle mesh objects from an Evo workspace using checkboxes, merge them into a single mesh, and publish the result as a new triangle mesh object. + +## Inputs +Two or more [triangle mesh](https://developer.seequent.com/docs/data-structures/geoscience-objects/schemas/objects/triangle-mesh/) objects in the selected Evo workspace. The notebook lists every triangle mesh in the workspace and you tick the ones to merge. + +All selected meshes must use the same coordinate reference system, as the notebook does not reproject data. A mesh with an unspecified coordinate reference system cannot be merged with a mesh that has one. + +## Outputs +- A new triangle mesh object with the name and path you provide, containing the vertices and triangles of all selected meshes. The triangle indices of each mesh are offset by the total number of vertices in the meshes before it. + +Only the mesh geometry is merged. Attributes, parts, and edges of the source meshes are not carried over. diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb new file mode 100644 index 000000000..be82fbd2a --- /dev/null +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb @@ -0,0 +1,345 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Merge Triangle Mesh objects\n", + "\n", + "This example shows how to select any number of existing triangle mesh objects from an Evo workspace using checkboxes, merge them into a single mesh, and publish the result as a new triangle mesh object using the Evo Python SDK.\n", + "\n", + "A [triangle mesh](https://developer.seequent.com/docs/data-structures/geoscience-objects/schemas/objects/triangle-mesh/) stores its geometry in two tables:\n", + "- `triangles.vertices`: the `x`, `y`, `z` coordinates of every vertex.\n", + "- `triangles.indices`: triplets of 0-based indices (`n0`, `n1`, `n2`) into the vertex table, one row per triangle.\n", + "\n", + "To merge the meshes, their vertex tables are concatenated, and the triangle indices of each mesh are offset by the total number of vertices in the meshes before it so that they still point at the correct vertices.\n", + "\n", + "### Requirements\n", + "\n", + "You must have a Seequent account with the Evo entitlement to use this notebook.\n", + "\n", + "The following parameters must be provided:\n", + "\n", + "- The client ID of your Evo application.\n", + "- The callback/redirect URL of your Evo application.\n", + "\n", + "To obtain these app credentials, refer to the [Apps and tokens guide](https://developer.seequent.com/docs/guides/getting-started/apps-and-tokens) in the Seequent Developer Portal.\n", + "\n", + "The selected workspace must contain at least two triangle mesh objects. You can publish one using the [Publish a Triangular Mesh](../../publish-triangular-mesh/publish-triangular-mesh.ipynb) notebook." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from evo.notebooks import ServiceManagerWidget\n", + "\n", + "# Evo app credentials\n", + "client_id = \"\" # Replace with your client ID\n", + "redirect_url = \"\" # Replace with your redirect URL\n", + "\n", + "manager = await ServiceManagerWidget.with_auth_code(client_id=client_id, redirect_url=redirect_url).login()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Use the Evo Python SDK to create an object client and a data client\n", + "\n", + "The data client uses its own cache under the temp directory for Parquet files." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import tempfile\n", + "\n", + "from evo.common.utils import Cache\n", + "from evo.objects import ObjectAPIClient\n", + "\n", + "# The object client will manage your auth token and Geoscience Object API requests.\n", + "object_client = ObjectAPIClient(manager.get_environment(), manager.get_connector())\n", + "\n", + "parquet_cache = Cache(os.path.join(tempfile.gettempdir(), \"evo-notebook-data\"), mkdir=True)\n", + "print(f\"Caching Parquet data in: {parquet_cache.root}\")\n", + "\n", + "# The data client will manage downloading and saving your data as Parquet and publishing your data to Evo storage.\n", + "data_client = object_client.get_data_client(parquet_cache)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create the triangle mesh helper\n", + "\n", + "[triangle_mesh_helpers.py](triangle_mesh_helpers.py) contains the helpers used in this notebook:\n", + "- `TriangleMeshHelper` lists the triangle meshes in the workspace, downloads mesh data, preserves the coordinate reference system, and displays a link to view the new object in the Evo portal.\n", + "- `MeshSelectorWidget` displays a checkbox for each mesh, plus fields for the name and path of the merged mesh." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from triangle_mesh_helpers import TriangleMeshHelper\n", + "\n", + "mesh_helper = TriangleMeshHelper(object_client, data_client)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Select the triangle meshes to merge\n", + "\n", + "List all triangle mesh objects in the workspace and tick the checkboxes of the meshes to merge (at least two). Use **Select all** to toggle every mesh at once. You can also set the name and path of the merged object that will be published." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from triangle_mesh_helpers import MeshSelectorWidget\n", + "\n", + "triangle_mesh_objects = await mesh_helper.list_triangle_meshes()\n", + "if len(triangle_mesh_objects) < 2:\n", + " raise RuntimeError(\n", + " f\"Found {len(triangle_mesh_objects)} triangle mesh object(s) in the workspace, but at least two are required. \"\n", + " \"Publish a triangle mesh using the 'publish-triangular-mesh' notebook.\"\n", + " )\n", + "\n", + "print(f\"Found {len(triangle_mesh_objects)} triangle mesh objects.\")\n", + "mesh_selector = MeshSelectorWidget(triangle_mesh_objects)\n", + "mesh_selector" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Download and merge the selected meshes\n", + "\n", + "Run the cell below after making your selections. All selected meshes must use the same coordinate reference system; this is checked before any mesh data is downloaded. The vertices of all selected meshes are concatenated and the triangle indices of each mesh are offset by the total number of vertices in the meshes before it.\n", + "\n", + "> **Note:** Only the mesh geometry is merged. Attributes, parts and edges of the source meshes are not carried over to the merged mesh." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "selected_meshes = mesh_selector.selected_meshes\n", + "if len(selected_meshes) < 2:\n", + " raise ValueError(f\"Select at least two triangle meshes to merge ({len(selected_meshes)} selected).\")\n", + "\n", + "# Download only the object definitions first, so the coordinate reference systems can be checked before any data is downloaded.\n", + "mesh_objects = []\n", + "meshes_by_crs = [] # (crs, [mesh paths]) for each distinct CRS, including unspecified.\n", + "for mesh in selected_meshes:\n", + " mesh_object = await mesh_helper.download_triangle_mesh_object(mesh)\n", + " mesh_objects.append(mesh_object)\n", + "\n", + " crs = mesh_object.get(\"coordinate_reference_system\") or \"unspecified\"\n", + " crs_group = next((paths for group_crs, paths in meshes_by_crs if group_crs == crs), None)\n", + " if crs_group is None:\n", + " crs_group = []\n", + " meshes_by_crs.append((crs, crs_group))\n", + " crs_group.append(mesh.path)\n", + "\n", + "# All meshes must share the same coordinate reference system, and an unspecified CRS does not match a specified one.\n", + "# This notebook does not reproject data.\n", + "if len(meshes_by_crs) > 1:\n", + " crs_details = \"\\n\".join(\n", + " f\" - {mesh_helper.describe_crs(crs)}: \" + \", \".join(f\"'{path}'\" for path in paths)\n", + " for crs, paths in meshes_by_crs\n", + " )\n", + " raise ValueError(\n", + " f\"Cannot merge the selected meshes because they use {len(meshes_by_crs)} different coordinate \"\n", + " f\"reference systems:\\n{crs_details}\\n\"\n", + " \"Deselect the meshes that do not match, or reproject them to a common coordinate reference system \"\n", + " \"and run this cell again.\"\n", + " )\n", + "merged_crs = meshes_by_crs[0][0]\n", + "\n", + "vertex_arrays, index_arrays = [], []\n", + "mesh_summaries = []\n", + "vertex_offset = 0\n", + "for mesh, mesh_object in zip(selected_meshes, mesh_objects):\n", + " vertices, indices = await mesh_helper.download_triangle_mesh_data(mesh, mesh_object)\n", + "\n", + " vertex_arrays.append(vertices)\n", + " # Offset the indices so they point at this mesh's vertices within the merged vertex table.\n", + " index_arrays.append(indices + np.uint64(vertex_offset))\n", + " vertex_offset += len(vertices)\n", + " mesh_summaries.append((len(vertices), len(indices), mesh.path))\n", + "\n", + "merged_vertices = np.vstack(vertex_arrays)\n", + "merged_indices = np.vstack(index_arrays)\n", + "\n", + "print(f\"{'Vertices':>12} {'Triangles':>12} Mesh\")\n", + "for vertex_count, triangle_count, mesh_path in mesh_summaries:\n", + " print(f\"{vertex_count:>12,} {triangle_count:>12,} {mesh_path}\")\n", + "print(f\"{len(merged_vertices):>12,} {len(merged_indices):>12,} Merged mesh ({len(selected_meshes)} meshes)\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Save the merged vertices and indices as Parquet\n", + "\n", + "The vertices are saved using the `float-array-3` table format and the triangle indices using the `index-array-3` table format, as required by the triangle mesh schema." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import pyarrow as pa\n", + "from evo_schemas.components import BoundingBox_V1_0_1, Triangles_V1_2_0_Indices, Triangles_V1_2_0_Vertices\n", + "\n", + "from evo.objects.utils.table_formats import FLOAT_ARRAY_3, INDEX_ARRAY_3\n", + "\n", + "vertices_table = pa.table(\n", + " {\n", + " \"x\": pa.array(merged_vertices[:, 0], type=pa.float64()),\n", + " \"y\": pa.array(merged_vertices[:, 1], type=pa.float64()),\n", + " \"z\": pa.array(merged_vertices[:, 2], type=pa.float64()),\n", + " }\n", + ")\n", + "indices_table = pa.table(\n", + " {\n", + " \"n0\": pa.array(merged_indices[:, 0], type=pa.uint64()),\n", + " \"n1\": pa.array(merged_indices[:, 1], type=pa.uint64()),\n", + " \"n2\": pa.array(merged_indices[:, 2], type=pa.uint64()),\n", + " }\n", + ")\n", + "\n", + "mesh_vertices = Triangles_V1_2_0_Vertices.from_dict(data_client.save_table(vertices_table, table_format=FLOAT_ARRAY_3))\n", + "mesh_indices = Triangles_V1_2_0_Indices.from_dict(data_client.save_table(indices_table, table_format=INDEX_ARRAY_3))\n", + "\n", + "# Define the bounding box from the merged vertices.\n", + "min_x, min_y, min_z = merged_vertices.min(axis=0)\n", + "max_x, max_y, max_z = merged_vertices.max(axis=0)\n", + "merged_bounding_box = BoundingBox_V1_0_1(\n", + " min_x=float(min_x),\n", + " max_x=float(max_x),\n", + " min_y=float(min_y),\n", + " max_y=float(max_y),\n", + " min_z=float(min_z),\n", + " max_z=float(max_z),\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create the merged triangle mesh and publish it to Evo\n", + "\n", + "Geoscience object data must conform to a specific object schema. The `evo-schemas` package provides Pydantic models that make it easy to work with the equivalent JSON schemas. For this example we'll use v2.2.0 of the triangle mesh schema, via the relevant Pydantic model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "from datetime import datetime, timezone\n", + "\n", + "from evo_schemas.components import Triangles_V1_2_0\n", + "from evo_schemas.objects import TriangleMesh_V2_2_0\n", + "\n", + "from evo.notebooks import FeedbackWidget\n", + "\n", + "object_name = mesh_selector.merged_name.strip() or \"Merged_Mesh_SDK_demo\"\n", + "if object_name.endswith(\".json\"):\n", + " object_name = object_name[: -len(\".json\")]\n", + "if os.environ.get(\"CI\"):\n", + " object_name += f\"_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S_%f')}\"\n", + "object_path = mesh_selector.merged_path.strip().strip(\"/\")\n", + "\n", + "# The object name requires the `.json` extension.\n", + "full_obj_path = f\"{object_path}/{object_name}.json\" if object_path else f\"{object_name}.json\"\n", + "\n", + "merged_mesh = TriangleMesh_V2_2_0(\n", + " name=object_name,\n", + " uuid=None,\n", + " description=f\"Merge of {len(selected_meshes)} triangle meshes: \"\n", + " + \", \".join(f\"'{mesh.path}'\" for mesh in selected_meshes)\n", + " + \".\",\n", + " bounding_box=merged_bounding_box,\n", + " tags={\"Source\": \"Jupyter Notebook\"},\n", + " coordinate_reference_system=mesh_helper.to_crs_model(merged_crs),\n", + " triangles=Triangles_V1_2_0(vertices=mesh_vertices, indices=mesh_indices),\n", + ")\n", + "\n", + "# Upload the Parquet data to Evo.\n", + "await data_client.upload_referenced_data(merged_mesh.as_dict(), FeedbackWidget(\"Uploading data\"))\n", + "\n", + "# Create the geoscience object.\n", + "merged_mesh_metadata = await object_client.create_geoscience_object(full_obj_path, merged_mesh.as_dict())\n", + "print(f\"Published merged triangle mesh to '{full_obj_path}' (Object ID: {merged_mesh_metadata.id})\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### View the object in the Evo portal" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "mesh_helper.build_portal_url(merged_mesh_metadata)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Success! You now have a new geoscience object in Evo containing the merged mesh data.\n", + "\n", + "## Summary\n", + "\n", + "In this example, we've completed the following:\n", + "* Listed the triangle mesh objects in a workspace and selected the meshes to merge using checkboxes.\n", + "* Downloaded the vertex and triangle index data of each selected mesh.\n", + "* Merged the meshes by concatenating the vertices and offsetting the triangle indices of each mesh by the number of preceding vertices.\n", + "* Saved the merged data in Parquet format and combined it into the triangle-mesh schema format.\n", + "* Uploaded the Parquet files and the newly assembled object in JSON format to Evo." + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py new file mode 100644 index 000000000..56bc6c6ca --- /dev/null +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py @@ -0,0 +1,224 @@ +# Copyright © 2026 Bentley Systems, Incorporated +# Licensed 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. + +"""Helpers for listing, selecting and downloading triangle meshes, preserving their CRS, and viewing published +objects in Evo.""" + +import re + +import ipywidgets as widgets +import numpy as np +from evo_schemas.components import Crs_V1_0_1_EpsgCode, Crs_V1_0_1_OgcWkt +from IPython.display import HTML, display + +from evo.notebooks import FeedbackWidget + + +class MeshSelectorWidget(widgets.VBox): + """Widget for selecting triangle meshes to merge with checkboxes, and naming the merged mesh.""" + + def __init__(self, meshes, default_name="Merged_Mesh_SDK_demo", default_path="Jupyter_Example/Mesh"): + """ + Args: + meshes (list[ObjectMetadata]): The triangle mesh objects to list, in display order. + default_name (str): The initial name of the merged mesh. + default_path (str): The initial path of the merged mesh. + """ + self.meshes = list(meshes) + + widget_style = {"description_width": "120px"} + widget_layout = widgets.Layout(width="90%") + + self.mesh_checkboxes = [ + widgets.Checkbox(value=False, description=f"{obj.path} ({obj.id})", indent=False, layout=widget_layout) + for obj in self.meshes + ] + self.select_all_checkbox = widgets.Checkbox(value=False, description="Select all", indent=False) + self.selection_label = widgets.Label() + + self.select_all_checkbox.observe(self._toggle_all, names="value") + for checkbox in self.mesh_checkboxes: + checkbox.observe(self._update_selection_label, names="value") + self._update_selection_label() + + self.merged_name_text = widgets.Text( + value=default_name, description="Merged name:", style=widget_style, layout=widget_layout + ) + self.merged_path_text = widgets.Text( + value=default_path, description="Merged path:", style=widget_style, layout=widget_layout + ) + + # Scroll the mesh list if the workspace contains many meshes. + mesh_list = widgets.VBox( + self.mesh_checkboxes, + layout=widgets.Layout(max_height="300px", overflow="auto", border="1px solid lightgray", padding="4px"), + ) + + super().__init__( + [ + widgets.HBox([self.select_all_checkbox, self.selection_label]), + mesh_list, + self.merged_name_text, + self.merged_path_text, + ] + ) + + @property + def selected_meshes(self): + """list[ObjectMetadata]: The meshes whose checkboxes are ticked, in display order.""" + return [obj for obj, checkbox in zip(self.meshes, self.mesh_checkboxes) if checkbox.value] + + @property + def merged_name(self): + """str: The name entered for the merged mesh.""" + return self.merged_name_text.value + + @property + def merged_path(self): + """str: The path entered for the merged mesh.""" + return self.merged_path_text.value + + def _update_selection_label(self, _=None): + selected_count = sum(checkbox.value for checkbox in self.mesh_checkboxes) + self.selection_label.value = f"{selected_count} of {len(self.mesh_checkboxes)} meshes selected" + + def _toggle_all(self, change): + for checkbox in self.mesh_checkboxes: + checkbox.value = change["new"] + + +class TriangleMeshHelper: + """Helper for working with triangle mesh geoscience objects.""" + + def __init__(self, object_client, data_client): + """ + Args: + object_client (ObjectAPIClient): Client used to download geoscience objects. + data_client (ObjectDataClient): Client used to download the Parquet data referenced by objects. + """ + self.object_client = object_client + self.data_client = data_client + + async def list_triangle_meshes(self): + """ + List all triangle mesh objects in the workspace. + + Returns: + list[ObjectMetadata]: The triangle mesh objects, sorted by path. + """ + all_objects = await self.object_client.list_all_objects() + return sorted( + (obj for obj in all_objects if obj.schema_id.sub_classification == "triangle-mesh"), + key=lambda obj: obj.path.lower(), + ) + + async def download_triangle_mesh_object(self, object_metadata): + """ + Download the definition of a triangle mesh object, without its vertex and index data. + + Args: + object_metadata (ObjectMetadata): Metadata of the triangle mesh object to download. + + Returns: + dict: The object definition, including its `coordinate_reference_system` and `triangles` table references. + """ + downloaded_object = await self.object_client.download_object_by_id( + object_id=object_metadata.id, version=object_metadata.version_id + ) + object_dict = downloaded_object.as_dict() + + triangles = object_dict.get("triangles") + if not triangles or "vertices" not in triangles or "indices" not in triangles: + raise ValueError(f"Object '{object_metadata.name}' does not contain triangle vertices and indices.") + return object_dict + + async def download_triangle_mesh_data(self, object_metadata, object_dict): + """ + Download the vertex and index data of a triangle mesh object. + + Args: + object_metadata (ObjectMetadata): Metadata of the triangle mesh object. + object_dict (dict): The object definition returned by `download_triangle_mesh_object`. + + Returns: + tuple: An (N, 3) float64 array of vertices and an (M, 3) uint64 array of triangle indices. + """ + triangles = object_dict["triangles"] + vertices_table = await self.data_client.download_table( + object_id=object_metadata.id, + version_id=object_metadata.version_id, + table_info=triangles["vertices"], + fb=FeedbackWidget(f"Downloading vertices of '{object_metadata.name}'"), + ) + indices_table = await self.data_client.download_table( + object_id=object_metadata.id, + version_id=object_metadata.version_id, + table_info=triangles["indices"], + fb=FeedbackWidget(f"Downloading indices of '{object_metadata.name}'"), + ) + + vertices = vertices_table.to_pandas().to_numpy(dtype=np.float64) + indices = indices_table.to_pandas().to_numpy(dtype=np.uint64) + return vertices, indices + + @staticmethod + def to_crs_model(crs): + """ + Convert a coordinate reference system from an object definition into the equivalent evo-schemas model. + + Args: + crs (dict | str): The `coordinate_reference_system` value of a downloaded object. + + Returns: + Crs_V1_0_1_EpsgCode | Crs_V1_0_1_OgcWkt | str: The CRS model to use for the new object. + """ + if isinstance(crs, dict) and "epsg_code" in crs: + return Crs_V1_0_1_EpsgCode(epsg_code=crs["epsg_code"]) + if isinstance(crs, dict) and "ogc_wkt" in crs: + return Crs_V1_0_1_OgcWkt(ogc_wkt=crs["ogc_wkt"]) + return crs if isinstance(crs, str) else "unspecified" + + @staticmethod + def describe_crs(crs): + """ + Describe a coordinate reference system from an object definition in a human-readable form. + + Args: + crs (dict | str): The `coordinate_reference_system` value of a downloaded object. + + Returns: + str: For example `EPSG:32650`, `WKT "WGS 84 / UTM zone 50N"` or `Unspecified`. + """ + if isinstance(crs, dict) and "epsg_code" in crs: + return f"EPSG:{crs['epsg_code']}" + if isinstance(crs, dict) and "ogc_wkt" in crs: + # The first quoted string in a WKT definition is the name of the CRS. + wkt_name = re.search(r'"([^"]+)"', crs["ogc_wkt"]) + return f'WKT "{wkt_name.group(1)}"' if wkt_name else f"WKT {crs['ogc_wkt'][:60]}..." + return "Unspecified" if crs == "unspecified" else str(crs) + + @staticmethod + def build_portal_url(object_metadata): + """ + Build the URL to view the object in the Evo Portal and display it as a link. + + Args: + object_metadata (ObjectMetadata): The object metadata object returned after the object is created. + """ + hub_url = object_metadata.environment.hub_url + hub_name = hub_url.split("://")[1].split(".")[0] + org_id = object_metadata.environment.org_id + workspace_id = object_metadata.environment.workspace_id + object_id = object_metadata.id + + url = f"https://evo.seequent.com/{org_id}/workspaces/{hub_name}/{workspace_id}/viewer?id={object_id}" + + display(HTML(f'View object in the Evo Portal')) From ee1d40a8e4195fa8c80f8dcc9569ad7fab0a006a Mon Sep 17 00:00:00 2001 From: Shivang Jariwala <97551095+shivangj-10@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:43:44 -0500 Subject: [PATCH 2/3] support to update existing merged mesh --- .../bonus/merge-triangle-meshes/README.md | 3 +- .../merge-triangle-meshes.ipynb | 69 ++++++++++++------- .../triangle_mesh_helpers.py | 61 +++++++++++++--- 3 files changed, 97 insertions(+), 36 deletions(-) diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md index 0467b557d..96f3d99b0 100644 --- a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md @@ -1,5 +1,5 @@ # Merge Triangle Meshes -This folder contains a Jupyter notebook showing how to select any number of existing triangle mesh objects from an Evo workspace using checkboxes, merge them into a single mesh, and publish the result as a new triangle mesh object. +This folder contains a Jupyter notebook showing how to select any number of existing triangle mesh objects from an Evo workspace, merge them into a single mesh, and publish the result either as a new triangle mesh object or as a new version of an existing triangle mesh object. ## Inputs Two or more [triangle mesh](https://developer.seequent.com/docs/data-structures/geoscience-objects/schemas/objects/triangle-mesh/) objects in the selected Evo workspace. The notebook lists every triangle mesh in the workspace and you tick the ones to merge. @@ -8,5 +8,6 @@ All selected meshes must use the same coordinate reference system, as the notebo ## Outputs - A new triangle mesh object with the name and path you provide, containing the vertices and triangles of all selected meshes. The triangle indices of each mesh are offset by the total number of vertices in the meshes before it. +- Alternatively, tick **Update existing merged mesh** and select a target mesh to publish the merge as a new version of that mesh. The target keeps its ID, name, and path. Meshes ticked for merging cannot be chosen as the target. Only the mesh geometry is merged. Attributes, parts, and edges of the source meshes are not carried over. diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb index be82fbd2a..8c93e6f38 100644 --- a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb @@ -6,7 +6,7 @@ "source": [ "## Merge Triangle Mesh objects\n", "\n", - "This example shows how to select any number of existing triangle mesh objects from an Evo workspace using checkboxes, merge them into a single mesh, and publish the result as a new triangle mesh object using the Evo Python SDK.\n", + "This example shows how to select any number of existing triangle mesh objects from an Evo workspace, merge them into a single mesh, and publish the result using the Evo Python SDK, either as a new triangle mesh object or as a new version of an existing triangle mesh object.\n", "\n", "A [triangle mesh](https://developer.seequent.com/docs/data-structures/geoscience-objects/schemas/objects/triangle-mesh/) stores its geometry in two tables:\n", "- `triangles.vertices`: the `x`, `y`, `z` coordinates of every vertex.\n", @@ -82,7 +82,7 @@ "\n", "[triangle_mesh_helpers.py](triangle_mesh_helpers.py) contains the helpers used in this notebook:\n", "- `TriangleMeshHelper` lists the triangle meshes in the workspace, downloads mesh data, preserves the coordinate reference system, and displays a link to view the new object in the Evo portal.\n", - "- `MeshSelectorWidget` displays a checkbox for each mesh, plus fields for the name and path of the merged mesh." + "- `MeshSelectorWidget` displays a checkbox for each mesh, plus fields for the name and path of the merged mesh. Alternatively, tick **Update existing merged mesh** to pick an existing mesh to update instead." ] }, { @@ -102,7 +102,9 @@ "source": [ "### Select the triangle meshes to merge\n", "\n", - "List all triangle mesh objects in the workspace and tick the checkboxes of the meshes to merge (at least two). Use **Select all** to toggle every mesh at once. You can also set the name and path of the merged object that will be published." + "List all triangle mesh objects in the workspace and tick the checkboxes of the meshes to merge (at least two). Use **Select all** to toggle every mesh at once. You can also set the name and path of the merged object that will be published.\n", + "\n", + "To publish the merge as a new version of an existing mesh instead of creating a new object, tick **Update existing merged mesh** and select the target mesh from the dropdown. The target keeps its ID, name and path, and its geometry is replaced by the merge of the selected meshes. The dropdown only lists meshes that are not ticked for merging, and is updated as you change the selection." ] }, { @@ -117,7 +119,6 @@ "if len(triangle_mesh_objects) < 2:\n", " raise RuntimeError(\n", " f\"Found {len(triangle_mesh_objects)} triangle mesh object(s) in the workspace, but at least two are required. \"\n", - " \"Publish a triangle mesh using the 'publish-triangular-mesh' notebook.\"\n", " )\n", "\n", "print(f\"Found {len(triangle_mesh_objects)} triangle mesh objects.\")\n", @@ -147,10 +148,12 @@ "selected_meshes = mesh_selector.selected_meshes\n", "if len(selected_meshes) < 2:\n", " raise ValueError(f\"Select at least two triangle meshes to merge ({len(selected_meshes)} selected).\")\n", + "if mesh_selector.update_existing and mesh_selector.target_mesh is None:\n", + " raise ValueError(\"Select the target mesh to update, or untick 'Update existing merged mesh'.\")\n", "\n", "# Download only the object definitions first, so the coordinate reference systems can be checked before any data is downloaded.\n", "mesh_objects = []\n", - "meshes_by_crs = [] # (crs, [mesh paths]) for each distinct CRS, including unspecified.\n", + "meshes_by_crs = []\n", "for mesh in selected_meshes:\n", " mesh_object = await mesh_helper.download_triangle_mesh_object(mesh)\n", " mesh_objects.append(mesh_object)\n", @@ -184,7 +187,6 @@ " vertices, indices = await mesh_helper.download_triangle_mesh_data(mesh, mesh_object)\n", "\n", " vertex_arrays.append(vertices)\n", - " # Offset the indices so they point at this mesh's vertices within the merged vertex table.\n", " index_arrays.append(indices + np.uint64(vertex_offset))\n", " vertex_offset += len(vertices)\n", " mesh_summaries.append((len(vertices), len(indices), mesh.path))\n", @@ -255,7 +257,11 @@ "source": [ "### Create the merged triangle mesh and publish it to Evo\n", "\n", - "Geoscience object data must conform to a specific object schema. The `evo-schemas` package provides Pydantic models that make it easy to work with the equivalent JSON schemas. For this example we'll use v2.2.0 of the triangle mesh schema, via the relevant Pydantic model." + "Geoscience object data must comply to a specific object schema. The `evo-schemas` package provides Pydantic models that make it easy to work with the equivalent JSON schemas. For this example we'll use v2.2.0 of the triangle mesh schema, via the relevant Pydantic model.\n", + "\n", + "If **Update existing merged mesh** is ticked, the object is given the UUID and name of the target mesh and published with `update_geoscience_object`, which creates a new version of the target. Otherwise, a new object is created at the name and path you entered with `create_geoscience_object`.\n", + "\n", + "> **Note:** When updating an existing mesh, the new version replaces the target's description, tags, bounding box and coordinate reference system with those of the merged mesh. Its previous versions are kept in Evo." ] }, { @@ -272,19 +278,26 @@ "\n", "from evo.notebooks import FeedbackWidget\n", "\n", - "object_name = mesh_selector.merged_name.strip() or \"Merged_Mesh_SDK_demo\"\n", - "if object_name.endswith(\".json\"):\n", - " object_name = object_name[: -len(\".json\")]\n", - "if os.environ.get(\"CI\"):\n", - " object_name += f\"_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S_%f')}\"\n", - "object_path = mesh_selector.merged_path.strip().strip(\"/\")\n", + "target_mesh = mesh_selector.target_mesh if mesh_selector.update_existing else None\n", "\n", - "# The object name requires the `.json` extension.\n", - "full_obj_path = f\"{object_path}/{object_name}.json\" if object_path else f\"{object_name}.json\"\n", + "if target_mesh is None:\n", + " object_name = mesh_selector.merged_name.strip() or \"Merged_Mesh_SDK_demo\"\n", + " if object_name.endswith(\".json\"):\n", + " object_name = object_name[: -len(\".json\")]\n", + " if os.environ.get(\"CI\"):\n", + " object_name += f\"_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S_%f')}\"\n", + " object_path = mesh_selector.merged_path.strip().strip(\"/\")\n", + "\n", + " # The object name requires the `.json` extension.\n", + " full_obj_path = f\"{object_path}/{object_name}.json\" if object_path else f\"{object_name}.json\"\n", + "else:\n", + " # Keep the name of the target mesh; its ID and path do not change when a new version is published.\n", + " object_name = target_mesh.name[: -len(\".json\")] if target_mesh.name.endswith(\".json\") else target_mesh.name\n", + " full_obj_path = target_mesh.path\n", "\n", "merged_mesh = TriangleMesh_V2_2_0(\n", " name=object_name,\n", - " uuid=None,\n", + " uuid=None if target_mesh is None else target_mesh.id,\n", " description=f\"Merge of {len(selected_meshes)} triangle meshes: \"\n", " + \", \".join(f\"'{mesh.path}'\" for mesh in selected_meshes)\n", " + \".\",\n", @@ -297,9 +310,17 @@ "# Upload the Parquet data to Evo.\n", "await data_client.upload_referenced_data(merged_mesh.as_dict(), FeedbackWidget(\"Uploading data\"))\n", "\n", - "# Create the geoscience object.\n", - "merged_mesh_metadata = await object_client.create_geoscience_object(full_obj_path, merged_mesh.as_dict())\n", - "print(f\"Published merged triangle mesh to '{full_obj_path}' (Object ID: {merged_mesh_metadata.id})\")" + "if target_mesh is None:\n", + " # Create a new geoscience object.\n", + " merged_mesh_metadata = await object_client.create_geoscience_object(full_obj_path, merged_mesh.as_dict())\n", + " print(f\"Published merged triangle mesh to '{full_obj_path}' (Object ID: {merged_mesh_metadata.id})\")\n", + "else:\n", + " # Publish a new version of the target geoscience object.\n", + " merged_mesh_metadata = await object_client.update_geoscience_object(merged_mesh.as_dict())\n", + " print(\n", + " f\"Published a new version of '{full_obj_path}' (Object ID: {merged_mesh_metadata.id}, \"\n", + " f\"Version ID: {merged_mesh_metadata.version_id})\"\n", + " )" ] }, { @@ -322,7 +343,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Success! You now have a new geoscience object in Evo containing the merged mesh data.\n", + "Success! You now have a geoscience object in Evo containing the merged mesh data, either as a new object or as a new version of the target mesh.\n", "\n", "## Summary\n", "\n", @@ -331,15 +352,11 @@ "* Downloaded the vertex and triangle index data of each selected mesh.\n", "* Merged the meshes by concatenating the vertices and offsetting the triangle indices of each mesh by the number of preceding vertices.\n", "* Saved the merged data in Parquet format and combined it into the triangle-mesh schema format.\n", - "* Uploaded the Parquet files and the newly assembled object in JSON format to Evo." + "* Uploaded the Parquet files and the assembled object in JSON format to Evo, either as a new object or as a new version of an existing mesh." ] } ], - "metadata": { - "language_info": { - "name": "python" - } - }, + "metadata": {}, "nbformat": 4, "nbformat_minor": 4 } diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py index 56bc6c6ca..1707a0d38 100644 --- a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/triangle_mesh_helpers.py @@ -23,7 +23,8 @@ class MeshSelectorWidget(widgets.VBox): - """Widget for selecting triangle meshes to merge with checkboxes, and naming the merged mesh.""" + """Widget for selecting triangle meshes to merge with checkboxes, and either naming a new merged mesh or choosing + an existing mesh to update with a new version.""" def __init__(self, meshes, default_name="Merged_Mesh_SDK_demo", default_path="Jupyter_Example/Mesh"): """ @@ -31,6 +32,9 @@ def __init__(self, meshes, default_name="Merged_Mesh_SDK_demo", default_path="Ju meshes (list[ObjectMetadata]): The triangle mesh objects to list, in display order. default_name (str): The initial name of the merged mesh. default_path (str): The initial path of the merged mesh. + + Tick "Update existing merged mesh" to choose an existing mesh from a dropdown; the merge is then published as + a new version of that mesh instead of as a new mesh. """ self.meshes = list(meshes) @@ -44,17 +48,28 @@ def __init__(self, meshes, default_name="Merged_Mesh_SDK_demo", default_path="Ju self.select_all_checkbox = widgets.Checkbox(value=False, description="Select all", indent=False) self.selection_label = widgets.Label() - self.select_all_checkbox.observe(self._toggle_all, names="value") - for checkbox in self.mesh_checkboxes: - checkbox.observe(self._update_selection_label, names="value") - self._update_selection_label() - self.merged_name_text = widgets.Text( value=default_name, description="Merged name:", style=widget_style, layout=widget_layout ) self.merged_path_text = widgets.Text( value=default_path, description="Merged path:", style=widget_style, layout=widget_layout ) + self.new_mesh_fields = widgets.VBox([self.merged_name_text, self.merged_path_text]) + + self.update_existing_checkbox = widgets.Checkbox( + value=False, description="Update existing merged mesh", indent=False + ) + self.target_mesh_dropdown = widgets.Dropdown( + description="Target mesh:", + style=widget_style, + layout=widgets.Layout(width="90%", display="none"), + ) + self.update_existing_checkbox.observe(self._toggle_update_existing, names="value") + + self.select_all_checkbox.observe(self._toggle_all, names="value") + for checkbox in self.mesh_checkboxes: + checkbox.observe(self._on_selection_changed, names="value") + self._on_selection_changed() # Scroll the mesh list if the workspace contains many meshes. mesh_list = widgets.VBox( @@ -66,8 +81,9 @@ def __init__(self, meshes, default_name="Merged_Mesh_SDK_demo", default_path="Ju [ widgets.HBox([self.select_all_checkbox, self.selection_label]), mesh_list, - self.merged_name_text, - self.merged_path_text, + self.update_existing_checkbox, + self.target_mesh_dropdown, + self.new_mesh_fields, ] ) @@ -86,9 +102,36 @@ def merged_path(self): """str: The path entered for the merged mesh.""" return self.merged_path_text.value - def _update_selection_label(self, _=None): + @property + def update_existing(self): + """bool: Whether to publish the merge as a new version of an existing mesh instead of a new mesh.""" + return self.update_existing_checkbox.value + + @property + def target_mesh(self): + """ObjectMetadata | None: The existing mesh to update when `update_existing` is ticked. Selected meshes are + excluded from the choices.""" + return self.target_mesh_dropdown.value + + def _toggle_update_existing(self, change): + # Show the target mesh dropdown when updating, otherwise show the name and path fields for a new mesh. + self.target_mesh_dropdown.layout.display = None if change["new"] else "none" + self.new_mesh_fields.layout.display = "none" if change["new"] else None + + def _on_selection_changed(self, _=None): selected_count = sum(checkbox.value for checkbox in self.mesh_checkboxes) self.selection_label.value = f"{selected_count} of {len(self.mesh_checkboxes)} meshes selected" + self._update_target_options() + + def _update_target_options(self): + """Offer only the meshes that are not selected for merging as targets to update.""" + available = [obj for obj, checkbox in zip(self.meshes, self.mesh_checkboxes) if not checkbox.value] + current = self.target_mesh_dropdown.value + # Changing the options resets the dropdown, so restore the current target if it is still available. + self.target_mesh_dropdown.options = [("Select a target mesh...", None)] + [ + (f"{obj.path} ({obj.id})", obj) for obj in available + ] + self.target_mesh_dropdown.value = current if current in available else None def _toggle_all(self, change): for checkbox in self.mesh_checkboxes: From ef35c7e12f9dc8a1cd0d5222902d609e94505a0a Mon Sep 17 00:00:00 2001 From: Shivang Jariwala <97551095+shivangj-10@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:41:07 -0500 Subject: [PATCH 3/3] requested changes --- .../geoscience-objects/bonus/merge-triangle-meshes/README.md | 4 ++-- .../bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md index 96f3d99b0..a0ccdc773 100644 --- a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/README.md @@ -7,7 +7,7 @@ Two or more [triangle mesh](https://developer.seequent.com/docs/data-structures/ All selected meshes must use the same coordinate reference system, as the notebook does not reproject data. A mesh with an unspecified coordinate reference system cannot be merged with a mesh that has one. ## Outputs -- A new triangle mesh object with the name and path you provide, containing the vertices and triangles of all selected meshes. The triangle indices of each mesh are offset by the total number of vertices in the meshes before it. -- Alternatively, tick **Update existing merged mesh** and select a target mesh to publish the merge as a new version of that mesh. The target keeps its ID, name, and path. Meshes ticked for merging cannot be chosen as the target. +- A new triangle mesh object with the name and path you provide, and containing the vertices and triangles of all selected meshes. The triangle indices of each mesh are offset by the total number of vertices in the meshes before it. +- Alternatively, tick **Update existing merged mesh** and select a target mesh to publish the merge as a new version of that mesh. The target keeps its ID, name and path. Meshes ticked for merging cannot be chosen as the target. Only the mesh geometry is merged. Attributes, parts, and edges of the source meshes are not carried over. diff --git a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb index 8c93e6f38..2ccc3952f 100644 --- a/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb +++ b/code-samples/geoscience-objects/bonus/merge-triangle-meshes/merge-triangle-meshes.ipynb @@ -104,7 +104,7 @@ "\n", "List all triangle mesh objects in the workspace and tick the checkboxes of the meshes to merge (at least two). Use **Select all** to toggle every mesh at once. You can also set the name and path of the merged object that will be published.\n", "\n", - "To publish the merge as a new version of an existing mesh instead of creating a new object, tick **Update existing merged mesh** and select the target mesh from the dropdown. The target keeps its ID, name and path, and its geometry is replaced by the merge of the selected meshes. The dropdown only lists meshes that are not ticked for merging, and is updated as you change the selection." + "To publish the merge as a new version of an existing mesh instead of creating a new object, tick **Update existing merged mesh** and select the target mesh from the dropdown. The target keeps its ID, name and path. Its geometry is replaced by the merge of the selected meshes. The dropdown only lists meshes that are not ticked for merging, and is updated as you change the selection." ] }, {