PageRenderTime 47ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/simulations/percolation-mobility-quasiunitdisk-Model-EC2/run_pgg_2.py

https://bitbucket.org/mekman/complex-systems
Python | 179 lines | 153 code | 2 blank | 24 comment | 0 complexity | 253d195a799829ef944ac4151e5cbf28 MD5 | raw file
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # -------------------------------------------------------------------------------
  4. # Copyright (c) 2012 Vincent Gauthier.
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining
  7. # a copy of this software and associated documentation files (the
  8. # "Software"), to deal in the Software without restriction, including
  9. # without limitation the rights to use, copy, modify, merge, publish,
  10. # distribute, sublicense, and/or sell copies of the Software, and to
  11. # permit persons to whom the Software is furnished to do so, subject to
  12. # the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included
  15. # in all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  20. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  21. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  22. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  23. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. # -------------------------------------------------------------------------------
  25. __author__ = """\n""".join(['Vincent Gauthier'])
  26. from sumatra.decorators import capture
  27. @capture
  28. def parameters_sweep(parameters):
  29. import networkx as nx
  30. from complex_systems.pgg import PublicGoodGames
  31. import numpy as np
  32. import csv
  33. import itertools
  34. from IPython.parallel import Client
  35. ####### Init the variables #######
  36. synergy_step = parameters['synergy_step']
  37. synergy_max = parameters['synergy_max']
  38. synergy_min = parameters['synergy_min']
  39. filename_txt = parameters['filename'] + '_%s.dat' \
  40. % parameters['sumatra_label']
  41. filename_jpg = parameters['filename'] + '_%s.jpg' \
  42. % parameters['sumatra_label']
  43. nb_batch = parameters['nb_batch']
  44. synergy_range = np.arange(synergy_min, synergy_max, synergy_step)
  45. job_id_list = []
  46. resultats_raw = dict()
  47. X = []
  48. Y = []
  49. Z = []
  50. # Init Dictionary
  51. for entry in synergy_range:
  52. resultats_raw[entry] = []
  53. ####### Init the Multiprocessing Pool #######
  54. rc = Client(packer='pickle')
  55. #rc = Client()
  56. dview = rc[:]
  57. lbview = rc.load_balanced_view()
  58. # Print the number of engine ready
  59. print 'Run with ', rc.ids, ' Ipython Engines'
  60. ####### Start the Batch of simualtion #######
  61. for synergy in synergy_range:
  62. # Run the Game
  63. jobid = [lbview.apply_async(run_simu, parameters, synergy) for i in range(nb_batch)]
  64. job_id_list.append(jobid)
  65. print 'Job list submited to the scheduler'
  66. ####### Gather the simulations results #######
  67. for batch in job_id_list:
  68. for job in batch:
  69. resultat = job.get()
  70. print 'Number of job still runing:', len(rc.outstanding)
  71. map_id, val1, val2 = resultat
  72. resultats_raw[map_id].append((val1,val2))
  73. print 'Finish the batch of simulation for synergy=', map_id
  74. items = resultats_raw.items()
  75. items.sort()
  76. ####### Reduce the results #######
  77. for key,val in items:
  78. x, y, z = reduceR(key, val)
  79. X.append(x)
  80. Y.append(y)
  81. Z.append(z)
  82. ####### Save the Result in csv file #######
  83. with open(filename_txt, 'wb') as f:
  84. writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_ALL)
  85. for row_id in xrange(len(X)):
  86. row = [X[row_id], Y[row_id], Z[row_id]]
  87. writer.writerow(row)
  88. def reduceR(key, val):
  89. import numpy as np
  90. val1, val2 = zip(*val)
  91. print 'Reducer:', val1
  92. return key, np.mean(val1), np.mean(val2)
  93. def run_simu(parameters, synergy):
  94. import numpy as np
  95. import networkx as nx
  96. from complex_systems.dygraph import DyGraph
  97. from complex_systems.pgg import PublicGoodGames
  98. from complex_systems.quasi_unit_disk_graph import gen_quasi_unit_disk_weight
  99. from complex_systems.quasi_unit_disk_graph import remove_edges_from_graph
  100. number_of_node = parameters['number_of_node']
  101. size_of_simulation_area = parameters['size_of_simulation_area']
  102. outer_radius = parameters['outer_radius']
  103. inner_radius = parameters['inner_radius']
  104. alpha_quasi_unit_disk = parameters['alpha_quasi_unit_disk']
  105. coop_ratio = parameters['initial_cooperator_ratio']
  106. simulation_length = parameters['simulation_length']
  107. sampling_interval = parameters['sampling_interval']
  108. alpha_levy = parameters['alpha_levy']
  109. noise_var = parameters['noise_variance']
  110. beta = parameters['beta']
  111. f_min = parameters['f_min']
  112. f_max = parameters['f_max']
  113. s_min = parameters['s_min']
  114. s_max = parameters['s_max']
  115. velocity = parameters['velocity']
  116. G = DyGraph(time_stop=simulation_length, time_step=sampling_interval)
  117. G.generate_mobility_levy_walk(
  118. alpha=alpha_levy,
  119. beta=beta,
  120. size_max=size_of_simulation_area,
  121. f_min=f_min,
  122. f_max=f_max,
  123. s_min=s_min,
  124. s_max=s_max,
  125. b_c=2,
  126. radius=outer_radius,
  127. nb_node=number_of_node,
  128. velocity=velocity,
  129. )
  130. first_run = True
  131. resultats = []
  132. for g in G:
  133. g = gen_quasi_unit_disk_weight(G=g, outer_radius=outer_radius,
  134. inner_radius=inner_radius, alpha=alpha_quasi_unit_disk)
  135. g = remove_edges_from_graph(g)
  136. if first_run == True:
  137. PGG = PublicGoodGames(G=g, synergy=synergy,
  138. cooperator_ratio=coop_ratio,
  139. noise_var=noise_var)
  140. nb_coop = PGG.run_game(sampling_interval)
  141. resultats.append(nb_coop)
  142. strategies = PGG.get_strategies()
  143. first_run = False
  144. else:
  145. PGG = PublicGoodGames(G=g, synergy=synergy,
  146. cooperator_ratio=coop_ratio,
  147. noise_var=noise_var)
  148. PGG.set_strategies(strategies)
  149. nb_coop = PGG.run_game(sampling_interval)
  150. strategies = PGG.get_strategies()
  151. resultats.append(nb_coop)
  152. return (synergy, nb_coop, np.mean(G.avg_degree()))
  153. if __name__ == '__main__':
  154. import sys
  155. from sumatra.parameters import build_parameters
  156. sys.path.append('../..')
  157. parameter_file = sys.argv[1]
  158. parameters = build_parameters(parameter_file)
  159. parameters_sweep(parameters)