Advertisement
AmCholadawan

trophPlot v3

Jan 24th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. plot_title = "Trophallaxis Activity: Trophallaxis_Generous_Random & Levy"
  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.         'trophallaxis']
  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. # ->
  46. # 1 for Default avg area plot
  47. # 2 for Normalised area plot (Avg / (food/bots))
  48. drawY = 1
  49.  
  50. # ->
  51. # 0 don't draw error bars
  52. # 1 draw error bars
  53. drawError = 0
  54.  
  55. #
  56. path = []
  57. root = []
  58. testNumber = 'test14'
  59. #Levy_No_Trophallaxis Levy_Trophallaxis_Generous Random_No_Trophallaxis Random_Trophallaxis_Generous
  60. UTfolder = ['Random_Trophallaxis_Generous', 'Levy_Trophallaxis_Generous']
  61. trophFolder = 'test14Finitefood'
  62. #cwd='/Users/ammacpro1/AnacondaProjects/self_energy_robot/'+testNumber+'/'+UTfolder+'/'+trophFolder
  63. cwd='/Users/ammacpro1/simulation_results/self_energy_robot/'+testNumber
  64. #cwd = os.getcwd()
  65. #cwd = cwd + "/" + testNumber
  66. #root = cwd+'/'+UTfolder[0]+'/'+trophFolder
  67. for f in UTfolder:
  68.     path.append(cwd+'/'+f+'/'+trophFolder+'/Bot*/*Timestep.csv')
  69.     root.append(cwd+'/'+f+'/'+trophFolder)
  70. #init_food_per_groups = [32, 40, 48, 56, 64]
  71. #
  72.  
  73. fig, ax = plt.subplots()
  74.  
  75. def findGroupsB(root, ngroups):
  76.     # currently works only for a single UTfolder at once
  77.     #groups = {}
  78.     groups = []
  79.     for root_ut in root:
  80.         for g in range(ngroups):
  81.             #groups["Group" + str(g+1)] = glob(root + '/*Boundary' + str(g+1) + 'Max*')
  82.             #groups.append(glob(root + '/*Boundary' + str(g+1) + 'Max*/*Timestep.csv'))
  83.             groups.append(root_ut + '/*Boundary' + str(g+1) + '*/*Timestep.csv')
  84.     #print(groups)
  85.     return groups
  86.  
  87. def findGroupsF(root, group_types):
  88.     global ngroups
  89.     ngroups = len(group_types)
  90.     # currently works only for a single UTfolder at once
  91.     #groups = {}
  92.     groups = []
  93.     for root_ut in root:
  94.         for g in group_types:
  95.             #groups["Group" + str(g+1)] = glob(root + '/*Boundary' + str(g+1) + 'Max*')
  96.             #groups.append(glob(root + '/*Boundary' + str(g+1) + 'Max*/*Timestep.csv'))
  97.             groups.append(root_ut + '/*Food' + g + '*/*Timestep.csv')
  98.     #print(groups)
  99.     return groups
  100.  
  101. def analyseFolders(folder, curr_p, drawY, drawError):
  102.     files = glob(folder)
  103.     data = {}
  104.     for _data in data_to_import:
  105.         data[_data] = []
  106.     #indexesOfInterest = [0, 2, 7] # count, food_patches, trophallaxis
  107.     for file in files:
  108.         #print(file)
  109.         with open(file, 'rt') as f:
  110.             reader = csv.reader(f, delimiter=',')
  111.             for row in reader:
  112.                 #print(row)
  113.                 if row[0].isdigit():
  114.                     #currentIndex = 0
  115.                     #for _data in data_to_import:
  116.                         ##if row[0] in [_data]:
  117.                         ##    data[_data].append(row[1])
  118.                         #data[_data].append(row[currentIndex])
  119.                         #currentIndex += 1
  120.                     data[data_to_import[0]].append(row[0])
  121.                     data[data_to_import[1]].append(row[2])
  122.                     data[data_to_import[2]].append(row[7])
  123.  
  124.     '''
  125.    print(data["trophallaxis"])
  126.    print(len(data))
  127.    print(len(data[data_to_import[0]]))
  128.    print(len(data[data_to_import[1]]))
  129.    print(len(data[data_to_import[2]]))
  130.    '''
  131.  
  132.     sorted_data = dict.fromkeys(data.keys(),[])
  133.     data_to_plot = {}
  134.  
  135.     keys = [key for key, value in data.items()]
  136.     #print(keys)
  137.  
  138.     timeSteps = sorted(list(set(data["count"])), key=int)
  139.     foodPatchSize = sorted(list(set(data["food_patches"])), key=int)
  140.    
  141.     #timeSteps = [int(x) for x in timeSteps]
  142.     #foodPatchSize= [int(x) for x in foodPatchSize]
  143.     #print(foodPatchSize)
  144.     #input("Press Enter to terminate.")
  145.    
  146.     '''
  147.    for SSize in timeSteps:
  148.        for PSize in foodPatchSize:
  149.            data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize] = \
  150.                    [float(i)
  151.                            for i, j, k in zip(
  152.                                data["trophallaxis"],
  153.                                data["count"],
  154.                                data["food_patches"])
  155.                            if j == SSize and k == PSize]
  156.    '''
  157.     for SSize in timeSteps:
  158.         data_to_plot["trophallaxis_ts" + SSize] = \
  159.                 [float(i)
  160.                         for i, j in zip(
  161.                             data["trophallaxis"],
  162.                             data["count"])
  163.                         if j == SSize]
  164.  
  165.     #print(data_to_plot)
  166.     #input("Press Enter to terminate.")
  167.  
  168.     #colors = iter(cm.Greys(np.linspace(0.4, 1, len(foodPatchSize))))
  169.     #colors = cm.rainbow(np.linspace(0.4, 1, len(UTfolder)))
  170.     #widths = np.linspace(2, 0.5, len(UTfolder))
  171.     colors = cm.rainbow(np.linspace(0.4, 1, ngroups))
  172.     widths = np.linspace(2, 0.5, ngroups)
  173.     c = colors[curr_p % ngroups]
  174.     w = widths[curr_p % ngroups]
  175.  
  176.     #fig, ax = plt.subplots()
  177.     #data_dict = {k:v for (k,v) in data_to_plot.items() if _data in k}
  178.  
  179.     Markers = ['+','s','^','o','p']
  180.     LineTypes = ['-','--','-.',':']
  181.     LineStyles = [LineTypes[r] for r in (range(len(root) % len(LineTypes))) for i in range(ngroups)]
  182.     #MarkerIndex = 0;
  183.  
  184.     data_mean = []
  185.     data_sd = []
  186.    
  187.     '''
  188.    for SSize in timeSteps:
  189.        for PSize in foodPatchSize:
  190.            #food_dict = {k: v for (k, v) in data_dict.items() if PSize in k}
  191.            vals = []
  192.            sd = []
  193.            if len(data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize]) > 0:
  194.                vals = np.mean(data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize])
  195.                if (drawError):
  196.                    sd = np.std(data_to_plot["trophallaxis_ts" + SSize + "_food" + PSize])
  197.                else:
  198.                    sd = 0
  199.            else:
  200.                vals = 0
  201.                sd = 0
  202.            #if (drawY == 2):
  203.            #    vals /= (int(PSize)/int(SSize))
  204.            data_mean.append(vals)
  205.            data_sd.append(sd)
  206.    '''
  207.  
  208.     for SSize in timeSteps:
  209.         vals = []
  210.         sd = []
  211.         if len(data_to_plot["trophallaxis_ts" + SSize]) > 0:
  212.             vals = np.mean(data_to_plot["trophallaxis_ts" + SSize])
  213.             if (drawError):
  214.                 sd = np.std(data_to_plot["trophallaxis_ts" + SSize])
  215.             else:
  216.                 sd = 0
  217.         else:
  218.             vals = 0
  219.             sd = 0
  220.         #if (drawY == 2):
  221.         #    vals /= (int(PSize)/int(SSize))
  222.         data_mean.append(vals)
  223.         data_sd.append(sd)
  224.  
  225.     timeSteps = [int(x) for x in timeSteps]
  226.     foodPatchSize= [int(x) for x in foodPatchSize]
  227.  
  228.     #print(timeSteps)
  229.     #print(foodPatchSize)
  230.     #input("Press Enter to terminate.")
  231.  
  232.     ax.errorbar(timeSteps,
  233.             data_mean,
  234.             data_sd,
  235.             #sd, fmt = 'o',
  236.             #capsize = 2,
  237.             linestyle = LineStyles[curr_p % len(LineStyles)],
  238.             #linestyle = "None",
  239.             linewidth = w,
  240.             marker = Markers[curr_p % len(Markers)],
  241.             #marker='o',
  242.             color=c,
  243.             #label="Number of food patches = " + str(PSize))
  244.             #label=UTfolder[curr_p])
  245.             label=("Group " + str((curr_p // ngroups) +1) + "-" + str((curr_p % ngroups) + 1)))
  246.  
  247.     ax.set_title(plot_title)
  248.     ax.legend(frameon=False, loc="best", prop={'size': 10})
  249.     ax.set_xlabel("Timesteps")
  250.     if (drawY == 1):
  251.         ax.set_ylabel("Average Trophallaxis")
  252.     #elif (drawY == 2):
  253.     #    ax.set_ylabel("Normalised Average Area: Avg/(food/bots)")
  254.     #ax.set_title(plot_title)
  255.  
  256.     #plotname = path + '/' + plot_title + "_" + _data
  257.     #fig.savefig(plotname + '.pdf', orientation='landscape')
  258.     #fig.savefig(plotname + '.png', orientation='landscape')
  259.     #plt.show()
  260.  
  261. curr_p = 0
  262. if findType == 'Boundary':
  263.     groups = findGroupsB(root, ngroups)
  264. elif findType == 'Food':
  265.     groups = findGroupsF(root, group_types)
  266. #print(groups)
  267. for group in groups:
  268.     #for p in path:
  269.     analyseFolders(group, curr_p, drawY, drawError)
  270.     curr_p += 1
  271.  
  272. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement