Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.34 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.image as mpimg
  5. from matplotlib.text import TextPath
  6. from mpl_toolkits.mplot3d import Axes3D
  7. from matplotlib import cm
  8. #
  9. # Types of problems to handle
  10. # https://www.rangevoting.org/AssetBC.html
  11. # https://groups.google.com/forum/#!topic/electionscience/Rk4ZGf-s-s8
  12.  
  13. #centerists = False
  14. centerists = True
  15. #maximize = False
  16. maximize = True
  17.  
  18. #Number of winners
  19. W = 5
  20.  
  21. #the maximum possible score is 5
  22. K = 5.0
  23.  
  24. mean_red = [-2.5*np.sqrt(3), 2.5]
  25. cov_red = [[5, 0], [0, 5]]  # diagonal covariance
  26. pos_red = np.random.multivariate_normal(mean_red, cov_red, 5000)
  27. df_red = pd.DataFrame.from_records(pos_red, columns = ['x','y'])
  28. df_red['colour'] = 'red'
  29.  
  30. mean_green = [0, -5]
  31. cov_green = [[5, 0], [0, 5]]  # diagonal covariance
  32. pos_green = np.random.multivariate_normal(mean_green, cov_green, 5000)
  33. df_green = pd.DataFrame.from_records(pos_green, columns = ['x','y'])
  34. df_green['colour'] = 'green'
  35.  
  36. mean_blue = [2.5*np.sqrt(3), 2.5]
  37. cov_blue = [[5, 0], [0, 5]]  # diagonal covariance
  38. pos_blue = np.random.multivariate_normal(mean_blue, cov_blue, 5000)
  39. df_blue = pd.DataFrame.from_records(pos_blue, columns = ['x','y'])
  40. df_blue['colour'] = 'blue'
  41.  
  42. candidates = [['A',0,0],
  43.                 ['Z',0,2.5],
  44.                 ['R1',-1*np.sqrt(3), 1],
  45.                 ['R2',-2.5*np.sqrt(3), 2.5],
  46.                 ['R3',-4*np.sqrt(3), 4],
  47.                 ['G1',0, -2],
  48.                 ['G2',0, -5],
  49.                 ['G3',0, -8],
  50.                 ['B1',1*np.sqrt(3), 1],
  51.                 ['B2',2.5*np.sqrt(3),2.5],
  52.                 ['B3',4*np.sqrt(3), 4]]
  53.  
  54. df_can = pd.DataFrame.from_records(candidates, columns = ['Name','x','y'] )
  55.  
  56. fig = plt.figure(figsize=(20,10))
  57. fig.suptitle('Political Simulation')
  58.  
  59. #image
  60. ax1 = fig.add_subplot(1, 2, 1)
  61. img=mpimg.imread('Political Compass.jpg')
  62. ax1.imshow(img)
  63. ax1.axis('off')
  64.  
  65. # Scatter plot
  66. ax2 = fig.add_subplot(1, 2, 2)
  67. ax2.plot(df_red['x'],df_red['y'],".",label = 'Red', color='r')
  68. ax2.plot(df_green['x'],df_green['y'],".",label = 'Green', color='g')
  69. ax2.plot(df_blue['x'],df_blue['y'],".",label = 'Blue', color='b')
  70.  
  71. #Candidates
  72. for c in candidates:
  73.     ax2.plot(c[1], c[2],marker=TextPath((0,0), c[0]),markersize=20, color='k')
  74.  
  75. ax2.set_xlim(-10, 10)
  76. ax2.set_ylim(-10, 10)    
  77. ax2.set_title('Political Compass')
  78. ax2.set_xlabel('Planned Economy  <--  Economics  -->  Free Market')
  79. ax2.set_ylabel('Liberal  <-- Government  --> Authoritarian')    
  80. lgd2 = ax2.legend(loc=1)
  81. fig.savefig("Simulated_Spectrum", dpi=300)
  82.  
  83. if centerists:
  84.     mean_center = [0,0]
  85.     cov_center = [[5, 0], [0, 5]]  # diagonal covariance
  86.     pos_center = np.random.multivariate_normal(mean_center, cov_center, 3500)
  87.     df_center = pd.DataFrame.from_records(pos_center, columns = ['x','y'])
  88.     df_center['colour'] = 'center'
  89.    
  90.     df_voters = pd.concat([df_red, df_green, df_blue, df_center],ignore_index=True)
  91. else:
  92.     df_voters = pd.concat([df_red, df_green, df_blue],ignore_index=True)
  93.        
  94.  
  95. #Number of voters
  96. V = df_voters.shape[0]
  97.  
  98. #Make 3d plot of df_voters
  99. fig2 = plt.figure(figsize=(15,20))
  100. fig2.suptitle('Voter Density')
  101.  
  102. #histogram
  103. axa = fig2.add_subplot(211, projection='3d')
  104. hist, xedges, yedges = np.histogram2d(df_voters['x'], df_voters['y'], bins=20, range=[[-10, 10], [-10, 10]])
  105. xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
  106. xpos = xpos.ravel()
  107. ypos = ypos.ravel()
  108. zpos = 0
  109.  
  110. # Construct arrays with the dimensions for the bars.
  111. dx = dy = 0.5 * np.ones_like(zpos)
  112. dz = hist.ravel()
  113.  
  114. axa.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average')
  115. axa.set_xlabel('Economic')
  116. axa.set_ylabel('Government')
  117. axa.set_zlabel('Voter Count')
  118. axa.view_init(60, 240)
  119.  
  120. #surface
  121. X, Y = np.meshgrid(xedges[:-1] + 0.5, yedges[:-1] + 0.5, indexing="ij")
  122.  
  123. axb = fig2.add_subplot(212, projection='3d')
  124. surf = axb.plot_surface(X, Y, hist, cmap="jet", linewidth=0, antialiased=False)
  125. surf.set_edgecolors(surf.to_rgba(surf._A))
  126. #surf.set_facecolors("white")
  127. #cset = axb.contour(X, Y, hist, zdir='z', offset=-100, cmap=cm.coolwarm)
  128. #cset = axb.contour(X, Y, hist, zdir='x', offset=-40, cmap=cm.coolwarm)
  129. #cset = axb.contour(X, Y, hist, zdir='y', offset=40, cmap=cm.coolwarm)
  130. axb.set_xlabel('Economic')
  131. axb.set_ylabel('Government')
  132. axb.set_zlabel('Voter Count')
  133. axb.view_init(60, 240)
  134. fig2.colorbar(ax = axb, mappable = surf, shrink=0.5, aspect=5)
  135. fig2.savefig("3D_Population", dpi=300)
  136.        
  137. distance = pd.DataFrame()
  138. S = pd.DataFrame()
  139.        
  140. for c in candidates:
  141.     distance[c[0]] = df_voters[['x', 'y']].sub(np.array([c[1], c[2]])).pow(2).sum(1).pow(0.5)    
  142.     S[c[0]] = round(np.clip(K - distance[c[0]], 0, np.inf))
  143.  
  144. #rowwise max set to 5
  145. if maximize:
  146.     columns = distance.idxmin('columns')
  147.     for index in S.index:
  148.         S.loc[index,columns[index]] = 5
  149.  
  150. #define seleciton algorithm
  151. def get_winners(S_in,Selection = 'default'):
  152.     #print(Selection)
  153.     score_remaining = np.ones(V)
  154.     winner_list = []
  155.     while len(winner_list) < W:
  156.  
  157.         #select winner
  158.         if Selection == 'Monroe':
  159.             sum_scores = pd.DataFrame.from_records(np.sort(S_in.values, axis=0), columns = S_in.columns).tail(round(V/W)).sum()
  160.         else:            
  161.             sum_scores = S_in.sum()
  162.        
  163.         #print( sum_scores)  
  164.                    
  165.         #w = index with highest sum_scores
  166.         w = sum_scores.idxmax()  
  167.        
  168.         #print(w)
  169.            
  170.         winner_list.append(w)
  171.         surplus_factor = max( sum_scores[w] *W/V , 1)
  172.    
  173.         #Score spent on each winner by each voter
  174.         score_spent = S_in[w]/ surplus_factor
  175.        
  176.         #Total score left to be spent by each voter
  177.         score_remaining = np.clip(score_remaining-score_spent,0,1)
  178.    
  179.         #Update Ballots
  180.         #set scores to zero for winner so they don't win again
  181.         #S_in[w]=0
  182.         #Take score off of ballot (ie reweight)
  183.    
  184.         for c in S_in.columns:
  185.             S_in[c] = pd.DataFrame([S_in[c], score_remaining]).min()
  186.        
  187.     return winner_list
  188.  
  189. default_winners = get_winners(S_in=S.divide(K).copy(),Selection = 'default')
  190. monroe_winners = get_winners(S_in=S.divide(K).copy(),Selection = 'Monroe')
  191.  
  192.  
  193. print('Utilitarian Winner set is:')
  194. print(default_winners)
  195.  
  196. print('Monroe Winner set is:')
  197. print(monroe_winners)
  198.        
  199. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement