forked from Qiskit/rustworkx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcentrality.rs
825 lines (801 loc) · 31.6 KB
/
centrality.rs
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
#![allow(clippy::too_many_arguments)]
use std::convert::TryFrom;
use crate::digraph;
use crate::graph;
use crate::iterators::{CentralityMapping, EdgeCentralityMapping};
use crate::CostFn;
use crate::FailedToConverge;
use hashbrown::HashMap;
use petgraph::graph::NodeIndex;
use petgraph::visit::EdgeIndexable;
use petgraph::visit::EdgeRef;
use petgraph::visit::IntoNodeIdentifiers;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use rustworkx_core::centrality;
/// Compute the betweenness centrality of all nodes in a PyGraph.
///
/// Betweenness centrality of a node :math:`v` is the sum of the
/// fraction of all-pairs shortest paths that pass through :math`v`
///
/// .. math::
///
/// c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
///
/// where :math:`V` is the set of nodes, :math:`\sigma(s, t)` is the number of
/// shortest :math:`(s, t)` paths, and :math:`\sigma(s, t|v)` is the number of
/// those paths passing through some node :math:`v` other than :math:`s, t`.
/// If :math:`s = t`, :math:`\sigma(s, t) = 1`, and if :math:`v \in {s, t}`,
/// :math:`\sigma(s, t|v) = 0`
///
/// The algorithm used in this function is based on:
///
/// Ulrik Brandes, A Faster Algorithm for Betweenness Centrality.
/// Journal of Mathematical Sociology 25(2):163-177, 2001.
///
/// This function is multithreaded and will run in parallel if the number
/// of nodes in the graph is above the value of ``parallel_threshold`` (it
/// defaults to 50). If the function will be running in parallel the env var
/// ``RAYON_NUM_THREADS`` can be used to adjust how many threads will be used.
///
/// See Also
/// --------
/// graph_edge_betweenness_centrality
///
/// :param PyGraph graph: The input graph
/// :param bool normalized: Whether to normalize the betweenness scores by the number of distinct
/// paths between all pairs of nodes.
/// :param bool endpoints: Whether to include the endpoints of paths in pathlengths used to
/// compute the betweenness.
/// :param int parallel_threshold: The number of nodes to calculate the
/// the betweenness centrality in parallel at if the number of nodes in
/// the graph is less than this value it will run in a single thread. The
/// default value is 50
///
/// :returns: a read-only dict-like object whose keys are the node indices and values are the
/// betweenness score for each node.
/// :rtype: CentralityMapping
#[pyfunction(
signature = (
graph,
normalized=true,
endpoints=false,
parallel_threshold=50
)
)]
#[pyo3(text_signature = "(graph, /, normalized=True, endpoints=False, parallel_threshold=50)")]
pub fn graph_betweenness_centrality(
graph: &graph::PyGraph,
normalized: bool,
endpoints: bool,
parallel_threshold: usize,
) -> CentralityMapping {
let betweenness =
centrality::betweenness_centrality(&graph.graph, endpoints, normalized, parallel_threshold);
CentralityMapping {
centralities: betweenness
.into_iter()
.enumerate()
.filter_map(|(i, v)| v.map(|x| (i, x)))
.collect(),
}
}
/// Compute the betweenness centrality of all nodes in a PyDiGraph.
///
/// Betweenness centrality of a node :math:`v` is the sum of the
/// fraction of all-pairs shortest paths that pass through :math`v`
///
/// .. math::
///
/// c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
///
/// where :math:`V` is the set of nodes, :math:`\sigma(s, t)` is the number of
/// shortest :math`(s, t)` paths, and :math:`\sigma(s, t|v)` is the number of
/// those paths passing through some node :math:`v` other than :math:`s, t`.
/// If :math:`s = t`, :math:`\sigma(s, t) = 1`, and if :math:`v \in {s, t}`,
/// :math:`\sigma(s, t|v) = 0`
///
/// The algorithm used in this function is based on:
///
/// Ulrik Brandes, A Faster Algorithm for Betweenness Centrality.
/// Journal of Mathematical Sociology 25(2):163-177, 2001.
///
/// This function is multithreaded and will run in parallel if the number
/// of nodes in the graph is above the value of ``parallel_threshold`` (it
/// defaults to 50). If the function will be running in parallel the env var
/// ``RAYON_NUM_THREADS`` can be used to adjust how many threads will be used.
///
/// See Also
/// --------
/// digraph_edge_betweenness_centrality
///
/// :param PyDiGraph graph: The input graph
/// :param bool normalized: Whether to normalize the betweenness scores by the number of distinct
/// paths between all pairs of nodes.
/// :param bool endpoints: Whether to include the endpoints of paths in pathlengths used to
/// compute the betweenness.
/// :param int parallel_threshold: The number of nodes to calculate the
/// the betweenness centrality in parallel at if the number of nodes in
/// the graph is less than this value it will run in a single thread. The
/// default value is 50
///
/// :returns: a read-only dict-like object whose keys are the node indices and values are the
/// betweenness score for each node.
/// :rtype: CentralityMapping
#[pyfunction(
signature = (
graph,
normalized=true,
endpoints=false,
parallel_threshold=50
)
)]
#[pyo3(text_signature = "(graph, /, normalized=True, endpoints=False, parallel_threshold=50)")]
pub fn digraph_betweenness_centrality(
graph: &digraph::PyDiGraph,
normalized: bool,
endpoints: bool,
parallel_threshold: usize,
) -> CentralityMapping {
let betweenness =
centrality::betweenness_centrality(&graph.graph, endpoints, normalized, parallel_threshold);
CentralityMapping {
centralities: betweenness
.into_iter()
.enumerate()
.filter_map(|(i, v)| v.map(|x| (i, x)))
.collect(),
}
}
/// Compute the closeness centrality of each node in a :class:`~.PyGraph` object.
///
/// The closeness centrality of a node :math:`u` is defined as the
/// reciprocal of the average shortest path distance to :math:`u` over all
/// :math:`n-1` reachable nodes in the graph. In it's general form this can
/// be expressed as:
///
/// .. math::
///
/// C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
///
/// where:
///
/// * :math:`d(v, u)` - the shortest-path distance between :math:`v` and
/// :math:`u`
/// * :math:`n` - the number of nodes that can reach :math:`u`.
///
/// In the case of a graphs with more than one connected component there is
/// an alternative improved formula that calculates the closeness centrality
/// as "a ratio of the fraction of actors in the group who are reachable, to
/// the average distance" [WF]_. This can be expressed as
///
/// .. math::
///
/// C_{WF}(u) = \frac{n-1}{N-1} \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
///
/// where :math:`N` is the number of nodes in the graph. This alternative
/// formula can be used with the ``wf_improved`` argument.
///
/// :param PyGraph graph: The input graph. Can either be a
/// :class:`~retworkx.PyGraph` or :class:`~retworkx.PyDiGraph`.
/// :param bool wf_improved: This is optional; the default is True. If True,
/// scale by the fraction of nodes reachable.
///
/// :returns: A dictionary mapping each node index to its closeness centrality.
/// :rtype: CentralityMapping
#[pyfunction(signature = (graph, wf_improved=true))]
pub fn graph_closeness_centrality(graph: &graph::PyGraph, wf_improved: bool) -> CentralityMapping {
let closeness = centrality::closeness_centrality(&graph.graph, wf_improved);
CentralityMapping {
centralities: closeness
.into_iter()
.enumerate()
.filter_map(|(i, v)| v.map(|x| (i, x)))
.collect(),
}
}
/// Compute the closeness centrality of each node in a :class:`~.PyDiGraph` object.
///
/// The closeness centrality of a node :math:`u` is defined as the
/// reciprocal of the average shortest path distance to :math:`u` over all
/// :math:`n-1` reachable nodes in the graph. In it's general form this can
/// be expressed as:
///
/// .. math::
///
/// C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
///
/// where:
///
/// * :math:`d(v, u)` - the shortest-path distance between :math:`v` and
/// :math:`u`
/// * :math:`n` - the number of nodes that can reach :math:`u`.
///
/// In the case of a graphs with more than one connected component there is
/// an alternative improved formula that calculates the closeness centrality
/// as "a ratio of the fraction of actors in the group who are reachable, to
/// the average distance" [WF]_. This can be expressed as
///
/// .. math::
///
/// C_{WF}(u) = \frac{n-1}{N-1} \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
///
/// where :math:`N` is the number of nodes in the graph. This alternative
/// formula can be used with the ``wf_improved`` argument.
///
/// :param PyDiGraph graph: The input graph. Can either be a
/// :class:`~retworkx.PyGraph` or :class:`~retworkx.PyDiGraph`.
/// :param bool wf_improved: This is optional; the default is True. If True,
/// scale by the fraction of nodes reachable.
///
/// :returns: A dictionary mapping each node index to its closeness centrality.
/// :rtype: CentralityMapping
#[pyfunction(signature = (graph, wf_improved=true))]
pub fn digraph_closeness_centrality(
graph: &digraph::PyDiGraph,
wf_improved: bool,
) -> CentralityMapping {
let closeness = centrality::closeness_centrality(&graph.graph, wf_improved);
CentralityMapping {
centralities: closeness
.into_iter()
.enumerate()
.filter_map(|(i, v)| v.map(|x| (i, x)))
.collect(),
}
}
/// Compute the edge betweenness centrality of all edges in a :class:`~PyGraph`.
///
/// Edge betweenness centrality of an edge :math:`e` is the sum of the
/// fraction of all-pairs shortest paths that pass through :math`e`
///
/// .. math::
///
/// c_B(e) =\sum_{s,t \in V} \frac{\sigma(s, t|e)}{\sigma(s, t)}
///
/// where :math:`V` is the set of nodes, :math:`\sigma(s, t)` is the
/// number of shortest :math:`(s, t)`-paths, and :math:`\sigma(s, t|e)` is
/// the number of those paths passing through edge :math:`e`.
///
/// The above definition and the algorithm used in this function is based on:
///
/// Ulrik Brandes, On Variants of Shortest-Path Betweenness Centrality
/// and their Generic Computation. Social Networks 30(2):136-145, 2008.
///
/// This function is multithreaded and will run in parallel if the number
/// of nodes in the graph is above the value of ``parallel_threshold`` (it
/// defaults to 50). If the function will be running in parallel the env var
/// ``RAYON_NUM_THREADS`` can be used to adjust how many threads will be used.
///
/// See Also
/// --------
/// graph_betweenness_centrality
///
/// :param PyGraph graph: The input graph
/// :param bool normalized: Whether to normalize the betweenness scores by the number of distinct
/// paths between all pairs of nodes.
/// :param int parallel_threshold: The number of nodes to calculate the
/// the betweenness centrality in parallel at if the number of nodes in
/// the graph is less than this value it will run in a single thread. The
/// default value is 50
///
/// :returns: a read-only dict-like object whose keys are the edge indices and values are the
/// betweenness score for each edge.
/// :rtype: EdgeCentralityMapping
#[pyfunction(
signature = (
graph,
normalized=true,
parallel_threshold=50
)
)]
#[pyo3(text_signature = "(graph, /, normalized=True, parallel_threshold=50)")]
pub fn graph_edge_betweenness_centrality(
graph: &graph::PyGraph,
normalized: bool,
parallel_threshold: usize,
) -> PyResult<EdgeCentralityMapping> {
let betweenness =
centrality::edge_betweenness_centrality(&graph.graph, normalized, parallel_threshold);
Ok(EdgeCentralityMapping {
centralities: betweenness
.into_iter()
.enumerate()
.filter_map(|(i, v)| v.map(|x| (i, x)))
.collect(),
})
}
/// Compute the edge betweenness centrality of all edges in a :class:`~PyDiGraph`.
///
/// Edge betweenness centrality of an edge :math:`e` is the sum of the
/// fraction of all-pairs shortest paths that pass through :math`e`
///
/// .. math::
///
/// c_B(e) =\sum_{s,t \in V} \frac{\sigma(s, t|e)}{\sigma(s, t)}
///
/// where :math:`V` is the set of nodes, :math:`\sigma(s, t)` is the
/// number of shortest :math:`(s, t)`-paths, and :math:`\sigma(s, t|e)` is
/// the number of those paths passing through edge :math:`e`.
///
/// The above definition and the algorithm used in this function is based on:
///
/// Ulrik Brandes, On Variants of Shortest-Path Betweenness Centrality
/// and their Generic Computation. Social Networks 30(2):136-145, 2008.
///
/// This function is multithreaded and will run in parallel if the number
/// of nodes in the graph is above the value of ``parallel_threshold`` (it
/// defaults to 50). If the function will be running in parallel the env var
/// ``RAYON_NUM_THREADS`` can be used to adjust how many threads will be used.
///
/// See Also
/// --------
/// digraph_betweenness_centrality
///
/// :param PyGraph graph: The input graph
/// :param bool normalized: Whether to normalize the betweenness scores by the number of distinct
/// paths between all pairs of nodes.
/// :param int parallel_threshold: The number of nodes to calculate the
/// the betweenness centrality in parallel at if the number of nodes in
/// the graph is less than this value it will run in a single thread. The
/// default value is 50
///
/// :returns: a read-only dict-like object whose keys are edges and values are the
/// betweenness score for each node.
/// :rtype: EdgeCentralityMapping
#[pyfunction(
signature = (
graph,
normalized=true,
parallel_threshold=50
)
)]
#[pyo3(text_signature = "(graph, /, normalized=True, parallel_threshold=50)")]
pub fn digraph_edge_betweenness_centrality(
graph: &digraph::PyDiGraph,
normalized: bool,
parallel_threshold: usize,
) -> PyResult<EdgeCentralityMapping> {
let betweenness =
centrality::edge_betweenness_centrality(&graph.graph, normalized, parallel_threshold);
Ok(EdgeCentralityMapping {
centralities: betweenness
.into_iter()
.enumerate()
.filter_map(|(i, v)| v.map(|x| (i, x)))
.collect(),
})
}
/// Compute the eigenvector centrality of a :class:`~PyGraph`.
///
/// For details on the eigenvector centrality refer to:
///
/// Phillip Bonacich. “Power and Centrality: A Family of Measures.”
/// American Journal of Sociology 92(5):1170–1182, 1986
/// <https://doi.org/10.1086/228631>
///
/// This function uses a power iteration method to compute the eigenvector
/// and convergence is not guaranteed. The function will stop when `max_iter`
/// iterations is reached or when the computed vector between two iterations
/// is smaller than the error tolerance multiplied by the number of nodes.
/// The implementation of this algorithm is based on the NetworkX
/// `eigenvector_centrality() <https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.centrality.eigenvector_centrality.html>`__
/// function.
///
/// In the case of multigraphs the weights of any parallel edges will be
/// summed when computing the eigenvector centrality.
///
/// :param PyGraph graph: The graph object to run the algorithm on
/// :param weight_fn: An optional input callable that will be passed the edge's
/// payload object and is expected to return a `float` weight for that edge.
/// If this is not specified ``default_weight`` will be used as the weight
/// for every edge in ``graph``
/// :param float default_weight: If ``weight_fn`` is not set the default weight
/// value to use for the weight of all edges
/// :param int max_iter: The maximum number of iterations in the power method. If
/// not specified a default value of 100 is used.
/// :param float tol: The error tolerance used when checking for convergence in the
/// power method. If this is not specified default value of 1e-6 is used.
///
/// :returns: a read-only dict-like object whose keys are the node indices and values are the
/// centrality score for that node.
/// :rtype: CentralityMapping
#[pyfunction(
signature = (
graph,
weight_fn=None,
default_weight=1.0,
max_iter=100,
tol=1e-6
)
)]
#[pyo3(text_signature = "(graph, /, weight_fn=None, default_weight=1.0, max_iter=100, tol=1e-6)")]
pub fn graph_eigenvector_centrality(
py: Python,
graph: &graph::PyGraph,
weight_fn: Option<PyObject>,
default_weight: f64,
max_iter: usize,
tol: f64,
) -> PyResult<CentralityMapping> {
let mut edge_weights = vec![default_weight; graph.graph.edge_bound()];
if weight_fn.is_some() {
let cost_fn = CostFn::try_from((weight_fn, default_weight))?;
for edge in graph.graph.edge_indices() {
edge_weights[edge.index()] =
cost_fn.call(py, graph.graph.edge_weight(edge).unwrap())?;
}
}
let ev_centrality = centrality::eigenvector_centrality(
&graph.graph,
|e| -> PyResult<f64> { Ok(edge_weights[e.id().index()]) },
Some(max_iter),
Some(tol),
)?;
match ev_centrality {
Some(centrality) => Ok(CentralityMapping {
centralities: centrality
.iter()
.enumerate()
.filter_map(|(k, v)| {
if graph.graph.contains_node(NodeIndex::new(k)) {
Some((k, *v))
} else {
None
}
})
.collect(),
}),
None => Err(FailedToConverge::new_err(format!(
"Function failed to converge on a solution in {} iterations",
max_iter
))),
}
}
/// Compute the eigenvector centrality of a :class:`~PyDiGraph`.
///
/// For details on the eigenvector centrality refer to:
///
/// Phillip Bonacich. “Power and Centrality: A Family of Measures.”
/// American Journal of Sociology 92(5):1170–1182, 1986
/// <https://doi.org/10.1086/228631>
///
/// This function uses a power iteration method to compute the eigenvector
/// and convergence is not guaranteed. The function will stop when `max_iter`
/// iterations is reached or when the computed vector between two iterations
/// is smaller than the error tolerance multiplied by the number of nodes.
/// The implementation of this algorithm is based on the NetworkX
/// `eigenvector_centrality() <https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.centrality.eigenvector_centrality.html>`__
/// function.
///
/// In the case of multigraphs the weights of any parallel edges will be
/// summed when computing the eigenvector centrality.
///
/// :param PyDiGraph graph: The graph object to run the algorithm on
/// :param weight_fn: An optional input callable that will be passed the edge's
/// payload object and is expected to return a `float` weight for that edge.
/// If this is not specified ``default_weight`` will be used as the weight
/// for every edge in ``graph``
/// :param float default_weight: If ``weight_fn`` is not set the default weight
/// value to use for the weight of all edges
/// :param int max_iter: The maximum number of iterations in the power method. If
/// not specified a default value of 100 is used.
/// :param float tol: The error tolerance used when checking for convergence in the
/// power method. If this is not specified default value of 1e-6 is used.
///
/// :returns: a read-only dict-like object whose keys are the node indices and values are the
/// centrality score for that node.
/// :rtype: CentralityMapping
#[pyfunction(
signature = (
graph,
weight_fn=None,
default_weight=1.0,
max_iter=100,
tol=1e-6
)
)]
#[pyo3(text_signature = "(graph, /, weight_fn=None, default_weight=1.0, max_iter=100, tol=1e-6)")]
pub fn digraph_eigenvector_centrality(
py: Python,
graph: &digraph::PyDiGraph,
weight_fn: Option<PyObject>,
default_weight: f64,
max_iter: usize,
tol: f64,
) -> PyResult<CentralityMapping> {
let mut edge_weights = vec![default_weight; graph.graph.edge_bound()];
if weight_fn.is_some() {
let cost_fn = CostFn::try_from((weight_fn, default_weight))?;
for edge in graph.graph.edge_indices() {
edge_weights[edge.index()] =
cost_fn.call(py, graph.graph.edge_weight(edge).unwrap())?;
}
}
let ev_centrality = centrality::eigenvector_centrality(
&graph.graph,
|e| -> PyResult<f64> { Ok(edge_weights[e.id().index()]) },
Some(max_iter),
Some(tol),
)?;
match ev_centrality {
Some(centrality) => Ok(CentralityMapping {
centralities: centrality
.iter()
.enumerate()
.filter_map(|(k, v)| {
if graph.graph.contains_node(NodeIndex::new(k)) {
Some((k, *v))
} else {
None
}
})
.collect(),
}),
None => Err(FailedToConverge::new_err(format!(
"Function failed to converge on a solution in {} iterations",
max_iter
))),
}
}
/// Compute the Katz centrality of a :class:`~PyGraph`.
///
/// For details on the Katz centrality refer to:
///
/// Leo Katz. “A New Status Index Derived from Sociometric Index.”
/// Psychometrika 18(1):39–43, 1953
/// <https://link.springer.com/content/pdf/10.1007/BF02289026.pdf>
///
/// This function uses a power iteration method to compute the eigenvector
/// and convergence is not guaranteed. The function will stop when `max_iter`
/// iterations is reached or when the computed vector between two iterations
/// is smaller than the error tolerance multiplied by the number of nodes.
/// The implementation of this algorithm is based on the NetworkX
/// `katz_centrality() <https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.centrality.katz_centrality.html>`__
/// function.
///
/// In the case of multigraphs the weights of any parallel edges will be
/// summed when computing the Katz centrality.
///
/// :param PyGraph graph: The graph object to run the algorithm on
/// :param float alpha: Attenuation factor. If this is not specified default value of 0.1 is used.
/// :param float | dict beta: Immediate neighbourhood weights. If a float is provided, the neighbourhood
/// weight is used for all nodes. If a dictionary is provided, it must contain all node indices.
/// If beta is not specified, a default value of 1.0 is used.
/// :param weight_fn: An optional input callable that will be passed the edge's
/// payload object and is expected to return a `float` weight for that edge.
/// If this is not specified ``default_weight`` will be used as the weight
/// for every edge in ``graph``
/// :param float default_weight: If ``weight_fn`` is not set the default weight
/// value to use for the weight of all edges
/// :param int max_iter: The maximum number of iterations in the power method. If
/// not specified a default value of 1000 is used.
/// :param float tol: The error tolerance used when checking for convergence in the
/// power method. If this is not specified default value of 1e-6 is used.
///
/// :returns: a read-only dict-like object whose keys are the node indices and values are the
/// centrality score for that node.
/// :rtype: CentralityMapping
#[pyfunction(
signature = (
graph,
alpha=0.1,
beta=None,
weight_fn=None,
default_weight=1.0,
max_iter=1000,
tol=1e-6
)
)]
#[pyo3(
text_signature = "(graph, /, alpha=0.1, beta=None, weight_fn=None, default_weight=1.0, max_iter=1000, tol=1e-6)"
)]
pub fn graph_katz_centrality(
py: Python,
graph: &graph::PyGraph,
alpha: f64,
beta: Option<PyObject>,
weight_fn: Option<PyObject>,
default_weight: f64,
max_iter: usize,
tol: f64,
) -> PyResult<CentralityMapping> {
let mut edge_weights = vec![default_weight; graph.graph.edge_bound()];
if weight_fn.is_some() {
let cost_fn = CostFn::try_from((weight_fn, default_weight))?;
for edge in graph.graph.edge_indices() {
edge_weights[edge.index()] =
cost_fn.call(py, graph.graph.edge_weight(edge).unwrap())?;
}
}
let mut beta_map: HashMap<usize, f64> = HashMap::new();
if let Some(beta) = beta {
match beta.extract::<f64>(py) {
Ok(beta_scalar) => {
// User provided a scalar, populate beta_map with the value
for node_index in graph.graph.node_identifiers() {
beta_map.insert(node_index.index(), beta_scalar);
}
}
Err(_) => {
beta_map = beta.extract::<HashMap<usize, f64>>(py)?;
for node_index in graph.graph.node_identifiers() {
if !beta_map.contains_key(&node_index.index()) {
return Err(PyValueError::new_err(
"Beta does not contain all node indices",
));
}
}
}
}
} else {
// Populate with 1.0
for node_index in graph.graph.node_identifiers() {
beta_map.insert(node_index.index(), 1.0);
}
}
let ev_centrality = centrality::katz_centrality(
&graph.graph,
|e| -> PyResult<f64> { Ok(edge_weights[e.id().index()]) },
Some(alpha),
Some(beta_map),
None,
Some(max_iter),
Some(tol),
)?;
match ev_centrality {
Some(centrality) => Ok(CentralityMapping {
centralities: centrality
.iter()
.enumerate()
.filter_map(|(k, v)| {
if graph.graph.contains_node(NodeIndex::new(k)) {
Some((k, *v))
} else {
None
}
})
.collect(),
}),
None => Err(FailedToConverge::new_err(format!(
"Function failed to converge on a solution in {} iterations",
max_iter
))),
}
}
/// Compute the Katz centrality of a :class:`~PyDiGraph`.
///
/// For details on the Katz centrality refer to:
///
/// Leo Katz. “A New Status Index Derived from Sociometric Index.”
/// Psychometrika 18(1):39–43, 1953
/// <https://link.springer.com/content/pdf/10.1007/BF02289026.pdf>
///
/// This function uses a power iteration method to compute the eigenvector
/// and convergence is not guaranteed. The function will stop when `max_iter`
/// iterations is reached or when the computed vector between two iterations
/// is smaller than the error tolerance multiplied by the number of nodes.
/// The implementation of this algorithm is based on the NetworkX
/// `katz_centrality() <https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.centrality.katz_centrality.html>`__
/// function.
///
/// In the case of multigraphs the weights of any parallel edges will be
/// summed when computing the Katz centrality.
///
/// :param PyDiGraph graph: The graph object to run the algorithm on
/// :param float alpha: Attenuation factor. If this is not specified default value of 0.1 is used.
/// :param float | dict beta: Immediate neighbourhood weights. If a float is provided, the neighbourhood
/// weight is used for all nodes. If a dictionary is provided, it must contain all node indices.
/// If beta is not specified, a default value of 1.0 is used.
/// :param weight_fn: An optional input callable that will be passed the edge's
/// payload object and is expected to return a `float` weight for that edge.
/// If this is not specified ``default_weight`` will be used as the weight
/// for every edge in ``graph``
/// :param float default_weight: If ``weight_fn`` is not set the default weight
/// value to use for the weight of all edges
/// :param int max_iter: The maximum number of iterations in the power method. If
/// not specified a default value of 1000 is used.
/// :param float tol: The error tolerance used when checking for convergence in the
/// power method. If this is not specified default value of 1e-6 is used.
///
/// :returns: a read-only dict-like object whose keys are the node indices and values are the
/// centrality score for that node.
/// :rtype: CentralityMapping
#[pyfunction(
signature = (
graph,
alpha=0.1,
beta=None,
weight_fn=None,
default_weight=1.0,
max_iter=1000,
tol=1e-6
)
)]
#[pyo3(
text_signature = "(graph, /, alpha=0.1, beta=None, weight_fn=None, default_weight=1.0, max_iter=1000, tol=1e-6)"
)]
pub fn digraph_katz_centrality(
py: Python,
graph: &digraph::PyDiGraph,
alpha: f64,
beta: Option<PyObject>,
weight_fn: Option<PyObject>,
default_weight: f64,
max_iter: usize,
tol: f64,
) -> PyResult<CentralityMapping> {
let mut edge_weights = vec![default_weight; graph.graph.edge_bound()];
if weight_fn.is_some() {
let cost_fn = CostFn::try_from((weight_fn, default_weight))?;
for edge in graph.graph.edge_indices() {
edge_weights[edge.index()] =
cost_fn.call(py, graph.graph.edge_weight(edge).unwrap())?;
}
}
let mut beta_map: HashMap<usize, f64> = HashMap::new();
if let Some(beta) = beta {
match beta.extract::<f64>(py) {
Ok(beta_scalar) => {
// User provided a scalar, populate beta_map with the value
for node_index in graph.graph.node_identifiers() {
beta_map.insert(node_index.index(), beta_scalar);
}
}
Err(_) => {
beta_map = beta.extract::<HashMap<usize, f64>>(py)?;
for node_index in graph.graph.node_identifiers() {
if !beta_map.contains_key(&node_index.index()) {
return Err(PyValueError::new_err(
"Beta does not contain all node indices",
));
}
}
}
}
} else {
// Populate with 1.0
for node_index in graph.graph.node_identifiers() {
beta_map.insert(node_index.index(), 1.0);
}
}
let ev_centrality = centrality::katz_centrality(
&graph.graph,
|e| -> PyResult<f64> { Ok(edge_weights[e.id().index()]) },
Some(alpha),
Some(beta_map),
None,
Some(max_iter),
Some(tol),
)?;
match ev_centrality {
Some(centrality) => Ok(CentralityMapping {
centralities: centrality
.iter()
.enumerate()
.filter_map(|(k, v)| {
if graph.graph.contains_node(NodeIndex::new(k)) {
Some((k, *v))
} else {
None
}
})
.collect(),
}),
None => Err(FailedToConverge::new_err(format!(
"Function failed to converge on a solution in {} iterations",
max_iter
))),
}
}