From 03fb54d46fe0f031b342693c16d2a44a429c8533 Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 21:53:07 -0500 Subject: [PATCH 1/8] feat(objects): smooth an object along a ztrace in 3D Object attributes > Smooth along ztrace... stores a source ztrace, an optional target ztrace and a window on the object. When the 3D scene or mesh export meshes it, each section is shifted from its source point to the target point, or to a smoothed copy of the source fitted against section depth. Traces, section transforms, the object list and its measurements do not change. Exported meshes carry _smooth or _smooth- in the file name, and the mesh data export gains a ZtraceSmoothing column. Remove ztrace smoothing clears it; undo reverts either. --- .../modules/backend/volume/export_volumes.py | 27 ++- .../backend/volume/generate_volumes.py | 11 +- .../modules/backend/volume/objects_3D.py | 27 +++ PyReconstruct/modules/calc/__init__.py | 5 + PyReconstruct/modules/calc/smooth.py | 153 ++++++++++++++ PyReconstruct/modules/datatypes/series.py | 192 +++++++++++++++++- .../modules/gui/main/context_menu_list.py | 2 + .../modules/gui/main/field_widget_3_object.py | 92 ++++++++- manual/readme.md | 28 +++ 9 files changed, 513 insertions(+), 24 deletions(-) create mode 100644 PyReconstruct/modules/calc/smooth.py diff --git a/PyReconstruct/modules/backend/volume/export_volumes.py b/PyReconstruct/modules/backend/volume/export_volumes.py index 193629118..02775d723 100644 --- a/PyReconstruct/modules/backend/volume/export_volumes.py +++ b/PyReconstruct/modules/backend/volume/export_volumes.py @@ -6,7 +6,7 @@ import numpy as np import trimesh -from .objects_3D import Surface, Spheres, Contours +from .objects_3D import Surface, Spheres, Contours, meshTform from PyReconstruct.modules.datatypes import Series from PyReconstruct.modules.gui.utils import notify @@ -38,7 +38,9 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t for obj_name, obj_3D in obj_data.items(): - output_file = output_directory / f"{obj_name}.{export_type}" + # a smoothed mesh says so in its name, e.g. dendrite_smooth4.obj + suffix = f"_{obj_3D.smoothing}" if obj_3D.smoothing else "" + output_file = output_directory / f"{obj_name}{suffix}.{export_type}" if type(obj_3D) is Surface or type(obj_3D) is Spheres: @@ -56,7 +58,7 @@ def export3DData(series: Series, obj_names: list, output_fp: str, notify_user: b """Export quantitative data from meshes.""" sep = "," - csv_str = f"Series{sep}Name{sep}MeshType{sep}SurfaceArea{sep}Volume\n" + csv_str = f"Series{sep}Name{sep}MeshType{sep}SurfaceArea{sep}Volume{sep}ZtraceSmoothing\n" series_code = series.code errors = {} @@ -72,7 +74,8 @@ def export3DData(series: Series, obj_names: list, output_fp: str, notify_user: b surface_area = round(tm.area, 5) volume = round(tm.volume, 5) - csv_str += f"{series_code}{sep}{obj}{sep}{obj_type}{sep}{surface_area}{sep}{volume}\n" + # the mesh is smoothed along a ztrace if ZtraceSmoothing is not blank + csv_str += f"{series_code}{sep}{obj}{sep}{obj_type}{sep}{surface_area}{sep}{volume}{sep}{obj_data.smoothing}\n" except Exception as e: @@ -108,6 +111,10 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou elif mode == "contours": obj_data = Contours(obj_name, series) + ## Shifts if the object is smoothed along a ztrace + + offsets, obj_data.smoothing = series.getZtraceSmoothing(obj_name) + ## Iterate through sections and collect data for snum, section in series.enumerateSections(show_progress=False): @@ -119,16 +126,8 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou continue - ## Get alignment - obj_alignment = series.getAttr(obj_name, "alignment") - - if not obj_alignment: - - tform = section.tform - - else: - - tform = section.tforms[obj_alignment] + ## Get alignment and smoothing shift + tform = meshTform(series, obj_name, snum, section, offsets) for trace in section.contours[obj_name]: diff --git a/PyReconstruct/modules/backend/volume/generate_volumes.py b/PyReconstruct/modules/backend/volume/generate_volumes.py index 261033054..a372cae01 100644 --- a/PyReconstruct/modules/backend/volume/generate_volumes.py +++ b/PyReconstruct/modules/backend/volume/generate_volumes.py @@ -1,6 +1,6 @@ from typing import Union -from .objects_3D import Surface, Spheres, Contours, Ztrace3D +from .objects_3D import Surface, Spheres, Contours, Ztrace3D, meshTform from PyReconstruct.modules.datatypes import Series @@ -51,6 +51,9 @@ def generateVolumes(series_like : Series_like_obj, objs : dict, ztraces : dict): elif mode == "contours": obj_data[name] = Contours(*args) + # the per-section shifts of objects smoothed along a ztrace + offsets = {name: series.getZtraceSmoothing(name)[0] for name in obj_data} + # iterate through all sections and gather points (and colors) mags = [] thicknesses = [] @@ -63,11 +66,7 @@ def generateVolumes(series_like : Series_like_obj, objs : dict, ztraces : dict): for obj_name in obj_data.keys(): if obj_name in section.contours: # get the transform sepcific to the object - alignment = series.getAttr(obj_name, "alignment") - if not alignment: - tform = section.tform - else: - tform = section.tforms[alignment] + tform = meshTform(series, obj_name, snum, section, offsets[obj_name]) for trace in section.contours[obj_name]: # collect all points if generating a full surface obj_data[obj_name].addTrace(trace, snum, tform) diff --git a/PyReconstruct/modules/backend/volume/objects_3D.py b/PyReconstruct/modules/backend/volume/objects_3D.py index 87a8d5dc7..0d353db76 100644 --- a/PyReconstruct/modules/backend/volume/objects_3D.py +++ b/PyReconstruct/modules/backend/volume/objects_3D.py @@ -37,6 +37,32 @@ def exportMesh(tm, output_file, export_type): fp.write(trimesh.exchange.dae.export_collada(tm)) +def meshTform(series : Series, obj_name : str, snum : int, section, offsets : dict = None) -> Transform: + """Return the transform that places an object's traces on a section in 3D. + + Params: + series (Series): the series containing the object + obj_name (str): the object + snum (int): the section number + section (Section): the section + offsets (dict): section number : (dx, dy) smoothing shifts (from Series.getZtraceSmoothing) + Returns: + (Transform): the object's alignment, then its smoothing shift + """ + alignment = series.getAttr(obj_name, "alignment") + if not alignment: + tform = section.tform + else: + tform = section.tforms[alignment] + + if offsets and snum in offsets: + dx, dy = offsets[snum] + # the left transform applies first: align, then shift + tform = tform * Transform([1, 0, dx, 0, 1, dy]) + + return tform + + class Object3D(): def __init__(self, name, series : Series, color=None, alpha=None, tform=None): @@ -46,6 +72,7 @@ def __init__(self, name, series : Series, color=None, alpha=None, tform=None): self.alpha = alpha self.tform = tform self.extremes = [] # xmin, xmax, ymin, ymax, zmin, zmax + self.smoothing = "" # label of a ztrace smoothing applied to the mesh def addToExtremes(self, x, y, s): """Keep track of the extreme values.""" diff --git a/PyReconstruct/modules/calc/__init__.py b/PyReconstruct/modules/calc/__init__.py index 403b43833..4ceec7d7b 100644 --- a/PyReconstruct/modules/calc/__init__.py +++ b/PyReconstruct/modules/calc/__init__.py @@ -36,3 +36,8 @@ point_list_2_pix ) from .correlation import correlate +from .smooth import ( + ztraceResiduals, + ztraceDifferences, + sectionOffsets +) diff --git a/PyReconstruct/modules/calc/smooth.py b/PyReconstruct/modules/calc/smooth.py new file mode 100644 index 000000000..0f56219c9 --- /dev/null +++ b/PyReconstruct/modules/calc/smooth.py @@ -0,0 +1,153 @@ +"""Per-section offsets that smooth an object in 3D along a z-trace. + +A z-trace drawn through an object's midpoints wiggles where the sections sit +at the wrong offsets. Either a smoothed copy of that z-trace or a second +z-trace drawn by hand says where each section should sit; that point minus +the source point is the section's offset. The offset is a pure translation, +so no contour changes shape, area or volume. + +Everything here works in field coordinates and knows nothing about series, +sections or Qt. +""" + +from bisect import bisect_left + + +def smoothedPath(points : list, window : int, depths : list = None) -> list: + """Smooth a path by fitting a line through each point's window of neighbors. + + The window holds window // 2 points on each side, the width of the moving + average Ztrace.smooth uses. Near the ends it shifts to stay inside the + path instead of repeating the end point. Each line is fitted against + depth, so a path that is straight in space stays where it is, however its + points are spaced. With evenly spaced points and a window that fits, the + result equals the moving average. + + Params: + points (list): (x, y) points in path order + window (int): the smoothing window + depths (list): the depth of each point (default: its index) + Returns: + (list): the smoothed (x, y) points + """ + n = len(points) + if depths is None: + depths = list(range(n)) + width = min(2 * (window // 2) + 1, n) + + smoothed = [] + for i in range(n): + start = min(max(i - width // 2, 0), n - width) + span = range(start, start + width) + mean_z = sum(depths[j] for j in span) / width + spread = sum((depths[j] - mean_z) ** 2 for j in span) + fitted = [] + for axis in (0, 1): + mean_v = sum(points[j][axis] for j in span) / width + if spread == 0: # every point in the window at one depth + fitted.append(mean_v) + continue + slope = sum( + (depths[j] - mean_z) * (points[j][axis] - mean_v) for j in span + ) / spread + fitted.append(mean_v + slope * (depths[i] - mean_z)) + smoothed.append(tuple(fitted)) + + return smoothed + + +def ztraceResiduals(field_points : list, window : int, depths : dict = None) -> list: + """Return the smoothed-minus-raw offset of every z-trace point. + + Params: + field_points (list): (x, y, snum) z-trace points in field coordinates + window (int): the smoothing window + depths (dict): section number : depth (default: the section number) + Returns: + (list): (dx, dy, snum) for each point, in the same order + """ + smoothed = smoothedPath( + [(x, y) for x, y, _ in field_points], + window, + [depths[snum] if depths else snum for _, _, snum in field_points], + ) + + return [ + (sx - x, sy - y, snum) + for (sx, sy), (x, y, snum) in zip(smoothed, field_points) + ] + + +def ztraceDifferences(source_points : list, target_points : list) -> list: + """Return the target-minus-source offset on each section both z-traces cover. + + Several points on one section are averaged first. A section only one of + the z-traces covers gives no offset here; sectionOffsets fills it in. + + Params: + source_points (list): (x, y, snum) source points in field coordinates + target_points (list): (x, y, snum) target points in field coordinates + Returns: + (list): (dx, dy, snum) for each shared section, in section order + """ + def means(points): + sums = {} + for x, y, snum in points: + sx, sy, n = sums.get(snum, (0.0, 0.0, 0)) + sums[snum] = (sx + x, sy + y, n + 1) + return {snum: (sx / n, sy / n) for snum, (sx, sy, n) in sums.items()} + + source, target = means(source_points), means(target_points) + + return [ + (target[snum][0] - source[snum][0], target[snum][1] - source[snum][1], snum) + for snum in sorted(source.keys() & target.keys()) + ] + + +def sectionOffsets(residuals : list, section_numbers) -> dict: + """Return one (dx, dy) offset for each requested section. + + Rules, in order: + - a section with several z-trace points gets the mean of their offsets; + - a section between covered sections gets a linear interpolation by + section number, which is how the z-trace line is drawn across skipped + sections; + - a section before the first or after the last covered section holds the + nearest end's offset (clamped), so the mesh has no step at the ends. + + Params: + residuals (list): (dx, dy, snum) offsets + section_numbers (iterable): the sections that need an offset + Returns: + (dict): section number : (dx, dy) + """ + sums = {} + for dx, dy, snum in residuals: + sx, sy, n = sums.get(snum, (0.0, 0.0, 0)) + sums[snum] = (sx + dx, sy + dy, n + 1) + + if not sums: + raise ValueError("No z-trace points to take offsets from.") + + covered = {snum: (sx / n, sy / n) for snum, (sx, sy, n) in sums.items()} + ordered = sorted(covered) + first, last = ordered[0], ordered[-1] + + offsets = {} + for snum in section_numbers: + if snum in covered: + offsets[snum] = covered[snum] + elif snum < first: + offsets[snum] = covered[first] + elif snum > last: + offsets[snum] = covered[last] + else: + # the nearest covered sections on either side + k = bisect_left(ordered, snum) + below, above = ordered[k - 1], ordered[k] + t = (snum - below) / (above - below) + (x0, y0), (x1, y1) = covered[below], covered[above] + offsets[snum] = (x0 + t * (x1 - x0), y0 + t * (y1 - y0)) + + return offsets diff --git a/PyReconstruct/modules/datatypes/series.py b/PyReconstruct/modules/datatypes/series.py index 8cecde704..a747af5bf 100644 --- a/PyReconstruct/modules/datatypes/series.py +++ b/PyReconstruct/modules/datatypes/series.py @@ -20,7 +20,13 @@ from .default_settings import default_settings, default_series_settings from .host_tree import HostTree -from PyReconstruct.modules.calc import area, lineDistance +from PyReconstruct.modules.calc import ( + area, + lineDistance, + ztraceResiduals, + ztraceDifferences, + sectionOffsets +) from PyReconstruct.modules.constants import ( createHiddenDir, @@ -1090,7 +1096,189 @@ def deleteZtraces(self, names : list, log_event=True): if log_event: self.addLog(name, None, "Delete ztrace") - + + def _alignment3D(self, name : str, ztrace=False) -> str: + """Return the alignment the 3D scene places an object or ztrace in.""" + return self.getAttr(name, "alignment", ztrace=ztrace) or self.alignment + + def _ztraceFieldPoints(self, ztrace_name : str, alignment : str) -> list: + """Return a ztrace's points in field coordinates under an alignment.""" + sections = self.data["sections"] + points = [] + for x, y, snum in self.ztraces[ztrace_name].points: + if snum not in sections: + continue + fx, fy = sections[snum]["tforms"][alignment].map(x, y) + points.append((fx, fy, snum)) + return points + + def ztraceSmoothingProblems(self, obj_names : list, source : str, target : str, window : int) -> list: + """List the reasons the objects cannot be smoothed along the ztrace. + + Params: + obj_names (list): the objects to smooth + source (str): the ztrace the objects were traced along + target (str): the ztrace to move the source onto (None: a smoothed copy of the source) + window (int): the smoothing window, in sections + Returns: + (list): one message per problem; empty if smoothing can run + """ + ztraces = [z for z in (source, target) if z] + for z in ztraces: + if z not in self.ztraces: + return [f"Ztrace {z} does not exist."] + if window < 2: + return ["The window must be at least 2 sections."] + + alignments = self.alignments + z_align = self._alignment3D(source, ztrace=True) + for z in ztraces: + a = self._alignment3D(z, ztrace=True) + if a not in alignments: + return [f"Ztrace {z} uses alignment {a}, which no longer exists."] + if a != z_align: + return [ + f"Ztrace {source} uses alignment {z_align} but ztrace " + f"{target} uses {a}. Give them the same alignment first." + ] + + z_points = self._ztraceFieldPoints(source, z_align) + if len(z_points) < 2: + return [f"Ztrace {source} has fewer than 2 points."] + z_sections = set(snum for _, _, snum in z_points) + if target: + t_sections = set(snum for _, _, snum in self._ztraceFieldPoints(target, z_align)) + if not z_sections & t_sections: + return [f"Ztraces {source} and {target} share no section."] + + problems = [] + for obj_name in obj_names: + if obj_name not in self.data["objects"]: + problems.append(f"Object {obj_name} has no traces.") + continue + + base = self._alignment3D(obj_name) + if base not in alignments: + problems.append(f"Object {obj_name} uses alignment {base}, which no longer exists.") + continue + if base != z_align: + problems.append( + f"Object {obj_name} uses alignment {base} but ztrace " + f"{source} uses {z_align}. Give them the same alignment first." + ) + + obj_sections = set(self.data["objects"][obj_name].traces) + covered = len(obj_sections & z_sections) + if covered < 3: + problems.append( + f"Ztrace {source} covers {covered} of the sections " + f"{obj_name} is on. It needs to cover at least 3." + ) + + return problems + + def ztraceSmoothingOffsets(self, obj_name : str, source : str, target : str, window : int) -> dict: + """Return the shift for each section that smooths an object along a ztrace. + + Without a target, each section moves from its source ztrace point to the + same point on a smoothed copy of the source. With a target, it moves from + the source point to the target point on the same section. Check + ztraceSmoothingProblems first. + + Params: + obj_name (str): the object to smooth + source (str): the ztrace the object was traced along + target (str): the ztrace to move the source onto (None: a smoothed copy of the source) + window (int): the smoothing window, in sections + Returns: + (dict): section number : (dx, dy) in field coordinates + """ + alignment = self._alignment3D(obj_name) + source_points = self._ztraceFieldPoints(source, alignment) + if target: + residuals = ztraceDifferences( + source_points, self._ztraceFieldPoints(target, alignment) + ) + else: + residuals = ztraceResiduals(source_points, window, self.getZValues()) + + return sectionOffsets(residuals, self.sections) + + def getZtraceSmoothing(self, obj_name : str) -> tuple: + """Return the shifts the 3D scene and mesh export apply to an object. + + Params: + obj_name (str): the object + Returns: + (dict): section number : (dx, dy), or None if the object is meshed as traced + (str): the label for an exported mesh, e.g. smooth4; empty if not smoothed + """ + smoothing = self.getAttr(obj_name, "3D_smooth") + if not smoothing: + return None, "" + + source, target, window = smoothing["source"], smoothing["target"], smoothing["window"] + problems = self.ztraceSmoothingProblems([obj_name], source, target, window) + if problems: + print(f"{obj_name} is meshed as traced, without smoothing:") + print("\n".join(problems)) + return None, "" + + offsets = self.ztraceSmoothingOffsets(obj_name, source, target, window) + label = f"smooth-{target}" if target else f"smooth{window}" + + return offsets, label + + def setZtraceSmoothing(self, obj_names : list, source : str, target : str, window : int, log_event=True): + """Smooth objects in the 3D scene and mesh export along a ztrace. + + Stores the settings on each object. Nothing else changes: the shifts are + computed from the live ztraces each time the object is meshed, and the + traces, section transforms and measurements stay as traced. + + Params: + obj_names (list): the objects to smooth + source (str): the ztrace the objects were traced along + target (str): the ztrace to move the source onto (None: a smoothed copy of the source) + window (int): the smoothing window, in sections + log_event (bool): True if event should be logged + """ + target = target or None + problems = self.ztraceSmoothingProblems(obj_names, source, target, window) + if problems: + raise ValueError("\n".join(problems)) + + for obj_name in obj_names: + self.setAttr( + obj_name, + "3D_smooth", + {"source": source, "target": target, "window": window} + ) + if log_event: + if target: + event = f"Smooth along ztrace {source} toward {target}" + else: + event = f"Smooth along ztrace {source} (window {window})" + self.addLog(obj_name, None, event) + + self.modified = True + + def removeZtraceSmoothing(self, obj_names : list, log_event=True): + """Mesh objects as traced again. + + Params: + obj_names (list): the objects + log_event (bool): True if event should be logged + """ + for obj_name in obj_names: + if self.getAttr(obj_name, "3D_smooth") is None: + continue + self.setAttr(obj_name, "3D_smooth", None) + if log_event: + self.addLog(obj_name, None, "Remove ztrace smoothing") + + self.modified = True + def rename(self, new_name : str): """Rename the series. diff --git a/PyReconstruct/modules/gui/main/context_menu_list.py b/PyReconstruct/modules/gui/main/context_menu_list.py index 5ef1f5624..9b221f84e 100644 --- a/PyReconstruct/modules/gui/main/context_menu_list.py +++ b/PyReconstruct/modules/gui/main/context_menu_list.py @@ -77,6 +77,8 @@ def get_context_menu_list_obj(self): ("removeobjallgroups_act", "Remove from all groups", "", self.removeFromAllGroups), None, ("setobjalignment_act", "Change object alignment...", "", self.editAlignment), + ("smoothobjztrace_act", "Smooth along ztrace...", "", self.smoothAlongZtrace), + ("unsmoothobjztrace_act", "Remove ztrace smoothing", "", self.removeZtraceSmoothing), None, ("lockobj_act", "Lock", "", self.lockObjects), ("unlockobj_act", "Unlock", "", lambda : self.lockObjects(False)) diff --git a/PyReconstruct/modules/gui/main/field_widget_3_object.py b/PyReconstruct/modules/gui/main/field_widget_3_object.py index 8587eeb7d..55589f54c 100644 --- a/PyReconstruct/modules/gui/main/field_widget_3_object.py +++ b/PyReconstruct/modules/gui/main/field_widget_3_object.py @@ -1,3 +1,6 @@ +import math +from statistics import median + from .context_menu_list import get_context_menu_list_obj from PySide6.QtWidgets import ( @@ -17,7 +20,8 @@ TextWidget, ) from PyReconstruct.modules.gui.utils import ( - notify + notify, + notifyConfirm ) from PyReconstruct.modules.gui.table import ( HistoryTableWidget, @@ -373,7 +377,91 @@ def editAlignment(self, obj_names : list): self.table_manager.refreshObjects(lambda name: name in edited) return True - + + @object_function(update_objects=False, reload_field=False) + def smoothAlongZtrace(self, obj_names : list): + """Smooth objects in the 3D scene and mesh export along a ztrace.""" + ztrace_names = sorted(self.series.ztraces) + if not ztrace_names: + notify("There are no ztraces in this series.") + return False + + # offer the current settings, else the object's own ztrace + source, target, window = None, None, 4 + if len(obj_names) == 1: + current = self.series.getAttr(obj_names[0], "3D_smooth") + if current: + source, target, window = current["source"], current["target"], current["window"] + elif f"{obj_names[0]}_zlen" in self.series.ztraces: + source = f"{obj_names[0]}_zlen" + + obj_sections = set() + for name in obj_names: + if name in self.series.data["objects"]: + obj_sections.update(self.series.data["objects"][name].traces) + thickness = median( + self.series.data["sections"][snum]["thickness"] for snum in obj_sections + ) if obj_sections else self.series.avg_thickness + + structure = [ + ["Source ztrace:", (True, "combo", ztrace_names, source)], + ["Target ztrace (optional):", ("combo", ztrace_names, target)], + ["Window N (sections):", (True, "int", window)], + [f"Sections here are {thickness:.3g} um thick, so N = 4 spans {4 * thickness:.3g} um."], + ["Bends shorter than about 3N sections are smoothed away, real or not. Use the smallest N that removes the jitter."], + ] + response, confirmed = QuickDialog.get(self, structure, "Smooth Along Ztrace") + if not confirmed: + return False + source, target, window = response + target = target or None + + problems = self.series.ztraceSmoothingProblems(obj_names, source, target, window) + if problems: + notify("\n\n".join(problems)) + return False + + # the largest shift any section of these objects gets + largest = 0 + for name in obj_names: + offsets = self.series.ztraceSmoothingOffsets(name, source, target, window) + for snum in self.series.data["objects"][name].traces: + largest = max(largest, math.hypot(*offsets[snum])) + + if target: + how = f"toward ztrace {target}" + else: + how = f"with a window of {window} sections ({window * thickness:.3g} um)" + message = ( + f"Smooth {', '.join(obj_names)} along ztrace {source} {how}. " + f"The largest shift is {largest:.3g} um.\n\n" + "Only the 3D scene and exported meshes move. Traces, the object " + "list and its measurements stay as traced. An object already in an " + "open 3D scene keeps its old shape until it is generated again." + ) + if not notifyConfirm(message): + return False + + self.series_states.addState() + self.series.setZtraceSmoothing(obj_names, source, target, window) + self.mainwindow.seriesModified(True) + + return True + + @object_function(update_objects=False, reload_field=False) + def removeZtraceSmoothing(self, obj_names : list): + """Mesh objects as traced again.""" + smoothed = [n for n in obj_names if self.series.getAttr(n, "3D_smooth")] + if not smoothed: + notify("The selected objects are not smoothed along a ztrace.") + return False + + self.series_states.addState() + self.series.removeZtraceSmoothing(smoothed) + self.mainwindow.seriesModified(True) + + return True + @object_function(update_objects=True, reload_field=True) def editRadius(self, obj_names : list): """Modify the radius of the trace on an entire object.""" diff --git a/manual/readme.md b/manual/readme.md index 2f7321474..62312627a 100644 --- a/manual/readme.md +++ b/manual/readme.md @@ -635,6 +635,34 @@ Removes all tags on traces associated with the selected object(s) Allows the user to set the hidden status for all individual traces associated with an objects. +### Object Attributes + +#### Smooth Along Ztrace + +Smooths the selected object(s) along a ztrace in the 3D scene and in exported meshes, without realigning the series. + +Choose a source ztrace, an optional target ztrace, and a window N in sections (default 4). The object's own `_zlen` ztrace (Create ztrace > On contour midpoints) is offered as the source. The dialog shows how far N sections span in um, and the confirmation shows the largest shift. + +- With no target, each section is shifted from its source ztrace point to the same point on a smoothed copy of the source. Each point is smoothed by fitting a straight line, against section depth, through it and N/2 neighbors on each side. A straight ztrace, slanted or not, is left where it is. +- With a target, each section is shifted from its source ztrace point to the target ztrace point on the same section. +- A section with several ztrace points is shifted by their average, a section the ztrace skips is interpolated from its neighbors, and a section past either end keeps the shift at that end. + +What moves: the object in the 3D scene and in exported meshes. What does not move: traces, images, section transforms, and the object list and its CSV export, including the object's flat area, volume and radius. Everything measured on an exported mesh is smoothed: 3D length, surface area and tortuosity, and also the mesh's own volume, because the surface is rebuilt between the shifted sections. The exported file name ends in `_smooth` (or `_smooth-` with a target), and Export quantitative data fills in the ZtraceSmoothing column for it. + +Smoothing cannot tell jitter from a real bend. Bends shorter than about 3N sections are smoothed away, real or not. Use the smallest N that removes the jitter. + +A step at a flaw, such as a fold or a lost section, is spread over the window but not removed. To remove it, make a second ztrace that follows the object as it should run (for example, Smooth on the source ztrace with a new ztrace), move its points on the sections around the flaw so it crosses the flaw without the step, and choose it as the target. + +The object and the ztraces must use the same alignment. The setting is saved with the series, and the shifts are computed from the ztraces each time the object is generated or exported, so an edited ztrace takes effect the next time. An object already in an open 3D scene keeps its old shape until it is generated again. + +This action can be undone with Ctrl+Z or Edit>Undo. + +#### Remove Ztrace Smoothing + +Generates and exports the selected object(s) as traced again. + +This action can be undone with Ctrl+Z or Edit>Undo. + ### 3D #### Generate 3D From 3d6e484dec12da0e451cbb1da81c9dc5ddb8a20d Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 22:22:58 -0500 Subject: [PATCH 2/8] fix(objects): label, read and keep ztrace smoothing in the 3D scene Export scene names a smoothed mesh _smooth or _smooth-, alone and in the combined file. The coordinate readout and double-click take the shift back off. Renaming a ztrace updates the settings that name it; deleting one clears them in the same undo step, with a notice. A setting that cannot be applied meshes as traced with a warning naming the object. Series import skips the setting and lists the objects. The window counts ztrace points, and the dialog shows how deep N points reach. The manual says the measurement columns are unchanged. --- .../modules/backend/volume/export_volumes.py | 28 +++++- .../backend/volume/generate_volumes.py | 12 ++- .../modules/backend/volume/objects_3D.py | 2 + PyReconstruct/modules/calc/__init__.py | 1 + PyReconstruct/modules/calc/smooth.py | 23 +++++ PyReconstruct/modules/datatypes/series.py | 87 ++++++++++++++++--- .../modules/gui/main/field_widget_2_trace.py | 7 +- .../modules/gui/main/field_widget_3_object.py | 23 +++-- PyReconstruct/modules/gui/main/main_window.py | 14 ++- .../modules/gui/popup/custom_plotter.py | 24 ++++- manual/readme.md | 8 +- 11 files changed, 191 insertions(+), 38 deletions(-) diff --git a/PyReconstruct/modules/backend/volume/export_volumes.py b/PyReconstruct/modules/backend/volume/export_volumes.py index 02775d723..248240192 100644 --- a/PyReconstruct/modules/backend/volume/export_volumes.py +++ b/PyReconstruct/modules/backend/volume/export_volumes.py @@ -32,6 +32,8 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t obj_data[obj_name] = get_3D_mesh(series, obj_name) + reportSmoothingProblems([o.smoothing_problem for o in obj_data.values()], notify_user) + ## Iterate through objects and export 3D meshes output_directory = Path(output_dir) @@ -62,12 +64,14 @@ def export3DData(series: Series, obj_names: list, output_fp: str, notify_user: b series_code = series.code errors = {} + problems = [] for obj in obj_names: try: obj_data = get_3D_mesh(series, obj) + problems.append(obj_data.smoothing_problem) obj_type = type(obj_data).__name__.lower() tm = obj_data.generateTrimesh() @@ -81,6 +85,8 @@ def export3DData(series: Series, obj_names: list, output_fp: str, notify_user: b errors[obj] = e + reportSmoothingProblems(problems, notify_user) + if not errors: with open(output_fp, "w") as fp: @@ -113,7 +119,7 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou ## Shifts if the object is smoothed along a ztrace - offsets, obj_data.smoothing = series.getZtraceSmoothing(obj_name) + obj_data.offsets, obj_data.smoothing, obj_data.smoothing_problem = series.getZtraceSmoothing(obj_name) ## Iterate through sections and collect data @@ -127,7 +133,7 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou continue ## Get alignment and smoothing shift - tform = meshTform(series, obj_name, snum, section, offsets) + tform = meshTform(series, obj_name, snum, section, obj_data.offsets) for trace in section.contours[obj_name]: @@ -137,6 +143,24 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou return obj_data +def reportSmoothingProblems(problems: list, notify_user: bool = True) -> None: + """Say which objects were meshed as traced because their ztrace smoothing cannot be applied.""" + + problems = [p for p in problems if p] + + if not problems: + + return + + message = "\n\n".join(problems) + + if notify_user: + notify(message) + + else: + print(message) + + def convert_vedo_to_tm(obj) -> trimesh.Trimesh: """Convert vtk/vedo meshes to trimesh meshes.""" diff --git a/PyReconstruct/modules/backend/volume/generate_volumes.py b/PyReconstruct/modules/backend/volume/generate_volumes.py index a372cae01..fc3845f07 100644 --- a/PyReconstruct/modules/backend/volume/generate_volumes.py +++ b/PyReconstruct/modules/backend/volume/generate_volumes.py @@ -52,7 +52,8 @@ def generateVolumes(series_like : Series_like_obj, objs : dict, ztraces : dict): obj_data[name] = Contours(*args) # the per-section shifts of objects smoothed along a ztrace - offsets = {name: series.getZtraceSmoothing(name)[0] for name in obj_data} + for name, obj_3D in obj_data.items(): + obj_3D.offsets, obj_3D.smoothing, obj_3D.smoothing_problem = series.getZtraceSmoothing(name) # iterate through all sections and gather points (and colors) mags = [] @@ -66,7 +67,7 @@ def generateVolumes(series_like : Series_like_obj, objs : dict, ztraces : dict): for obj_name in obj_data.keys(): if obj_name in section.contours: # get the transform sepcific to the object - tform = meshTform(series, obj_name, snum, section, offsets[obj_name]) + tform = meshTform(series, obj_name, snum, section, obj_data[obj_name].offsets) for trace in section.contours[obj_name]: # collect all points if generating a full surface obj_data[obj_name].addTrace(trace, snum, tform) @@ -95,6 +96,13 @@ def generateVolumes(series_like : Series_like_obj, objs : dict, ztraces : dict): mesh_data_list.append(obj_3D.generate3D()) elif type(obj_3D) is Contours: mesh_data_list.append(obj_3D.generate3D()) + + # the scene keeps each object's smoothing, to label exports and read field coordinates + for mesh_data in mesh_data_list: + obj_3D = obj_data[mesh_data["name"]] + mesh_data["smoothing"] = obj_3D.smoothing + mesh_data["offsets"] = obj_3D.offsets + mesh_data["smoothing_problem"] = obj_3D.smoothing_problem for _, ztrace_3D in ztrace_data.items(): mesh_data = ztrace_3D.generate3D() diff --git a/PyReconstruct/modules/backend/volume/objects_3D.py b/PyReconstruct/modules/backend/volume/objects_3D.py index 0d353db76..d14e22c9b 100644 --- a/PyReconstruct/modules/backend/volume/objects_3D.py +++ b/PyReconstruct/modules/backend/volume/objects_3D.py @@ -73,6 +73,8 @@ def __init__(self, name, series : Series, color=None, alpha=None, tform=None): self.tform = tform self.extremes = [] # xmin, xmax, ymin, ymax, zmin, zmax self.smoothing = "" # label of a ztrace smoothing applied to the mesh + self.offsets = None # section number : (dx, dy) of that smoothing + self.smoothing_problem = "" # why a ztrace smoothing setting was not applied def addToExtremes(self, x, y, s): """Keep track of the extreme values.""" diff --git a/PyReconstruct/modules/calc/__init__.py b/PyReconstruct/modules/calc/__init__.py index 4ceec7d7b..58f7ca0c2 100644 --- a/PyReconstruct/modules/calc/__init__.py +++ b/PyReconstruct/modules/calc/__init__.py @@ -37,6 +37,7 @@ ) from .correlation import correlate from .smooth import ( + windowDepthSpan, ztraceResiduals, ztraceDifferences, sectionOffsets diff --git a/PyReconstruct/modules/calc/smooth.py b/PyReconstruct/modules/calc/smooth.py index 0f56219c9..67e3eba1c 100644 --- a/PyReconstruct/modules/calc/smooth.py +++ b/PyReconstruct/modules/calc/smooth.py @@ -56,6 +56,29 @@ def smoothedPath(points : list, window : int, depths : list = None) -> list: return smoothed +def windowDepthSpan(depths : list, window : int) -> float: + """Return how far in depth a smoothing window of path points reaches. + + The window is the one smoothedPath fits a line through. Points can be + spaced unevenly, so this is the median over the path. + + Params: + depths (list): the depth of each point, in path order + window (int): the smoothing window + Returns: + (float): the median depth from a window's first point to its last + """ + n = len(depths) + width = min(2 * (window // 2) + 1, n) + spans = sorted( + abs(depths[start + width - 1] - depths[start]) + for start in range(n - width + 1) + ) + mid = len(spans) // 2 + + return spans[mid] if len(spans) % 2 else (spans[mid - 1] + spans[mid]) / 2 + + def ztraceResiduals(field_points : list, window : int, depths : dict = None) -> list: """Return the smoothed-minus-raw offset of every z-trace point. diff --git a/PyReconstruct/modules/datatypes/series.py b/PyReconstruct/modules/datatypes/series.py index a747af5bf..69c64aa9d 100644 --- a/PyReconstruct/modules/datatypes/series.py +++ b/PyReconstruct/modules/datatypes/series.py @@ -23,6 +23,7 @@ from PyReconstruct.modules.calc import ( area, lineDistance, + windowDepthSpan, ztraceResiduals, ztraceDifferences, sectionOffsets @@ -1034,6 +1035,13 @@ def editZtraceAttributes(self, name : str, new_name : str, new_color : tuple, lo for g in groups: self.ztrace_groups.add(g, new_name) self.ztrace_groups.removeObject(name) + # objects smoothed along the ztrace follow it to the new name + for obj_name in self._smoothedAlong(name): + smoothing = dict(self.getAttr(obj_name, "3D_smooth")) + for key in ("source", "target"): + if smoothing[key] == name: + smoothing[key] = new_name + self.setAttr(obj_name, "3D_smooth", smoothing) if new_color: ztrace.color = new_color @@ -1084,11 +1092,20 @@ def smoothZtraces(self, names : list, smooth : int, newztrace : bool, log_event= if log_event: self.addLog(name, None, "Smooth ztrace") - def deleteZtraces(self, names : list, log_event=True): - """Delete a list of ztraces: + def deleteZtraces(self, names : list, log_event=True) -> list: + """Delete a list of ztraces. + + Objects smoothed along or toward a deleted ztrace are meshed as traced again. + Params: names (list): the names of the ztraces + Returns: + (list): the objects whose ztrace smoothing was removed """ + unsmoothed = sorted(set(obj for name in names for obj in self._smoothedAlong(name))) + if unsmoothed: + self.removeZtraceSmoothing(unsmoothed, log_event) + for name in names: del(self.ztraces[name]) self.modified_ztraces.add(name) @@ -1097,6 +1114,17 @@ def deleteZtraces(self, names : list, log_event=True): if log_event: self.addLog(name, None, "Delete ztrace") + return unsmoothed + + def _smoothedAlong(self, ztrace_name : str) -> list: + """List the objects smoothed along or toward a ztrace.""" + return [ + obj_name for obj_name, attrs in self.obj_attrs.items() + if attrs.get("3D_smooth") and ztrace_name in ( + attrs["3D_smooth"]["source"], attrs["3D_smooth"]["target"] + ) + ] + def _alignment3D(self, name : str, ztrace=False) -> str: """Return the alignment the 3D scene places an object or ztrace in.""" return self.getAttr(name, "alignment", ztrace=ztrace) or self.alignment @@ -1119,7 +1147,7 @@ def ztraceSmoothingProblems(self, obj_names : list, source : str, target : str, obj_names (list): the objects to smooth source (str): the ztrace the objects were traced along target (str): the ztrace to move the source onto (None: a smoothed copy of the source) - window (int): the smoothing window, in sections + window (int): the smoothing window, in ztrace points Returns: (list): one message per problem; empty if smoothing can run """ @@ -1128,7 +1156,7 @@ def ztraceSmoothingProblems(self, obj_names : list, source : str, target : str, if z not in self.ztraces: return [f"Ztrace {z} does not exist."] if window < 2: - return ["The window must be at least 2 sections."] + return ["The window must be at least 2 ztrace points."] alignments = self.alignments z_align = self._alignment3D(source, ztrace=True) @@ -1189,7 +1217,7 @@ def ztraceSmoothingOffsets(self, obj_name : str, source : str, target : str, win obj_name (str): the object to smooth source (str): the ztrace the object was traced along target (str): the ztrace to move the source onto (None: a smoothed copy of the source) - window (int): the smoothing window, in sections + window (int): the smoothing window, in ztrace points Returns: (dict): section number : (dx, dy) in field coordinates """ @@ -1204,6 +1232,25 @@ def ztraceSmoothingOffsets(self, obj_name : str, source : str, target : str, win return sectionOffsets(residuals, self.sections) + def ztraceWindowSpan(self, ztrace_name : str, window : int) -> float: + """Return how far in depth a smoothing window reaches on a ztrace. + + Params: + ztrace_name (str): the ztrace + window (int): the smoothing window, in ztrace points + Returns: + (float): the median depth a window of its points spans, in um; None if it has fewer than 2 points + """ + zvalues = self.getZValues() + depths = [ + zvalues[snum] for _, _, snum in self.ztraces[ztrace_name].points + if snum in zvalues + ] + if len(depths) < 2: + return None + + return windowDepthSpan(depths, window) + def getZtraceSmoothing(self, obj_name : str) -> tuple: """Return the shifts the 3D scene and mesh export apply to an object. @@ -1212,22 +1259,22 @@ def getZtraceSmoothing(self, obj_name : str) -> tuple: Returns: (dict): section number : (dx, dy), or None if the object is meshed as traced (str): the label for an exported mesh, e.g. smooth4; empty if not smoothed + (str): why a smoothing setting cannot be applied; empty if it can or there is none """ smoothing = self.getAttr(obj_name, "3D_smooth") if not smoothing: - return None, "" + return None, "", "" source, target, window = smoothing["source"], smoothing["target"], smoothing["window"] problems = self.ztraceSmoothingProblems([obj_name], source, target, window) if problems: - print(f"{obj_name} is meshed as traced, without smoothing:") - print("\n".join(problems)) - return None, "" + problem = f"{obj_name} is meshed as traced, without ztrace smoothing: " + " ".join(problems) + return None, "", problem offsets = self.ztraceSmoothingOffsets(obj_name, source, target, window) label = f"smooth-{target}" if target else f"smooth{window}" - return offsets, label + return offsets, label, "" def setZtraceSmoothing(self, obj_names : list, source : str, target : str, window : int, log_event=True): """Smooth objects in the 3D scene and mesh export along a ztrace. @@ -1240,7 +1287,7 @@ def setZtraceSmoothing(self, obj_names : list, source : str, target : str, windo obj_names (list): the objects to smooth source (str): the ztrace the objects were traced along target (str): the ztrace to move the source onto (None: a smoothed copy of the source) - window (int): the smoothing window, in sections + window (int): the smoothing window, in ztrace points log_event (bool): True if event should be logged """ target = target or None @@ -2376,11 +2423,16 @@ def importUserCols(self, other, regex_filters=[], restrict_to=[]): def importObjAttrs(self, other, regex_filters=[], restrict_to=[]): """Import the object attributes from another series. + + Ztrace smoothing is not imported: its ztraces may be renamed or missing here. Params: other (Series): the other series regex_filters (list): the regex filters for the objects to include + Returns: + (list): the objects whose ztrace smoothing was not imported """ + skipped = [] for obj_name, obj_data in other.obj_attrs.items(): @@ -2403,6 +2455,10 @@ def importObjAttrs(self, other, regex_filters=[], restrict_to=[]): if attr_name == "user_columns": continue + if attr_name == "3D_smooth": + skipped.append(obj_name) + continue + if obj_name not in self.obj_attrs: self.obj_attrs[obj_name] = {} @@ -2414,6 +2470,8 @@ def importObjAttrs(self, other, regex_filters=[], restrict_to=[]): other_date = attr_value[-1] if other_date >= self_date: self.obj_attrs[obj_name]["curation"] = attr_value + + return skipped def importTraces( self, @@ -2445,6 +2503,8 @@ def importTraces( keep_below (str): the series that is favored in the case of a conflict (overlap not reaching the threshold; "self", "other", or "") series_states (dict): optional dict of undo states for GUI log_event (bool): True if event should be logged + Returns: + (list): the objects whose ztrace smoothing was not imported """ # # ensure that the two series have the same sections # if sorted(list(self.sections.keys())) != sorted(list(other.sections.keys())): @@ -2501,11 +2561,12 @@ def importTraces( restrict_to += other_groups[gf] ## Import ALL object attributes + skipped = [] if import_obj_attrs: self.importObjectGroups(other, regex_filters, group_filters) self.importHostTree(other, regex_filters, restrict_to) - self.importObjAttrs(other, regex_filters, restrict_to) + skipped = self.importObjAttrs(other, regex_filters, restrict_to) self.importUserCols(other, regex_filters, restrict_to) ## Import history @@ -2524,6 +2585,8 @@ def importTraces( self.addLog(None, None, "Finish importing traces from another series") self.save() + + return skipped def importZtraces(self, other, regex_filters : list = [], import_attrs : bool = True, series_states=None, log_event=True): """Import all the ztraces from another series. diff --git a/PyReconstruct/modules/gui/main/field_widget_2_trace.py b/PyReconstruct/modules/gui/main/field_widget_2_trace.py index ff9147690..dbf9f7260 100644 --- a/PyReconstruct/modules/gui/main/field_widget_2_trace.py +++ b/PyReconstruct/modules/gui/main/field_widget_2_trace.py @@ -1454,6 +1454,11 @@ def deleteZtrace(self, names : list): # save the series state self.series_states.addState() - self.series.deleteZtraces(names) + unsmoothed = self.series.deleteZtraces(names) + if unsmoothed: + notify( + f"Ztrace smoothing was removed from {', '.join(unsmoothed)}, " + "because it used a deleted ztrace." + ) return True diff --git a/PyReconstruct/modules/gui/main/field_widget_3_object.py b/PyReconstruct/modules/gui/main/field_widget_3_object.py index 55589f54c..0bd901fbf 100644 --- a/PyReconstruct/modules/gui/main/field_widget_3_object.py +++ b/PyReconstruct/modules/gui/main/field_widget_3_object.py @@ -1,5 +1,4 @@ import math -from statistics import median from .context_menu_list import get_context_menu_list_obj @@ -395,20 +394,19 @@ def smoothAlongZtrace(self, obj_names : list): elif f"{obj_names[0]}_zlen" in self.series.ztraces: source = f"{obj_names[0]}_zlen" - obj_sections = set() - for name in obj_names: - if name in self.series.data["objects"]: - obj_sections.update(self.series.data["objects"][name].traces) - thickness = median( - self.series.data["sections"][snum]["thickness"] for snum in obj_sections - ) if obj_sections else self.series.avg_thickness + # how deep the window reaches depends on how far apart the ztrace's points are + span = self.series.ztraceWindowSpan(source, window) if source in self.series.ztraces else None + if span is None: + reach = "The confirmation shows how far N points reach on the chosen ztrace." + else: + reach = f"On ztrace {source}, N = {window} points span about {span:.3g} um." structure = [ ["Source ztrace:", (True, "combo", ztrace_names, source)], ["Target ztrace (optional):", ("combo", ztrace_names, target)], - ["Window N (sections):", (True, "int", window)], - [f"Sections here are {thickness:.3g} um thick, so N = 4 spans {4 * thickness:.3g} um."], - ["Bends shorter than about 3N sections are smoothed away, real or not. Use the smallest N that removes the jitter."], + ["Window N (ztrace points):", (True, "int", window)], + [reach], + ["Bends shorter than about 3N ztrace points are smoothed away, real or not. Use the smallest N that removes the jitter."], ] response, confirmed = QuickDialog.get(self, structure, "Smooth Along Ztrace") if not confirmed: @@ -431,7 +429,8 @@ def smoothAlongZtrace(self, obj_names : list): if target: how = f"toward ztrace {target}" else: - how = f"with a window of {window} sections ({window * thickness:.3g} um)" + span = self.series.ztraceWindowSpan(source, window) + how = f"with a window of {window} ztrace points (about {span:.3g} um on this ztrace)" message = ( f"Smooth {', '.join(obj_names)} along ztrace {source} {how}. " f"The largest shift is {largest:.3g} um.\n\n" diff --git a/PyReconstruct/modules/gui/main/main_window.py b/PyReconstruct/modules/gui/main/main_window.py index d28a594b1..c29139adb 100644 --- a/PyReconstruct/modules/gui/main/main_window.py +++ b/PyReconstruct/modules/gui/main/main_window.py @@ -2997,6 +2997,8 @@ def importFromSeries(self): o_series.close() return + not_smoothed = set() # objects whose ztrace smoothing was not imported + if "traces" in response: ( srange, @@ -3010,7 +3012,7 @@ def importFromSeries(self): keep_below, ) = tuple(response["traces"]) - self.series.importTraces( + not_smoothed.update(self.series.importTraces( o_series, srange, regex_filters, @@ -3022,7 +3024,7 @@ def importFromSeries(self): keep_above, keep_below, self.field.series_states - ) + )) if "z-traces" in response: regex_filters = response["z-traces"][0] @@ -3056,7 +3058,7 @@ def importFromSeries(self): if bools[3]: self.series.importZtraceGroups(o_series) if bools[4]: - self.series.importObjAttrs(o_series) + not_smoothed.update(self.series.importObjAttrs(o_series)) if "alignments" in response: import_as = response["alignments"] @@ -3089,6 +3091,12 @@ def importFromSeries(self): self.field.table_manager.refresh() notify("Import successful.") + + if not_smoothed: + notify( + f"Ztrace smoothing was not imported for {', '.join(sorted(not_smoothed))}. " + "Smooth them along a ztrace in this series if needed." + ) def importFromZarrLabels(self): """Import label data from a neuroglancer zarr.""" diff --git a/PyReconstruct/modules/gui/popup/custom_plotter.py b/PyReconstruct/modules/gui/popup/custom_plotter.py index 9b15a4e52..ada0094ab 100644 --- a/PyReconstruct/modules/gui/popup/custom_plotter.py +++ b/PyReconstruct/modules/gui/popup/custom_plotter.py @@ -539,13 +539,22 @@ def placeInScene(self, result): # add objects and ztraces to scene mesh_data_list, series = result + problems = [] for md in mesh_data_list: vm = vedo.Mesh([md["vertices"], md["faces"]], md["color"], md["alpha"]) obj = self.objs.add(vm, series, md["name"], md["type"], md["color"], md["alpha"]) + # an object smoothed along a ztrace keeps its label and shifts + obj.smoothing = md.get("smoothing", "") + obj.offsets = md.get("offsets") + if md.get("smoothing_problem"): + problems.append(md["smoothing_problem"]) if md["tform"]: obj.applyTform(md["tform"]) self.add(vm) self.render() + + if problems: + notify("\n\n".join(problems)) def addToScene(self, objs : list, ztraces : list, remove_first=True, series=None, save_state=True): """Add objects to the scene. @@ -732,6 +741,12 @@ def getFieldCoords(self, msh : vedo.Mesh, pt : tuple): # get the section s = self.getSectionFromZ(z) + # undo the shift of an object smoothed along a ztrace + offsets = self.objs[msh].offsets + if offsets and s in offsets: + dx, dy = offsets[s] + x, y = x - dx, y - dy + return round(x, 3), round(y, 3), s def selectAll(self, select=True): @@ -1327,6 +1342,8 @@ def __init__(self, msh : vedo.Mesh, series : Series, name : str, type : str, col self.color = color self.alpha = alpha self.id = None + self.smoothing = "" # label of a ztrace smoothing applied to the mesh + self.offsets = None # section number : (dx, dy) of that smoothing def setID(self, new_id : str): """Set the ID of the scene object.""" @@ -1574,7 +1591,10 @@ def exportAsObjs(self, export_dir): obj_name = obj.name.replace(" ", "_") # "Scale_Cube" and not "Scale Cube" - obj_fp = export_dir / f"{obj_name}.obj" + # a smoothed mesh says so in its name, e.g. dendrite_smooth4 + label = f"{obj_name}_{obj.smoothing}" if obj.smoothing else obj_name + + obj_fp = export_dir / f"{label}.obj" mtl_fp = obj_fp.with_suffix(".mtl") ## Write obj file @@ -1587,7 +1607,7 @@ def exportAsObjs(self, export_dir): obj_lines = obj_lines.split("\n") obj_lines.insert(1, f"mtllib {mtl_fp.name}") - obj_lines.insert(2, f"o {obj_name}") + obj_lines.insert(2, f"o {label}") obj_lines.insert(3, f"usemtl {obj_name}") with obj_fp.open("w") as f: diff --git a/manual/readme.md b/manual/readme.md index 62312627a..fb02ee31e 100644 --- a/manual/readme.md +++ b/manual/readme.md @@ -641,15 +641,15 @@ Allows the user to set the hidden status for all individual traces associated wi Smooths the selected object(s) along a ztrace in the 3D scene and in exported meshes, without realigning the series. -Choose a source ztrace, an optional target ztrace, and a window N in sections (default 4). The object's own `_zlen` ztrace (Create ztrace > On contour midpoints) is offered as the source. The dialog shows how far N sections span in um, and the confirmation shows the largest shift. +Choose a source ztrace, an optional target ztrace, and a window N in ztrace points (default 4). The object's own `_zlen` ztrace (Create ztrace > On contour midpoints) is offered as the source. Ztrace points can be one section apart or several, so the dialog and the confirmation show how far N points span in um on the ztrace. The confirmation also shows the largest shift. -- With no target, each section is shifted from its source ztrace point to the same point on a smoothed copy of the source. Each point is smoothed by fitting a straight line, against section depth, through it and N/2 neighbors on each side. A straight ztrace, slanted or not, is left where it is. +- With no target, each section is shifted from its source ztrace point to the same point on a smoothed copy of the source. Each point is smoothed by fitting a straight line, against section depth, through it and N/2 neighboring ztrace points on each side. A straight ztrace, slanted or not, is left where it is. - With a target, each section is shifted from its source ztrace point to the target ztrace point on the same section. - A section with several ztrace points is shifted by their average, a section the ztrace skips is interpolated from its neighbors, and a section past either end keeps the shift at that end. -What moves: the object in the 3D scene and in exported meshes. What does not move: traces, images, section transforms, and the object list and its CSV export, including the object's flat area, volume and radius. Everything measured on an exported mesh is smoothed: 3D length, surface area and tortuosity, and also the mesh's own volume, because the surface is rebuilt between the shifted sections. The exported file name ends in `_smooth` (or `_smooth-` with a target), and Export quantitative data fills in the ZtraceSmoothing column for it. +What moves: the object in the 3D scene and in exported meshes. What does not move: traces, images, section transforms, and the measurement columns of the object list and its CSV export, including the object's flat area, volume and radius. The Last user column can change, because smoothing is logged on the object. Everything measured on an exported mesh is smoothed: 3D length, surface area and tortuosity, and also the mesh's own volume, because the surface is rebuilt between the shifted sections. The exported file name ends in `_smooth` (or `_smooth-` with a target), and Export quantitative data fills in the ZtraceSmoothing column for it. -Smoothing cannot tell jitter from a real bend. Bends shorter than about 3N sections are smoothed away, real or not. Use the smallest N that removes the jitter. +Smoothing cannot tell jitter from a real bend. Bends shorter than about 3N ztrace points are smoothed away, real or not. Use the smallest N that removes the jitter. A step at a flaw, such as a fold or a lost section, is spread over the window but not removed. To remove it, make a second ztrace that follows the object as it should run (for example, Smooth on the source ztrace with a new ztrace), move its points on the sections around the flaw so it crosses the flaw without the step, and choose it as the target. From 088a7238771af6131e17fde701a0128828af53f9 Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 22:28:16 -0500 Subject: [PATCH 3/8] docs(objects): word smoothing notice; manual on rename and import --- PyReconstruct/modules/gui/main/field_widget_3_object.py | 4 ++-- manual/readme.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/PyReconstruct/modules/gui/main/field_widget_3_object.py b/PyReconstruct/modules/gui/main/field_widget_3_object.py index 0bd901fbf..f314a289f 100644 --- a/PyReconstruct/modules/gui/main/field_widget_3_object.py +++ b/PyReconstruct/modules/gui/main/field_widget_3_object.py @@ -434,8 +434,8 @@ def smoothAlongZtrace(self, obj_names : list): message = ( f"Smooth {', '.join(obj_names)} along ztrace {source} {how}. " f"The largest shift is {largest:.3g} um.\n\n" - "Only the 3D scene and exported meshes move. Traces, the object " - "list and its measurements stay as traced. An object already in an " + "Only the 3D scene and exported meshes move. Traces and the " + "object list's measurements stay as traced. An object already in an " "open 3D scene keeps its old shape until it is generated again." ) if not notifyConfirm(message): diff --git a/manual/readme.md b/manual/readme.md index fb02ee31e..ca2324728 100644 --- a/manual/readme.md +++ b/manual/readme.md @@ -653,7 +653,7 @@ Smoothing cannot tell jitter from a real bend. Bends shorter than about 3N ztrac A step at a flaw, such as a fold or a lost section, is spread over the window but not removed. To remove it, make a second ztrace that follows the object as it should run (for example, Smooth on the source ztrace with a new ztrace), move its points on the sections around the flaw so it crosses the flaw without the step, and choose it as the target. -The object and the ztraces must use the same alignment. The setting is saved with the series, and the shifts are computed from the ztraces each time the object is generated or exported, so an edited ztrace takes effect the next time. An object already in an open 3D scene keeps its old shape until it is generated again. +The object and the ztraces must use the same alignment. The setting is saved with the series, and the shifts are computed from the ztraces each time the object is generated or exported, so an edited ztrace takes effect the next time. Renaming a ztrace keeps the setting pointed at it. Deleting a ztrace the setting uses removes the smoothing from those objects, and a notice says so. Importing objects from another series does not bring their smoothing settings, and a notice lists them. An object already in an open 3D scene keeps its old shape until it is generated again. This action can be undone with Ctrl+Z or Edit>Undo. From 774a8d55e2af2baf9e48b79928c615879a5ecfb0 Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 22:44:42 -0500 Subject: [PATCH 4/8] fix(objects): read scene sections at mesh depth; guard scene export The 3D scene keeps the depth each section was meshed at and reads a point's section from it. The readout, the smoothing shift it takes off and the section a double-click opens are then right when section thicknesses differ. Renaming a ztrace moves its attributes, such as its alignment, to the new name in the same undo step. Export scene refuses, naming both objects, when two would be saved to one file. The manual says a scene file keeps its name and labels each smoothed object inside. --- .../backend/volume/generate_volumes.py | 4 ++ PyReconstruct/modules/datatypes/series.py | 3 ++ .../modules/gui/popup/custom_plotter.py | 44 ++++++++++++++++--- manual/readme.md | 2 +- 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/PyReconstruct/modules/backend/volume/generate_volumes.py b/PyReconstruct/modules/backend/volume/generate_volumes.py index fc3845f07..0de1f7749 100644 --- a/PyReconstruct/modules/backend/volume/generate_volumes.py +++ b/PyReconstruct/modules/backend/volume/generate_volumes.py @@ -97,12 +97,16 @@ def generateVolumes(series_like : Series_like_obj, objs : dict, ztraces : dict): elif type(obj_3D) is Contours: mesh_data_list.append(obj_3D.generate3D()) + # the depth each section was meshed at, to read a point's section back + section_depths = {snum: snum * series.avg_thickness for snum in series.sections} + # the scene keeps each object's smoothing, to label exports and read field coordinates for mesh_data in mesh_data_list: obj_3D = obj_data[mesh_data["name"]] mesh_data["smoothing"] = obj_3D.smoothing mesh_data["offsets"] = obj_3D.offsets mesh_data["smoothing_problem"] = obj_3D.smoothing_problem + mesh_data["section_depths"] = section_depths for _, ztrace_3D in ztrace_data.items(): mesh_data = ztrace_3D.generate3D() diff --git a/PyReconstruct/modules/datatypes/series.py b/PyReconstruct/modules/datatypes/series.py index 69c64aa9d..7ba7f53bb 100644 --- a/PyReconstruct/modules/datatypes/series.py +++ b/PyReconstruct/modules/datatypes/series.py @@ -1035,6 +1035,9 @@ def editZtraceAttributes(self, name : str, new_name : str, new_color : tuple, lo for g in groups: self.ztrace_groups.add(g, new_name) self.ztrace_groups.removeObject(name) + # the ztrace keeps its attributes, such as its alignment + if name in self.ztrace_attrs: + self.ztrace_attrs[new_name] = self.ztrace_attrs.pop(name) # objects smoothed along the ztrace follow it to the new name for obj_name in self._smoothedAlong(name): smoothing = dict(self.getAttr(obj_name, "3D_smooth")) diff --git a/PyReconstruct/modules/gui/popup/custom_plotter.py b/PyReconstruct/modules/gui/popup/custom_plotter.py index ada0094ab..dd3f2494d 100644 --- a/PyReconstruct/modules/gui/popup/custom_plotter.py +++ b/PyReconstruct/modules/gui/popup/custom_plotter.py @@ -546,6 +546,7 @@ def placeInScene(self, result): # an object smoothed along a ztrace keeps its label and shifts obj.smoothing = md.get("smoothing", "") obj.offsets = md.get("offsets") + obj.section_depths = md.get("section_depths") if md.get("smoothing_problem"): problems.append(md["smoothing_problem"]) if md["tform"]: @@ -738,11 +739,16 @@ def getFieldCoords(self, msh : vedo.Mesh, pt : tuple): # get the transform and apply its inverse to a point x, y, z = msh.get_transform().GetInverse().TransformFloatPoint(*pt) - # get the section - s = self.getSectionFromZ(z) + # get the section, from the depths the mesh was built with if known + scene_obj = self.objs[msh] + depths = scene_obj.section_depths + if depths: + s = min(depths, key=lambda snum: abs(depths[snum] - z)) + else: + s = self.getSectionFromZ(z) # undo the shift of an object smoothed along a ztrace - offsets = self.objs[msh].offsets + offsets = scene_obj.offsets if offsets and s in offsets: dx, dy = offsets[s] x, y = x - dx, y - dy @@ -1266,6 +1272,17 @@ def setStep(self): def exportScene(self): """Export 3D scene as an obj file.""" + # two objects saved to one file would overwrite each other + clash = self.plt.objs.exportClash() + if clash: + first, second = clash + notify( + f"The scene was not exported: {first.name} and {second.name} would both be " + f"saved as {first.export_name}.obj. Remove one of them from the scene, " + "or rename it, and export again." + ) + return + fp = FileDialog.get( "save", self, "Save scene as obj", filter="*.obj", @@ -1344,6 +1361,13 @@ def __init__(self, msh : vedo.Mesh, series : Series, name : str, type : str, col self.id = None self.smoothing = "" # label of a ztrace smoothing applied to the mesh self.offsets = None # section number : (dx, dy) of that smoothing + self.section_depths = None # section number : z the section was meshed at + + @property + def export_name(self): + """The name the object is exported under; a smoothed mesh says so, e.g. dendrite_smooth4.""" + name = self.name.replace(" ", "_") # "Scale_Cube" and not "Scale Cube" + return f"{name}_{self.smoothing}" if self.smoothing else name def setID(self, new_id : str): """Set the ID of the scene object.""" @@ -1580,6 +1604,16 @@ def getHostGroup(self, scene_obj : SceneObject): return host_group + def exportClash(self): + """Return the first two objects that would be exported to the same file, or None.""" + exported = {} + for obj in self.scene_objects.values(): + key = obj.export_name.casefold() # file names ignore case on macOS and Windows + if key in exported: + return exported[key], obj + exported[key] = obj + return None + def exportAsObjs(self, export_dir): """Export scene objects as obj and mtl files.""" @@ -1590,9 +1624,7 @@ def exportAsObjs(self, export_dir): try: obj_name = obj.name.replace(" ", "_") # "Scale_Cube" and not "Scale Cube" - - # a smoothed mesh says so in its name, e.g. dendrite_smooth4 - label = f"{obj_name}_{obj.smoothing}" if obj.smoothing else obj_name + label = obj.export_name obj_fp = export_dir / f"{label}.obj" mtl_fp = obj_fp.with_suffix(".mtl") diff --git a/manual/readme.md b/manual/readme.md index ca2324728..4b9f7c3f0 100644 --- a/manual/readme.md +++ b/manual/readme.md @@ -647,7 +647,7 @@ Choose a source ztrace, an optional target ztrace, and a window N in ztrace poin - With a target, each section is shifted from its source ztrace point to the target ztrace point on the same section. - A section with several ztrace points is shifted by their average, a section the ztrace skips is interpolated from its neighbors, and a section past either end keeps the shift at that end. -What moves: the object in the 3D scene and in exported meshes. What does not move: traces, images, section transforms, and the measurement columns of the object list and its CSV export, including the object's flat area, volume and radius. The Last user column can change, because smoothing is logged on the object. Everything measured on an exported mesh is smoothed: 3D length, surface area and tortuosity, and also the mesh's own volume, because the surface is rebuilt between the shifted sections. The exported file name ends in `_smooth` (or `_smooth-` with a target), and Export quantitative data fills in the ZtraceSmoothing column for it. +What moves: the object in the 3D scene and in exported meshes. What does not move: traces, images, section transforms, and the measurement columns of the object list and its CSV export, including the object's flat area, volume and radius. The Last user column can change, because smoothing is logged on the object. Everything measured on an exported mesh is smoothed: 3D length, surface area and tortuosity, and also the mesh's own volume, because the surface is rebuilt between the shifted sections. Each exported mesh file name ends in `_smooth` (or `_smooth-` with a target). A scene file from Export scene... in the 3D window keeps the file name you choose, and each smoothed object inside it carries the label in its name, for example `dendrite_smooth4`. Export quantitative data fills in the ZtraceSmoothing column for a smoothed object. Smoothing cannot tell jitter from a real bend. Bends shorter than about 3N ztrace points are smoothed away, real or not. Use the smallest N that removes the jitter. From 9c6c84d1ea615986eac0708492b8446361fefc26 Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 22:58:52 -0500 Subject: [PATCH 5/8] fix(objects): hide x/y for smoothed meshes; guard mesh export clash The 3D readout no longer shows x and y for an object smoothed along a ztrace: a point on a shifted mesh has no exact field coordinate. It shows the name, the smoothing label and the section, and double-click still goes to that section. Traced objects keep x and y. A point on a deleted section reads "(removed)", and double-click asks to generate the object again. The object list mesh export refuses two objects that would save to one file, with the same check as the scene export. --- .../modules/backend/volume/export_volumes.py | 64 ++++++++++++++++--- .../modules/gui/popup/custom_plotter.py | 30 +++++---- manual/readme.md | 2 +- 3 files changed, 73 insertions(+), 23 deletions(-) diff --git a/PyReconstruct/modules/backend/volume/export_volumes.py b/PyReconstruct/modules/backend/volume/export_volumes.py index 248240192..28b4aa3b2 100644 --- a/PyReconstruct/modules/backend/volume/export_volumes.py +++ b/PyReconstruct/modules/backend/volume/export_volumes.py @@ -34,22 +34,46 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t reportSmoothingProblems([o.smoothing_problem for o in obj_data.values()], notify_user) - ## Iterate through objects and export 3D meshes + ## Name the files, and refuse to save two objects to one file - output_directory = Path(output_dir) + output_files = {} for obj_name, obj_3D in obj_data.items(): - # a smoothed mesh says so in its name, e.g. dendrite_smooth4.obj - suffix = f"_{obj_3D.smoothing}" if obj_3D.smoothing else "" - output_file = output_directory / f"{obj_name}{suffix}.{export_type}" - if type(obj_3D) is Surface or type(obj_3D) is Spheres: - obj_3D.exportTrimesh( - output_file, - export_type, - ) + # a smoothed mesh says so in its name, e.g. dendrite_smooth4.obj + suffix = f"_{obj_3D.smoothing}" if obj_3D.smoothing else "" + output_files[obj_name] = f"{obj_name}{suffix}.{export_type}" + + clash = findExportClash(output_files) + + if clash: + + first, second = clash + message = ( + f"The objects were not exported: {first} and {second} would both be saved as " + f"{output_files[first]}. Rename one of them, or export them to separate folders." + ) + + if notify_user: + notify(message) + + else: + print(message) + + return + + ## Iterate through objects and export 3D meshes + + output_directory = Path(output_dir) + + for obj_name, file_name in output_files.items(): + + obj_data[obj_name].exportTrimesh( + output_directory / file_name, + export_type, + ) if notify_user: @@ -143,6 +167,26 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou return obj_data +def findExportClash(file_names: dict): + """Return the first two keys that would be exported to the same file, or None. + + Params: + file_names (dict): key : the file name it is exported under + """ + exported = {} + + for key, file_name in file_names.items(): + + folded = file_name.casefold() # file names ignore case on macOS and Windows + + if folded in exported: + return exported[folded], key + + exported[folded] = key + + return None + + def reportSmoothingProblems(problems: list, notify_user: bool = True) -> None: """Say which objects were meshed as traced because their ztrace smoothing cannot be applied.""" diff --git a/PyReconstruct/modules/gui/popup/custom_plotter.py b/PyReconstruct/modules/gui/popup/custom_plotter.py index dd3f2494d..1ad7fbcb8 100644 --- a/PyReconstruct/modules/gui/popup/custom_plotter.py +++ b/PyReconstruct/modules/gui/popup/custom_plotter.py @@ -19,7 +19,8 @@ convert_vedo_to_tm, return_mesh_mtl, combine_mtl_files, - combine_obj_files + combine_obj_files, + findExportClash ) from PyReconstruct.modules.gui.utils import ( populateMenuBar, @@ -108,7 +109,14 @@ def mouseMoveEvent(self, event): pt = event.picked3d # 3d coords of point under mouse x, y, s = self.getFieldCoords(msh, pt) - txt = f"{name}\nsection {s}\nx={x:.3f} y={y:.3f}" + section_txt = f"section {s}" + if obj.series_fp == self.series.jser_fp and s not in self.series.sections: + section_txt += " (removed)" + if obj.smoothing: + # a point on a mesh smoothed along a ztrace has no exact field x/y + txt = f"{name}\n{obj.smoothing}\n{section_txt}" + else: + txt = f"{name}\n{section_txt}\nx={x:.3f} y={y:.3f}" self.pos_text.text(txt) # update text message self.render() @@ -182,9 +190,13 @@ def leftButtonClickEvent(self, event): return pt = event.picked3d # 3d coords of point under mouse x, y, s = self.getFieldCoords(msh, pt) - - self.mainwindow.field.moveTo(s, x, y) - self.mainwindow.activateWindow() + + # the mesh was generated before the section was deleted + if s not in self.series.sections: + notify(f"Section {s} no longer exists. Generate {self.objs[msh].name} again to update the 3D scene.") + else: + self.mainwindow.field.moveTo(s, x, y) + self.mainwindow.activateWindow() msh = event.actor if not msh: @@ -1606,13 +1618,7 @@ def getHostGroup(self, scene_obj : SceneObject): def exportClash(self): """Return the first two objects that would be exported to the same file, or None.""" - exported = {} - for obj in self.scene_objects.values(): - key = obj.export_name.casefold() # file names ignore case on macOS and Windows - if key in exported: - return exported[key], obj - exported[key] = obj - return None + return findExportClash({obj: obj.export_name for obj in self.scene_objects.values()}) def exportAsObjs(self, export_dir): """Export scene objects as obj and mtl files.""" diff --git a/manual/readme.md b/manual/readme.md index 4b9f7c3f0..8df55942a 100644 --- a/manual/readme.md +++ b/manual/readme.md @@ -653,7 +653,7 @@ Smoothing cannot tell jitter from a real bend. Bends shorter than about 3N ztrac A step at a flaw, such as a fold or a lost section, is spread over the window but not removed. To remove it, make a second ztrace that follows the object as it should run (for example, Smooth on the source ztrace with a new ztrace), move its points on the sections around the flaw so it crosses the flaw without the step, and choose it as the target. -The object and the ztraces must use the same alignment. The setting is saved with the series, and the shifts are computed from the ztraces each time the object is generated or exported, so an edited ztrace takes effect the next time. Renaming a ztrace keeps the setting pointed at it. Deleting a ztrace the setting uses removes the smoothing from those objects, and a notice says so. Importing objects from another series does not bring their smoothing settings, and a notice lists them. An object already in an open 3D scene keeps its old shape until it is generated again. +The object and the ztraces must use the same alignment. The setting is saved with the series, and the shifts are computed from the ztraces each time the object is generated or exported, so an edited ztrace takes effect the next time. Renaming a ztrace keeps the setting pointed at it. Deleting a ztrace the setting uses removes the smoothing from those objects, and a notice says so. Importing objects from another series does not bring their smoothing settings, and a notice lists them. An object already in an open 3D scene keeps its old shape until it is generated again. In the 3D scene, the readout shows no x and y for a smoothed object, only its name, label and section; a double-click still goes to that section. This action can be undone with Ctrl+Z or Edit>Undo. From 75150691141cd7c2bf02b8a30b5978dea41a738b Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 23:15:16 -0500 Subject: [PATCH 6/8] fix(objects): refuse mesh export over a file already in the folder A smoothed object is saved as _smooth, so exporting it into a folder that already held that file from a traced object of that name replaced the file without a word. The object-list export and Export scene now check the folder with the shared clash check before writing anything, and refuse with a message that names the object and the file. Export scene checks each object's obj and mtl files, which it writes before it makes the scene file. --- .../modules/backend/volume/export_volumes.py | 34 +++++++++++++------ .../modules/gui/popup/custom_plotter.py | 30 +++++++++++++--- 2 files changed, 50 insertions(+), 14 deletions(-) diff --git a/PyReconstruct/modules/backend/volume/export_volumes.py b/PyReconstruct/modules/backend/volume/export_volumes.py index 28b4aa3b2..2b5dd6ad8 100644 --- a/PyReconstruct/modules/backend/volume/export_volumes.py +++ b/PyReconstruct/modules/backend/volume/export_volumes.py @@ -34,7 +34,7 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t reportSmoothingProblems([o.smoothing_problem for o in obj_data.values()], notify_user) - ## Name the files, and refuse to save two objects to one file + ## Name the files, and refuse to save two objects to one file or over a file already there output_files = {} @@ -46,15 +46,23 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t suffix = f"_{obj_3D.smoothing}" if obj_3D.smoothing else "" output_files[obj_name] = f"{obj_name}{suffix}.{export_type}" - clash = findExportClash(output_files) + clash = findExportClash(output_files, output_dir) if clash: - first, second = clash - message = ( - f"The objects were not exported: {first} and {second} would both be saved as " - f"{output_files[first]}. Rename one of them, or export them to separate folders." - ) + first, second, file_name = clash + + if first is None: + message = ( + f"The objects were not exported: {second} would be saved as {file_name}, which is " + "already in the folder. Move that file, or export to another folder." + ) + + else: + message = ( + f"The objects were not exported: {first} and {second} would both be saved as " + f"{file_name}. Rename one of them, or export them to separate folders." + ) if notify_user: notify(message) @@ -167,11 +175,14 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou return obj_data -def findExportClash(file_names: dict): - """Return the first two keys that would be exported to the same file, or None. +def findExportClash(file_names: dict, folder=None): + """Return the first two keys that would be exported to the same file, and that file, or None. + + A file already in the folder clashes as if exported first, under the key None. Params: file_names (dict): key : the file name it is exported under + folder (str or Path): the folder it is exported to, or None to check the names only """ exported = {} @@ -180,7 +191,10 @@ def findExportClash(file_names: dict): folded = file_name.casefold() # file names ignore case on macOS and Windows if folded in exported: - return exported[folded], key + return exported[folded], key, file_name + + if folder is not None and (Path(folder) / file_name).exists(): + return None, key, file_name exported[folded] = key diff --git a/PyReconstruct/modules/gui/popup/custom_plotter.py b/PyReconstruct/modules/gui/popup/custom_plotter.py index 1ad7fbcb8..2f77b158b 100644 --- a/PyReconstruct/modules/gui/popup/custom_plotter.py +++ b/PyReconstruct/modules/gui/popup/custom_plotter.py @@ -1287,7 +1287,7 @@ def exportScene(self): # two objects saved to one file would overwrite each other clash = self.plt.objs.exportClash() if clash: - first, second = clash + first, second, _ = clash notify( f"The scene was not exported: {first.name} and {second.name} would both be " f"saved as {first.export_name}.obj. Remove one of them from the scene, " @@ -1306,6 +1306,17 @@ def exportScene(self): combo_obj_fp = Path(fp) export_dir = combo_obj_fp.parent + # each object is saved to its own files first, which would replace a file already there + clash = self.plt.objs.exportClash(export_dir) + if clash: + _, obj, file_name = clash + notify( + f"The scene was not exported: {obj.name} would be saved as {file_name} while the " + "scene is made, and that file is already in the folder. Move it, or save the " + "scene in another folder." + ) + return + obj_files = self.plt.objs.exportAsObjs(export_dir) mtl_files = [f.with_suffix(".mtl") for f in obj_files] @@ -1616,9 +1627,20 @@ def getHostGroup(self, scene_obj : SceneObject): return host_group - def exportClash(self): - """Return the first two objects that would be exported to the same file, or None.""" - return findExportClash({obj: obj.export_name for obj in self.scene_objects.values()}) + def exportClash(self, folder=None): + """Return the first two objects that would be exported to the same file, and that file, or None. + + With a folder, an object whose obj or mtl file is already in it clashes with None. + """ + for extension in ("obj", "mtl"): + clash = findExportClash( + {obj: f"{obj.export_name}.{extension}" for obj in self.scene_objects.values()}, + folder, + ) + if clash: + return clash + + return None def exportAsObjs(self, export_dir): """Export scene objects as obj and mtl files.""" From 87f96a411e71fbc5fb372b08dc0365a96cc4a6c0 Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 23:15:16 -0500 Subject: [PATCH 7/8] fix(objects): write the 3D data CSV with csv.writer A field with a comma in it, such as the label smooth-hand,edit from a target ztrace named hand,edit, was split into two columns. Rows are now written with csv.writer, which quotes such a field; other rows are written as before. --- .../modules/backend/volume/export_volumes.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/PyReconstruct/modules/backend/volume/export_volumes.py b/PyReconstruct/modules/backend/volume/export_volumes.py index 2b5dd6ad8..57c28e93d 100644 --- a/PyReconstruct/modules/backend/volume/export_volumes.py +++ b/PyReconstruct/modules/backend/volume/export_volumes.py @@ -1,5 +1,6 @@ """Export 3D objects.""" +import csv from pathlib import Path from typing import List, Union @@ -91,8 +92,7 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t def export3DData(series: Series, obj_names: list, output_fp: str, notify_user: bool=True) -> None: """Export quantitative data from meshes.""" - sep = "," - csv_str = f"Series{sep}Name{sep}MeshType{sep}SurfaceArea{sep}Volume{sep}ZtraceSmoothing\n" + rows = [["Series", "Name", "MeshType", "SurfaceArea", "Volume", "ZtraceSmoothing"]] series_code = series.code errors = {} @@ -111,7 +111,7 @@ def export3DData(series: Series, obj_names: list, output_fp: str, notify_user: b volume = round(tm.volume, 5) # the mesh is smoothed along a ztrace if ZtraceSmoothing is not blank - csv_str += f"{series_code}{sep}{obj}{sep}{obj_type}{sep}{surface_area}{sep}{volume}{sep}{obj_data.smoothing}\n" + rows.append([series_code, obj, obj_type, surface_area, volume, obj_data.smoothing]) except Exception as e: @@ -121,8 +121,9 @@ def export3DData(series: Series, obj_names: list, output_fp: str, notify_user: b if not errors: - with open(output_fp, "w") as fp: - fp.write(csv_str) + # a field with a comma in it, e.g. the label smooth-hand,edit, is quoted + with open(output_fp, "w", newline="") as fp: + csv.writer(fp, lineterminator="\n").writerows(rows) if notify_user: notify(f"Data exported to:\n\n{Path(output_fp).absolute()}\n") From 2b894d37a201cd58a15550ea16ecd6e3acdf2ef4 Mon Sep 17 00:00:00 2001 From: Dusten Hubbard Date: Thu, 15 Oct 2026 23:24:58 -0500 Subject: [PATCH 8/8] fix(objects): ask before mesh export replaces files in the folder A mesh export from the object list, or the per-object files of Export scene, that would write onto files already in the folder now shows one dialog that lists every such file, with Overwrite and Cancel. Cancel writes nothing; Overwrite replaces them as before. Two objects that map to one file are still refused. notifyConfirm takes an optional label for its OK button. --- .../modules/backend/volume/export_volumes.py | 51 +++++++++++-------- .../modules/gui/popup/custom_plotter.py | 37 +++++++------- PyReconstruct/modules/gui/utils/utils.py | 9 +++- 3 files changed, 56 insertions(+), 41 deletions(-) diff --git a/PyReconstruct/modules/backend/volume/export_volumes.py b/PyReconstruct/modules/backend/volume/export_volumes.py index 57c28e93d..6b130f3c2 100644 --- a/PyReconstruct/modules/backend/volume/export_volumes.py +++ b/PyReconstruct/modules/backend/volume/export_volumes.py @@ -10,7 +10,7 @@ from .objects_3D import Surface, Spheres, Contours, meshTform from PyReconstruct.modules.datatypes import Series -from PyReconstruct.modules.gui.utils import notify +from PyReconstruct.modules.gui.utils import notify, notifyConfirm def export3DObjects(series: Series, obj_names : list, output_dir : str, export_type: str, notify_user: bool = True) -> None: @@ -35,7 +35,7 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t reportSmoothingProblems([o.smoothing_problem for o in obj_data.values()], notify_user) - ## Name the files, and refuse to save two objects to one file or over a file already there + ## Name the files, refuse to save two objects to one file, and ask before replacing a file output_files = {} @@ -47,23 +47,15 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t suffix = f"_{obj_3D.smoothing}" if obj_3D.smoothing else "" output_files[obj_name] = f"{obj_name}{suffix}.{export_type}" - clash = findExportClash(output_files, output_dir) + same_file, existing = findExportClash(output_files, output_dir) - if clash: + if same_file: - first, second, file_name = clash - - if first is None: - message = ( - f"The objects were not exported: {second} would be saved as {file_name}, which is " - "already in the folder. Move that file, or export to another folder." - ) - - else: - message = ( - f"The objects were not exported: {first} and {second} would both be saved as " - f"{file_name}. Rename one of them, or export them to separate folders." - ) + first, second, file_name = same_file + message = ( + f"The objects were not exported: {first} and {second} would both be saved as " + f"{file_name}. Rename one of them, or export them to separate folders." + ) if notify_user: notify(message) @@ -73,6 +65,17 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t return + if existing and notify_user: + + message = ( + "These files are already in the folder and would be replaced:\n\n" + + "\n".join(existing) + + "\n\nOverwrite them?" + ) + + if not notifyConfirm(message, ok_text="Overwrite"): + return + ## Iterate through objects and export 3D meshes output_directory = Path(output_dir) @@ -177,29 +180,33 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou def findExportClash(file_names: dict, folder=None): - """Return the first two keys that would be exported to the same file, and that file, or None. + """Return the files an export would clash on, as (same_file, existing). - A file already in the folder clashes as if exported first, under the key None. + same_file is the first two keys that would be exported to the same file, and that file, + or None. existing lists the file names already in the folder, in export order. Params: file_names (dict): key : the file name it is exported under folder (str or Path): the folder it is exported to, or None to check the names only """ exported = {} + same_file = None + existing = [] for key, file_name in file_names.items(): folded = file_name.casefold() # file names ignore case on macOS and Windows if folded in exported: - return exported[folded], key, file_name + same_file = same_file or (exported[folded], key, file_name) + continue if folder is not None and (Path(folder) / file_name).exists(): - return None, key, file_name + existing.append(file_name) exported[folded] = key - return None + return same_file, existing def reportSmoothingProblems(problems: list, notify_user: bool = True) -> None: diff --git a/PyReconstruct/modules/gui/popup/custom_plotter.py b/PyReconstruct/modules/gui/popup/custom_plotter.py index 2f77b158b..78418d40e 100644 --- a/PyReconstruct/modules/gui/popup/custom_plotter.py +++ b/PyReconstruct/modules/gui/popup/custom_plotter.py @@ -1285,9 +1285,9 @@ def exportScene(self): """Export 3D scene as an obj file.""" # two objects saved to one file would overwrite each other - clash = self.plt.objs.exportClash() - if clash: - first, second, _ = clash + same_file, _ = self.plt.objs.exportClash() + if same_file: + first, second, _ = same_file notify( f"The scene was not exported: {first.name} and {second.name} would both be " f"saved as {first.export_name}.obj. Remove one of them from the scene, " @@ -1307,15 +1307,16 @@ def exportScene(self): export_dir = combo_obj_fp.parent # each object is saved to its own files first, which would replace a file already there - clash = self.plt.objs.exportClash(export_dir) - if clash: - _, obj, file_name = clash - notify( - f"The scene was not exported: {obj.name} would be saved as {file_name} while the " - "scene is made, and that file is already in the folder. Move it, or save the " - "scene in another folder." + _, existing = self.plt.objs.exportClash(export_dir) + if existing: + message = ( + "The scene is made from a file for each object, saved in the folder and then deleted. " + "These files are already in the folder and would be replaced, then deleted:\n\n" + + "\n".join(existing) + + "\n\nOverwrite them?" ) - return + if not notifyConfirm(message, ok_text="Overwrite"): + return obj_files = self.plt.objs.exportAsObjs(export_dir) mtl_files = [f.with_suffix(".mtl") for f in obj_files] @@ -1628,19 +1629,21 @@ def getHostGroup(self, scene_obj : SceneObject): return host_group def exportClash(self, folder=None): - """Return the first two objects that would be exported to the same file, and that file, or None. + """Return the files the objects would be exported to that clash, as (same_file, existing). - With a folder, an object whose obj or mtl file is already in it clashes with None. + same_file is the first two objects that would be exported to the same file, and that + file, or None. existing lists the obj and mtl files already in the folder. """ + same_file, existing = None, [] for extension in ("obj", "mtl"): - clash = findExportClash( + pair, found = findExportClash( {obj: f"{obj.export_name}.{extension}" for obj in self.scene_objects.values()}, folder, ) - if clash: - return clash + same_file = same_file or pair + existing += found - return None + return same_file, existing def exportAsObjs(self, export_dir): """Export scene objects as obj and mtl files.""" diff --git a/PyReconstruct/modules/gui/utils/utils.py b/PyReconstruct/modules/gui/utils/utils.py index 07b8d7227..9afe1622c 100644 --- a/PyReconstruct/modules/gui/utils/utils.py +++ b/PyReconstruct/modules/gui/utils/utils.py @@ -231,8 +231,8 @@ def notify(message): input("Press any key to continue...") -def notifyConfirm(message, yn=False): - """Notify the user and give option to OK or cancel.""" +def notifyConfirm(message, yn=False, ok_text=None): + """Notify the user and give option to OK or cancel; ok_text names the OK button, e.g. Overwrite.""" if yn: @@ -256,6 +256,11 @@ def notifyConfirm(message, yn=False): else: if QApplication.instance() and not qt_offscreen: + + if ok_text: + box = QMessageBox(QMessageBox.Warning, " ", message, QMessageBox.Ok | QMessageBox.Cancel, mainwindow) + box.button(QMessageBox.Ok).setText(ok_text) + return box.exec() == QMessageBox.Ok response = QMessageBox.warning( mainwindow,