diff --git a/PyReconstruct/modules/datatypes/series.py b/PyReconstruct/modules/datatypes/series.py index 633f352c0..8cecde704 100644 --- a/PyReconstruct/modules/datatypes/series.py +++ b/PyReconstruct/modules/datatypes/series.py @@ -20,6 +20,8 @@ from .default_settings import default_settings, default_series_settings from .host_tree import HostTree +from PyReconstruct.modules.calc import area, lineDistance + from PyReconstruct.modules.constants import ( createHiddenDir, welcome_series_dir, @@ -1440,9 +1442,13 @@ def smoothObject(self, obj_names: list, series_states=None, log_event=True) -> l return malformed - def deleteMalformedTraces(self, records : list, series_states=None) -> list: + def deleteMalformedTraces(self, records : list, series_states=None, message="Deleting malformed contours...") -> list: """Delete specific malformed traces reported by smoothObject. + Also used by the data clean-up operations (pixel-dust / empty traces), + which produce records with the same schema (name, section, match); pass + a different ``message`` so the progress bar reads sensibly. + Each record must carry the keys produced by smoothObject — in particular "name", "section" and "match" (a {"color", "points"} signature). Because sections are reloaded fresh from disk, the stored @@ -1468,7 +1474,7 @@ def deleteMalformedTraces(self, records : list, series_states=None) -> list: deleted = [] for snum, section in self.enumerateSections( - message="Deleting malformed contours...", + message=message, series_states=series_states ): removed_any = False @@ -1507,6 +1513,471 @@ def _traceMatchesSignature(trace, signature) -> bool: return False return True + @staticmethod + def _cleanupRecord(obj_name, snum, index, trace, reason, area=None) -> dict: + """Build a clean-up candidate record. + + Uses the same schema smoothObject produces (so the records can be + deleted with deleteMalformedTraces and shown in the review dialog): a + "match" signature of color + 7-decimal-rounded points re-finds the exact + trace after the section is reloaded from disk. An optional physical + area (um^2) is carried for display in the pixel-dust review list. + """ + num_points = len(trace.points) + record = { + "name": obj_name, + "section": snum, + "index": index, + "points": num_points, + "location": ( + tuple(round(c, 4) for c in trace.points[0]) + if num_points else None + ), + "reason": reason, + "match": { + "color": trace.color, + "points": [ + (round(x, 7), round(y, 7)) for x, y in trace.points + ], + }, + } + if area is not None: + record["area"] = area + return record + + @staticmethod + def _traceArea(trace, tform) -> float: + """Physical area (um^2) of a trace, matching the object/trace tables. + + Mirrors TraceData: map the points through the section transform, then + run the same quantification the tables use. Open traces have no + enclosed area. + """ + if not trace.closed or len(trace.points) < 3: + return 0.0 + return abs(area(tform.map(trace.points))) + + def findPixelDustTraces(self, threshold_area : float, include_locked=False) -> list: + """Find tiny "pixel-dust" traces at or below an area threshold. + + A candidate is a CLOSED trace whose physical area (um^2, computed the + same way the object/trace tables report it) is greater than zero and at + or below ``threshold_area``. Zero-area / degenerate traces are left to + findEmptyTraces so the two operations stay disjoint. Open traces (lines) + have no enclosed area and are never pixel dust. Locked objects are + skipped unless ``include_locked`` is True. This only scans; nothing is + modified. Use deleteMalformedTraces to remove the chosen records. + + Params: + threshold_area (float): the maximum area (um^2), inclusive + include_locked (bool): True to also consider locked objects + Returns: + (list): candidate records (see _cleanupRecord) + """ + candidates = [] + for snum, section in self.enumerateSections( + message="Scanning for pixel-dust traces...", + ): + tform = section.tform + for cname in section.contours: + if not include_locked and self.getAttr(cname, "locked"): + continue + for index, trace in enumerate(section.contours[cname]): + if not trace.closed or len(trace.points) < 3: + continue + trace_area = self._traceArea(trace, tform) + if 0 < trace_area <= threshold_area: + candidates.append(self._cleanupRecord( + cname, snum, index, trace, + reason=( + f"Area {trace_area:.6g} um^2 " + f"(<= {threshold_area:.6g})" + ), + area=trace_area, + )) + return candidates + + def findEmptyTraces(self, include_locked=False) -> list: + """Find empty / degenerate traces (no meaningful geometry). + + A trace is empty when it encloses/spans nothing: no points, a closed + trace with zero area (fewer than 3 points or fully collinear/coincident + points), or an open trace with zero length (all points coincident). + These are unambiguous to remove. Locked objects are skipped unless + ``include_locked`` is True. Scans only; use deleteMalformedTraces to + remove the chosen records. + + Params: + include_locked (bool): True to also consider locked objects + Returns: + (list): candidate records (see _cleanupRecord) + """ + candidates = [] + for snum, section in self.enumerateSections( + message="Scanning for empty traces...", + ): + tform = section.tform + for cname in section.contours: + if not include_locked and self.getAttr(cname, "locked"): + continue + for index, trace in enumerate(section.contours[cname]): + npts = len(trace.points) + if npts == 0: + reason = "No points" + elif trace.closed: + if self._traceArea(trace, tform) == 0: + reason = "Closed trace enclosing zero area" + else: + continue + else: + length = lineDistance( + tform.map(trace.points), closed=False + ) + if length == 0: + reason = "Open trace of zero length" + else: + continue + candidates.append(self._cleanupRecord( + cname, snum, index, trace, reason=reason, + )) + return candidates + + ## A pair of traces is only worth measuring an overlap ratio for if that + ## ratio could possibly clear the threshold. _duplicatePairs proves a + ## ceiling on the ratio from quantities it already has, and skips the pair + ## when the ceiling falls this far below the threshold. The ceiling bounds + ## the ratio of the true geometry; getOverlapRatio measures a rasterized + ## approximation of it, which can read slightly high, so the ceiling is not + ## applied at the threshold itself. + _OVERLAP_CEILING_MARGIN = 0.05 + + @classmethod + def _duplicatePairs(cls, entries : list, threshold : float): + """Yield every pair of traces on a section that overlap. + + ``entries`` is one tuple per trace, + ``(xmin, ymin, xmax, ymax, area, name, index, trace)``, where the bounds + and area are in the trace's own untransformed coordinates (the space + Trace.getOverlapRatio works in). Yields + ``(entry_a, entry_b, ratio, points_match)`` per overlapping pair, ``a`` + before ``b`` in (name, index) order so the output does not depend on + which order the section's contours were walked in. + + Duplicates can sit under one name or under two, so every trace on the + section is compared with every other, and a dense autosegmented section + carries enough traces that measuring an overlap ratio for each of those + pairs is not viable: + Trace.getOverlapRatio rasterizes both polygons, which costs about 3 ms a + pair. Two filters keep the number of ratios measured proportional to the + number of traces rather than to its square: + + 1. **An x-sorted sweep.** Entries are sorted by ``xmin``, so once a + later entry starts to the right of where the current one ends, no + remaining entry can touch it and the inner loop stops. Pairs whose + bounding boxes are disjoint are therefore never even enumerated, + and Trace.getOverlapRatio would have answered 0 for all of them. + 2. **A ceiling on the ratio.** The overlap ratio is an + intersection-over-union, so it is at most + ``min(box_intersection, area_a, area_b) / max(area_a, area_b)``: + the shapes cannot share more than the overlap of their bounding + boxes, nor more than the smaller of them, and their union is at + least the larger of them. Two traces of the same structure have + nearly the same area and nearly the same bounding box, which puts + that ceiling near 1; two neighboring autosegmented traces whose + boxes merely touch put it near 0. + + Point-for-point matches are settled before either filter can reach them, + because a trace with no area at all (a straight line, say) is still a + duplicate of an identical copy of itself, and both filters reason about + areas. That mirrors Trace.overlaps, which also answers on points first. + + **Every bounding-box test here is slack by Trace's point-match + tolerance**, and it has to be. Two traces can match point for point + within that tolerance while their bounding boxes do not quite touch, so a + strict box test throws away pairs that Trace.overlaps calls duplicates. + + Params: + entries (list): per-trace tuples, described above + threshold (float): the overlap ratio above which two traces + count as duplicates, as in Trace.overlaps + Yields: + (tuple): (entry_a, entry_b, ratio, points_match) + """ + ## sorted by xmin so the inner loop can stop rather than run to the end + entries = sorted(entries, key=lambda e: e[0]) + ceiling_floor = threshold - cls._OVERLAP_CEILING_MARGIN + tol = Trace.POINTS_MATCH_TOLERANCE + n = len(entries) + for i in range(n): + a = entries[i] + axmin, aymin, axmax, aymax, aarea, aname, aindex, atrace = a + for j in range(i + 1, n): + b = entries[j] + bxmin, bymin, bxmax, bymax, barea, bname, bindex, btrace = b + if bxmin > axmax + tol: + break # sorted by xmin: nothing further can reach a + if atrace.closed != btrace.closed: + continue # as in Trace.overlaps + if aymax + tol < bymin or bymax + tol < aymin: + continue # boxes overlap in x but not in y + + ## first, second: the pair in a stable order for the caller + if (aname, aindex) <= (bname, bindex): + first, second = a, b + else: + first, second = b, a + + if atrace.pointsMatch(btrace): + yield first, second, 1.0, True + continue + + ## the ceiling (see the docstring). Both areas zero means there + ## is nothing to reason about, and getOverlapRatio answers 0 for + ## that case rather than dividing by a collapsed bounding box. + ## The box overlap is clamped at zero because the tests above are + ## slack by the point-match tolerance, so a pair whose boxes miss + ## each other by less than that reaches here. + larger = aarea if aarea > barea else barea + if larger > 0: + box_intersection = max( + 0.0, + min(axmax, bxmax) - max(axmin, bxmin) + ) * max( + 0.0, + min(aymax, bymax) - max(aymin, bymin) + ) + ceiling = min(box_intersection, aarea, barea) / larger + if ceiling <= ceiling_floor: + continue + + ratio = atrace.getOverlapRatio(btrace) + if Trace.ratioIsOverlap(ratio, threshold): + yield first, second, ratio, False + + def findDuplicateTraces(self, threshold : float, + include_locked=False) -> list: + """Find traces that duplicate each other, grouped by structure. + + One scan for both kinds of duplicate: a structure traced twice under + one name, and a structure traced under two names, which is what two + people tracing it produce. Every trace on a section is compared with + every other (see _duplicatePairs), and the overlapping pairs are + joined into groups: a structure traced three times is one group of + three, not three pairs. The joining is transitive, so A over B and B + over C is one group even if A and C fall just short of each other. + + This scan modifies nothing. Which name to keep is a question about the + data, so combineDuplicateTraces only acts on a name the caller picks. + Locked objects are skipped unless ``include_locked`` is True, matching + findPixelDustTraces and findEmptyTraces; even then, combining never + deletes a trace of a locked object (see combineDuplicateTraces). + + Overlap is decided as Trace.overlaps decides it: an identical point + sequence, or an overlap ratio above ``threshold``. + + Params: + threshold (float): the overlap ratio above which two traces + count as duplicates + include_locked (bool): True to also consider locked objects + Returns: + (list): one dict per group, in section order: "section"; + "members", one record per trace (see _cleanupRecord) in + (name, index) order; "names", the distinct object names, + sorted; "count", the number of traces; "ratio", the lowest + overlap ratio among the pairs that joined the group (1.0 + for a point-for-point match); and "location", the first + member's + """ + groups = [] + for snum, section in self.enumerateSections( + message="Scanning for duplicate traces...", + ): + entries = [] + for cname in section.contours: + if not include_locked and self.getAttr(cname, "locked"): + continue + for index, trace in enumerate(section.contours[cname]): + if not trace.points: + continue # nothing to compare; findEmptyTraces' business + xmin, ymin, xmax, ymax = trace.getBounds() + ## the untransformed polygon area, in the same coordinates + ## getOverlapRatio rasterizes, for the ceiling in + ## _duplicatePairs + entries.append(( + xmin, ymin, xmax, ymax, abs(area(trace.points)), + cname, index, trace + )) + + ## union-find over (name, index): each overlapping pair is an edge + ## and each group is a connected component + parent = {} + + def find(key): + parent.setdefault(key, key) + while parent[key] != key: + parent[key] = parent[parent[key]] + key = parent[key] + return key + + traces = {} + edges = [] + for first, second, ratio, _points_match in self._duplicatePairs( + entries, threshold + ): + fkey, skey = (first[5], first[6]), (second[5], second[6]) + traces[fkey], traces[skey] = first[7], second[7] + froot, sroot = find(fkey), find(skey) + if froot != sroot: + parent[sroot] = froot + edges.append((fkey, ratio)) + if not edges: + continue + + keys_by_root = {} + for key in traces: + keys_by_root.setdefault(find(key), []).append(key) + lowest = {} + for key, ratio in edges: + root = find(key) + lowest[root] = min(lowest.get(root, ratio), ratio) + + section_groups = [] + for root, keys in keys_by_root.items(): + keys.sort() + members = [ + self._cleanupRecord( + name, snum, index, traces[(name, index)], reason="" + ) + for name, index in keys + ] + section_groups.append({ + "section": snum, + "members": members, + "names": sorted({m["name"] for m in members}), + "count": len(members), + "ratio": float(lowest[root]), + "location": members[0]["location"], + }) + section_groups.sort( + key=lambda g: (g["members"][0]["name"], g["members"][0]["index"]) + ) + groups.extend(section_groups) + + return groups + + @staticmethod + def duplicateKeptMember(members : list, keep : str): + """The member of a duplicate group that combining under ``keep`` keeps. + + A name can hold more than one trace of the group (a structure traced + twice under one name), so the name alone does not pick a trace. The + one with the most points is kept, as the most detailed tracing, then + the first in its contour. + + Params: + members (list): the group's member records + keep (str): the object name chosen + Returns: + (dict): the member record kept, or None when no member has + that name + """ + candidates = [m for m in members if m["name"] == keep] + if not candidates: + return None + return min(candidates, key=lambda m: (-m["points"], m["index"])) + + def combineDuplicateTraces(self, choices : list, series_states=None, + log_event=True) -> list: + """Combine each chosen duplicate group into one trace. + + Each choice is a ``(group, keep)`` tuple: ``group`` from + findDuplicateTraces and ``keep`` the object name to keep, one of the + group's own "names". One trace under that name survives (see + duplicateKeptMember) and takes the tags of every other trace in the + group; the others are deleted. A choice whose ``keep`` is empty or not + one of the group's names is skipped: the name is never guessed. + + A locked object never loses a trace here: a group that would delete a + trace of a locked object is skipped whole. Keeping a locked trace is + allowed, since only its tags change. + + A group is combined whole or not at all. Sections are reloaded fresh, + so each member is found again by its color and points, as + deleteMalformedTraces does. If any member cannot be found (it changed + or went after the scan), the group is left alone. + + All the chosen groups are combined in one pass of enumerateSections, + so they are one undo step. + + Params: + choices (list): (group, keep) tuples, described above + series_states (dict): optional dict of undo states for GUI + log_event (bool): True if events should be logged + Returns: + (list): the (group, keep) tuples that were combined + """ + plans = {} + for choice in choices: + group, keep = choice + if not keep or keep not in group["names"]: + continue + kept = self.duplicateKeptMember(group["members"], keep) + doomed = [m for m in group["members"] if m is not kept] + if any(self.getAttr(m["name"], "locked") for m in doomed): + continue + plans.setdefault(group["section"], []).append( + (choice, [kept] + doomed) + ) + + if not plans: + return [] + + combined = [] + for snum, section in self.enumerateSections( + message="Combining duplicate traces...", + series_states=series_states + ): + used = set() + kept_names = set() + for choice, members in plans.get(snum, []): + traces = [] + for member in members: + contour = section.contours.get(member["name"]) or [] + trace = next(( + t for t in contour + if id(t) not in used + and self._traceMatchesSignature(t, member["match"]) + ), None) + if trace is None: + break + used.add(id(trace)) + traces.append(trace) + if len(traces) != len(members): + ## changed since the scan: leave the group whole, and free + ## the traces it claimed for the groups after it + used.difference_update(id(t) for t in traces) + continue + kept_trace = traces[0] + for trace in traces[1:]: + kept_trace.mergeTags(trace) + section.removeTrace(trace, log_event=log_event) + if log_event: + self.addLog( + kept_trace.name, snum, "Combine duplicate traces" + ) + kept_names.add(kept_trace.name) + combined.append(choice) + + if kept_names: + ## mergeTags changed the kept traces in place: name their + ## contours as modified so the undo state records them + section.modified_contours.update(kept_names) + section.save() + + if combined: + self.modified = True + return combined + def editObjectRadius(self, obj_names : list, new_rad : float, series_states=None): """Change the radii of all traces of an object. @@ -2089,48 +2560,6 @@ def getRecentSegGroup(self) -> str: g = group return g - def deleteDuplicateTraces(self, threshold : float, include_locked=False, series_states=None, log_event=True): - """Delete all duplicate traces in the series (keep tags). - - Params: - threshold (float): the threshold for overlapping traces to be considered duplicates - series_states (dict): optional dict of undo states for GUI - log_event (bool): True if event should be logged - """ - removed = {} - for snum, section in self.enumerateSections( - message="Removing duplicate traces...", - series_states=series_states - ): - found_on_section = False - for cname in section.contours: - if not include_locked and self.getAttr(cname, "locked"): - continue - i = 1 - while i < len(section.contours[cname]): - trace1 = section.contours[cname][i] - # check against all previous traces - for j in range(i-1, -1, -1): - trace2 = section.contours[cname][j] - # if overlaps, remove trace and break - if trace1.overlaps(trace2, threshold=threshold): - if snum not in removed: - removed[snum] = set() - removed[snum].add(cname) - found_on_section = True - trace1.mergeTags(trace2) - section.removeTrace(trace2) - i -= 1 - break - i += 1 - if found_on_section: - section.save() - - if log_event: - self.addLog(None, None, "Delete all duplicate traces") - - return removed - def addLog(self, obj_name : str, snum : int, event : str): """Add a log to the log set. diff --git a/PyReconstruct/modules/datatypes/trace.py b/PyReconstruct/modules/datatypes/trace.py index 04e511b51..c235d3149 100644 --- a/PyReconstruct/modules/datatypes/trace.py +++ b/PyReconstruct/modules/datatypes/trace.py @@ -96,9 +96,63 @@ def isSameTrace(self, other) -> bool: return False return True + ## How far apart, per axis, two corresponding points may sit and still count + ## as the same point. Named because a caller that wants to skip a pair of + ## traces cheaply has to allow for it: two traces can match point for point + ## under this tolerance while their bounding boxes do not touch, so a + ## bounding-box test that rules a pair out has to be slack by this much or it + ## will rule out pairs that pointsMatch accepts. Real data has such pairs; + ## see Series._duplicatePairs. + POINTS_MATCH_TOLERANCE = 1e-2 + + def pointsMatch(self, other) -> bool: + """Check if two traces are the same point sequence, within a tolerance. + + The cheap half of overlaps(): equal point counts and every pair of + corresponding points within POINTS_MATCH_TOLERANCE in both axes. Settled + without measuring any area, which is what lets overlaps() answer for + shapes that have no area to measure (see getOverlapRatio's zero-area + note). + + Params: + other (Trace): the trace to compare + Returns: + (bool): whether the two point sequences coincide + """ + if len(self.points) != len(other.points): + return False + tol = self.POINTS_MATCH_TOLERANCE + for (x1, y1), (x2, y2) in zip(self.points, other.points): + if abs(x1-x2) > tol or abs(y1-y2) > tol: + return False + return True + + @staticmethod + def ratioIsOverlap(r : float, threshold : float) -> bool: + """Apply the overlap threshold to an already-measured overlap ratio. + + Split out of overlaps() so a caller that needs the ratio itself (to + report it, say) can measure once and still reach the same verdict + overlaps() would. The threshold is exclusive below 1, and a threshold of + exactly 1 demands an exact ratio of 1. + + Params: + r (float): an overlap ratio, as returned by getOverlapRatio + threshold (float): the threshold overlap ratio (exclusive) + Returns: + (bool): whether that ratio counts as overlapping + """ + ## bool(), not the comparison itself: getOverlapRatio divides two + ## numpy sums, so the comparison yields numpy.bool_ and callers that + ## assert `is True` would fail on it. overlaps() has always returned a + ## plain bool here and tests hold it to that. + if threshold < 1: + return bool(r > threshold) + return bool(threshold == r == 1) + def overlaps(self, other, threshold=0.99): """Check if trace points overlap. - + Params: other (Trace): the trace to compare threshold (float): the threshold overlap ratio to define overlapping (exclusive) @@ -107,27 +161,13 @@ def overlaps(self, other, threshold=0.99): """ if self.closed != other.closed: return False - + # compare points directly - points_match = True - if len(self.points) != len(other.points): - points_match = False - else: - for (x1, y1), (x2, y2) in zip(self.points, other.points): - if abs(x1-x2) > 1e-2 or abs(y1-y2) > 1e-2: - points_match = False - break - if points_match: + if self.pointsMatch(other): return True - + # compare amount of overlap - r = self.getOverlapRatio(other) - if threshold < 1 and r > threshold: - return True - elif threshold == r == 1: - return True - else: - return False + return self.ratioIsOverlap(self.getOverlapRatio(other), threshold) def setHidden(self, hidden=True): """Set whether the trace is hidden. @@ -524,6 +564,18 @@ def getOverlapRatio(self, other): xmin, xmax = min(xmin1, xmin2), max(xmax1, xmax2) ymin, ymax = min(ymin1, ymin2), max(ymax1, ymax2) initial_area = (xmax-xmin) * (ymax-ymin) + + # The combined bounding box collapses when both traces sit on the same + # vertical or the same horizontal line: a single point and a vertical + # run through it, two collinear segments, and so on. Traces like this + # are real (smooth() already skips sub-three-point "pixel dust") and + # there is no box to rasterize into, so no area to compare. Two such + # traces cannot overlap by area, and identical ones are already settled + # by the point-by-point comparison in overlaps(), which never asks for a + # ratio. Answer 0 rather than dividing by zero. + if initial_area == 0: + return 0 + scale_factor = (1e4 / initial_area) ** 0.5 # scale the points diff --git a/PyReconstruct/modules/gui/dialog/__init__.py b/PyReconstruct/modules/gui/dialog/__init__.py index a2c8085a5..ed28f82c0 100644 --- a/PyReconstruct/modules/gui/dialog/__init__.py +++ b/PyReconstruct/modules/gui/dialog/__init__.py @@ -19,5 +19,9 @@ from .backup_comment import BackupCommentDialog from .table_columns import TableColumnsDialog from .import_series import ImportSeriesDialog, ImportAlignmentsDialog -from .malformed_contours import MalformedContoursDialog +from .malformed_contours import ( + MalformedContoursDialog, + PixelDustDialog, + DuplicateTracesDialog, +) from .copy_to_sections import CopyToSectionsDialog, format_copy_result diff --git a/PyReconstruct/modules/gui/dialog/malformed_contours.py b/PyReconstruct/modules/gui/dialog/malformed_contours.py index d25a75071..bff95271f 100644 --- a/PyReconstruct/modules/gui/dialog/malformed_contours.py +++ b/PyReconstruct/modules/gui/dialog/malformed_contours.py @@ -1,10 +1,14 @@ import csv +import html from PySide6.QtWidgets import ( QWidget, QDialog, QLabel, QVBoxLayout, + QHBoxLayout, + QToolButton, + QToolTip, QTableWidget, QTableWidgetItem, QPushButton, @@ -13,12 +17,18 @@ QAbstractItemView, QApplication, QFileDialog, + QComboBox, + QStyledItemDelegate, ) from PySide6.QtCore import Qt from PyReconstruct.modules.gui.utils import notifyConfirm +# the Keep cell of the duplicates list stores the row's names here +NAMES_ROLE = Qt.UserRole + 1 + + class MalformedContoursDialog(QDialog): """Report traces skipped during object smoothing. @@ -31,6 +41,25 @@ class MalformedContoursDialog(QDialog): """ COLUMNS = ["Object", "Section", "Point count", "Location (x, y)", "Reason"] + WINDOW_TITLE = "Traces skipped during smoothing" + # column the table is sorted by when it opens; subclasses that put a + # different column at index 1 override it to keep the sort meaningful + DEFAULT_SORT_COLUMN = 1 + + def _columnSpecs(self): + """Return (record-key, kind) pairs, one per column in COLUMNS. + + kind is one of "str", "int", "float", "loc" and controls how the cell + value is stored (numeric kinds sort numerically). Subclasses override + this together with COLUMNS to show different fields. + """ + return [ + ("name", "str"), + ("section", "int"), + ("points", "int"), + ("location", "loc"), + ("reason", "str"), + ] def __init__(self, mainwindow: QWidget, records: list, navigate=None, delete=None): @@ -58,11 +87,26 @@ def __init__(self, mainwindow: QWidget, records: list, navigate=None, self.navigate = navigate self.delete = delete - self.setWindowTitle("Traces skipped during smoothing") + self.setWindowTitle(self.WINDOW_TITLE) self.resize(660, 420) - self.heading = QLabel(self._headingText(), self) - self.heading.setWordWrap(True) + # one line above the list; the full explanation is the tooltip of + # the "?" beside it + self.heading = QLabel(self) + # a button, not a label, so the keyboard can reach it too: Tab to + # it and press Space to show the same tooltip a hover shows + self.help_icon = QToolButton(self) + self.help_icon.setText("?") + self.help_icon.setAccessibleName("Explanation") + self.help_icon.setFocusPolicy(Qt.StrongFocus) + self.help_icon.setFixedSize(18, 18) + self.help_icon.setCursor(Qt.WhatsThisCursor) + self.help_icon.setStyleSheet( + "QToolButton { border: 1px solid palette(mid); border-radius: 9px;" + " font-weight: bold; padding: 0; }" + ) + self.help_icon.clicked.connect(self._showExplanation) + self._refreshHeading() self.table = QTableWidget(len(self.records), len(self.COLUMNS), self) self.table.setHorizontalHeaderLabels(self.COLUMNS) @@ -73,7 +117,7 @@ def __init__(self, mainwindow: QWidget, records: list, navigate=None, self.table.setSortingEnabled(False) self._populate() self.table.setSortingEnabled(True) - self.table.sortItems(1) # default sort by section number + self.table.sortItems(self.DEFAULT_SORT_COLUMN) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table.cellDoubleClicked.connect(self._onDoubleClick) @@ -118,12 +162,19 @@ def __init__(self, mainwindow: QWidget, records: list, navigate=None, self.delete_all_button.setEnabled(bool(self.records)) self.delete_all_button.clicked.connect(self.deleteAllContours) + # subclass hook, run before the selection signal is connected so + # anything it adds is already there the first time the slot fires + self.extra_buttons = [] # (button, needs_a_selected_row) + self._addExtraButtons() + # connected after the buttons exist so the slot can safely touch them self.table.itemSelectionChanged.connect(self._updateRowActionButtons) buttonbox = QDialogButtonBox(QDialogButtonBox.Close, self) buttonbox.rejected.connect(self.reject) buttonbox.addButton(self.goto_button, QDialogButtonBox.ActionRole) + for button, _ in self.extra_buttons: + buttonbox.addButton(button, QDialogButtonBox.ActionRole) buttonbox.addButton(copy_button, QDialogButtonBox.ActionRole) buttonbox.addButton(save_button, QDialogButtonBox.ActionRole) if self.delete: @@ -134,14 +185,46 @@ def __init__(self, mainwindow: QWidget, records: list, navigate=None, self.delete_all_button, QDialogButtonBox.ActionRole ) + heading_row = QHBoxLayout() + heading_row.addWidget(self.heading) + heading_row.addWidget(self.help_icon) + heading_row.addStretch(1) + layout = QVBoxLayout() - layout.addWidget(self.heading) + layout.addLayout(heading_row) layout.addWidget(self.table) layout.addWidget(buttonbox) self.setLayout(layout) - def _headingText(self): - """Build the heading text from the current records.""" + def _refreshHeading(self): + """Set the one-line heading and the "?" tooltip from the records.""" + self.heading.setText(self._summaryText()) + explanation = self._explanationText() + # rich text, so Qt wraps the tooltip instead of drawing one long line + self.help_icon.setToolTip("".join( + f"

{html.escape(paragraph, quote=False)}

" + for paragraph in explanation.split("\n\n") + )) + self.help_icon.setAccessibleDescription(explanation) + + def _showExplanation(self): + """Show the "?" tooltip under the icon, for a click or a key.""" + QToolTip.showText( + self.help_icon.mapToGlobal(self.help_icon.rect().bottomLeft()), + self.help_icon.toolTip(), + self.help_icon, + ) + + def _summaryText(self): + """One short line that says what the list holds.""" + num_traces = len(self.records) + if not num_traces: + return "All listed traces have been deleted." + trace_word = "trace" if num_traces == 1 else "traces" + return f"{num_traces} {trace_word} could not be smoothed." + + def _explanationText(self): + """Build the full explanation (the "?" tooltip) from the records.""" num_traces = len(self.records) if not num_traces: return ( @@ -179,27 +262,27 @@ def _populate(self): # resolve it back to the real record via this map; the key travels with # the row through re-sorting. self._records_by_key = {} + specs = self._columnSpecs() for row, r in enumerate(self.records): self._records_by_key[row] = r - name_item = QTableWidgetItem(str(r["name"])) - name_item.setData(Qt.UserRole, row) - - section_item = QTableWidgetItem() - section_item.setData(Qt.DisplayRole, int(r["section"])) - - points_item = QTableWidgetItem() - points_item.setData(Qt.DisplayRole, int(r["points"])) - - loc = r.get("location") - loc_item = QTableWidgetItem(self._format_location(loc)) - - reason_item = QTableWidgetItem(str(r["reason"])) - - for col, item in enumerate( - (name_item, section_item, points_item, loc_item, reason_item) - ): + for col, (key, kind) in enumerate(specs): + if kind == "int": + item = QTableWidgetItem() + item.setData(Qt.DisplayRole, int(r[key])) + elif kind == "float": + # store as a float so the column sorts numerically + item = QTableWidgetItem() + item.setData(Qt.DisplayRole, round(float(r[key]), 8)) + elif kind == "loc": + item = QTableWidgetItem(self._format_location(r.get(key))) + else: # "str" + item = QTableWidgetItem(str(r[key])) + # a stable per-row key on the first column, resolved back to the + # real record by _recordAtRow; it travels with the row on sort + if col == 0: + item.setData(Qt.UserRole, row) item.setTextAlignment(Qt.AlignCenter) # show the full cell value on hover; columns are stretched to # fit the window, so wider values (e.g. the Reason) truncate @@ -213,12 +296,23 @@ def _format_location(loc): return "—" return f"({loc[0]}, {loc[1]})" + def _addExtraButtons(self): + """Subclass hook: append (button, needs_selection) to extra_buttons. + + Nothing here by default. A button appended with needs_selection True is + disabled while no row is selected, exactly like "Go to trace". + """ + return + def _updateRowActionButtons(self): """Enable selection-dependent buttons only while a row is selected.""" has_selection = self.table.selectionModel().hasSelection() self.goto_button.setEnabled(has_selection) if self.delete_selected_button is not None: self.delete_selected_button.setEnabled(has_selection) + for button, needs_selection in self.extra_buttons: + if needs_selection: + button.setEnabled(has_selection) def _recordAtRow(self, row): """Return the record for the given table row (or None).""" @@ -296,7 +390,7 @@ def _pruneRecords(self, deleted): self.table.removeRow(row) del self._records_by_key[key] self.records = list(self._records_by_key.values()) - self.heading.setText(self._headingText()) + self._refreshHeading() if self.delete_all_button is not None: self.delete_all_button.setEnabled(bool(self.records)) self._updateRowActionButtons() @@ -334,3 +428,341 @@ def saveCSV(self): return with open(fp, "w", newline="") as f: csv.writer(f).writerows(self._rows_for_export()) + + +class PixelDustDialog(MalformedContoursDialog): + """Review tiny "pixel-dust" traces before removing them. + + A data clean-up review list: every row is a small closed trace at or below + the area threshold the user chose. The user inspects the candidates (and can + "Go to trace" to confirm), then deselects any legitimate small trace before + "Delete selected" / "Delete all". Reuses all of the selection, navigation, + deletion (undoable), and export behavior of MalformedContoursDialog; only + the columns (an Area column) and the explanatory heading differ. + """ + + COLUMNS = ["Object", "Section", "Area (um^2)", "Point count", + "Location (x, y)", "Reason"] + WINDOW_TITLE = "Remove pixel-dust traces" + + def _columnSpecs(self): + return [ + ("name", "str"), + ("section", "int"), + ("area", "float"), + ("points", "int"), + ("location", "loc"), + ("reason", "str"), + ] + + def _summaryText(self): + num_traces = len(self.records) + if not num_traces: + return "All listed traces have been deleted." + trace_word = "trace" if num_traces == 1 else "traces" + return f"{num_traces} {trace_word} at or below the area threshold." + + def _explanationText(self): + """Explain the pixel-dust review and how to act on it.""" + num_traces = len(self.records) + if not num_traces: + return ( + "All listed traces have been deleted.\n\n" + "You can close this window." + ) + + num_objs = len({r["name"] for r in self.records}) + trace_word = "trace" if num_traces == 1 else "traces" + obj_word = "object" if num_objs == 1 else "objects" + + return ( + f"{num_traces} small (pixel-dust) {trace_word} across " + f"{num_objs} {obj_word} at or below the area threshold.\n\n" + "These are typically stray specks left by segmentation. Review the " + "candidates below, select a row and click “Go to trace” to inspect " + "one, and deselect any legitimate trace you want to keep. Then use " + "“Delete selected” or “Delete all” to remove them (can be undone)." + "\n\nNothing is removed until you choose to delete." + ) + + +class _KeepNameCombo(QComboBox): + """A drop-down that ignores the mouse wheel. + + Several styles change a combo box's value on a wheel turn over it, so + scrolling the list would change the picks it passed over. The wheel + scrolls the table instead. + """ + + def wheelEvent(self, event): + event.ignore() + + +class _KeepNameDelegate(QStyledItemDelegate): + """The drop-down in a duplicates row's Keep cell. + + The pick is stored as the cell's own text, so it travels with its row + through a column sort and reaches the copied table as it is; the + drop-down is only the editor over it, kept open on every row. + """ + + PLACEHOLDER = "Pick a name" + + def createEditor(self, parent, option, index): + combo = _KeepNameCombo(parent) + combo.addItems(index.data(NAMES_ROLE) or []) + combo.setPlaceholderText(self.PLACEHOLDER) + combo.setCurrentIndex(-1) + combo.currentIndexChanged.connect( + lambda _i, c=combo: self.commitData.emit(c) + ) + return combo + + def setEditorData(self, editor, index): + name = index.data(Qt.DisplayRole) or "" + editor.blockSignals(True) + editor.setCurrentIndex(editor.findText(name) if name else -1) + editor.blockSignals(False) + + def setModelData(self, editor, model, index): + name = editor.currentText() if editor.currentIndex() >= 0 else "" + model.setData(index, name, Qt.EditRole) + + +class DuplicateTracesDialog(MalformedContoursDialog): + """Review duplicate traces and combine each structure into one trace. + + Each row is one group from Series.findDuplicateTraces: a structure traced + more than once, under one name or under several. The Keep cell is a + drop-down of the row's names. A row with one name has it picked; a row + with more than one starts with none, because which name is right is a + question about the data, and a row with no name picked is never combined. + + "Combine selected" and "Combine all" hand the picked rows to the + ``combine`` callback, after a confirmation. Combining keeps one trace + under the picked name with the tags of the others and deletes the rest + (Series.combineDuplicateTraces). The base class's Delete buttons never + appear: this dialog passes no ``delete`` callback up. + """ + + COLUMNS = ["Keep", "Traced as", "Section", "Traces", "Overlap", + "Location (x, y)"] + WINDOW_TITLE = "Duplicates" + DEFAULT_SORT_COLUMN = 2 # "Section" + KEEP_COLUMN = 0 + + def __init__(self, mainwindow: QWidget, records: list, navigate=None, + combine=None): + """Create the duplicates list. + + Params: + mainwindow (QWidget): the parent window + records (list): groups from Series.findDuplicateTraces + navigate (callable): optional navigate(section_num, obj_name, + index) callback for "Go to trace" + combine (callable): optional combine(choices) callback taking + ``(group, keep)`` tuples as Series.combineDuplicateTraces + does and returning the tuples it combined. The Combine + buttons are only shown when it is provided. + """ + self.combine = combine + super().__init__(mainwindow, records, navigate=navigate, delete=None) + self.resize(760, 440) + self.table.setItemDelegateForColumn( + self.KEEP_COLUMN, _KeepNameDelegate(self.table) + ) + for row in range(self.table.rowCount()): + self.table.openPersistentEditor( + self.table.item(row, self.KEEP_COLUMN) + ) + self.table.itemChanged.connect(self._updateRowActionButtons) + self._updateRowActionButtons() + + def _populate(self): + """Fill the table from the groups.""" + self._records_by_key = {} + for row, group in enumerate(self.records): + self._records_by_key[row] = group + names = list(group["names"]) + keep = QTableWidgetItem(names[0] if len(names) == 1 else "") + keep.setData(Qt.UserRole, row) + keep.setData(NAMES_ROLE, names) + section = QTableWidgetItem() + section.setData(Qt.DisplayRole, int(group["section"])) + count = QTableWidgetItem() + count.setData(Qt.DisplayRole, int(group["count"])) + ratio = QTableWidgetItem() + ratio.setData(Qt.DisplayRole, round(float(group["ratio"]), 8)) + cells = [ + keep, + QTableWidgetItem(", ".join(names)), + section, + count, + ratio, + QTableWidgetItem(self._format_location(group.get("location"))), + ] + for col, item in enumerate(cells): + item.setTextAlignment(Qt.AlignCenter) + if col != self.KEEP_COLUMN: + item.setToolTip(item.text()) + self.table.setItem(row, col, item) + + def _choicesForRows(self, rows): + """(group, keep) for each of the rows with a name picked, and how + many rows had none.""" + choices = [] + unpicked = 0 + for row in rows: + group = self._recordAtRow(row) + if group is None: + continue + keep = self.table.item(row, self.KEEP_COLUMN).text() + if keep: + choices.append((group, keep)) + else: + unpicked += 1 + return choices, unpicked + + def _selectedRows(self): + return sorted( + index.row() for index in self.table.selectionModel().selectedRows() + ) + + def _addExtraButtons(self): + """Add the two Combine buttons when there is a callback for them.""" + self.combine_selected_button = None + self.combine_all_button = None + if not self.combine: + return + self.combine_selected_button = QPushButton("Combine selected", self) + self.combine_selected_button.setToolTip( + "Combine each selected row into one trace under the name picked " + "(can be undone)" + ) + self.combine_selected_button.clicked.connect( + lambda: self._combineRows(self._selectedRows()) + ) + self.extra_buttons.append((self.combine_selected_button, False)) + + self.combine_all_button = QPushButton("Combine all", self) + self.combine_all_button.setToolTip( + "Combine every row with a name picked into one trace under that " + "name (can be undone)" + ) + self.combine_all_button.clicked.connect( + lambda: self._combineRows(range(self.table.rowCount())) + ) + self.extra_buttons.append((self.combine_all_button, False)) + + def _updateRowActionButtons(self, *_args): + """Also enable each Combine button only while it has a picked row.""" + super()._updateRowActionButtons() + if self.combine_all_button is None: + return + all_rows = range(self.table.rowCount()) + self.combine_all_button.setEnabled( + bool(self._choicesForRows(all_rows)[0]) + ) + self.combine_selected_button.setEnabled( + bool(self._choicesForRows(self._selectedRows())[0]) + ) + + def _combineRows(self, rows): + """Confirm, combine the picked rows, and prune the ones combined.""" + if not self.combine: + return + choices, unpicked = self._choicesForRows(rows) + if not choices: + return + count = len(choices) + noun = "row" if count == 1 else "rows" + unpicked_note = "" + if unpicked: + was = "row was" if unpicked == 1 else "rows were" + unpicked_note = ( + f"\n\n{unpicked} {was} left alone because no name is picked." + ) + if not notifyConfirm( + f"Combine {count} {noun}?\n\n" + "In each row, one trace is kept under the name you picked, the " + "tags of the other traces are added to it, and the others are " + f"deleted.{unpicked_note}\n\n" + "This can be undone (Ctrl+Z).", + yn=True, + ): + return + applied = self.combine(choices) or [] + if not applied: + return + + ## a combine deletes every trace of a group but the one kept, so a + ## later trace of the same object on the same section moves up in its + ## contour; shift the indexes of the rows left so "Go to trace" still + ## frames the trace in its row + from PyReconstruct.modules.datatypes.series import Series + removed = [] + for group, keep in applied: + kept = Series.duplicateKeptMember(group["members"], keep) + removed.extend( + (m["section"], m["name"], m["index"]) + for m in group["members"] if m is not kept + ) + combined = {id(group) for group, _keep in applied} + for group in self.records: + if id(group) in combined: + continue + for member in group["members"]: + member["index"] -= sum( + 1 for section, name, index in removed + if section == member["section"] + and name == member["name"] and index < member["index"] + ) + self._pruneRecords([group for group, _keep in applied]) + + def _navigateToRow(self, row): + """Focus the field on a row's trace: the one kept once a name is + picked, and the row's first trace until then.""" + if not self.navigate: + return + group = self._recordAtRow(row) + if group is None: + return + from PyReconstruct.modules.datatypes.series import Series + keep = self.table.item(row, self.KEEP_COLUMN).text() + member = ( + Series.duplicateKeptMember(group["members"], keep) + or group["members"][0] + ) + self.navigate(member["section"], member["name"], member["index"]) + + def _summaryText(self): + num_rows = len(self.records) + if not num_rows: + return "Every row has been combined." + structures = "structure" if num_rows == 1 else "structures" + return f"{num_rows} {structures} traced more than once." + + def _explanationText(self): + """Explain what a row is and what combining it does.""" + num_rows = len(self.records) + if not num_rows: + return "Every row has been combined.\n\nYou can close this window." + + num_sections = len({g["section"] for g in self.records}) + structures = "structure" if num_rows == 1 else "structures" + sections = "section" if num_sections == 1 else "sections" + return ( + f"{num_rows} {structures} traced more than once, across " + f"{num_sections} {sections}. Each row is one structure, whether " + "its traces share a name or not.\n\n" + "Pick the name to keep in each row. Combining a row keeps one " + "trace under that name, adds the tags of the other traces to it, " + "and deletes the others. A row with one name has it picked " + "already. A row with more than one is left alone until you pick " + "one.\n\n" + "Select a row and click “Go to trace” to see it in the field. " + "The Overlap column is the lowest overlap ratio between the " + "row's traces (1 means the traces have the same points).\n\n" + "Nothing changes until you combine, and combining can be undone " + "(Ctrl+Z)." + ) diff --git a/PyReconstruct/modules/gui/main/field_widget_3_object.py b/PyReconstruct/modules/gui/main/field_widget_3_object.py index c9edc4395..1e6ba67ba 100644 --- a/PyReconstruct/modules/gui/main/field_widget_3_object.py +++ b/PyReconstruct/modules/gui/main/field_widget_3_object.py @@ -258,6 +258,73 @@ def deleteMalformedContours(self, records: list) -> list: ) return deleted + + def combineDuplicateTraces(self, choices: list) -> list: + """Combine the duplicate groups chosen in the duplicates list. + + The callback behind the list's Combine buttons. Each choice is a + ``(group, keep)`` tuple naming the object to keep. Mirrors + deleteMalformedContours: save field data, combine through the series + (whose enumerateSections records one undo state for the batch), then + refresh the tables and field. Returns the choices actually combined + so the dialog can prune exactly those rows. + + Series.combineDuplicateTraces refuses a group that would delete a + trace of a locked object, and one whose traces changed since the scan. + This layer says which, so no row goes uncombined without a reason. + """ + if not choices: + return [] + + # the rows the series will refuse for a lock, named so the notice can + # explain itself; the series checks the lock again regardless + locked_names = set() + locked_rows = 0 + for group, keep in choices: + kept = self.series.duplicateKeptMember(group["members"], keep) + names = { + m["name"] for m in group["members"] if m is not kept + and self.series.getAttr(m["name"], "locked") + } + if names: + locked_names |= names + locked_rows += 1 + + # persist field edits to section data before reloading sections + self.mainwindow.saveAllData() + + applied = self.series.combineDuplicateTraces( + choices, + series_states=self.series_states, + ) + + if applied: + names = set() + for group, _keep in applied: + names.update(group["names"]) + self.table_manager.updateObjects(names) + self.reload() + self.mainwindow.seriesModified(True) + + if locked_names: + rows = "1 row was" if locked_rows == 1 else f"{locked_rows} rows were" + notify( + f"{rows} not combined because combining would delete " + "traces of locked objects:\n\n" + + "\n".join(sorted(locked_names)) + + "\n\nUnlock them, or keep their names, and combine again." + ) + + missed = len(choices) - len(applied) - locked_rows + if missed > 0: + rows = "1 row was" if missed == 1 else f"{missed} rows were" + notify( + f"{rows} not combined because the traces changed after " + "the scan. Run the scan again to list them as " + "they are now." + ) + + return applied @object_function(update_objects=True, reload_field=False) def editComment(self, obj_names : list): diff --git a/PyReconstruct/modules/gui/main/main_imports.py b/PyReconstruct/modules/gui/main/main_imports.py index 1cb130862..0d5f2b962 100644 --- a/PyReconstruct/modules/gui/main/main_imports.py +++ b/PyReconstruct/modules/gui/main/main_imports.py @@ -59,6 +59,8 @@ ShortcutsDialog, BackupCommentDialog, ImportSeriesDialog, + PixelDustDialog, + DuplicateTracesDialog, ImportAlignmentsDialog, ) diff --git a/PyReconstruct/modules/gui/main/main_window.py b/PyReconstruct/modules/gui/main/main_window.py index d1d236e4a..d28a594b1 100644 --- a/PyReconstruct/modules/gui/main/main_window.py +++ b/PyReconstruct/modules/gui/main/main_window.py @@ -2463,32 +2463,106 @@ def setFindZoom(self): self.series.setOption("find_zoom", z) - def deleteDuplicateTraces(self): - """Remove all duplicate traces from the series.""" + def reviewDuplicateTraces(self): + """Find duplicate traces and open them for review. + + One scan finds overlapping traces whether their names match or not, + one row per structure however many times it was traced. The list + asks which name to keep in each row and changes nothing until the + user combines; combining is one undoable step per press. + """ self.saveAllData() structure = [ ["Overlap threshold:", ("float", 0.95, (0, 1))], - [("check", ("check locked traces", True))] + [("check", ("check locked traces", False))] ] - response, confirmed = QuickDialog.get(self, structure, "Remove duplicate traces") + response, confirmed = QuickDialog.get(self, structure, "Duplicates") if not confirmed: return threshold = response[0] include_locked = response[1][0][1] - - removed = self.series.deleteDuplicateTraces(threshold, include_locked, self.field.series_states) - if removed: - message = "The following duplicate traces were removed:" - for snum in removed: - message += f"\nSection {snum}: " + ", ".join(removed[snum]) - TextWidget(self, message, title="Removed Traces") - else: - notify("No duplicate traces found.") + groups = self.series.findDuplicateTraces(threshold, include_locked) + if not groups: + notify("No duplicate traces found at that overlap threshold.") + return - self.field.reload() - self.seriesModified(True) + self.duplicate_traces_dialog = DuplicateTracesDialog( + self, + groups, + navigate=self.field.focusMalformedContour, + combine=self.field.combineDuplicateTraces, + ) + self.duplicate_traces_dialog.show() + + def removePixelDustTraces(self): + """Find tiny "pixel-dust" traces and remove them through a review list. + + Scans the series for small closed traces at or below a user-chosen area + threshold (um^2), then opens a reviewable list: nothing is removed until + the user inspects the candidates, deselects any to keep, and deletes. + Deletion is a single undoable operation (see deleteMalformedContours). + """ + self.saveAllData() + + structure = [ + ["Maximum trace area (um^2):", ("float", 0.01)], + ] + response, confirmed = QuickDialog.get( + self, structure, "Remove pixel-dust traces" + ) + if not confirmed: + return + threshold = response[0] + if threshold is None or threshold <= 0: + notify("Please enter an area threshold greater than zero.") + return + + # locked objects are always left alone: the review-list delete path + # (deleteMalformedContours) refuses locked objects, so surfacing them + # here would be a dead end. Empty-trace removal skips locked the same way. + candidates = self.series.findPixelDustTraces(threshold) + if not candidates: + notify("No pixel-dust traces found at or below that area.") + return + + # reviewable list: the user confirms/deselects before anything is deleted + self.pixel_dust_dialog = PixelDustDialog( + self, + candidates, + navigate=self.field.focusMalformedContour, + delete=self.field.deleteMalformedContours, + ) + self.pixel_dust_dialog.show() + + def removeEmptyTraces(self): + """Find and remove empty / degenerate traces (no meaningful geometry). + + These are unambiguous (no points, zero-area closed traces, or zero-length + open traces), so they are removed after a single count-stating + confirmation rather than a review list. Locked objects are left alone. + Removal is one undoable operation. + """ + self.saveAllData() + + candidates = self.series.findEmptyTraces(include_locked=False) + if not candidates: + notify("No empty traces found.") + return + + count = len(candidates) + noun = "empty trace" if count == 1 else "empty traces" + if not notifyConfirm( + f"Remove {count} {noun} from the series?\n\n" + "This can be undone (Ctrl+Z).", + yn=True, + ): + return + + deleted = self.field.deleteMalformedContours(candidates) + if deleted: + notify(f"Removed {len(deleted)} {noun}.") def addTo3D(self, names, ztraces=False): """Generate the 3D view for a list of objects. diff --git a/PyReconstruct/modules/gui/main/menubar.py b/PyReconstruct/modules/gui/main/menubar.py index ccefd71f9..f1c8a1b55 100644 --- a/PyReconstruct/modules/gui/main/menubar.py +++ b/PyReconstruct/modules/gui/main/menubar.py @@ -197,7 +197,16 @@ def return_series_menu(self): }, None, ("findobjectfirst_act", "Find first object contour...", self.series, self.findObjectFirst), - ("removeduplicates_act", "Remove duplicate traces", "", self.deleteDuplicateTraces), + { + "attr_name": "cleanupmenu", + "text": "Clean up", + "opts": + [ + ("duplicates_act", "Duplicates...", "", self.reviewDuplicateTraces), + ("removepixeldust_act", "Remove pixel-dust traces...", "", self.removePixelDustTraces), + ("removeempty_act", "Remove empty traces...", "", self.removeEmptyTraces), + ] + }, None, ("updatecuration_act", "Update curation from history", "", self.updateCurationFromHistory), None,