TomBee

UROS Code

Aug 23rd, 2021
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.44 KB | None | 0 0
  1. ##Lissajous Curve Generation##
  2. import numpy as np
  3. from matplotlib import pyplot as plt
  4. from math import pi
  5. import matplotlib.animation as animation
  6. import time, os
  7. ##plt.rcParams['animation.ffmpeg_path'] = 'C:\ffmpeg\bin'
  8.  
  9. frame = 599  #number of frames wanted
  10. fps_val = 60
  11. t=np.linspace(0, 2 * pi, 1200) #creates an array of 1200 equally spaced
  12.                             #elements from zero to 2*pi (inclusive)
  13.                             #The higher the number, the smoother the lines
  14.  
  15. #first set of parameters
  16. A = 100
  17. B = 100
  18. a1 = 1
  19. b1 = 5
  20. delta = 0  #initial delta
  21.  
  22. delta_increase = np.linspace(0, 2*pi, frame) #Array containing the points of one
  23.                                 #2*pi rotation. With frame evenly spaced points
  24. ##print(len(delta_increase))
  25.  
  26. def calcFullData(deltaList):
  27.     """
  28.    Function calculates the full LJ curve data array for the animation function
  29.    the length of the array is the length of delta_increase
  30.    """
  31.     xdata = [A * np.sin(a1 * t + deltaList[i]) for i in range(len(deltaList))]
  32.     ydata = [B * np.sin(b1 * t) for j in range(len(deltaList))]
  33.  
  34.     return xdata, ydata
  35.  
  36. #These two functions calculate the data points for the inital plot
  37. def x1(delta):
  38.     return A * np.sin(a1 * t + delta)
  39.  
  40. def y1():
  41.     return B * np.sin(b1 * t)
  42. #########################
  43.  
  44. X1, Y1 = calcFullData(delta_increase)
  45. num = 0  #naming variable to systematically name the images
  46. def update(i):
  47.     """
  48.    Animation update function, matplotlib animation works by removing old
  49.    frames and redrawing new ones.
  50.    In this case, the new points are the next data elements from the array
  51.    calculated from the calcFullData function
  52.    """
  53.     global num
  54.     curve.set_data(X1[i], Y1[i]) #set the new plots
  55.     #save the figure (the frame) and name it, dpi controls quality. The higher the better
  56.     plt.savefig('{0}/Master/b4/rot_0.5/img{1}.png'.format(os.getcwd(), str(num).zfill(6)), dpi = 150)
  57.  
  58.     ##{0}/Master/b3/rot_0.5/img{1}.png is the file directory to where you want to save the image
  59.  
  60.     ##To save the images in the same folder as the script just use
  61.     ##plt.savefig('img{0}.png'.format(str(num)), dpi = [number])
  62.  
  63.     ##To save the figure in a different folder (Folder must be with the script) use
  64.     ##plt.savefig('{0}/FOLDER PATH/img{1}.png'.format(os.getcwd(), str(num).zfill(6)), dpi = 150)
  65.  
  66.     num += 1 #update the numbering variable
  67.     return curve, #return the new data point to the animation window
  68.  
  69. f = plt.figure() #define the figure
  70. plt.axis('off')#turn off teh axi
  71. ##dot = plt.scatter(0, 0 , color="red", s = 7)  #add a focusing dot if needed
  72. curve, = plt.plot(x1(delta), y1(), color='blue') ##Linewidth can be altered w/ , linewidth=1
  73. #animation variable that stores how matplotlib should redraw the animation
  74. #and in our case, how it should update and save each frame
  75. ani = animation.FuncAnimation(
  76.                         f,
  77.                         update,
  78.                         frames=len(delta_increase),
  79.                         interval=(1.6667),
  80.                         repeat=True,
  81.                         blit=True)
  82. plt.show() #needed in order for the plots to save
  83. #the window show an empty plot, that is normal. The figures will still save
  84.  
  85. #################################################################################################
  86.  
  87. ##Lissajous Curve Copy Tool - Copies files to later compile into video##
  88. import shutil
  89. import os
  90.  
  91. newimg = 600 #naming variable that names the copied files
  92. #initial starting number is +1 the final frame number
  93. #e.g. If you have 599 initial frames, newimg starts at 600
  94.  
  95. folderPath =  r'C:\Users\Thomas\Desktop\Python\Master\b4\rot_0.5\\'
  96. #directory to the initial images, to change use
  97. #    r'[Directory\to\images]\\'
  98. #must leave the r, must end with \\
  99.  
  100. for i in range(119): #this loop defines the number of batch copies you want
  101.     curr = 0 #naming variable to keep track of the frame we are coping
  102.     for i in range(599): #this loop copies all the initial 599 frames once
  103.         #Below copies the ith frame and renames it the the 'newimg'th frame
  104.         shutil.copy2('{0}/img{1}.png'.format(folderPath, str(curr).zfill(6)), '{0}/img{1}.png'.format(folderPath, str(newimg).zfill(6)))
  105.         newimg += 1    #update the copied image number
  106.         curr += 1     #switch to the next frame to copy
  107.  
  108. ###################################################################################################
  109.  
  110. ## Main Experiment Script - To display LJ Curves and Record Mouse Clicks##
  111. from tkinter import *
  112. import sys, time, os, math
  113. from datetime import datetime
  114. from contextlib import redirect_stdout
  115. import numpy as np
  116. import matplotlib.pyplot as plt
  117. from os import startfile
  118.  
  119. for runs in range(18):
  120.     video_to_play = input("Enter Speed : ")
  121.     lobe_parameter = input("Enter Lobe Parameter : ")
  122.     run_num = input("Enter the run number : ")
  123.  
  124.     time.sleep(5)
  125.  
  126.     startfile('{0}/videos/{1}/{2}.mp4'.format(os.getcwd(), lobe_parameter, video_to_play))
  127.  
  128.     log = []
  129.     timestamp = []
  130.     order = []
  131.     start = datetime.now()
  132.  
  133.     global l,r,m
  134.     l = 0
  135.     r = 0
  136.     m = 0
  137.     log.append("Started block period at {0}\n".format(start))
  138.     main = Tk()
  139.     main.attributes('-fullscreen',True)
  140.  
  141.     def Quit(event):
  142.         main.destroy()
  143.         end = datetime.now()
  144.         timestamp.append(end)
  145.         log.append("\nBlock period terminated at {0}".format(end))
  146.  
  147.     def leftClick(event):
  148.         global l; now = datetime.now()
  149.         timestamp.append(now)
  150.         log.append("L Click at {0}".format(now.strftime("%H:%M:%S:%f"))); order.append('Left')
  151.         l += 1
  152.         return
  153.  
  154.     def rightClick(event):
  155.         global r; now = datetime.now()
  156.         timestamp.append(now)
  157.         log.append("R Click at {0}".format(now.strftime("%H:%M:%S:%f"))); order.append('Right')
  158.         r += 1
  159.         return
  160.  
  161.     def middleClick(event):
  162.         global m; now = datetime.now()
  163.         timestamp.append(now)
  164.         log.append("M Click at {0}".format(now.strftime("%H:%M:%S:%f"))); order.append('Middle')
  165.         m += 1
  166.         return
  167.  
  168.     main.bind('<Button-1>', leftClick)
  169.     main.bind('<Button-3>', rightClick)
  170.     main.bind('<Button-2>', middleClick)
  171.     main.bind('<q>', Quit)
  172.  
  173.     main.focus()
  174.     main.mainloop()
  175.     ###############################################################################
  176.     with open('{0}/logs/{1}/Rotation_{2}_{3}_{4}.txt'.format(os.getcwd(), lobe_parameter, lobe_parameter,video_to_play, run_num), 'w') as f:
  177.         with redirect_stdout(f):
  178.             print("***Summary***")
  179.             print("Block for parameters *** gave the following results\nLeft Click(**) - {0}\nRight Click(**) - {1}\nMiddle Mouse Click(Unclear) - {2}\n".format(l,r,m))
  180.             print("Clicks were in the following order:")
  181.             for i in order:
  182.                 print(i)
  183.             print('\n\n***Specifics***')
  184.             for i in log:
  185.                 print(i)
  186.     with open('{0}/logs/{1}/Rotation_{2}_{3}_{4}_technicaldata.txt'.format(os.getcwd(), lobe_parameter, lobe_parameter, video_to_play, run_num), 'w') as f:
  187.         with redirect_stdout(f):
  188.             print(log)
  189.             print(timestamp)
  190.  
  191.     delta_ts = []
  192.     log.remove(log[0]); log.remove(log[-1])
  193.     timestamp.remove(timestamp[-1])
  194.  
  195.     a = timestamp[0] #current timestamp
  196.     for i in range(len(log) - 1):
  197.         b = timestamp[i + 1]  #next time stamp
  198.         delta_ts.append((b-a).total_seconds()) #difference in seconds
  199.         a = timestamp[i + 1]  #current timestamp now b
  200.  
  201.     print(delta_ts)
  202.     time.sleep(2)
  203.  
  204. ####################################################################################
  205.  
  206. ##Analysis of Data##
  207. import datetime, os, ast, math, sys
  208. import numpy as np
  209. import matplotlib.pyplot as plt
  210. from contextlib import redirect_stdout
  211.  
  212. combined_dts = []
  213. tests = int(input("How many times did you test this LJ curve? : "))
  214. values = ['2','3','4']
  215. speeds = ['0.625','0.833','1','2','3.33','5']
  216. ##rot = input("Enter Rotation Speed to analyse : ")
  217. ##lobe_param = input("What value of b did you want to analyse? : ")
  218. for val in values:
  219.     for speed in speeds:
  220.         rot = speed
  221.         lobe_param = val
  222.  
  223.         with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'w') as f:
  224.             with redirect_stdout(f):
  225.                 print("")
  226.         f.close()
  227.  
  228.  
  229.         for num in range(1, tests+1):
  230.             f = open('{0}/logs/b{1}/Rotation_b{1}_{2}_{3}_technicaldata.txt'.format(os.getcwd(), lobe_param, rot, num), 'r')
  231.             log = f.readline()
  232.             log = ast.literal_eval(log)
  233.  
  234.  
  235.             timestamps = f.readline()
  236.             timestamps = eval(timestamps)
  237.             f.close()
  238.             delta_ts = []
  239.             order = []
  240.  
  241.             log.remove(log[0]); log.remove(log[-1])
  242.             timestamps.remove(timestamps[-1])
  243.  
  244.             a = timestamps[0] #current timestamp
  245.             for i in range(len(log)):
  246.                 try:
  247.                     order.append(log[i][0])
  248.                     b = timestamps[i + 1]  #next time stamp
  249.                     delta_ts.append((b-a).total_seconds()) #difference in seconds
  250.                     a = timestamps[i + 1]  #current timestamp now b
  251.                 except:
  252.                     pass
  253. ##                    with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
  254. ##                        with redirect_stdout(f):
  255. ##                            print("Unable to perform an anlysis of b{0}_{1}_Dataset_{2} due to insufficient number of data points".format(lobe_param, rot, num))
  256. ##                            break
  257.  
  258.             try:
  259.                 marker = [] #job is to hold the indexes of the data points that cannot stay
  260.                 for j in range(len(delta_ts) - 1):
  261.                     if order[j] == order[j+1]:
  262.                         marker.append(j); marker.append(j+1)
  263.                     if order[j] == 'M':
  264.                         marker.append(j)
  265.  
  266.                 counter = 0 #marks the number of deletions
  267.             ##    print(len(marker))
  268.                 for mark in range(len(marker)):
  269.                     delta_ts.remove(delta_ts[mark - counter])
  270.                     counter += 1
  271.                 for j in delta_ts:
  272.                     combined_dts.append(j)
  273.  
  274.                 with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
  275.                     with redirect_stdout(f):
  276.                         print("{0} items removed from analysis of b{1}_{2}_Dataset_{3} due to".format(len(marker), lobe_param, rot, num))
  277.                         print("*Accidental misclicks causing two or more of the same directional mouse click\n*Middle mouse was pressed and following delta t had to be ignored")
  278.             except:
  279.                  with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
  280.                         with redirect_stdout(f):
  281.                             print("No histogram data generated")
  282.                             sys.exit()
  283.             f.close()
  284.         nopoints = len(combined_dts)
  285.         # Plotting the histogram
  286.         n, bins, patches = plt.hist(x=combined_dts, bins=math.ceil(math.sqrt(nopoints)), color='#0504aa')
  287.         plt.grid(axis='y', alpha=0.75)
  288.         plt.xlabel('Range of delta t')
  289.         plt.ylabel('Frequency')
  290.         plt.title('Histogram of time until state change recorded for {0} lobes at speed {1}'.format(lobe_param, rot))
  291.         maxfreq = n.max()
  292.         # Set a clean upper y-axis limit.
  293.         plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
  294.         plt.savefig('{0}/logs/b{1}/analysis/Figure_of_b{1}_Rotation_{2}.png'.format(os.getcwd(), lobe_param, rot).format(os.getcwd(), str(num).zfill(6)), dpi = 200)
  295.         print("Figure saved to {0}/logs/b{1}/analysis/".format(os.getcwd(), lobe_param))
  296.         print("Analysis of technical data saved to {0}/Logs/b{1}/analysis/".format(os.getcwd(), lobe_param))
  297.         with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
  298.             with redirect_stdout(f):
  299.                 print("n : {0}\nbins : {1}".format(n, bins))
  300.     ##        plt.show()
  301.         n, bins, patches, maxfreq = 0,0,0,0
  302.         plt.clf()
  303.         combined_dts = []
  304.  
Advertisement
Add Comment
Please, Sign In to add comment