Advertisement
Guest User

Data_Parse_csv.py

a guest
Mar 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.45 KB | None | 0 0
  1. import csv
  2. import math
  3. import sys
  4. import numpy as np
  5. import numpy.linalg
  6. import pylablib as py
  7. import matplotlib.pyplot as plt
  8. from scipy import integrate
  9. from scipy.interpolate import spline
  10. from datetime import datetime, timedelta
  11.  
  12.  
  13. # ---------------------------------------------------------------------
  14. # function to transform hex string like "0xff4c" into signed integer
  15. # ---------------------------------------------------------------------
  16. def hexStrToInt(hexstr):
  17.     val = int(hexstr, 16)           # convert to unsigned
  18.     if ((val & 0x8000) == 0x8000):  # check sign bit
  19.         val = -((val ^ 0xffff) + 1) # if set, inver and add one to get the negative value, then add the negative sign
  20.     return val
  21. # ---------------------------------------------------------------------
  22.  
  23. with open('Rotating.txt', 'r') as in_file:
  24.     stripped = (line.strip() for line in in_file)
  25.     lines = (line for line in stripped if line)
  26.     with open('ext_aconno_stream_4.csv', 'w', newline='') as out_file:
  27.         writer = csv.writer(out_file)
  28.         writer.writerow(('Time Stamp','X Acceleration','Y Acceleration','Z Acceleration','X Velocity','Y Velocity','Z Velocity','X Position', 'Y Position', 'Z Position'))
  29.  
  30.         #Create variables to recognize when notifications are enabled for each acceleration service
  31.         acc_enabled = 0
  32.  
  33.         #Create empty acceleration lists
  34.         x_acc, y_acc, z_acc = [],[],[];
  35.  
  36.         #Create timestamp for x,y,z
  37.         acc_times = []
  38.         g = 9.81
  39.         out_string_x, out_string_y, out_string_z = '','','';
  40.  
  41.         for line in lines:
  42.             line = line.strip()
  43.  
  44.             # Check for receiving values
  45.             if line.find('Notifications enabled for 00005283-0000-1000-8000-00805f9b34fb') != -1:
  46.                 acc_enabled = 1
  47.  
  48.             # Start recording once receiving receiving acceleration values
  49.             if acc_enabled == 1:
  50.  
  51.                 if line.find('received from 00005283') != -1:
  52.  
  53.                     out_string_x = line[88:90]; out_string_y = line[88:90];out_string_z = line[88:90] #0x
  54.  
  55.                     out_string_x += line[92:94]
  56.                     out_string_x += line[95:97]
  57.  
  58.                     out_string_y += line[98:100]
  59.                     out_string_y += line[101:103]
  60.  
  61.                     out_string_z += line[104:106]
  62.                     out_string_z += line[107:109]
  63.  
  64.  
  65.                     if acc_times == []:
  66.                         time_start = timedelta(hours=float(line[2:4]), minutes=float(line[5:7]),
  67.                                                seconds=float(line[8:10]), milliseconds=float(line[11:14]))
  68.                         print("Time Start: ", time_start)
  69.  
  70.                     acc_times.append(
  71.                         timedelta(hours=float(line[2:4]), minutes=float(line[5:7]), seconds=float(line[8:10]),
  72.                                   milliseconds=float(line[11:14])))
  73.  
  74.                     # if abs(float(hexStrToInt(out_string_x)) * (0.061 / 1000) * g) <= 0.5:
  75.                     #     x_acc.append(0.00)
  76.                     # else:
  77.                     #     x_acc.append(float(hexStrToInt(out_string_x)) * (0.061 / 1000) * g)
  78.                     x_acc.append(float(hexStrToInt(out_string_x)) * (0.061 / 1000) * g)
  79.                     y_acc.append(float(hexStrToInt(out_string_y)) * (0.061 / 1000) * g)
  80.                     z_acc.append(float(hexStrToInt(out_string_z)) * (0.061 / 1000) * g)
  81.  
  82.                     out_string_x, out_string_y,out_string_z = '','',''
  83.  
  84.         del acc_times[0:4],x_acc[0:4]; del y_acc[0:4]; del z_acc[0:4]  #Delete 0xAAAA values
  85.  
  86.         time_end = acc_times[-1]
  87.         print("Time End:   ",time_end)
  88.  
  89.         times = []
  90.         for time in acc_times:
  91.             new_time = (time/timedelta(seconds=1)) - (time_start/timedelta(seconds=1))
  92.             times.append(new_time)
  93.  
  94.         # Check to make sure lengths are equal
  95.         if len(x_acc) != len(y_acc) != len(z_acc) != len(times):
  96.             print("Acceleration lengths don't match",'\n')
  97.             acc_data_good = 0
  98.         else:
  99.             print("Acceleration Data is equal length",'\n')
  100.             acc_data_good = 1
  101.  
  102.  
  103.         print("Timestamp (seconds): ",times)
  104.         print("X acceleration:", x_acc)
  105.         print("Y acceleration:", y_acc)
  106.         print("Z acceleration:", z_acc,'\n')
  107.  
  108.         # ------------------------------------------------------
  109.         # Integrate Acceleration
  110.  
  111.         # Create empty acceleration lists
  112.         vel_x, vel_y, vel_z= np.array([]),np.array([]),np.array([]);
  113.         velocity_x, velocity_y, velocity_z = [0],[0],[0];
  114.         position_x, position_y, position_z = [0],[0],[0];
  115.  
  116.         time_vec = np.array(acc_times)
  117.         vel_x = np.array(x_acc)
  118.         vel_y = np.array(y_acc)
  119.         vel_z = np.array(z_acc)
  120.  
  121.         n_start = 0
  122.         n_end = len(vel_z)
  123.  
  124.         interv_to_int = (np.linspace(n_start, n_end, n_end - n_start + 1, dtype=int))
  125.         interv_to_int = interv_to_int[0:len(interv_to_int) - 2]
  126.  
  127.         print("1g is approximately: ",np.mean(vel_z[5:20]))
  128.  
  129.         vel_x = vel_x[interv_to_int] - np.mean(vel_x[5:20])
  130.         vel_y = vel_y[interv_to_int] - np.mean(vel_y[5:20])
  131.         vel_z = vel_z[interv_to_int] - np.mean(vel_z[5:20]) # value - approximate 1g
  132.  
  133.  
  134.         total_seconds = (time_end - time_start) / timedelta(seconds=1)
  135.         time_vec = time_vec[interv_to_int]
  136.  
  137.         delta_x = np.mean(np.diff(time_vec)) / timedelta(seconds=1)#average time between samples
  138.         delta_y = delta_x
  139.         delta_z = delta_x
  140.  
  141.         print("delta_z: ",delta_z)
  142.  
  143.         dx, dy, dz = total_seconds,total_seconds,total_seconds
  144.         print("total seconds: ", dz,'\n')
  145.  
  146.         for acc_x, acc_y, acc_z in zip(vel_x, vel_y, vel_z):
  147.             velocity_x.append(velocity_x[-1] + acc_x * delta_x)
  148.             velocity_y.append(velocity_y[-1] + acc_y * delta_y)
  149.             velocity_z.append(velocity_z[-1] + acc_z * delta_z)
  150.         del velocity_x[0],velocity_y[0],velocity_z[0]
  151.  
  152.         # velocity_x = integrate.cumtrapz(vel_x) * dx
  153.         # velocity_y = integrate.cumtrapz(vel_y) * dy
  154.         # velocity_z = integrate.cumtrapz(vel_z) * dz
  155.  
  156.         print("velocity in x: ", velocity_x,'\n')
  157.         print("velocity in y: ", velocity_y, '\n')
  158.         print("velocity in z: ", velocity_z, '\n')
  159.  
  160.         for v_x,v_y,v_z in zip(velocity_x,velocity_y,velocity_z):
  161.             position_x.append(position_x[-1] + v_x * delta_x)
  162.             position_y.append(position_y[-1] + v_y * delta_y)
  163.             position_z.append(position_z[-1] + v_z * delta_z)
  164.         del position_x[0],position_y[0],position_z[0]
  165.  
  166.         # position_x = integrate.cumtrapz(velocity_x) * dx
  167.         # position_y = integrate.cumtrapz(velocity_y) * dy
  168.         # position_z = integrate.cumtrapz(velocity_z) * dz
  169.  
  170.         print("position in x: ", position_x, '\n')
  171.         print("position in y: ", position_y, '\n')
  172.         print("position in z: ", position_z, '\n')
  173.  
  174.         # ------------------------------------------------------
  175.         # Write to CSV file
  176.         if acc_data_good == 1:
  177.             for acc_time, x_acc_f, y_acc_f, z_acc_f, velocity_x_f, velocity_y_f, velocity_z_f, position_x_f, position_y_f, position_z_f in zip(
  178.                     acc_times, x_acc, y_acc, z_acc, velocity_x, velocity_y, velocity_z, position_x, position_y, position_z):
  179.                 grouped = acc_time/timedelta(seconds=1)-time_start/timedelta(seconds=1), x_acc_f, y_acc_f, z_acc_f, velocity_x_f, velocity_y_f, velocity_z_f, position_x_f, position_y_f, position_z_f
  180.                 writer.writerow(grouped)
  181.  
  182.         # ------------------------------------------------------
  183.         #Calculate Magnitudes
  184.  
  185.         Mag_acc, Mag_vel, Mag_pos = [],[],[];
  186.  
  187.         for  x_acc_f, y_acc_f, z_acc_f, velocity_x_f, velocity_y_f, velocity_z_f, position_x_f, position_y_f, position_z_f in zip(
  188.                 x_acc, y_acc, z_acc, velocity_x, velocity_y, velocity_z, position_x, position_y, position_z):
  189.             Mag_acc.append((x_acc_f**2 + y_acc_f**2 + z_acc_f**2)**(1.0/2.0))
  190.             Mag_vel.append((velocity_x_f**2 + velocity_y_f**2 + velocity_z_f**2)**(1.0/2.0))
  191.             Mag_pos.append((position_x_f**2 + position_y_f**2 + position_z_f**2)**(1.0/2.0))
  192.  
  193.         print(Mag_acc,'\n',Mag_vel,'\n',Mag_pos)
  194.  
  195.         #--------------------------------------------------------
  196.         #Plot
  197.         #--------------------------------------------------------
  198.  
  199.         # Check to make sure lengths are equal
  200.         if len(times) != len(x_acc):
  201.             #print("times and acceleration x lengths don't match", '\n', len(times), len(velocity_x), '\n', times,'\n', velocity_x)
  202.             del times[-1]
  203.         else:
  204.             print("times and acceleration x lengths DO match", '\n')
  205.  
  206.         plt.subplot(3,3,1)
  207.         plt.plot(times, x_acc)
  208.         plt.title("Acceleration")
  209.         plt.ylabel("X")
  210.         plt.ylim(-20,20)
  211.  
  212.         plt.subplot(3, 3, 4)
  213.         plt.plot(times, y_acc)
  214.         plt.ylabel("Y")
  215.         plt.ylim(-20, 20)
  216.  
  217.         plt.subplot(3, 3, 7)
  218.         plt.plot(times, z_acc)
  219.         plt.ylabel("Z")
  220.         plt.ylim(-20, 20)
  221.         plt.xlabel("Time")
  222.  
  223.         # Check to make sure lengths are equal
  224.         if len(times) != len(velocity_x):
  225.             #print("times and velocity x lengths don't match", '\n',len(times),len(velocity_x),'\n',times,'\n',velocity_x)
  226.             del times[-1]
  227.             #del times[-1]
  228.         else:
  229.             print("times and velocity x lengths DO match", '\n')
  230.  
  231.         plt.subplot(3,3, 2)
  232.         plt.plot(times, velocity_x)
  233.         plt.title("Velocity")
  234.  
  235.         plt.subplot(3, 3, 5)
  236.         plt.plot(times, velocity_y)
  237.         #plt.title("Y Velocity")
  238.  
  239.         plt.subplot(3, 3, 8)
  240.         plt.plot(times, velocity_z)
  241.         #plt.title("Z Velocity")
  242.         plt.xlabel("Time")
  243.  
  244.         # Check to make sure lengths are equal
  245.         if len(times) != len(position_x):
  246.             # print("times and velocity x lengths don't match", '\n',len(times),len(velocity_x),'\n',times,'\n',velocity_x)
  247.             del times[-1]
  248.  
  249.         else:
  250.             print("times and velocity x lengths DO match", '\n')
  251.  
  252.         plt.subplot(3, 3, 3)
  253.         plt.plot(times, position_x)
  254.         plt.title("Position")
  255.  
  256.         plt.subplot(3, 3, 6)
  257.         plt.plot(times, position_y)
  258.         #plt.title("Y Position")
  259.  
  260.         plt.subplot(3, 3, 9)
  261.         plt.plot(times, position_z)
  262.         #plt.title("Z Position")
  263.         plt.xlabel("Time")
  264.  
  265.  
  266.         plt.show(block=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement