hyperbolic_graph_generator 0.1.3

Create different types of hyperbolic graphs.
Documentation
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
/*
 * Hyperbolic Graph Generator
 *
 * Chiara Orsini, CAIDA, UC San Diego
 * chiara@caida.org
 *
 * Copyright (C) 2014 The Regents of the University of California.
 *
 * This file is part of the Hyperbolic Graph Generator.
 *
 * The Hyperbolic Graph Generator is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of the
 * License, or  (at your option) any later version.
 *
 * The Hyperbolic Graph Generator is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the Hyperbolic Graph Generator.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

use std::collections::HashMap;
use std::mem;

use crate::hg_debug::*;
use crate::hg_utils::*;
use crate::hg_formats::*;
use crate::hg_math::*;


/* Various error messages */
const INVALID_K_BAR_MSG : &str = "Average degree must be greater than 0 and less than n-1.";
const INVALID_TEMPERATURE : &str = "Temperature must be positive (t >= 0).";
const INVALID_GAMMA : &str = "Gamma must be greater or equal 2 (gamma >= 2).";
const INVALID_GAMMA_WITH_ZETA : &str = "Zeta or eta make sense only at finite values of gamma.";


/* ================= graph construction utilities ================= */


/* RPrecomputedsinhcosh is a structure that contains the precomputed values
 * of sinh(zeta * r) and cosh(zeta * r) for each value of r. It is a map:
 *
 *         r => (sinh(zeta*r), cosh(zeta*r))
 *
 * this structure does not need to be exported outside this coding unit
 */

type RPrecomputedsinhcosh = HashMap<u64, (f64, f64)>;

// cast to usize to allow f64 as hash map key
fn f2u(f: f64) -> u64 {
  unsafe { mem::transmute(f) }
}

fn hg_assign_coordinates(
        nodes: &mut Vec<HgCoordinateType>,
        params: &HgParametersType,
        in_par: &HgAlgorithmParametersType,
        mut r_psc: Option<&mut RPrecomputedsinhcosh>,
        rnd_01: &mut FnMut() -> f64) {
  hg_debug!("Assigning coordinates");

  match params.gtype {
    HgGraphType::HyperbolicRgg
    | HgGraphType::HyperbolicStandard
    | HgGraphType::SoftConfigurationModel => {
      for _ in 0..params.expected_n {
        let zeta = params.zeta_eta;
        let r = hg_quasi_uniform_radial_coordinate(in_par.radius, in_par.alpha, rnd_01);
        if let Some(ref mut r_psc) = r_psc {
          r_psc.insert(f2u(r), ((zeta * r).sinh(), (zeta * r).cosh()));
        }
        nodes.push(HgCoordinateType {
          r: r,
          theta: hg_uniform_angular_coordinate(rnd_01)
        });
      }
    },
    HgGraphType::AngularRgg
    | HgGraphType::SoftRgg
    | HgGraphType::ErdosRenyi => {
      for _ in 0..params.expected_n {
        nodes.push(HgCoordinateType {
          r: in_par.radius, // HG_INF_RADIUS,
          theta: hg_uniform_angular_coordinate(rnd_01)
        });
      }
    }
  }
}

/* ================= useful mathematical functions  ================= */


fn hg_get_rr_from_numerical_integration(
        params: &HgParametersType,
        p: &HgAlgorithmParametersType) -> f64 {
  return hg_get_rr(params, p);
}

fn hg_get_lambda_from_gauss_hypergeometric_function(
        params: &HgParametersType,
        p: &HgAlgorithmParametersType) -> f64 {
  return hg_get_lambda(params, p);
}


/* ================= single model graph generators  ================= */


