randmio_dir_signed.m 2.7 KB

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