diff --git a/PyReconstruct/modules/backend/volume/export_volumes.py b/PyReconstruct/modules/backend/volume/export_volumes.py index 193629118..6b130f3c2 100644 --- a/PyReconstruct/modules/backend/volume/export_volumes.py +++ b/PyReconstruct/modules/backend/volume/export_volumes.py @@ -1,15 +1,16 @@ """Export 3D objects.""" +import csv from pathlib import Path from typing import List, Union 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 +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: @@ -32,20 +33,59 @@ def export3DObjects(series: Series, obj_names : list, output_dir : str, export_t obj_data[obj_name] = get_3D_mesh(series, obj_name) - ## Iterate through objects and export 3D meshes + reportSmoothingProblems([o.smoothing_problem for o in obj_data.values()], notify_user) - output_directory = Path(output_dir) + ## Name the files, refuse to save two objects to one file, and ask before replacing a file - for obj_name, obj_3D in obj_data.items(): + output_files = {} - output_file = output_directory / f"{obj_name}.{export_type}" + for obj_name, obj_3D in obj_data.items(): 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}" + + same_file, existing = findExportClash(output_files, output_dir) + + if same_file: + + 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) + + else: + print(message) + + 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) + + for obj_name, file_name in output_files.items(): + + obj_data[obj_name].exportTrimesh( + output_directory / file_name, + export_type, + ) if notify_user: @@ -55,33 +95,38 @@ 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\n" + rows = [["Series", "Name", "MeshType", "SurfaceArea", "Volume", "ZtraceSmoothing"]] 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() 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 + rows.append([series_code, obj, obj_type, surface_area, volume, obj_data.smoothing]) except Exception as e: errors[obj] = e + reportSmoothingProblems(problems, notify_user) + 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") @@ -108,6 +153,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 + + obj_data.offsets, obj_data.smoothing, obj_data.smoothing_problem = series.getZtraceSmoothing(obj_name) + ## Iterate through sections and collect data for snum, section in series.enumerateSections(show_progress=False): @@ -119,16 +168,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, obj_data.offsets) for trace in section.contours[obj_name]: @@ -138,6 +179,54 @@ def get_3D_mesh(series: Series, obj_name: str) -> Union[Surface, Spheres, Contou return obj_data +def findExportClash(file_names: dict, folder=None): + """Return the files an export would clash on, as (same_file, existing). + + 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: + same_file = same_file or (exported[folded], key, file_name) + continue + + if folder is not None and (Path(folder) / file_name).exists(): + existing.append(file_name) + + exported[folded] = key + + return same_file, existing + + +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 261033054..0de1f7749 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,10 @@ 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 + 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 = [] thicknesses = [] @@ -63,11 +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 - alignment = series.getAttr(obj_name, "alignment") - if not alignment: - tform = section.tform - else: - tform = section.tforms[alignment] + 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) @@ -96,6 +96,17 @@ 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 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/backend/volume/objects_3D.py b/PyReconstruct/modules/backend/volume/objects_3D.py index 87a8d5dc7..d14e22c9b 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,9 @@ 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 + 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 403b43833..58f7ca0c2 100644 --- a/PyReconstruct/modules/calc/__init__.py +++ b/PyReconstruct/modules/calc/__init__.py @@ -36,3 +36,9 @@ point_list_2_pix ) 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 new file mode 100644 index 000000000..67e3eba1c --- /dev/null +++ b/PyReconstruct/modules/calc/smooth.py @@ -0,0 +1,176 @@ +"""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 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. + + 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..7ba7f53bb 100644 --- a/PyReconstruct/modules/datatypes/series.py +++ b/PyReconstruct/modules/datatypes/series.py @@ -20,7 +20,14 @@ 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, + windowDepthSpan, + ztraceResiduals, + ztraceDifferences, + sectionOffsets +) from PyReconstruct.modules.constants import ( createHiddenDir, @@ -1028,6 +1035,16 @@ 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")) + 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 @@ -1078,11 +1095,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) @@ -1090,7 +1116,219 @@ 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 + + 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 ztrace points + 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 ztrace points."] + + 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 ztrace points + 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 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. + + 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 + (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, "", "" + + source, target, window = smoothing["source"], smoothing["target"], smoothing["window"] + problems = self.ztraceSmoothingProblems([obj_name], source, target, window) + if problems: + 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, "" + + 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 ztrace points + 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. @@ -2188,11 +2426,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(): @@ -2215,6 +2458,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] = {} @@ -2226,6 +2473,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, @@ -2257,6 +2506,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())): @@ -2313,11 +2564,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 @@ -2336,6 +2588,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/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_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 8587eeb7d..f314a289f 100644 --- a/PyReconstruct/modules/gui/main/field_widget_3_object.py +++ b/PyReconstruct/modules/gui/main/field_widget_3_object.py @@ -1,3 +1,5 @@ +import math + from .context_menu_list import get_context_menu_list_obj from PySide6.QtWidgets import ( @@ -17,7 +19,8 @@ TextWidget, ) from PyReconstruct.modules.gui.utils import ( - notify + notify, + notifyConfirm ) from PyReconstruct.modules.gui.table import ( HistoryTableWidget, @@ -373,7 +376,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" + + # 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 (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: + 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: + 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" + "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): + 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/PyReconstruct/modules/gui/main/main_window.py b/PyReconstruct/modules/gui/main/main_window.py index 62461ec62..93ea118c9 100644 --- a/PyReconstruct/modules/gui/main/main_window.py +++ b/PyReconstruct/modules/gui/main/main_window.py @@ -3001,6 +3001,8 @@ def importFromSeries(self): o_series.close() return + not_smoothed = set() # objects whose ztrace smoothing was not imported + if "traces" in response: ( srange, @@ -3014,7 +3016,7 @@ def importFromSeries(self): keep_below, ) = tuple(response["traces"]) - self.series.importTraces( + not_smoothed.update(self.series.importTraces( o_series, srange, regex_filters, @@ -3026,7 +3028,7 @@ def importFromSeries(self): keep_above, keep_below, self.field.series_states - ) + )) if "z-traces" in response: regex_filters = response["z-traces"][0] @@ -3060,7 +3062,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"] @@ -3093,6 +3095,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..78418d40e 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: @@ -539,13 +551,23 @@ 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") + obj.section_depths = md.get("section_depths") + 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. @@ -729,8 +751,19 @@ 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 = scene_obj.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 @@ -1251,6 +1284,17 @@ def setStep(self): def exportScene(self): """Export 3D scene as an obj file.""" + # two objects saved to one file would overwrite each other + 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, " + "or rename it, and export again." + ) + return + fp = FileDialog.get( "save", self, "Save scene as obj", filter="*.obj", @@ -1262,6 +1306,18 @@ 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 + _, 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?" + ) + 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] @@ -1327,6 +1383,15 @@ 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 + 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.""" @@ -1563,6 +1628,23 @@ def getHostGroup(self, scene_obj : SceneObject): return host_group + def exportClash(self, folder=None): + """Return the files the objects would be exported to that clash, as (same_file, existing). + + 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"): + pair, found = findExportClash( + {obj: f"{obj.export_name}.{extension}" for obj in self.scene_objects.values()}, + folder, + ) + same_file = same_file or pair + existing += found + + return same_file, existing + def exportAsObjs(self, export_dir): """Export scene objects as obj and mtl files.""" @@ -1573,8 +1655,9 @@ def exportAsObjs(self, export_dir): try: obj_name = obj.name.replace(" ", "_") # "Scale_Cube" and not "Scale Cube" + label = obj.export_name - obj_fp = export_dir / f"{obj_name}.obj" + obj_fp = export_dir / f"{label}.obj" mtl_fp = obj_fp.with_suffix(".mtl") ## Write obj file @@ -1587,7 +1670,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/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, diff --git a/manual/readme.md b/manual/readme.md index 2f7321474..8df55942a 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 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 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 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. + +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. 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. + +#### 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