fn hg_hyperbolic_distance_hyperbolic_rgg_standard_(
        zeta_eta: f64,
        node1: &HgCoordinateType,
        node2: &HgCoordinateType,
        r_psc: Option<&RPrecomputedsinhcosh>) -> f64 {
  // check if it is the same node
  if (node1.r == node2.r) && (node1.theta == node2.theta) {
    return 0.0;
  }

  // if the nodes have the same angular coordinates
  // then we return the euclidean distance
  if node1.theta == node2.theta {
    return (node1.r - node2.r).abs();
  }

  // equation 13
  let zeta = zeta_eta;
  let delta_theta = HG_PI - (HG_PI - (node1.theta - node2.theta).abs()).abs();
  let (part1, part2) = if let Some(r_psc) = r_psc {
    let n1 = r_psc.get(&f2u(node1.r)).unwrap();
    let n2 = r_psc.get(&f2u(node2.r)).unwrap();

    (n1.1 * n2.1,
     n1.0 * n2.0 * delta_theta.cos())
  } else {
    ((zeta * node1.r).cosh() * (zeta * node2.r).cosh(),
     (zeta * node1.r).sinh() * (zeta * node2.r).sinh() * delta_theta.cos())
  };
  return (part1 - part2).acosh() / zeta;
}

pub fn hg_hyperbolic_distance_hyperbolic_rgg_standard(
        zeta_eta: f64,
        node1: &HgCoordinateType,
        node2: &HgCoordinateType) -> f64 {
  hg_hyperbolic_distance_hyperbolic_rgg_standard_(zeta_eta, node1, node2, None)
}

fn hg_connection_probability_hyperbolic_rgg(
          params: &HgParametersType,
          p: &HgAlgorithmParametersType,
          node1: &HgCoordinateType,
          node2: &HgCoordinateType,
          r_psc: Option<&RPrecomputedsinhcosh>) -> f64 {
  // equation 32: Heaviside function
  if hg_hyperbolic_distance_hyperbolic_rgg_standard_(params.zeta_eta, node1, node2, r_psc) <= p.radius {
    return 1.0;
  } else {
    return 0.0;
  }
}

pub fn hg_hyperbolic_rgg(
        n: usize,
        rnd_01: &mut FnMut() -> f64,
        k_bar: f64,
        exp_gamma: f64,
        zeta: f64) -> Result<Graph, &'static str>{

  if (k_bar < 1.0) || (k_bar > (n - 1) as f64) {
    return Err(INVALID_K_BAR_MSG);
  }

  if exp_gamma < 2.0 {
    return Err(INVALID_GAMMA);
  }

  if exp_gamma >= HG_INF_GAMMA {
    return Err(INVALID_GAMMA_WITH_ZETA);
  }

  let mut nodes = Vec::<HgCoordinateType>::with_capacity(n);
  let mut links = Vec::<HgConnectionType>::with_capacity(n);

  hg_debug!("-> Hyperbolic Random Geometric Graph");

  let params = HgParametersType::new(n, k_bar,
    exp_gamma, 0.0 /* t = 0 */,
    zeta, HgGraphType::HyperbolicRgg);

  // computing internal parameters
  hg_debug!("Internal parameters computation");
  let mut p = HgAlgorithmParametersType::new();
  p.alpha = 0.5 * zeta * (exp_gamma - 1.0);
  p.radius = hg_get_rr_from_numerical_integration(&params, &p);

  let mut r_psc = RPrecomputedsinhcosh::new();
  hg_assign_coordinates(&mut nodes, &params, &p, Some(&mut r_psc), rnd_01);

  hg_debug!("Internal parameters:");
  hg_debug!("\tAlpha: {}", p.alpha);
  hg_debug!("\tRadius: {}", p.radius);

  hg_debug!("Creating links");

  for id in 0..params.expected_n {
    for other_id in (id + 1)..params.expected_n {
      if rnd_01() < hg_connection_probability_hyperbolic_rgg(&params, &p, &nodes[id], &nodes[other_id], Some(&r_psc)) {
        links.push(HgConnectionType {id: id, other_id: other_id});
      }
    }
  }

  Ok((nodes, links))
}

