Advertisement
AmCholadawan

Foodremove_compare

Mar 22nd, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.12 KB | None | 0 0
  1. from matplotlib import pyplot as plt
  2. import numpy as np
  3. import os
  4. from glob import glob
  5. import csv
  6. import matplotlib.cm as cm
  7. from collections import OrderedDict
  8. import ast
  9. import re
  10. import fnmatch
  11.  
  12. # data decription for plot titles
  13. dataSetName = "ScavengeTroph2017-05-28_"
  14.  
  15.  
  16. '''
  17. # the path to the data from where the current file is saved
  18. dirname = os.path.abspath(os.path.join(
  19.   os.path.dirname( __file__ ),
  20.   '../../../..',
  21.   "self_energy_robot"
  22.   + "/" + "steptaken_infinitefood"
  23.   ))
  24.  
  25. path = dirname + "/" + dataSetName
  26. #print(path)
  27. extension   = "*Summary.csv"
  28. files = []
  29.  
  30. for dir,_,_ in os.walk(path):
  31.   files.extend(glob(os.path.join(dir,extension)))
  32. '''
  33.  
  34. data_to_import = ['count',
  35.         'food_patches',
  36.         'total_food']
  37.  
  38. # 'Boundary' or 'Food'
  39. findType = 'Boundary'
  40. # use the following variable if you want to group by Boundary#
  41. ngroups = 5
  42. # use the following variable if you want to group by Food##
  43. group_types = ['25', '81']
  44.  
  45. boundary_values = [1, 3, 5]
  46. if len(boundary_values) != 0:
  47.     ngroups = len(boundary_values)
  48.  
  49. # ->
  50. # 1 for Default avg area plot
  51. # 2 for Normalised area plot (Avg / (food/bots))
  52. drawY = 1
  53.  
  54. # ->
  55. # 0 don't draw error bars
  56. # 1 draw error bars
  57. drawError = 0
  58.  
  59. #
  60. path = []
  61. root = []
  62. testNumber = 'test18'
  63. #Levy_No_Trophallaxis Levy_Trophallaxis_Generous Random_No_Trophallaxis Random_Trophallaxis_Generous
  64. #UTfolder = ['Levywalklike_Trophallaxis_Generous', 'Random_Trophallaxis_Generous']
  65. UTfolder = ['Levy_walk_with_Trophallaxis',
  66.             #'Levy_walk_none_Trophallaxis',
  67.             #'Levy_walk_with_TrophallaxisP90',
  68.             #'Levy_walk_none_TrophallaxisP90',
  69.             'Random_walk_with_Trophallaxis',
  70.             #'Random_walk_none_Trophallaxis',
  71.             #'Levyrandom_with_Trophallaxis',
  72.             #'Levyrandom_none_Trophallaxis'
  73.             ]
  74.  
  75. UTplotNames = ['Levy walk',
  76.             #'Levy_walk_none_Trophallaxis',
  77.             #'Levy_walk_with_TrophallaxisP90',
  78.             #'Levy_walk_none_TrophallaxisP90',
  79.             'Random walk',
  80.             #'Random_walk_none_Trophallaxis',
  81.             #'Levyrandom_with_Trophallaxis',
  82.             #'Levyrandom_none_Trophallaxis'
  83.             ]
  84.  
  85. trophFolder = 'Bots81'
  86. #cwd='/Users/ammacpro1/AnacondaProjects/self_energy_robot/'+testNumber+'/'+UTfolder+'/'+trophFolder
  87. cwd='/Users/ammacpro1/simulation_results/self_energy_robot/'+testNumber
  88. #cwd = os.getcwd()
  89. #cwd = cwd + "/" + testNumber
  90. #root = cwd+'/'+UTfolder[0]+'/'+trophFolder
  91. for f in UTfolder:
  92.     path.append(cwd+'/'+f+'/'+trophFolder+'/Bot*/*Timestep.csv')
  93.     root.append(cwd+'/'+f+'/'+trophFolder)
  94. #init_food_per_groups = [32, 40, 48, 56, 64]
  95. #
  96. plot_title = "Total Food: " + trophFolder + " Finite Food: Random Troph vs Levy Troph"  
  97. fig, ax = plt.subplots()
  98.  
  99. def findGroupsB(root, ngroups):
  100.     # currently works only for a single UTfolder at once
  101.     #groups = {}
  102.     groups = []
  103.     for root_ut in root:
  104.         for g in range(ngroups):
  105.             #groups["Group" + str(g+1)] = glob(root + '/*Boundary' + str(g+1) + 'Max*')
  106.             #groups.append(glob(root + '/*Boundary' + str(g+1) + 'Max*/*Timestep.csv'))
  107.             #groups.append(root_ut + '/*Boundary' + str(g+1) + '*/*Timestep.csv')
  108.             if boundary_values == []:
  109.                 groups.append(root_ut + '/*Boundary' + str(g+1) + '*/*Timestep.csv')
  110.             else:
  111.                 groups.append(root_ut + '/*Boundary' + str(boundary_values[g]) + '*/*Timestep.csv')
  112.     #print(groups)
  113.     return groups
  114.  
  115. def findGroupsF(root, group_types):
  116.     global ngroups
  117.     ngroups = len(group_types)
  118.     # currently works only for a single UTfolder at once
  119.     #groups = {}
  120.     groups = []
  121.     for root_ut in root:
  122.         for g in group_types:
  123.             #groups["Group" + str(g+1)] = glob(root + '/*Boundary' + str(g+1) + 'Max*')
  124.             #groups.append(glob(root + '/*Boundary' + str(g+1) + 'Max*/*Timestep.csv'))
  125.             groups.append(root_ut + '/*Food' + g + '*/*Timestep.csv')
  126.     #print(groups)
  127.     return groups
  128.  
  129. def analyseFolders(folder, curr_p, drawY, drawError):
  130.     files = glob(folder)
  131.     data = {}
  132.     for _data in data_to_import:
  133.         data[_data] = []
  134.     #indexesOfInterest = [0, 2, 7] # count, food_patches, trophallaxis
  135.     for file in files:
  136.         #print(file)
  137.         with open(file, 'rt') as f:
  138.             reader = csv.reader(f, delimiter=',')
  139.             for row in reader:
  140.                 #print(row)
  141.                 if row[0].isdigit():
  142.                     #currentIndex = 0
  143.                     #for _data in data_to_import:
  144.                         ##if row[0] in [_data]:
  145.                         ##    data[_data].append(row[1])
  146.                         #data[_data].append(row[currentIndex])
  147.                         #currentIndex += 1
  148.                     data[data_to_import[0]].append(row[0])
  149.                     data[data_to_import[1]].append(row[2])
  150.                     data[data_to_import[2]].append(row[1])
  151.  
  152.     '''
  153.   print(data["trophallaxis"])
  154.   print(len(data))
  155.   print(len(data[data_to_import[0]]))
  156.   print(len(data[data_to_import[1]]))
  157.   print(len(data[data_to_import[2]]))
  158.   '''
  159.  
  160.     sorted_data = dict.fromkeys(data.keys(),[])
  161.     data_to_plot = {}
  162.  
  163.     keys = [key for key, value in data.items()]
  164.     #print(keys)
  165.  
  166.     timeSteps = sorted(list(set(data["count"])), key=int)
  167.     foodPatchSize = sorted(list(set(data["food_patches"])), key=int)
  168.    
  169.     #timeSteps = [int(x) for x in timeSteps]
  170.     #foodPatchSize= [int(x) for x in foodPatchSize]
  171.     #print(foodPatchSize)
  172.     #input("Press Enter to terminate.")
  173.    
  174.     '''
  175.   for SSize in timeSteps:
  176.       for PSize in foodPatchSize:
  177.           data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize] = \
  178.                   [float(i)
  179.                           for i, j, k in zip(
  180.                               data["trophallaxis"],
  181.                               data["count"],
  182.                               data["food_patches"])
  183.                           if j == SSize and k == PSize]
  184.   '''
  185.     for SSize in timeSteps:
  186.         data_to_plot["total_food_ts" + SSize] = \
  187.                 [float(i)
  188.                         for i, j in zip(
  189.                             data["total_food"],
  190.                             data["count"])
  191.                         if j == SSize]
  192.  
  193.     #print(data_to_plot)
  194.     #input("Press Enter to terminate.")
  195.  
  196.     #colors = iter(cm.Greys(np.linspace(0.4, 1, len(foodPatchSize))))
  197.     #colors = cm.rainbow(np.linspace(0.4, 1, len(UTfolder)))
  198.     #widths = np.linspace(2, 0.5, len(UTfolder))
  199.     #colors = cm.gray(np.linspace(0.1, 0.8, len(ngroups)))
  200.     colors = cm.gray(np.linspace(0.1, 0.5, ngroups))
  201.     #colors = cm.rainbow(np.linspace(0.4, 1, ngroups))
  202.     widths = np.linspace(1.5, 1, ngroups)
  203.     c = colors[curr_p % ngroups]
  204.     w = widths[curr_p % ngroups]
  205.  
  206.     #fig, ax = plt.subplots()
  207.     #data_dict = {k:v for (k,v) in data_to_plot.items() if _data in k}
  208.  
  209.     Markers = ['+','s','^','o','p']
  210.     LineTypes = ['-','--','-.',':']
  211.     LineStyles = [LineTypes[r] for r in (range(len(root) % len(LineTypes))) for i in range(ngroups)]
  212.     #MarkerIndex = 0;
  213.  
  214.     data_mean = []
  215.     data_sd = []
  216.    
  217.     '''
  218.   for SSize in timeSteps:
  219.       for PSize in foodPatchSize:
  220.           #food_dict = {k: v for (k, v) in data_dict.items() if PSize in k}
  221.           vals = []
  222.           sd = []
  223.           if len(data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize]) > 0:
  224.               vals = np.mean(data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize])
  225.               if (drawError):
  226.                   sd = np.std(data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize])
  227.               else:
  228.                   sd = 0
  229.           else:
  230.               vals = 0
  231.               sd = 0
  232.           #if (drawY == 2):
  233.           #    vals /= (int(PSize)/int(SSize))
  234.           data_mean.append(vals)
  235.           data_sd.append(sd)
  236.   '''
  237.  
  238.     for SSize in timeSteps:
  239.         vals = []
  240.         sd = []
  241.         if len(data_to_plot["total_food_ts" + SSize]) > 0:
  242.             vals = np.mean(data_to_plot["total_food_ts" + SSize])
  243.             if (drawError):
  244.                 sd = np.std(data_to_plot["total_food_ts" + SSize])
  245.             else:
  246.                 sd = 0
  247.         else:
  248.             vals = 0
  249.             sd = 0
  250.         #if (drawY == 2):
  251.         #    vals /= (int(PSize)/int(SSize))
  252.         data_mean.append(vals)
  253.         data_sd.append(sd)
  254.  
  255.     timeSteps = [int(x) for x in timeSteps]
  256.     foodPatchSize= [int(x) for x in foodPatchSize]
  257.  
  258.     #print(timeSteps)
  259.     #print(foodPatchSize)
  260.     #input("Press Enter to terminate.")
  261.  
  262.     ax.errorbar(timeSteps,
  263.             data_mean,
  264.             data_sd,
  265.             #sd, fmt = 'o',
  266.             #capsize = 2,
  267.             linestyle = LineStyles[curr_p % len(LineStyles)],
  268.             #linestyle = "None",
  269.             linewidth = w,
  270.             #marker = Markers[curr_p % len(Markers)],
  271.             #marker='o',
  272.             color=c,
  273.             #label="Number of food patches = " + str(PSize))
  274.             #label=UTfolder[curr_p])
  275.             #label=("Group " + str((curr_p // ngroups) +1) + "-" + str((curr_p % ngroups) + 1)))
  276.             #label=(UTplotNames[curr_p // ngroups] + "-food distance:" + str((curr_p % ngroups) + 1)))
  277.             label=(UTplotNames[curr_p // ngroups] + "-food distance:" + str(boundary_values[curr_p % ngroups])))
  278.    
  279.     #ax.set_title(plot_title)
  280.     ax.legend(frameon=False, loc="best", prop={'size': 10})
  281.     ax.set_xlabel("Time steps")
  282.     if (drawY == 1):
  283.         ax.set_ylabel("Total Food")
  284.     elif (drawY == 2):
  285.         ax.set_ylabel("Total Food/(food/bots)")
  286.    
  287.     #ax.set_title(plot_title)
  288.  
  289.     #plotname = path + '/' + plot_title + "_" + _data
  290.     #fig.savefig(plotname + '.pdf', orientation='landscape')
  291.     #fig.savefig(plotname + '.png', orientation='landscape')
  292.     #plt.show()
  293.  
  294. curr_p = 0
  295. if findType == 'Boundary':
  296.     groups = findGroupsB(root, ngroups)
  297. elif findType == 'Food':
  298.     groups = findGroupsF(root, group_types)
  299. #print(groups)
  300. for group in groups:
  301.     #for p in path:
  302.     analyseFolders(group, curr_p, drawY, drawError)
  303.     curr_p += 1
  304.  
  305. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement