import vtk import numpy as np import gudhi import sys import os # Add the topology directory to Python path sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..')) ############################################################################### # The following parameters are from `topologyScoring.py` ############################################################################### # Set to True to allow data that is not perfectly predicted to score a perfect 10. # If this is set to False, the highest possible score that an imperfect prediction can score is a 9. canImperfectPredictionsScore10 = False # The order of the Wasserstein distance wassersteinOrder = 1.0 # The ground metric used for computing the Wasserstein distance wassersteinGroundMetric = float('inf') # This is the maximum average Wasserstein distance (the average is taken over (|P|+|Q|)/2) that can score points. # Any distance above this score will score a 0. maximumAverageWassersteinDistance = 0.2 ############################################################################### # You can integrate the following two functions into `topologyScoring.py` ############################################################################### def _loadPersistenceDiagramFromVTK(pdFilename : str) -> np.ndarray: """ Load a persistence diagram from a VTK file computed with TTK. Args: pdFilename: The path to the VTK file containing the persistence diagram. Returns: A numpy array of shape (n, 2) where each row is a (birth, death) pair for finite persistence pairs. """ reader = vtk.vtkDataSetReader() reader.SetFileName(pdFilename) reader.Update() output = reader.GetOutput() if output is None: raise ValueError(f"Could not read VTK file: {pdFilename}") cellData = output.GetCellData() birthArray = cellData.GetArray("Birth") persistenceArray = cellData.GetArray("Persistence") isFiniteArray = cellData.GetArray("IsFinite") if birthArray is None or persistenceArray is None: raise ValueError(f"VTK file {pdFilename} does not contain required 'Birth' and 'Persistence' arrays") pairs = [] numCells = output.GetNumberOfCells() for i in range(numCells): isFinite = isFiniteArray.GetTuple1(i) if isFiniteArray else 1 if isFinite: birth = birthArray.GetTuple1(i) persistence = persistenceArray.GetTuple1(i) death = birth + persistence pairs.append((birth, death)) return np.array(pairs) # ====== PERSISTENCE DIAGRAM WASSERSTEIN SCORE ====== def persistenceDiagramWassersteinScore(gtFilename : str, reconFilename : str, verbose : bool = False) -> int: """ Compute a similarity score (0-10) between two persistence diagrams stored in VTK files using Wasserstein distance. Args: gtFilename: Path to the ground truth persistence diagram VTK file. reconFilename: Path to the reconstructed persistence diagram VTK file. verbose: Whether to print error messages. Returns: An integer score from 0-10 indicating similarity (10 is best). """ try: gtDiagram = _loadPersistenceDiagramFromVTK(gtFilename) except Exception as e: if verbose: print(f"Error loading GT diagram: {e}") return 0 try: reconDiagram = _loadPersistenceDiagramFromVTK(reconFilename) except Exception as e: if verbose: print(f"Error loading recon diagram: {e}") return 0 if len(gtDiagram) == 0 and len(reconDiagram) == 0: return 10 elif len(gtDiagram) == 0 or len(reconDiagram) == 0: return 0 # Normalize using GT's min-max minFunctionValue = np.min(gtDiagram) maxFunctionValue = np.max(gtDiagram) gtDiagram = (gtDiagram - minFunctionValue) / (maxFunctionValue - minFunctionValue) reconDiagram = (reconDiagram - minFunctionValue) / (maxFunctionValue - minFunctionValue) wassersteinDistance = gudhi.wasserstein.wasserstein_distance(gtDiagram, reconDiagram, order=wassersteinOrder, internal_p=wassersteinGroundMetric) numAverage = (gtDiagram.shape[0] + reconDiagram.shape[0]) / 2 wassersteinDistance /= numAverage if wassersteinDistance == 0: return 10 score = round(10 * (maximumAverageWassersteinDistance - wassersteinDistance) / maximumAverageWassersteinDistance) if not canImperfectPredictionsScore10 and score == 10: return 9 if score < 0: return 0 return score def evaluateNoisyTerrainPersistenceDiagram(gtFilename : str, reconFilename : str, verbose : bool = False): """ Given two persistence diagrams, return a similarity score from 0-10. A score of 0 is considered bad and a score of 10 is considered good. Args: gtFilename: The name of a file in legacy VTK format (.vtk) that stores the persistence diagram of the ground truth data. reconFilename: The name of a file in legacy VTK format (.vtk) that stores the persistence diagram of the reconstructed data. verbose: Should error messages be printed if there are issues with the input files. """ return persistenceDiagramWassersteinScore(gtFilename, reconFilename, verbose) if __name__ == "__main__": if len(sys.argv) != 3: print(f"{os.path.basename(__file__)}: usage is 'python3 {os.path.basename(__file__)} gt_points.vtk recon_points.vtk'") exit(1) score = evaluateNoisyTerrainPersistenceDiagram(sys.argv[1], sys.argv[2], verbose=True) print(f"These critical points scored: {score}")