fn hg_connection_probability_hyperbolic_standard(
        params: &HgParametersType,
        p: &HgAlgorithmParametersType,
        node1: &HgCoordinateType,
        node2: &HgCoordinateType,
        r_psc: Option<&RPrecomputedsinhcosh>) -> f64 {
  // check if it is the same node
  if (node1.r == node2.r) && (node1.theta == node2.theta) {
    return 0.0;
  }

  // equation 12: Fermi-Dirac function
  let zeta = params.zeta_eta;
  let t =  params.temperature;
  let x = hg_hyperbolic_distance_hyperbolic_rgg_standard_(params.zeta_eta, node1, node2, r_psc);
  let exponent = (1.0 / t) * (zeta / 2.0)  * (x - p.radius);

  return 1.0 / (exponent.exp() + 1.0);
}

pub fn hg_hyperbolic_standard(
        n: usize,
        rnd_01: &mut FnMut() -> f64,
        k_bar: f64,
        exp_gamma: f64,
        temperature: f64,
        zeta: f64) -> Result<Graph, &'static str>{

  if (k_bar < 1.0) || (k_bar > (n - 1) as f64) {
    return Err(INVALID_K_BAR_MSG);
  }

  if exp_gamma < 2.0 {
    return Err(INVALID_GAMMA);
  }

  if exp_gamma >= HG_INF_GAMMA {
    return Err(INVALID_GAMMA_WITH_ZETA);
  }

  if temperature < 0.0 {
    return Err(INVALID_TEMPERATURE);
  }

  let mut nodes = Vec::<HgCoordinateType>::with_capacity(n);
  let mut links = Vec::<HgConnectionType>::with_capacity(n);

  hg_debug!("-> Hyperbolic Standard Graph\n");

  let params = HgParametersType::new(n, k_bar, exp_gamma, temperature,
    zeta, HgGraphType::HyperbolicStandard);

  // computing internal parameters
  hg_debug!("Internal parameters computation");
  let mut p = HgAlgorithmParametersType::new();

  // alpha calculation. different for cold and hot regimes
  p.alpha = if temperature <= 1.0 {
    0.5 * zeta * (exp_gamma - 1.0)
  } else {
    0.5 * (zeta / temperature) * (exp_gamma - 1.0)
  };

  p.radius = hg_get_rr_from_numerical_integration(&params, &p);

  hg_debug!("Internal parameters:");
  hg_debug!("\tAlpha: {}", p.alpha);
  hg_debug!("\tRadius: {}", p.radius);

  let mut r_psc = RPrecomputedsinhcosh::new();
  hg_assign_coordinates(&mut nodes, &params, &p, Some(&mut r_psc), rnd_01);

  hg_debug!("Creating links");
  for id in 0..params.expected_n {
    for other_id in (id + 1)..params.expected_n {
      if rnd_01() < hg_connection_probability_hyperbolic_standard(&params, &p, &nodes[id], &nodes[other_id], Some(&r_psc)) {
        links.push(HgConnectionType {id: id, other_id: other_id});
      }
    }
  }

  Ok((nodes, links))
}

pub fn hg_hyperbolic_distance_scm(
        node1: &HgCoordinateType,
        node2: &HgCoordinateType) -> f64 {
  // check if it is the same node
  if (node1.r == node2.r) && (node1.theta == node2.theta) {
    return 0.0;
  }
  // curvature is infinite, so 1/zeta goes to zero
  return node1.r + node2.r;
}

fn hg_connection_probability_scm(
        p: &HgAlgorithmParametersType,
        node1: &HgCoordinateType,
        node2: &HgCoordinateType) -> f64 {
  // equation (39)
  let x = hg_hyperbolic_distance_scm(node1, node2);
  let exponent = (p.eta / 2.0) * (x - p.radius);
  return 1.0 / (exponent.exp() + 1.0);
}

