Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. 1111111111111111 (Initial 16 species, choose 11 survivors)
  2. 0110110101101111 (11 species, choose 9 survivors)
  3. 0110110101100011 (9 species, choose 5 survivors)
  4. 0100100000100011 (End of simulation)
  5.  
  6. import numpy as np
  7.  
  8. def using_2D_matrix(nspp=1000, nscene=250):
  9.  
  10. # define a matrix to hold the communities and
  11. # set the initial community
  12. m = np.zeros((nscene, nspp), dtype='bool_')
  13. m[0, ] = 1
  14.  
  15. # loop over each extinction scene, looking up the indices
  16. # of live species and then selecting survivors
  17. for i in range(0, nscene - 1):
  18. candidates = np.where(m[i,])[0]
  19. n_surv = np.random.binomial(len(candidates), 0.99)
  20. surv = np.random.choice(candidates, size=n_surv, replace=False)
  21. m[i + 1, surv] = 1
  22.  
  23. return m
  24.  
  25. def using_dict_of_arrays(nspp=1000, nscene=250):
  26.  
  27. # initialise a dictionary holding an array giving a
  28. # unique integer to each species
  29. m = {0: np.arange(nspp)}
  30.  
  31. # loop over the scenes, selecting survivors
  32. for i in range(0, nscene - 1):
  33. n_surv = np.random.binomial(len(m[i]), 0.99)
  34. surv = np.random.choice(m[i], size=n_surv, replace=False)
  35. m[i + 1] = surv
  36.  
  37. return m
  38.  
  39. import timeit
  40. A = timeit.Timer(using_2D_matrix)
  41. A.timeit(100)
  42. # 1.6549
  43. B = timeit.Timer(using_dictionary_of_arrays)
  44. B.timeit(100)
  45. # 1.3580
  46.  
  47. def using_bitarray(nspp=1000, nscene=250):
  48. # initialise the starting community
  49. m = {0: bitarray('1' * nspp)}
  50.  
  51. for i in range(0, nscene):
  52. # pick how many die and which they are (fewer bits to swap)
  53. n_die = np.random.binomial(m[i].count(True), 0.01)
  54. unlucky = np.random.choice(m[i].search(bitarray('1')), size=n_die, replace=False)
  55. # clone the source community and kill some off
  56. m[i + 1] = bitarray(m[i])
  57. for s in unlucky:
  58. m[i + 1][s] = False
  59.  
  60. return m
  61.  
  62. C = timeit.Timer(using_bitarray)
  63. C.timeit(100)
  64. # 2.54035
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement