randmio_und_signed.m 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. function [R,eff] = randmio_und_signed(W, ITER)
  2. % RANDMIO_UND_SIGNED Random graph with preserved signed degree distribution
  3. %
  4. % R = randmio_und_signed(W,ITER);
  5. % [R,eff] = randmio_und_signed(W,ITER);
  6. %
  7. % This function randomizes an undirected network with positively and
  8. % negatively signed connections, while preserving the positively and
  9. % negatively signed degree distribution. The function does not preserve
  10. % the strength distribution in weighted networks.
  11. %
  12. % Input: W, undirected (binary/weighted) connection matrix
  13. % ITER, rewiring parameter
  14. % (each edge is rewired approximately ITER times)
  15. %
  16. % Output: R, randomized network
  17. % eff, number of actual rewirings carried out
  18. %
  19. % Reference: Maslov and Sneppen (2002) Science 296:910
  20. %
  21. %
  22. % 2011-2015
  23. % Dani Bassett, UCSB
  24. % Olaf Sporns, Indiana U
  25. % Mika Rubinov, U Cambridge
  26. % Modification History:
  27. % Mar 2011: Original (Dani Bassett, based on randmio_und.m)
  28. % Mar 2012: Limit number of rewiring attempts,
  29. % count number of successful rewirings (Olaf Sporns)
  30. % Dec 2015: Rewritten the core of the rewiring algorithm to allow
  31. % unbiased exploration of all network configurations. The new
  32. % algorithm allows positive-positive/negative-negative
  33. % rewirings, in addition to the previous positive-positive/0-0
  34. % and negative-negative/0-0 rewirings (Mika Rubinov).
  35. if nargin('randperm')==1
  36. warning('This function requires a recent (>2011) version of MATLAB.')
  37. end
  38. R = double(W); % sign function requires double input
  39. n = size(R,1);
  40. ITER = ITER*n*(n-1)/2;
  41. % maximal number of rewiring attempts per 'iter'
  42. maxAttempts = round(n/2);
  43. % actual number of successful rewirings
  44. eff = 0;
  45. for iter=1:ITER
  46. att=0;
  47. while (att<=maxAttempts) %while not rewired
  48. %select four distinct vertices
  49. nodes = randperm(n,4);
  50. a = nodes(1);
  51. b = nodes(2);
  52. c = nodes(3);
  53. d = nodes(4);
  54. r0_ab = R(a,b);
  55. r0_cd = R(c,d);
  56. r0_ad = R(a,d);
  57. r0_cb = R(c,b);
  58. %rewiring condition
  59. if (sign(r0_ab)==sign(r0_cd)) && ...
  60. (sign(r0_ad)==sign(r0_cb)) && ...
  61. (sign(r0_ab)~=sign(r0_ad))
  62. R(a,d)=r0_ab; R(a,b)=r0_ad;
  63. R(d,a)=r0_ab; R(b,a)=r0_ad;
  64. R(c,b)=r0_cd; R(c,d)=r0_cb;
  65. R(b,c)=r0_cd; R(d,c)=r0_cb;
  66. eff = eff+1;
  67. break;
  68. end %rewiring condition
  69. att=att+1;
  70. end %while not rewired
  71. end %iterations