pub fn hg_soft_configuration_model(
        n: usize,
        rnd_01: &mut FnMut() -> f64,
        k_bar: f64,
        exp_gamma: f64,
        eta: f64) -> Result<Graph, &'static str>{

  if (k_bar < 1.0) || (k_bar > (n - 1) as f64) {
    return Err(INVALID_K_BAR_MSG);
  }

  if exp_gamma < 2.0 {
    return Err(INVALID_GAMMA);
  }

  let mut nodes = Vec::<HgCoordinateType>::with_capacity(n);
  let mut links = Vec::<HgConnectionType>::with_capacity(n);

  hg_debug!("-> Soft Configuration Model Graph\n");

  let params = HgParametersType::new(n, k_bar, exp_gamma,
    HG_INF_TEMPERATURE /* t = inf */,
    eta, HgGraphType::SoftConfigurationModel);

  // computing internal parameters
  hg_debug!("Internal parameters computation");
  // zeta goes to infinity
  //graph.zeta_eta = numeric_limits<double>::max( );
  let mut p = HgAlgorithmParametersType::new();
  p.alpha = 0.5 * p.eta * (exp_gamma - 1.0);
  p.eta = params.zeta_eta;
  p.radius = hg_get_rr_from_numerical_integration(&params, &p);

  hg_debug!("\talpha: {}", p.alpha);
  hg_debug!("\teta: {}", p.eta);
  hg_debug!("\tradius: {}", p.radius);

  hg_assign_coordinates(&mut nodes, &params, &p, None, rnd_01);

  hg_debug!("Creating links");
  for id in 0..params.expected_n {
    for other_id in (id + 1)..params.expected_n {
      if rnd_01() < hg_connection_probability_scm(&p, &nodes[id], &nodes[other_id]) {
        links.push(HgConnectionType {id: id, other_id: other_id});
      }
    }
  }

  Ok((nodes, links))
}

pub fn hg_hyperbolic_distance_angular_soft_rgg(
        node1: &HgCoordinateType,
        node2: &HgCoordinateType) -> f64 {
  // check if it is the same node
  if (node1.r == node2.r) && (node1.theta == node2.theta) {
    return 0.0;
  }
  // delta theta
  return HG_PI - (HG_PI - (node1.theta - node2.theta).abs()).abs();
}

fn hg_connection_probability_angular_rgg(
        params: &HgParametersType,
        node1: &HgCoordinateType,
        node2: &HgCoordinateType) -> f64 {
  // equation 55: Heaviside function
  if hg_hyperbolic_distance_angular_soft_rgg(node1, node2)
     <= (HG_PI * params.expected_degree / (params.expected_n as f64)) {
    return 1.0;
  }
  return 0.0;
}

pub fn hg_angular_rgg(
        n: usize,
        rnd_01: &mut FnMut() -> f64,
        k_bar: f64,
        zeta: f64) -> Result<Graph, &'static str>{

  if (k_bar < 1.0) || (k_bar > (n - 1) as f64) {
    return Err(INVALID_K_BAR_MSG);
  }

  let mut nodes = Vec::<HgCoordinateType>::with_capacity(n);
  let mut links = Vec::<HgConnectionType>::with_capacity(n);

  hg_debug!("-> Angular Random Geometric Graph\n");

  let params = HgParametersType::new(n, k_bar,
    HG_INF_GAMMA /* exp_gamma = inf */,
    0.0 /* t = 0 */,
    zeta, HgGraphType::AngularRgg);

  // computing internal parameters
  hg_debug!("Internal parameters computation");
  let mut p = HgAlgorithmParametersType::new();
  p.radius = HG_INF_RADIUS;

  hg_assign_coordinates(&mut nodes, &params, &p, None, rnd_01);

  hg_debug!("Creating links");
  for id in 0..params.expected_n {
    for other_id in (id + 1)..params.expected_n {
      if rnd_01() < hg_connection_probability_angular_rgg(&params, &nodes[id], &nodes[other_id]) {
        links.push(HgConnectionType {id: id, other_id: other_id});
      }
    }
  }

  Ok((nodes, links))
}

