File size: 5,703 Bytes
eee57cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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}")