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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
extern crate nalgebra;
extern crate munkres;
extern crate closed01;
extern crate petgraph;
use nalgebra::{DMat, Shape, ApproxEq};
use munkres::{WeightMatrix, solve_assignment};
use std::cmp;
use std::mem;
use closed01::Closed01;
pub use traits::NodeColorMatching;
use traits::{Edges, Graph};
pub mod graph;
mod traits;
#[derive(Debug, Copy, Clone)]
pub enum ScoreNorm {
MinDegree,
MaxDegree,
}
#[derive(Debug)]
pub struct IgnoreNodeColors;
impl NodeColorMatching for IgnoreNodeColors {
fn node_color_matching(&self, _node_i: usize, _node_j: usize) -> Closed01<f32> {
Closed01::one()
}
}
#[inline(always)]
fn similarity_cost(weight: f32) -> f32 {
debug_assert!(weight >= 0.0 && weight <= 1.0);
1.0 - weight
}
#[inline]
fn s_next<T: Edges>(n_i: &T, n_j: &T, x: &DMat<f32>) -> Closed01<f32> {
let max_deg = cmp::max(n_i.num_edges(), n_j.num_edges());
let min_deg = cmp::min(n_i.num_edges(), n_j.num_edges());
debug_assert!(min_deg <= max_deg);
if max_deg == 0 {
return Closed01::one();
}
if min_deg == 0 {
return Closed01::zero();
}
assert!(min_deg > 0 && max_deg > 0);
let mapidx = |(a, b)| (n_i.nth_edge(a).unwrap(), n_j.nth_edge(b).unwrap());
let mut w = WeightMatrix::from_fn(min_deg, |ab| similarity_cost(x[mapidx(ab)]));
let assignment = solve_assignment(&mut w);
assert!(assignment.len() == min_deg);
let sum: f32 = assignment.iter().fold(0.0, |acc, &ab| acc + x[mapidx(ab)]);
return Closed01::new(sum / max_deg as f32);
}
#[derive(Debug)]
pub struct SimilarityMatrix<'a, F, G, E>
where F: NodeColorMatching,
G: Graph<E = E> + 'a,
E: Edges
{
graph_a: &'a G,
graph_b: &'a G,
node_color_matching: F,
current: DMat<f32>,
previous: DMat<f32>,
num_iterations: usize,
}
impl<'a, F, G, E> SimilarityMatrix<'a, F, G, E>
where F: NodeColorMatching,
G: Graph<E = E>,
E: Edges
{
pub fn new(graph_a: &'a G,
graph_b: &'a G,
node_color_matching: F)
-> SimilarityMatrix<'a, F, G, E> {
let x: DMat<f32> = DMat::from_fn(graph_a.num_nodes(), graph_b.num_nodes(), |i, j| {
if graph_a.node_degree(i) > 0 && graph_b.node_degree(j) > 0 {
node_color_matching.node_color_matching(i, j)
} else {
Closed01::zero()
}
.get()
});
let new_x: DMat<f32> = DMat::new_zeros(graph_a.num_nodes(), graph_b.num_nodes());
SimilarityMatrix {
graph_a: graph_a,
graph_b: graph_b,
node_color_matching: node_color_matching,
current: x,
previous: new_x,
num_iterations: 0,
}
}
fn in_eps(&self, eps: f32) -> bool {
self.previous.approx_eq_eps(&self.current, &eps)
}
pub fn next(&mut self) {
{
let x = &self.current;
let new_x = &mut self.previous;
let shape = x.shape();
for i in 0..shape.0 {
for j in 0..shape.1 {
let scale = self.node_color_matching.node_color_matching(i, j);
let in_score = s_next(self.graph_a.in_edges_of(i),
self.graph_b.in_edges_of(j),
x);
let out_score = s_next(self.graph_a.out_edges_of(i),
self.graph_b.out_edges_of(j),
x);
new_x[(i, j)] = in_score.average(out_score).mul(scale).get();
}
}
}
mem::swap(&mut self.previous, &mut self.current);
self.num_iterations += 1;
}
#[inline]
pub fn iterate(&mut self, stop_after_iter: usize, eps: f32) {
for _ in 0..stop_after_iter {
if self.in_eps(eps) {
break;
}
self.next();
}
}
pub fn matrix(&self) -> &DMat<f32> {
&self.current
}
pub fn num_iterations(&self) -> usize {
self.num_iterations
}
pub fn min_nodes(&self) -> usize {
cmp::min(self.current.nrows(), self.current.ncols())
}
pub fn max_nodes(&self) -> usize {
cmp::max(self.current.nrows(), self.current.ncols())
}
pub fn optimal_node_assignment(&self) -> Vec<(usize, usize)> {
let n = self.min_nodes();
let assignment = if n > 0 {
let mut w = WeightMatrix::from_fn(n, |ij| similarity_cost(self.current[ij]));
solve_assignment(&mut w)
} else {
Vec::new()
};
assert!(assignment.len() == n);
assignment
}
fn score_optimal_sum(&self, node_assignment: Option<&[(usize, usize)]>) -> f32 {
match node_assignment {
Some(node_assignment) => {
assert!(node_assignment.len() == self.min_nodes());
node_assignment.iter().fold(0.0, |acc, &ab| acc + self.current[ab])
}
None => {
let node_assignment = self.optimal_node_assignment();
assert!(node_assignment.len() == self.min_nodes());
node_assignment.iter().fold(0.0, |acc, &ab| acc + self.current[ab])
}
}
}
pub fn score_outgoing_edge_weights_sum_norm(&self,
node_assignment: &[(usize, usize)],
norm: ScoreNorm)
-> Closed01<f32> {
let n = self.min_nodes();
let m = self.max_nodes();
debug_assert!(m >= n);
assert!(node_assignment.len() == n);
let sum: f32 = node_assignment.iter().fold(0.0, |acc, &(node_i, node_j)| {
let score_ij = self.score_outgoing_edge_weights_of(node_i, node_j);
acc + score_ij.get()
});
assert!(sum >= 0.0 && sum <= n as f32);
match norm {
ScoreNorm::MinDegree => Closed01::new(sum / n as f32),
ScoreNorm::MaxDegree => Closed01::new(sum / m as f32),
}
}
fn score_outgoing_edge_weights_of(&self, node_i: usize, node_j: usize) -> Closed01<f32> {
let out_i = self.graph_a.out_edges_of(node_i);
let out_j = self.graph_b.out_edges_of(node_j);
let max_deg = cmp::max(out_i.num_edges(), out_j.num_edges());
if max_deg == 0 {
return Closed01::one();
}
let edge_weight_distance = &|(i, j)| {
match (out_i.nth_edge_weight(i), out_j.nth_edge_weight(j)) {
(Some(w_i), Some(w_j)) => w_i.distance(w_j),
_ => {
Closed01::one()
}
}
.get()
};
let mut w = WeightMatrix::from_fn(max_deg, edge_weight_distance);
let assignment = solve_assignment(&mut w);
assert!(assignment.len() == max_deg);
let sum: f32 = assignment.iter().fold(0.0, |acc, &ij| acc + edge_weight_distance(ij));
debug_assert!(sum >= 0.0 && sum <= max_deg as f32);
Closed01::new(sum / max_deg as f32).inv()
}
pub fn score_optimal_sum_norm(&self,
node_assignment: Option<&[(usize, usize)]>,
norm: ScoreNorm)
-> Closed01<f32> {
let n = self.min_nodes();
let m = self.max_nodes();
if n > 0 {
assert!(m > 0);
let sum = self.score_optimal_sum(node_assignment);
assert!(sum >= 0.0 && sum <= n as f32);
match norm {
ScoreNorm::MinDegree => Closed01::new(sum / n as f32),
ScoreNorm::MaxDegree => Closed01::new(sum / m as f32),
}
} else {
Closed01::zero()
}
}
pub fn score_average(&self) -> Closed01<f32> {
let n = self.min_nodes();
if n > 0 {
let items = self.current.as_vec();
let sum: f32 = items.iter().fold(0.0, |acc, &v| acc + v);
let len = items.len();
assert!(len > 0);
Closed01::new(sum / len as f32)
} else {
Closed01::zero()
}
}
}
pub fn similarity_max_degree<T: Graph>(a: &T, b: &T, num_iters: usize, eps: f32) -> Closed01<f32> {
let mut s = SimilarityMatrix::new(a, b, IgnoreNodeColors);
s.iterate(num_iters, eps);
s.score_optimal_sum_norm(None, ScoreNorm::MaxDegree)
}
pub fn similarity_min_degree<T: Graph>(a: &T, b: &T, num_iters: usize, eps: f32) -> Closed01<f32> {
let mut s = SimilarityMatrix::new(a, b, IgnoreNodeColors);
s.iterate(num_iters, eps);
s.score_optimal_sum_norm(None, ScoreNorm::MinDegree)
}
#[cfg(test)]
mod tests {
use super::graph::{Edge, EdgeList, Node, OwnedGraph, GraphBuilder};
use super::{ScoreNorm, SimilarityMatrix, IgnoreNodeColors};
fn edge(i: usize) -> Edge {
Edge::new_unweighted(i)
}
fn node(in_edges: Vec<Edge>, out_edges: Vec<Edge>) -> Node {
Node::new(EdgeList::new(in_edges), EdgeList::new(out_edges))
}
fn graph(nodes: Vec<Node>) -> OwnedGraph {
OwnedGraph::new(nodes)
}
#[test]
fn test_matrix() {
let a = graph(vec![node(vec![], vec![edge(1)]), node(vec![edge(0)], vec![])]);
let b = graph(vec![node(vec![edge(1)], vec![]), node(vec![], vec![edge(0)])]);
let mut s = SimilarityMatrix::new(&a, &b, IgnoreNodeColors);
s.iterate(100, 0.1);
println!("{:?}", s);
assert_eq!(2, s.num_iterations());
let mat = s.matrix();
assert_eq!(2, mat.nrows());
assert_eq!(2, mat.ncols());
assert_eq!(0.0, mat[(0, 0)]);
assert_eq!(1.0, mat[(0, 1)]);
assert_eq!(1.0, mat[(1, 0)]);
assert_eq!(0.0, mat[(1, 1)]);
}
#[test]
fn test_matrix_iter1() {
let a = graph(vec![
node(vec![edge(0), edge(0), edge(0)], vec![edge(0), edge(0), edge(0)]),
]);
let b = graph(vec![
node(vec![edge(0), edge(0), edge(0), edge(0), edge(0)], vec![edge(0), edge(0), edge(0), edge(0), edge(0)]),
]);
let mut s = SimilarityMatrix::new(&a, &b, IgnoreNodeColors);
s.iterate(1, 0.1);
assert_eq!(1, s.num_iterations());
let mat = s.matrix();
assert_eq!(3.0 / 5.0, mat[(0, 0)]);
}
#[test]
fn test_score() {
let a = graph(vec![node(vec![], vec![edge(1)]), node(vec![edge(0)], vec![])]);
let b = graph(vec![node(vec![edge(1)], vec![]), node(vec![], vec![edge(0)])]);
let mut s = SimilarityMatrix::new(&a, &b, IgnoreNodeColors);
s.iterate(100, 0.1);
assert_eq!(2, s.num_iterations());
assert_eq!(1.0,
s.score_optimal_sum_norm(None, ScoreNorm::MinDegree).get());
assert_eq!(1.0,
s.score_optimal_sum_norm(None, ScoreNorm::MaxDegree).get());
}
#[test]
fn test_score_with_graphbuilder() {
let mut a = GraphBuilder::new();
a.add_edge_unweighted(0, 1);
let mut b = GraphBuilder::new();
b.add_edge_unweighted(1, 0);
let ga = a.graph();
let gb = b.graph();
let mut s = SimilarityMatrix::new(&ga, &gb, IgnoreNodeColors);
s.iterate(100, 0.1);
assert_eq!(2, s.num_iterations());
assert_eq!(1.0,
s.score_optimal_sum_norm(None, ScoreNorm::MinDegree).get());
assert_eq!(1.0,
s.score_optimal_sum_norm(None, ScoreNorm::MaxDegree).get());
}
}