threshold.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. """
  2. Threshold Graphs - Creation, manipulation and identification.
  3. """
  4. from math import sqrt
  5. import networkx as nx
  6. from networkx.utils import py_random_state
  7. __all__ = ["is_threshold_graph", "find_threshold_graph"]
  8. def is_threshold_graph(G):
  9. """
  10. Returns `True` if `G` is a threshold graph.
  11. Parameters
  12. ----------
  13. G : NetworkX graph instance
  14. An instance of `Graph`, `DiGraph`, `MultiGraph` or `MultiDiGraph`
  15. Returns
  16. -------
  17. bool
  18. `True` if `G` is a threshold graph, `False` otherwise.
  19. Examples
  20. --------
  21. >>> from networkx.algorithms.threshold import is_threshold_graph
  22. >>> G = nx.path_graph(3)
  23. >>> is_threshold_graph(G)
  24. True
  25. >>> G = nx.barbell_graph(3, 3)
  26. >>> is_threshold_graph(G)
  27. False
  28. References
  29. ----------
  30. .. [1] Threshold graphs: https://en.wikipedia.org/wiki/Threshold_graph
  31. """
  32. return is_threshold_sequence([d for n, d in G.degree()])
  33. def is_threshold_sequence(degree_sequence):
  34. """
  35. Returns True if the sequence is a threshold degree sequence.
  36. Uses the property that a threshold graph must be constructed by
  37. adding either dominating or isolated nodes. Thus, it can be
  38. deconstructed iteratively by removing a node of degree zero or a
  39. node that connects to the remaining nodes. If this deconstruction
  40. fails then the sequence is not a threshold sequence.
  41. """
  42. ds = degree_sequence[:] # get a copy so we don't destroy original
  43. ds.sort()
  44. while ds:
  45. if ds[0] == 0: # if isolated node
  46. ds.pop(0) # remove it
  47. continue
  48. if ds[-1] != len(ds) - 1: # is the largest degree node dominating?
  49. return False # no, not a threshold degree sequence
  50. ds.pop() # yes, largest is the dominating node
  51. ds = [d - 1 for d in ds] # remove it and decrement all degrees
  52. return True
  53. def creation_sequence(degree_sequence, with_labels=False, compact=False):
  54. """
  55. Determines the creation sequence for the given threshold degree sequence.
  56. The creation sequence is a list of single characters 'd'
  57. or 'i': 'd' for dominating or 'i' for isolated vertices.
  58. Dominating vertices are connected to all vertices present when it
  59. is added. The first node added is by convention 'd'.
  60. This list can be converted to a string if desired using "".join(cs)
  61. If with_labels==True:
  62. Returns a list of 2-tuples containing the vertex number
  63. and a character 'd' or 'i' which describes the type of vertex.
  64. If compact==True:
  65. Returns the creation sequence in a compact form that is the number
  66. of 'i's and 'd's alternating.
  67. Examples:
  68. [1,2,2,3] represents d,i,i,d,d,i,i,i
  69. [3,1,2] represents d,d,d,i,d,d
  70. Notice that the first number is the first vertex to be used for
  71. construction and so is always 'd'.
  72. with_labels and compact cannot both be True.
  73. Returns None if the sequence is not a threshold sequence
  74. """
  75. if with_labels and compact:
  76. raise ValueError("compact sequences cannot be labeled")
  77. # make an indexed copy
  78. if isinstance(degree_sequence, dict): # labeled degree sequence
  79. ds = [[degree, label] for (label, degree) in degree_sequence.items()]
  80. else:
  81. ds = [[d, i] for i, d in enumerate(degree_sequence)]
  82. ds.sort()
  83. cs = [] # creation sequence
  84. while ds:
  85. if ds[0][0] == 0: # isolated node
  86. (d, v) = ds.pop(0)
  87. if len(ds) > 0: # make sure we start with a d
  88. cs.insert(0, (v, "i"))
  89. else:
  90. cs.insert(0, (v, "d"))
  91. continue
  92. if ds[-1][0] != len(ds) - 1: # Not dominating node
  93. return None # not a threshold degree sequence
  94. (d, v) = ds.pop()
  95. cs.insert(0, (v, "d"))
  96. ds = [[d[0] - 1, d[1]] for d in ds] # decrement due to removing node
  97. if with_labels:
  98. return cs
  99. if compact:
  100. return make_compact(cs)
  101. return [v[1] for v in cs] # not labeled
  102. def make_compact(creation_sequence):
  103. """
  104. Returns the creation sequence in a compact form
  105. that is the number of 'i's and 'd's alternating.
  106. Examples
  107. --------
  108. >>> from networkx.algorithms.threshold import make_compact
  109. >>> make_compact(["d", "i", "i", "d", "d", "i", "i", "i"])
  110. [1, 2, 2, 3]
  111. >>> make_compact(["d", "d", "d", "i", "d", "d"])
  112. [3, 1, 2]
  113. Notice that the first number is the first vertex
  114. to be used for construction and so is always 'd'.
  115. Labeled creation sequences lose their labels in the
  116. compact representation.
  117. >>> make_compact([3, 1, 2])
  118. [3, 1, 2]
  119. """
  120. first = creation_sequence[0]
  121. if isinstance(first, str): # creation sequence
  122. cs = creation_sequence[:]
  123. elif isinstance(first, tuple): # labeled creation sequence
  124. cs = [s[1] for s in creation_sequence]
  125. elif isinstance(first, int): # compact creation sequence
  126. return creation_sequence
  127. else:
  128. raise TypeError("Not a valid creation sequence type")
  129. ccs = []
  130. count = 1 # count the run lengths of d's or i's.
  131. for i in range(1, len(cs)):
  132. if cs[i] == cs[i - 1]:
  133. count += 1
  134. else:
  135. ccs.append(count)
  136. count = 1
  137. ccs.append(count) # don't forget the last one
  138. return ccs
  139. def uncompact(creation_sequence):
  140. """
  141. Converts a compact creation sequence for a threshold
  142. graph to a standard creation sequence (unlabeled).
  143. If the creation_sequence is already standard, return it.
  144. See creation_sequence.
  145. """
  146. first = creation_sequence[0]
  147. if isinstance(first, str): # creation sequence
  148. return creation_sequence
  149. elif isinstance(first, tuple): # labeled creation sequence
  150. return creation_sequence
  151. elif isinstance(first, int): # compact creation sequence
  152. ccscopy = creation_sequence[:]
  153. else:
  154. raise TypeError("Not a valid creation sequence type")
  155. cs = []
  156. while ccscopy:
  157. cs.extend(ccscopy.pop(0) * ["d"])
  158. if ccscopy:
  159. cs.extend(ccscopy.pop(0) * ["i"])
  160. return cs
  161. def creation_sequence_to_weights(creation_sequence):
  162. """
  163. Returns a list of node weights which create the threshold
  164. graph designated by the creation sequence. The weights
  165. are scaled so that the threshold is 1.0. The order of the
  166. nodes is the same as that in the creation sequence.
  167. """
  168. # Turn input sequence into a labeled creation sequence
  169. first = creation_sequence[0]
  170. if isinstance(first, str): # creation sequence
  171. if isinstance(creation_sequence, list):
  172. wseq = creation_sequence[:]
  173. else:
  174. wseq = list(creation_sequence) # string like 'ddidid'
  175. elif isinstance(first, tuple): # labeled creation sequence
  176. wseq = [v[1] for v in creation_sequence]
  177. elif isinstance(first, int): # compact creation sequence
  178. wseq = uncompact(creation_sequence)
  179. else:
  180. raise TypeError("Not a valid creation sequence type")
  181. # pass through twice--first backwards
  182. wseq.reverse()
  183. w = 0
  184. prev = "i"
  185. for j, s in enumerate(wseq):
  186. if s == "i":
  187. wseq[j] = w
  188. prev = s
  189. elif prev == "i":
  190. prev = s
  191. w += 1
  192. wseq.reverse() # now pass through forwards
  193. for j, s in enumerate(wseq):
  194. if s == "d":
  195. wseq[j] = w
  196. prev = s
  197. elif prev == "d":
  198. prev = s
  199. w += 1
  200. # Now scale weights
  201. if prev == "d":
  202. w += 1
  203. wscale = 1 / w
  204. return [ww * wscale for ww in wseq]
  205. # return wseq
  206. def weights_to_creation_sequence(
  207. weights, threshold=1, with_labels=False, compact=False
  208. ):
  209. """
  210. Returns a creation sequence for a threshold graph
  211. determined by the weights and threshold given as input.
  212. If the sum of two node weights is greater than the
  213. threshold value, an edge is created between these nodes.
  214. The creation sequence is a list of single characters 'd'
  215. or 'i': 'd' for dominating or 'i' for isolated vertices.
  216. Dominating vertices are connected to all vertices present
  217. when it is added. The first node added is by convention 'd'.
  218. If with_labels==True:
  219. Returns a list of 2-tuples containing the vertex number
  220. and a character 'd' or 'i' which describes the type of vertex.
  221. If compact==True:
  222. Returns the creation sequence in a compact form that is the number
  223. of 'i's and 'd's alternating.
  224. Examples:
  225. [1,2,2,3] represents d,i,i,d,d,i,i,i
  226. [3,1,2] represents d,d,d,i,d,d
  227. Notice that the first number is the first vertex to be used for
  228. construction and so is always 'd'.
  229. with_labels and compact cannot both be True.
  230. """
  231. if with_labels and compact:
  232. raise ValueError("compact sequences cannot be labeled")
  233. # make an indexed copy
  234. if isinstance(weights, dict): # labeled weights
  235. wseq = [[w, label] for (label, w) in weights.items()]
  236. else:
  237. wseq = [[w, i] for i, w in enumerate(weights)]
  238. wseq.sort()
  239. cs = [] # creation sequence
  240. cutoff = threshold - wseq[-1][0]
  241. while wseq:
  242. if wseq[0][0] < cutoff: # isolated node
  243. (w, label) = wseq.pop(0)
  244. cs.append((label, "i"))
  245. else:
  246. (w, label) = wseq.pop()
  247. cs.append((label, "d"))
  248. cutoff = threshold - wseq[-1][0]
  249. if len(wseq) == 1: # make sure we start with a d
  250. (w, label) = wseq.pop()
  251. cs.append((label, "d"))
  252. # put in correct order
  253. cs.reverse()
  254. if with_labels:
  255. return cs
  256. if compact:
  257. return make_compact(cs)
  258. return [v[1] for v in cs] # not labeled
  259. # Manipulating NetworkX.Graphs in context of threshold graphs
  260. def threshold_graph(creation_sequence, create_using=None):
  261. """
  262. Create a threshold graph from the creation sequence or compact
  263. creation_sequence.
  264. The input sequence can be a
  265. creation sequence (e.g. ['d','i','d','d','d','i'])
  266. labeled creation sequence (e.g. [(0,'d'),(2,'d'),(1,'i')])
  267. compact creation sequence (e.g. [2,1,1,2,0])
  268. Use cs=creation_sequence(degree_sequence,labeled=True)
  269. to convert a degree sequence to a creation sequence.
  270. Returns None if the sequence is not valid
  271. """
  272. # Turn input sequence into a labeled creation sequence
  273. first = creation_sequence[0]
  274. if isinstance(first, str): # creation sequence
  275. ci = list(enumerate(creation_sequence))
  276. elif isinstance(first, tuple): # labeled creation sequence
  277. ci = creation_sequence[:]
  278. elif isinstance(first, int): # compact creation sequence
  279. cs = uncompact(creation_sequence)
  280. ci = list(enumerate(cs))
  281. else:
  282. print("not a valid creation sequence type")
  283. return None
  284. G = nx.empty_graph(0, create_using)
  285. if G.is_directed():
  286. raise nx.NetworkXError("Directed Graph not supported")
  287. G.name = "Threshold Graph"
  288. # add nodes and edges
  289. # if type is 'i' just add nodea
  290. # if type is a d connect to everything previous
  291. while ci:
  292. (v, node_type) = ci.pop(0)
  293. if node_type == "d": # dominating type, connect to all existing nodes
  294. # We use `for u in list(G):` instead of
  295. # `for u in G:` because we edit the graph `G` in
  296. # the loop. Hence using an iterator will result in
  297. # `RuntimeError: dictionary changed size during iteration`
  298. for u in list(G):
  299. G.add_edge(v, u)
  300. G.add_node(v)
  301. return G
  302. def find_alternating_4_cycle(G):
  303. """
  304. Returns False if there aren't any alternating 4 cycles.
  305. Otherwise returns the cycle as [a,b,c,d] where (a,b)
  306. and (c,d) are edges and (a,c) and (b,d) are not.
  307. """
  308. for u, v in G.edges():
  309. for w in G.nodes():
  310. if not G.has_edge(u, w) and u != w:
  311. for x in G.neighbors(w):
  312. if not G.has_edge(v, x) and v != x:
  313. return [u, v, w, x]
  314. return False
  315. def find_threshold_graph(G, create_using=None):
  316. """
  317. Returns a threshold subgraph that is close to largest in `G`.
  318. The threshold graph will contain the largest degree node in G.
  319. Parameters
  320. ----------
  321. G : NetworkX graph instance
  322. An instance of `Graph`, or `MultiDiGraph`
  323. create_using : NetworkX graph class or `None` (default), optional
  324. Type of graph to use when constructing the threshold graph.
  325. If `None`, infer the appropriate graph type from the input.
  326. Returns
  327. -------
  328. graph :
  329. A graph instance representing the threshold graph
  330. Examples
  331. --------
  332. >>> from networkx.algorithms.threshold import find_threshold_graph
  333. >>> G = nx.barbell_graph(3, 3)
  334. >>> T = find_threshold_graph(G)
  335. >>> T.nodes # may vary
  336. NodeView((7, 8, 5, 6))
  337. References
  338. ----------
  339. .. [1] Threshold graphs: https://en.wikipedia.org/wiki/Threshold_graph
  340. """
  341. return threshold_graph(find_creation_sequence(G), create_using)
  342. def find_creation_sequence(G):
  343. """
  344. Find a threshold subgraph that is close to largest in G.
  345. Returns the labeled creation sequence of that threshold graph.
  346. """
  347. cs = []
  348. # get a local pointer to the working part of the graph
  349. H = G
  350. while H.order() > 0:
  351. # get new degree sequence on subgraph
  352. dsdict = dict(H.degree())
  353. ds = [(d, v) for v, d in dsdict.items()]
  354. ds.sort()
  355. # Update threshold graph nodes
  356. if ds[-1][0] == 0: # all are isolated
  357. cs.extend(zip(dsdict, ["i"] * (len(ds) - 1) + ["d"]))
  358. break # Done!
  359. # pull off isolated nodes
  360. while ds[0][0] == 0:
  361. (d, iso) = ds.pop(0)
  362. cs.append((iso, "i"))
  363. # find new biggest node
  364. (d, bigv) = ds.pop()
  365. # add edges of star to t_g
  366. cs.append((bigv, "d"))
  367. # form subgraph of neighbors of big node
  368. H = H.subgraph(H.neighbors(bigv))
  369. cs.reverse()
  370. return cs
  371. # Properties of Threshold Graphs
  372. def triangles(creation_sequence):
  373. """
  374. Compute number of triangles in the threshold graph with the
  375. given creation sequence.
  376. """
  377. # shortcut algorithm that doesn't require computing number
  378. # of triangles at each node.
  379. cs = creation_sequence # alias
  380. dr = cs.count("d") # number of d's in sequence
  381. ntri = dr * (dr - 1) * (dr - 2) / 6 # number of triangles in clique of nd d's
  382. # now add dr choose 2 triangles for every 'i' in sequence where
  383. # dr is the number of d's to the right of the current i
  384. for i, typ in enumerate(cs):
  385. if typ == "i":
  386. ntri += dr * (dr - 1) / 2
  387. else:
  388. dr -= 1
  389. return ntri
  390. def triangle_sequence(creation_sequence):
  391. """
  392. Return triangle sequence for the given threshold graph creation sequence.
  393. """
  394. cs = creation_sequence
  395. seq = []
  396. dr = cs.count("d") # number of d's to the right of the current pos
  397. dcur = (dr - 1) * (dr - 2) // 2 # number of triangles through a node of clique dr
  398. irun = 0 # number of i's in the last run
  399. drun = 0 # number of d's in the last run
  400. for i, sym in enumerate(cs):
  401. if sym == "d":
  402. drun += 1
  403. tri = dcur + (dr - 1) * irun # new triangles at this d
  404. else: # cs[i]="i":
  405. if prevsym == "d": # new string of i's
  406. dcur += (dr - 1) * irun # accumulate shared shortest paths
  407. irun = 0 # reset i run counter
  408. dr -= drun # reduce number of d's to right
  409. drun = 0 # reset d run counter
  410. irun += 1
  411. tri = dr * (dr - 1) // 2 # new triangles at this i
  412. seq.append(tri)
  413. prevsym = sym
  414. return seq
  415. def cluster_sequence(creation_sequence):
  416. """
  417. Return cluster sequence for the given threshold graph creation sequence.
  418. """
  419. triseq = triangle_sequence(creation_sequence)
  420. degseq = degree_sequence(creation_sequence)
  421. cseq = []
  422. for i, deg in enumerate(degseq):
  423. tri = triseq[i]
  424. if deg <= 1: # isolated vertex or single pair gets cc 0
  425. cseq.append(0)
  426. continue
  427. max_size = (deg * (deg - 1)) // 2
  428. cseq.append(tri / max_size)
  429. return cseq
  430. def degree_sequence(creation_sequence):
  431. """
  432. Return degree sequence for the threshold graph with the given
  433. creation sequence
  434. """
  435. cs = creation_sequence # alias
  436. seq = []
  437. rd = cs.count("d") # number of d to the right
  438. for i, sym in enumerate(cs):
  439. if sym == "d":
  440. rd -= 1
  441. seq.append(rd + i)
  442. else:
  443. seq.append(rd)
  444. return seq
  445. def density(creation_sequence):
  446. """
  447. Return the density of the graph with this creation_sequence.
  448. The density is the fraction of possible edges present.
  449. """
  450. N = len(creation_sequence)
  451. two_size = sum(degree_sequence(creation_sequence))
  452. two_possible = N * (N - 1)
  453. den = two_size / two_possible
  454. return den
  455. def degree_correlation(creation_sequence):
  456. """
  457. Return the degree-degree correlation over all edges.
  458. """
  459. cs = creation_sequence
  460. s1 = 0 # deg_i*deg_j
  461. s2 = 0 # deg_i^2+deg_j^2
  462. s3 = 0 # deg_i+deg_j
  463. m = 0 # number of edges
  464. rd = cs.count("d") # number of d nodes to the right
  465. rdi = [i for i, sym in enumerate(cs) if sym == "d"] # index of "d"s
  466. ds = degree_sequence(cs)
  467. for i, sym in enumerate(cs):
  468. if sym == "d":
  469. if i != rdi[0]:
  470. print("Logic error in degree_correlation", i, rdi)
  471. raise ValueError
  472. rdi.pop(0)
  473. degi = ds[i]
  474. for dj in rdi:
  475. degj = ds[dj]
  476. s1 += degj * degi
  477. s2 += degi**2 + degj**2
  478. s3 += degi + degj
  479. m += 1
  480. denom = 2 * m * s2 - s3 * s3
  481. numer = 4 * m * s1 - s3 * s3
  482. if denom == 0:
  483. if numer == 0:
  484. return 1
  485. raise ValueError(f"Zero Denominator but Numerator is {numer}")
  486. return numer / denom
  487. def shortest_path(creation_sequence, u, v):
  488. """
  489. Find the shortest path between u and v in a
  490. threshold graph G with the given creation_sequence.
  491. For an unlabeled creation_sequence, the vertices
  492. u and v must be integers in (0,len(sequence)) referring
  493. to the position of the desired vertices in the sequence.
  494. For a labeled creation_sequence, u and v are labels of veritices.
  495. Use cs=creation_sequence(degree_sequence,with_labels=True)
  496. to convert a degree sequence to a creation sequence.
  497. Returns a list of vertices from u to v.
  498. Example: if they are neighbors, it returns [u,v]
  499. """
  500. # Turn input sequence into a labeled creation sequence
  501. first = creation_sequence[0]
  502. if isinstance(first, str): # creation sequence
  503. cs = [(i, creation_sequence[i]) for i in range(len(creation_sequence))]
  504. elif isinstance(first, tuple): # labeled creation sequence
  505. cs = creation_sequence[:]
  506. elif isinstance(first, int): # compact creation sequence
  507. ci = uncompact(creation_sequence)
  508. cs = [(i, ci[i]) for i in range(len(ci))]
  509. else:
  510. raise TypeError("Not a valid creation sequence type")
  511. verts = [s[0] for s in cs]
  512. if v not in verts:
  513. raise ValueError(f"Vertex {v} not in graph from creation_sequence")
  514. if u not in verts:
  515. raise ValueError(f"Vertex {u} not in graph from creation_sequence")
  516. # Done checking
  517. if u == v:
  518. return [u]
  519. uindex = verts.index(u)
  520. vindex = verts.index(v)
  521. bigind = max(uindex, vindex)
  522. if cs[bigind][1] == "d":
  523. return [u, v]
  524. # must be that cs[bigind][1]=='i'
  525. cs = cs[bigind:]
  526. while cs:
  527. vert = cs.pop()
  528. if vert[1] == "d":
  529. return [u, vert[0], v]
  530. # All after u are type 'i' so no connection
  531. return -1
  532. def shortest_path_length(creation_sequence, i):
  533. """
  534. Return the shortest path length from indicated node to
  535. every other node for the threshold graph with the given
  536. creation sequence.
  537. Node is indicated by index i in creation_sequence unless
  538. creation_sequence is labeled in which case, i is taken to
  539. be the label of the node.
  540. Paths lengths in threshold graphs are at most 2.
  541. Length to unreachable nodes is set to -1.
  542. """
  543. # Turn input sequence into a labeled creation sequence
  544. first = creation_sequence[0]
  545. if isinstance(first, str): # creation sequence
  546. if isinstance(creation_sequence, list):
  547. cs = creation_sequence[:]
  548. else:
  549. cs = list(creation_sequence)
  550. elif isinstance(first, tuple): # labeled creation sequence
  551. cs = [v[1] for v in creation_sequence]
  552. i = [v[0] for v in creation_sequence].index(i)
  553. elif isinstance(first, int): # compact creation sequence
  554. cs = uncompact(creation_sequence)
  555. else:
  556. raise TypeError("Not a valid creation sequence type")
  557. # Compute
  558. N = len(cs)
  559. spl = [2] * N # length 2 to every node
  560. spl[i] = 0 # except self which is 0
  561. # 1 for all d's to the right
  562. for j in range(i + 1, N):
  563. if cs[j] == "d":
  564. spl[j] = 1
  565. if cs[i] == "d": # 1 for all nodes to the left
  566. for j in range(i):
  567. spl[j] = 1
  568. # and -1 for any trailing i to indicate unreachable
  569. for j in range(N - 1, 0, -1):
  570. if cs[j] == "d":
  571. break
  572. spl[j] = -1
  573. return spl
  574. def betweenness_sequence(creation_sequence, normalized=True):
  575. """
  576. Return betweenness for the threshold graph with the given creation
  577. sequence. The result is unscaled. To scale the values
  578. to the iterval [0,1] divide by (n-1)*(n-2).
  579. """
  580. cs = creation_sequence
  581. seq = [] # betweenness
  582. lastchar = "d" # first node is always a 'd'
  583. dr = float(cs.count("d")) # number of d's to the right of current pos
  584. irun = 0 # number of i's in the last run
  585. drun = 0 # number of d's in the last run
  586. dlast = 0.0 # betweenness of last d
  587. for i, c in enumerate(cs):
  588. if c == "d": # cs[i]=="d":
  589. # betweennees = amt shared with earlier d's and i's
  590. # + new isolated nodes covered
  591. # + new paths to all previous nodes
  592. b = dlast + (irun - 1) * irun / dr + 2 * irun * (i - drun - irun) / dr
  593. drun += 1 # update counter
  594. else: # cs[i]="i":
  595. if lastchar == "d": # if this is a new run of i's
  596. dlast = b # accumulate betweenness
  597. dr -= drun # update number of d's to the right
  598. drun = 0 # reset d counter
  599. irun = 0 # reset i counter
  600. b = 0 # isolated nodes have zero betweenness
  601. irun += 1 # add another i to the run
  602. seq.append(float(b))
  603. lastchar = c
  604. # normalize by the number of possible shortest paths
  605. if normalized:
  606. order = len(cs)
  607. scale = 1.0 / ((order - 1) * (order - 2))
  608. seq = [s * scale for s in seq]
  609. return seq
  610. def eigenvectors(creation_sequence):
  611. """
  612. Return a 2-tuple of Laplacian eigenvalues and eigenvectors
  613. for the threshold network with creation_sequence.
  614. The first value is a list of eigenvalues.
  615. The second value is a list of eigenvectors.
  616. The lists are in the same order so corresponding eigenvectors
  617. and eigenvalues are in the same position in the two lists.
  618. Notice that the order of the eigenvalues returned by eigenvalues(cs)
  619. may not correspond to the order of these eigenvectors.
  620. """
  621. ccs = make_compact(creation_sequence)
  622. N = sum(ccs)
  623. vec = [0] * N
  624. val = vec[:]
  625. # get number of type d nodes to the right (all for first node)
  626. dr = sum(ccs[::2])
  627. nn = ccs[0]
  628. vec[0] = [1.0 / sqrt(N)] * N
  629. val[0] = 0
  630. e = dr
  631. dr -= nn
  632. type_d = True
  633. i = 1
  634. dd = 1
  635. while dd < nn:
  636. scale = 1.0 / sqrt(dd * dd + i)
  637. vec[i] = i * [-scale] + [dd * scale] + [0] * (N - i - 1)
  638. val[i] = e
  639. i += 1
  640. dd += 1
  641. if len(ccs) == 1:
  642. return (val, vec)
  643. for nn in ccs[1:]:
  644. scale = 1.0 / sqrt(nn * i * (i + nn))
  645. vec[i] = i * [-nn * scale] + nn * [i * scale] + [0] * (N - i - nn)
  646. # find eigenvalue
  647. type_d = not type_d
  648. if type_d:
  649. e = i + dr
  650. dr -= nn
  651. else:
  652. e = dr
  653. val[i] = e
  654. st = i
  655. i += 1
  656. dd = 1
  657. while dd < nn:
  658. scale = 1.0 / sqrt(i - st + dd * dd)
  659. vec[i] = [0] * st + (i - st) * [-scale] + [dd * scale] + [0] * (N - i - 1)
  660. val[i] = e
  661. i += 1
  662. dd += 1
  663. return (val, vec)
  664. def spectral_projection(u, eigenpairs):
  665. """
  666. Returns the coefficients of each eigenvector
  667. in a projection of the vector u onto the normalized
  668. eigenvectors which are contained in eigenpairs.
  669. eigenpairs should be a list of two objects. The
  670. first is a list of eigenvalues and the second a list
  671. of eigenvectors. The eigenvectors should be lists.
  672. There's not a lot of error checking on lengths of
  673. arrays, etc. so be careful.
  674. """
  675. coeff = []
  676. evect = eigenpairs[1]
  677. for ev in evect:
  678. c = sum(evv * uv for (evv, uv) in zip(ev, u))
  679. coeff.append(c)
  680. return coeff
  681. def eigenvalues(creation_sequence):
  682. """
  683. Return sequence of eigenvalues of the Laplacian of the threshold
  684. graph for the given creation_sequence.
  685. Based on the Ferrer's diagram method. The spectrum is integral
  686. and is the conjugate of the degree sequence.
  687. See::
  688. @Article{degree-merris-1994,
  689. author = {Russel Merris},
  690. title = {Degree maximal graphs are Laplacian integral},
  691. journal = {Linear Algebra Appl.},
  692. year = {1994},
  693. volume = {199},
  694. pages = {381--389},
  695. }
  696. """
  697. degseq = degree_sequence(creation_sequence)
  698. degseq.sort()
  699. eiglist = [] # zero is always one eigenvalue
  700. eig = 0
  701. row = len(degseq)
  702. bigdeg = degseq.pop()
  703. while row:
  704. if bigdeg < row:
  705. eiglist.append(eig)
  706. row -= 1
  707. else:
  708. eig += 1
  709. if degseq:
  710. bigdeg = degseq.pop()
  711. else:
  712. bigdeg = 0
  713. return eiglist
  714. # Threshold graph creation routines
  715. @py_random_state(2)
  716. def random_threshold_sequence(n, p, seed=None):
  717. """
  718. Create a random threshold sequence of size n.
  719. A creation sequence is built by randomly choosing d's with
  720. probability p and i's with probability 1-p.
  721. s=nx.random_threshold_sequence(10,0.5)
  722. returns a threshold sequence of length 10 with equal
  723. probably of an i or a d at each position.
  724. A "random" threshold graph can be built with
  725. G=nx.threshold_graph(s)
  726. seed : integer, random_state, or None (default)
  727. Indicator of random number generation state.
  728. See :ref:`Randomness<randomness>`.
  729. """
  730. if not (0 <= p <= 1):
  731. raise ValueError("p must be in [0,1]")
  732. cs = ["d"] # threshold sequences always start with a d
  733. for i in range(1, n):
  734. if seed.random() < p:
  735. cs.append("d")
  736. else:
  737. cs.append("i")
  738. return cs
  739. # maybe *_d_threshold_sequence routines should
  740. # be (or be called from) a single routine with a more descriptive name
  741. # and a keyword parameter?
  742. def right_d_threshold_sequence(n, m):
  743. """
  744. Create a skewed threshold graph with a given number
  745. of vertices (n) and a given number of edges (m).
  746. The routine returns an unlabeled creation sequence
  747. for the threshold graph.
  748. FIXME: describe algorithm
  749. """
  750. cs = ["d"] + ["i"] * (n - 1) # create sequence with n insolated nodes
  751. # m <n : not enough edges, make disconnected
  752. if m < n:
  753. cs[m] = "d"
  754. return cs
  755. # too many edges
  756. if m > n * (n - 1) / 2:
  757. raise ValueError("Too many edges for this many nodes.")
  758. # connected case m >n-1
  759. ind = n - 1
  760. sum = n - 1
  761. while sum < m:
  762. cs[ind] = "d"
  763. ind -= 1
  764. sum += ind
  765. ind = m - (sum - ind)
  766. cs[ind] = "d"
  767. return cs
  768. def left_d_threshold_sequence(n, m):
  769. """
  770. Create a skewed threshold graph with a given number
  771. of vertices (n) and a given number of edges (m).
  772. The routine returns an unlabeled creation sequence
  773. for the threshold graph.
  774. FIXME: describe algorithm
  775. """
  776. cs = ["d"] + ["i"] * (n - 1) # create sequence with n insolated nodes
  777. # m <n : not enough edges, make disconnected
  778. if m < n:
  779. cs[m] = "d"
  780. return cs
  781. # too many edges
  782. if m > n * (n - 1) / 2:
  783. raise ValueError("Too many edges for this many nodes.")
  784. # Connected case when M>N-1
  785. cs[n - 1] = "d"
  786. sum = n - 1
  787. ind = 1
  788. while sum < m:
  789. cs[ind] = "d"
  790. sum += ind
  791. ind += 1
  792. if sum > m: # be sure not to change the first vertex
  793. cs[sum - m] = "i"
  794. return cs
  795. @py_random_state(3)
  796. def swap_d(cs, p_split=1.0, p_combine=1.0, seed=None):
  797. """
  798. Perform a "swap" operation on a threshold sequence.
  799. The swap preserves the number of nodes and edges
  800. in the graph for the given sequence.
  801. The resulting sequence is still a threshold sequence.
  802. Perform one split and one combine operation on the
  803. 'd's of a creation sequence for a threshold graph.
  804. This operation maintains the number of nodes and edges
  805. in the graph, but shifts the edges from node to node
  806. maintaining the threshold quality of the graph.
  807. seed : integer, random_state, or None (default)
  808. Indicator of random number generation state.
  809. See :ref:`Randomness<randomness>`.
  810. """
  811. # preprocess the creation sequence
  812. dlist = [i for (i, node_type) in enumerate(cs[1:-1]) if node_type == "d"]
  813. # split
  814. if seed.random() < p_split:
  815. choice = seed.choice(dlist)
  816. split_to = seed.choice(range(choice))
  817. flip_side = choice - split_to
  818. if split_to != flip_side and cs[split_to] == "i" and cs[flip_side] == "i":
  819. cs[choice] = "i"
  820. cs[split_to] = "d"
  821. cs[flip_side] = "d"
  822. dlist.remove(choice)
  823. # don't add or combine may reverse this action
  824. # dlist.extend([split_to,flip_side])
  825. # print >>sys.stderr,"split at %s to %s and %s"%(choice,split_to,flip_side)
  826. # combine
  827. if seed.random() < p_combine and dlist:
  828. first_choice = seed.choice(dlist)
  829. second_choice = seed.choice(dlist)
  830. target = first_choice + second_choice
  831. if target >= len(cs) or cs[target] == "d" or first_choice == second_choice:
  832. return cs
  833. # OK to combine
  834. cs[first_choice] = "i"
  835. cs[second_choice] = "i"
  836. cs[target] = "d"
  837. # print >>sys.stderr,"combine %s and %s to make %s."%(first_choice,second_choice,target)
  838. return cs