Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##Lissajous Curve Generation##
- import numpy as np
- from matplotlib import pyplot as plt
- from math import pi
- import matplotlib.animation as animation
- import time, os
- ##plt.rcParams['animation.ffmpeg_path'] = 'C:\ffmpeg\bin'
- frame = 599 #number of frames wanted
- fps_val = 60
- t=np.linspace(0, 2 * pi, 1200) #creates an array of 1200 equally spaced
- #elements from zero to 2*pi (inclusive)
- #The higher the number, the smoother the lines
- #first set of parameters
- A = 100
- B = 100
- a1 = 1
- b1 = 5
- delta = 0 #initial delta
- delta_increase = np.linspace(0, 2*pi, frame) #Array containing the points of one
- #2*pi rotation. With frame evenly spaced points
- ##print(len(delta_increase))
- def calcFullData(deltaList):
- """
- Function calculates the full LJ curve data array for the animation function
- the length of the array is the length of delta_increase
- """
- xdata = [A * np.sin(a1 * t + deltaList[i]) for i in range(len(deltaList))]
- ydata = [B * np.sin(b1 * t) for j in range(len(deltaList))]
- return xdata, ydata
- #These two functions calculate the data points for the inital plot
- def x1(delta):
- return A * np.sin(a1 * t + delta)
- def y1():
- return B * np.sin(b1 * t)
- #########################
- X1, Y1 = calcFullData(delta_increase)
- num = 0 #naming variable to systematically name the images
- def update(i):
- """
- Animation update function, matplotlib animation works by removing old
- frames and redrawing new ones.
- In this case, the new points are the next data elements from the array
- calculated from the calcFullData function
- """
- global num
- curve.set_data(X1[i], Y1[i]) #set the new plots
- #save the figure (the frame) and name it, dpi controls quality. The higher the better
- plt.savefig('{0}/Master/b4/rot_0.5/img{1}.png'.format(os.getcwd(), str(num).zfill(6)), dpi = 150)
- ##{0}/Master/b3/rot_0.5/img{1}.png is the file directory to where you want to save the image
- ##To save the images in the same folder as the script just use
- ##plt.savefig('img{0}.png'.format(str(num)), dpi = [number])
- ##To save the figure in a different folder (Folder must be with the script) use
- ##plt.savefig('{0}/FOLDER PATH/img{1}.png'.format(os.getcwd(), str(num).zfill(6)), dpi = 150)
- num += 1 #update the numbering variable
- return curve, #return the new data point to the animation window
- f = plt.figure() #define the figure
- plt.axis('off')#turn off teh axi
- ##dot = plt.scatter(0, 0 , color="red", s = 7) #add a focusing dot if needed
- curve, = plt.plot(x1(delta), y1(), color='blue') ##Linewidth can be altered w/ , linewidth=1
- #animation variable that stores how matplotlib should redraw the animation
- #and in our case, how it should update and save each frame
- ani = animation.FuncAnimation(
- f,
- update,
- frames=len(delta_increase),
- interval=(1.6667),
- repeat=True,
- blit=True)
- plt.show() #needed in order for the plots to save
- #the window show an empty plot, that is normal. The figures will still save
- #################################################################################################
- ##Lissajous Curve Copy Tool - Copies files to later compile into video##
- import shutil
- import os
- newimg = 600 #naming variable that names the copied files
- #initial starting number is +1 the final frame number
- #e.g. If you have 599 initial frames, newimg starts at 600
- folderPath = r'C:\Users\Thomas\Desktop\Python\Master\b4\rot_0.5\\'
- #directory to the initial images, to change use
- # r'[Directory\to\images]\\'
- #must leave the r, must end with \\
- for i in range(119): #this loop defines the number of batch copies you want
- curr = 0 #naming variable to keep track of the frame we are coping
- for i in range(599): #this loop copies all the initial 599 frames once
- #Below copies the ith frame and renames it the the 'newimg'th frame
- shutil.copy2('{0}/img{1}.png'.format(folderPath, str(curr).zfill(6)), '{0}/img{1}.png'.format(folderPath, str(newimg).zfill(6)))
- newimg += 1 #update the copied image number
- curr += 1 #switch to the next frame to copy
- ###################################################################################################
- ## Main Experiment Script - To display LJ Curves and Record Mouse Clicks##
- from tkinter import *
- import sys, time, os, math
- from datetime import datetime
- from contextlib import redirect_stdout
- import numpy as np
- import matplotlib.pyplot as plt
- from os import startfile
- for runs in range(18):
- video_to_play = input("Enter Speed : ")
- lobe_parameter = input("Enter Lobe Parameter : ")
- run_num = input("Enter the run number : ")
- time.sleep(5)
- startfile('{0}/videos/{1}/{2}.mp4'.format(os.getcwd(), lobe_parameter, video_to_play))
- log = []
- timestamp = []
- order = []
- start = datetime.now()
- global l,r,m
- l = 0
- r = 0
- m = 0
- log.append("Started block period at {0}\n".format(start))
- main = Tk()
- main.attributes('-fullscreen',True)
- def Quit(event):
- main.destroy()
- end = datetime.now()
- timestamp.append(end)
- log.append("\nBlock period terminated at {0}".format(end))
- def leftClick(event):
- global l; now = datetime.now()
- timestamp.append(now)
- log.append("L Click at {0}".format(now.strftime("%H:%M:%S:%f"))); order.append('Left')
- l += 1
- return
- def rightClick(event):
- global r; now = datetime.now()
- timestamp.append(now)
- log.append("R Click at {0}".format(now.strftime("%H:%M:%S:%f"))); order.append('Right')
- r += 1
- return
- def middleClick(event):
- global m; now = datetime.now()
- timestamp.append(now)
- log.append("M Click at {0}".format(now.strftime("%H:%M:%S:%f"))); order.append('Middle')
- m += 1
- return
- main.bind('<Button-1>', leftClick)
- main.bind('<Button-3>', rightClick)
- main.bind('<Button-2>', middleClick)
- main.bind('<q>', Quit)
- main.focus()
- main.mainloop()
- ###############################################################################
- 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:
- with redirect_stdout(f):
- print("***Summary***")
- print("Block for parameters *** gave the following results\nLeft Click(**) - {0}\nRight Click(**) - {1}\nMiddle Mouse Click(Unclear) - {2}\n".format(l,r,m))
- print("Clicks were in the following order:")
- for i in order:
- print(i)
- print('\n\n***Specifics***')
- for i in log:
- print(i)
- 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:
- with redirect_stdout(f):
- print(log)
- print(timestamp)
- delta_ts = []
- log.remove(log[0]); log.remove(log[-1])
- timestamp.remove(timestamp[-1])
- a = timestamp[0] #current timestamp
- for i in range(len(log) - 1):
- b = timestamp[i + 1] #next time stamp
- delta_ts.append((b-a).total_seconds()) #difference in seconds
- a = timestamp[i + 1] #current timestamp now b
- print(delta_ts)
- time.sleep(2)
- ####################################################################################
- ##Analysis of Data##
- import datetime, os, ast, math, sys
- import numpy as np
- import matplotlib.pyplot as plt
- from contextlib import redirect_stdout
- combined_dts = []
- tests = int(input("How many times did you test this LJ curve? : "))
- values = ['2','3','4']
- speeds = ['0.625','0.833','1','2','3.33','5']
- ##rot = input("Enter Rotation Speed to analyse : ")
- ##lobe_param = input("What value of b did you want to analyse? : ")
- for val in values:
- for speed in speeds:
- rot = speed
- lobe_param = val
- with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'w') as f:
- with redirect_stdout(f):
- print("")
- f.close()
- for num in range(1, tests+1):
- f = open('{0}/logs/b{1}/Rotation_b{1}_{2}_{3}_technicaldata.txt'.format(os.getcwd(), lobe_param, rot, num), 'r')
- log = f.readline()
- log = ast.literal_eval(log)
- timestamps = f.readline()
- timestamps = eval(timestamps)
- f.close()
- delta_ts = []
- order = []
- log.remove(log[0]); log.remove(log[-1])
- timestamps.remove(timestamps[-1])
- a = timestamps[0] #current timestamp
- for i in range(len(log)):
- try:
- order.append(log[i][0])
- b = timestamps[i + 1] #next time stamp
- delta_ts.append((b-a).total_seconds()) #difference in seconds
- a = timestamps[i + 1] #current timestamp now b
- except:
- pass
- ## with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
- ## with redirect_stdout(f):
- ## print("Unable to perform an anlysis of b{0}_{1}_Dataset_{2} due to insufficient number of data points".format(lobe_param, rot, num))
- ## break
- try:
- marker = [] #job is to hold the indexes of the data points that cannot stay
- for j in range(len(delta_ts) - 1):
- if order[j] == order[j+1]:
- marker.append(j); marker.append(j+1)
- if order[j] == 'M':
- marker.append(j)
- counter = 0 #marks the number of deletions
- ## print(len(marker))
- for mark in range(len(marker)):
- delta_ts.remove(delta_ts[mark - counter])
- counter += 1
- for j in delta_ts:
- combined_dts.append(j)
- with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
- with redirect_stdout(f):
- print("{0} items removed from analysis of b{1}_{2}_Dataset_{3} due to".format(len(marker), lobe_param, rot, num))
- 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")
- except:
- with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
- with redirect_stdout(f):
- print("No histogram data generated")
- sys.exit()
- f.close()
- nopoints = len(combined_dts)
- # Plotting the histogram
- n, bins, patches = plt.hist(x=combined_dts, bins=math.ceil(math.sqrt(nopoints)), color='#0504aa')
- plt.grid(axis='y', alpha=0.75)
- plt.xlabel('Range of delta t')
- plt.ylabel('Frequency')
- plt.title('Histogram of time until state change recorded for {0} lobes at speed {1}'.format(lobe_param, rot))
- maxfreq = n.max()
- # Set a clean upper y-axis limit.
- plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
- 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)
- print("Figure saved to {0}/logs/b{1}/analysis/".format(os.getcwd(), lobe_param))
- print("Analysis of technical data saved to {0}/Logs/b{1}/analysis/".format(os.getcwd(), lobe_param))
- with open('{0}/Logs/b{1}/analysis/Analysis_of_technicaldata_b{1}_Rotation_{2}.txt'.format(os.getcwd(), lobe_param, rot), 'a') as f:
- with redirect_stdout(f):
- print("n : {0}\nbins : {1}".format(n, bins))
- ## plt.show()
- n, bins, patches, maxfreq = 0,0,0,0
- plt.clf()
- combined_dts = []
Advertisement
Add Comment
Please, Sign In to add comment