fn hg_connection_probability_soft_rgg(
        params: &HgParametersType,
        p: &HgAlgorithmParametersType,
        node1: &HgCoordinateType,
        node2: &HgCoordinateType) -> f64 {
  let x = hg_hyperbolic_distance_angular_soft_rgg(node1, node2);
  // equation 46
  let beta = 1.0 / params.temperature;
  return 1.0 / (1.0 + p.c * (x / HG_PI).powf(beta));
}

pub fn hg_soft_rgg(
        n: usize,
        rnd_01: &mut FnMut() -> f64,
        k_bar: f64,
        temperature: f64,
        zeta: f64) -> Result<Graph, &'static str>{

  if (k_bar < 1.0) || (k_bar > (n - 1) as f64) {
    return Err(INVALID_K_BAR_MSG);
  }

  if temperature < 0.0 {
    return Err(INVALID_TEMPERATURE);
  }

  let mut nodes = Vec::<HgCoordinateType>::with_capacity(n);
  let mut links = Vec::<HgConnectionType>::with_capacity(n);

  hg_debug!("-> Soft Random Geometric Graph\n");

  let params = HgParametersType::new(n, k_bar,
    HG_INF_GAMMA /* exp_gamma = inf */,
    temperature /* t = 0 */,
    zeta, HgGraphType::SoftRgg);

  // computing internal parameters
  hg_debug!("Internal parameters computation");
  let mut p = HgAlgorithmParametersType::new();
  p.radius = HG_INF_RADIUS;
  p.c = hg_get_lambda_from_gauss_hypergeometric_function(&params, &p);

  hg_assign_coordinates(&mut nodes, &params, &p, None, rnd_01);

  hg_debug!("Creating links");
  for id in 0..params.expected_n {
    for other_id in (id + 1)..params.expected_n {
      if rnd_01() < hg_connection_probability_soft_rgg(&params, &p, &nodes[id], &nodes[other_id]) {
        links.push(HgConnectionType {id: id, other_id: other_id});
      }
    }
  }

  Ok((nodes, links))
}

pub fn hg_hyperbolic_distance_er(
        node1: &HgCoordinateType,
        node2: &HgCoordinateType) -> f64 {
  // check if it is the same node
  if (node1.r == node2.r) && (node1.theta == node2.theta) {
    return 0.0;
  }
  // there is no "real distance", indeed!
  return 1.0;
}

fn hg_connection_probability_er(
        params: &HgParametersType,
        _node1: &HgCoordinateType,
        _node2: &HgCoordinateType) -> f64 {
  // connection probability is given
  // by equation 61
  return 1.0 / (1.0 + (params.expected_n as f64) / (params.expected_degree as f64));
}

pub fn hg_erdos_renyi(
        n: usize,
        rnd_01: &mut FnMut() -> f64,
        k_bar: f64,
        zeta: f64) -> Result<Graph, &'static str>{

  if (k_bar < 1.0) || (k_bar > (n as f64 - 1.0)) {
    return Err(INVALID_K_BAR_MSG);
  }

  let mut nodes = Vec::<HgCoordinateType>::with_capacity(n);
  let mut links = Vec::<HgConnectionType>::with_capacity(n);

  hg_debug!("-> Erdos-Renyi Graph\n");

  let params = HgParametersType::new(n, k_bar,
    HG_INF_GAMMA /* exp_gamma = inf */,
    HG_INF_TEMPERATURE /* t = inf */,
    zeta, HgGraphType::ErdosRenyi);

  // computing internal parameters
  hg_debug!("Internal parameters computation");
  let mut p = HgAlgorithmParametersType::new();
  p.radius = HG_INF_RADIUS;

  hg_debug!("\tradius: {} (INF)", HG_INF_RADIUS);
  hg_assign_coordinates(&mut nodes, &params, &p, None, rnd_01);

  hg_debug!("Creating links");
  for id in 0..params.expected_n {
    for other_id in (id + 1)..params.expected_n {
      if rnd_01() < hg_connection_probability_er(&params, &nodes[id], &nodes[other_id]) {
        links.push(HgConnectionType {id: id, other_id: other_id});
      }
    }
  }

  Ok((nodes, links))
}