time_volt.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #
3 # Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 
18 import pickle
19 import csv
20 import pylab
21 import sys
22 import getopt
23 
24 from math import cos, sin
25 import numpy as np
26 
27 import rospy
28 import rosparam
29 import yaml
30 import savitzky
31 
32 def main(argv):
33  rospy.init_node('csv_proc')
34 
35  volt_values=[]
36  time_values=[]
37 
38  sg = savitzky.savitzky_golay(window_size=901, order=3)
39 
40 ####################
41 # Parameters for the Python script
42 ####################
43 
44  filename = rosparam.get_param("/csv_proc/file_name")
45  robot_name = rosparam.get_param("/csv_proc/robot_name")
46  mode = rosparam.get_param("/csv_proc/mode")
47  yaml_file = open("voltage_filter.yaml", "w")
48  yl = {}
49 
50  if(mode=="update"):
51  abcd = rosparam.get_param("/csv_proc/abcd")
52 
53  try:
54  opts, args = getopt.getopt(argv,"hf:r:",["ifile=", "irobot="])
55  except getopt.GetoptError:
56  print('time_volt.py -f <filename> -r <robotname>')
57  sys.exit(2)
58  for opt, arg in opts:
59  if opt == '-h':
60  print('time_volt.py -f <filename> -r <robotname>')
61  sys.exit()
62  elif opt in ("-f", "--ifile"):
63  filename = arg
64  elif opt in ("-r", "--irobot"):
65  robot_name = arg
66 
67 
68 ####################
69 # Opening the csv file and getting the values for time and voltage
70 ####################
71 
72  with open(filename, 'rb') as csvfile:
73 
74  csvreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
75  for row in csvreader:
76  row = row[0].split(',')
77  volt_v = (float)(row[1]) * 1000.0
78  if(volt_v < 48000 and volt_v > 44000):
79  time_values.append((float)(row[0]))
80  volt_values.append(volt_v)
81 
82  time_values[:] = [x - time_values[0] for x in time_values]
83  time_values = time_values[::-1]
84 
85 ####################
86 # Plotting graphics for the Voltage vs Time
87 ####################
88 
89  pylab.figure(1)
90 
91  pylab.plot(volt_values, time_values)
92  pylab.ylabel("Time elapsed(seconds)")
93  pylab.xlabel("Voltage(mV)")
94  pylab.title("Time x Volt,file="+ filename.replace('.csv',''))
95  pylab.grid(True)
96 
97  secArray = np.asarray(time_values)
98  voltArray = np.asarray(volt_values)
99 
100  # Polyfit for the voltage values
101  z1 = np.polyfit(voltArray, secArray,1)
102  z2 = np.polyfit(voltArray, secArray,2)
103  z3 = np.polyfit(voltArray, secArray,3)
104 
105  # Linear space for better visualization
106  xp = np.linspace(49000, 43000, 100)
107 
108  # Generating the polynomial function from the fit
109  p1 = np.poly1d(z1)
110  p2 = np.poly1d(z2)
111  p3 = np.poly1d(z3)
112 
113  pylab.plot(xp, p1(xp), 'r-', xp, p2(xp), 'g-', xp, p3(xp), 'm-')
114 
115  pylab.text(46000, 11900, 'p1=' + p1.__str__(), bbox=dict(facecolor='red', alpha=0.5))
116  pylab.text(46000, 11600, 'p2=' + p2.__str__(), bbox=dict(facecolor='green', alpha=0.5))
117  pylab.text(46000, 11200, 'p3=' + p3.__str__(), bbox=dict(facecolor='magenta', alpha=0.5))
118 
119  pylab.savefig(filename.replace('.csv',''), format="pdf")
120  #pylab.show()
121 
122 ####################
123 # Residuals Analysis
124 ####################
125 
126  pylab.figure(2)
127 
128  pylab.ylabel("Residuals(s)")
129  pylab.xlabel("Voltage(mV)")
130  pylab.title("Residuals x Voltage,file="+ filename.replace('.csv',''))
131 
132  #Evaluating the polynomial through all the volt values
133  z1_val = np.polyval(z1, volt_values)
134  z2_val = np.polyval(z2, volt_values)
135  z3_val = np.polyval(z3, volt_values)
136 
137  # Getting the residuals from the fit functions compared to the real values
138  z1_res = time_values - z1_val
139  z2_res = time_values - z2_val
140  z3_res = time_values - z3_val
141 
142  pylab.plot(time_values, z1_res, time_values, z2_res, time_values, z3_res)
143 
144  pylab.grid()
145 
146  pylab.legend(('Residuals 1st order', 'Residuals 2nd order', 'Residuals 3rd order'))
147 
148  pylab.savefig(filename.replace('.csv','')+'_res', format="pdf")
149 
150 ###################
151 # Savitzky Golay Filter Applied to the Battery Voltage
152 ###################
153 
154  values_filt = sg.filter(voltArray)
155 
156  pylab.figure(3)
157 
158  pylab.subplot(211)
159 
160  pylab.plot(voltArray, time_values)
161 
162  pylab.grid(True)
163  pylab.title('Comparison between real and filtered data')
164  pylab.ylabel('Real Values(mV)')
165 
166  pylab.subplot(212)
167 
168  pylab.plot(values_filt, time_values)
169 
170  pylab.grid(True)
171  pylab.ylabel('Filtered Values(mV)')
172  pylab.xlabel('Time(s)')
173 
174 #####
175 
176 ###################
177 # Filtered fits
178 ###################
179  pylab.figure(4)
180 
181  pylab.plot(values_filt, time_values)
182  pylab.ylabel("Time elapsed(seconds)")
183  pylab.xlabel("Voltage(mV)")
184  pylab.title("Time x Volt,file="+ filename.replace('.csv',''))
185  pylab.grid(True)
186 
187  secArray = np.asarray(time_values)
188 
189  # Polyfit for the voltage values
190  z1 = np.polyfit(values_filt, secArray,1)
191  z2 = np.polyfit(values_filt, secArray,2)
192  z3 = np.polyfit(values_filt, secArray,3)
193 
194  if (mode=="initial"):
195  z3_l = []
196 
197  for el in z3:
198  z3_l.append((float)(el))
199 
200  abcd = z3_l
201  yl["abcd"] = z3_l
202  yl["theta"] = 0.
203  yl["off_y"] = 0.
204 
205  # Linear space for better visualization
206  xp = np.linspace(49000, 43000, 100)
207 
208  # Generating the polynomial function from the fit
209  p1 = np.poly1d(z1)
210  p2 = np.poly1d(z2)
211  p3 = np.poly1d(z3)
212 
213  pylab.plot(xp, p1(xp), 'r-', xp, p2(xp), 'g-', xp, p3(xp), 'm-')
214 
215  pylab.text(46000, 11900, 'p1=' + p1.__str__(), bbox=dict(facecolor='red', alpha=0.5))
216  pylab.text(46000, 11600, 'p2=' + p2.__str__(), bbox=dict(facecolor='green', alpha=0.5))
217  pylab.text(46000, 11200, 'p3=' + p3.__str__(), bbox=dict(facecolor='magenta', alpha=0.5))
218 
219 ####################
220 # Residuals Analysis for the filtered Signal
221 ####################
222 
223  pylab.figure(5)
224 
225  pylab.ylabel("Residuals(s)")
226  pylab.xlabel("Voltage(mV)")
227  pylab.title("Residuals x Voltage,file="+ filename.replace('.csv',''))
228 
229  #Evaluating the polynomial through all the time values
230  z1_val = np.polyval(z1, values_filt)
231  z2_val = np.polyval(z2, values_filt)
232  z3_val = np.polyval(z3, values_filt)
233 
234  # Getting the residuals from the fit functions compared to the real values
235  z1_res = time_values - z1_val
236  z2_res = time_values - z2_val
237  z3_res = time_values - z3_val
238 
239  pylab.plot(time_values, z1_res, time_values, z2_res, time_values, z3_res)
240 
241  pylab.grid()
242 
243  pylab.legend(('Residuals 1st order', 'Residuals 2nd order', 'Residuals 3rd order'))
244 
245 ####################
246 # Polynomial Evaluation for the filtered signal and the function from the non-moving case
247 ####################
248 
249  if(mode == "update"):
250  pylab.figure(6)
251 
252 
253  poly_vals = np.polyval(abcd, values_filt)
254 
255 
256  pylab.plot(values_filt, poly_vals, values_filt, time_values)
257 
258  pylab.legend(('Polynomial', 'Real'))
259 
260  pylab.grid()
261  #####
262  pylab.figure(7)
263 
264  pylab.ylabel("Time available(seconds)")
265  pylab.xlabel("Voltage(mV)")
266  pylab.title("Time x Volt,file="+ filename.replace('.csv',''))
267  pylab.grid(True)
268 
269  poly_vals = np.polyval(abcd, values_filt)
270 
271  ss = lambda y1, y2: ((y1-y2)**2).sum()
272 
273  #theta = -0.07
274  #new_x = values_filt*cos(theta) - poly_vals*sin(theta)
275  #new_y = values_filt*sin(theta) + poly_vals*cos(theta)
276 
277  theta = -0.2
278  theta_values = []
279  cost_values = []
280  off_values = []
281 
282  while theta < 0.2:
283  theta +=0.01
284  new_x = values_filt*cos(theta) - poly_vals*sin(theta)
285  new_y = values_filt*sin(theta) + poly_vals*cos(theta)
286  print("new_x: {}, new_y: {}".format(new_x, new_y))
287 
288 
289  off_y = -6000
290 
291  cost_values_i =[]
292  off_y_values_i=[]
293 
294  while off_y < 6000:
295  off_y +=200
296  new_y_temp = new_y
297  new_y_temp = new_y_temp + off_y
298 
299  ss1=ss(time_values,new_y_temp)
300  print(ss1, off_y)
301 
302  cost_values_i.append(ss1)
303  off_y_values_i.append(off_y)
304 
305  #ss1=ss(time_values,new_y)
306  #print ss1, theta
307  #cost_values.append(ss1)
308  theta_values.append(theta)
309  cost_min = min(cost_values_i)
310  cost_min_index = cost_values_i.index(cost_min)
311  cost_values.append(cost_values_i[cost_min_index])
312  off_values.append(off_y_values_i[cost_min_index])
313 
314  cost_min = min(cost_values)
315  cost_min_index = cost_values.index(cost_min)
316 
317  theta = theta_values[cost_min_index]
318  off_y = off_values[cost_min_index]
319 
320  new_x = values_filt*cos(theta) - poly_vals*sin(theta)
321  new_y = values_filt*sin(theta) + poly_vals*cos(theta)
322  print("new_x: {}, new_y: {}".format(new_x, new_y))
323 
324  new_y = new_y + off_y
325 
326  yl["abcd"] = abcd
327  yl["theta"] = theta
328  yl["off_y"] = off_y
329  yl["maximum_time"] = (float)(new_y[0])
330 
331  pylab.plot(poly_vals, values_filt, time_values, values_filt, new_y, values_filt)
332 
333  pylab.legend(('Poly not moving', 'Real', 'Shifted Fit'))
334 
335  yaml.safe_dump(yl, yaml_file,default_flow_style=False)
336 
337  yaml_file.close()
338 
339  pylab.show()
340 
341 
342 
343 if __name__=="__main__":
344  main(sys.argv[1:])
def main(argv)
Definition: time_volt.py:32


cob_voltage_control
Author(s): Alexander Bubeck
autogenerated on Wed Apr 7 2021 02:11:57