-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistance_functions.py
99 lines (81 loc) · 2.68 KB
/
distance_functions.py
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
# -*- coding: utf-8 -*-
"""
In this script we define the siamese-based distance between writing systems.
Author: Claire Roman, Philippe Meyer
Email: philippemeyer68@yahoo.fr
Date: 04/2024
"""
import numpy as np
def closest_glyph(i, X_glyph, dict_dist_loc, invert):
"""
Finds the glyph in X_glyph closest to the glyph at index i.
Parameters
----------
i : int
Index of the glyph in X_glyph to find the closest glyph for.
X_glyph : numpy.ndarray
Array containing glyphs.
dict_dist_loc : dict
Dictionary containing distances between glyphs.
invert : bool
Flag indicating whether to invert the distance lookup.
Returns
-------
float
The distance between the glyph i and its closest glyph in X_glyph.
int
The index of the closest glyph in X_glyph.
"""
if invert:
l = [dict_dist_loc[(j, i)] for j in range(len(X_glyph))]
else:
l = [dict_dist_loc[(i, j)] for j in range(len(X_glyph))]
return (min(l), np.argmin(l))
def similarity_between_scripts_tilde(X_glyph_1, X_glyph_2, dict_dist_loc, invert):
"""
Computes the similarity of X_glyph_1 to X_glyph_2, corresponding to
d^tilde(X_glyph_1, X_glyph_2) in the paper.
Parameters
----------
X_glyph_1 : numpy.ndarray
Array containing glyphs for the first set.
X_glyph_2 : numpy.ndarray
Array containing glyphs for the second set.
dict_dist_loc : dict
Dictionary containing distances between glyphs.
invert : bool
Flag indicating whether to invert the distance lookup.
Returns
-------
float
The mean similarity between of the glyphs X_glyph_1 to the glyphs of X_glyph_2.
"""
l = []
for i in range(len(X_glyph_1)):
l.append(closest_glyph(i, X_glyph_2, dict_dist_loc, invert)[0])
return np.mean(l)
def similarity_between_scripts(X_glyph_1, X_glyph_2, dict_dist_loc):
"""
Computes the siamese-based distance between two sets of glyphs, corresponding to
d(X_glyph_1, X_glyph_2) in the paper.
Parameters
----------
X_glyph_1 : numpy.ndarray
Array containing glyphs for the first set.
X_glyph_2 : numpy.ndarray
Array containing glyphs for the second set.
dict_dist_loc : dict
Dictionary containing distances between glyphs.
Returns
-------
float
The siamese-based distance between the two sets of glyphs.
"""
sim_1 = similarity_between_scripts_tilde(
X_glyph_1, X_glyph_2, dict_dist_loc, invert=False
)
sim_2 = similarity_between_scripts_tilde(
X_glyph_2, X_glyph_1, dict_dist_loc, invert=True
)
sim = (sim_1 + sim_2) / 2
return sim