time_volt.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 #################################################################
00004 ##\file
00005 #
00006 # \note
00007 # Copyright (c) 2013 \n
00008 # Fraunhofer Institute for Manufacturing Engineering
00009 # and Automation (IPA) \n\n
00010 #
00011 #################################################################
00012 #
00013 # \note
00014 # Project name: Care-O-bot Research
00015 # \note
00016 # ROS package name: 
00017 #
00018 # \author
00019 # Author: Thiago de Freitas Oliveira Araujo, 
00020 # email:thiago.de.freitas.oliveira.araujo@ipa.fhg.de
00021 # \author
00022 # Supervised by: Florian Weisshardt, email:florian.weisshardt@ipa.fhg.de
00023 #
00024 # \date Date of creation: March 2013
00025 #
00026 # \brief
00027 # This module is for characterizing the Care-o-bot 3 battery
00028 #
00029 #################################################################
00030 #
00031 # Redistribution and use in source and binary forms, with or without
00032 # modification, are permitted provided that the following conditions are met:
00033 #
00034 # - Redistributions of source code must retain the above copyright
00035 # notice, this list of conditions and the following disclaimer. \n
00036 # - Redistributions in binary form must reproduce the above copyright
00037 # notice, this list of conditions and the following disclaimer in the
00038 # documentation and/or other materials provided with the distribution. \n
00039 # - Neither the name of the Fraunhofer Institute for Manufacturing
00040 # Engineering and Automation (IPA) nor the names of its
00041 # contributors may be used to endorse or promote products derived from
00042 # this software without specific prior written permission. \n
00043 #
00044 # This program is free software: you can redistribute it and/or modify
00045 # it under the terms of the GNU Lesser General Public License LGPL as
00046 # published by the Free Software Foundation, either version 3 of the
00047 # License, or (at your option) any later version.
00048 #
00049 # This program is distributed in the hope that it will be useful,
00050 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00051 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
00052 # GNU Lesser General Public License LGPL for more details.
00053 #
00054 # You should have received a copy of the GNU Lesser General Public
00055 # License LGPL along with this program.
00056 # If not, see < http://www.gnu.org/licenses/>.
00057 #
00058 #################################################################
00059 import pickle
00060 
00061 import csv
00062 import pylab
00063 import sys
00064 import getopt
00065 
00066 import savitzky
00067 
00068 import numpy as np
00069 
00070 from numpy import *
00071 from math import *
00072 from scipy import *
00073 
00074 import roslib; roslib.load_manifest('cob_bringup')
00075 import rospy
00076 import rosparam
00077 
00078 import yaml
00079 
00080 def main(argv):
00081     rospy.init_node('csv_proc')
00082     
00083     volt_values=[]
00084     time_values=[]
00085     
00086     sg = savitzky.savitzky_golay(window_size=901, order=3)
00087 
00088 ####################
00089 # Parameters for the Python script
00090 ####################
00091 
00092     filename = rosparam.get_param("/csv_proc/file_name")
00093     robot_name = rosparam.get_param("/csv_proc/robot_name")
00094     mode = rosparam.get_param("/csv_proc/mode")
00095     yaml_file = open("voltage_filter.yaml", "w")
00096     yl = {}
00097     
00098     if(mode=="update"):
00099         abcd = rosparam.get_param("/csv_proc/abcd")
00100     
00101     try:
00102         opts, args = getopt.getopt(argv,"hf:r:",["ifile=", "irobot="])
00103     except getopt.GetoptError:
00104         print 'time_volt.py -f <filename> -r <robotname>'
00105         sys.exit(2)
00106     for opt, arg in opts:
00107         if opt == '-h':
00108             print 'time_volt.py -f <filename> -r <robotname>'
00109             sys.exit()
00110         elif opt in ("-f", "--ifile"):
00111             filename = arg
00112         elif opt in ("-r", "--irobot"):
00113             robot_name = arg
00114             
00115 
00116 ####################
00117 # Opening the csv file and getting the values for time and voltage
00118 ####################
00119              
00120     with open(filename, 'rb') as csvfile:
00121 
00122         csvreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
00123         for row in csvreader:
00124             row = row[0].split(',')
00125             volt_v = (float)(row[1]) * 1000.0
00126             if(volt_v < 48000 and volt_v > 44000):
00127                 time_values.append((float)(row[0]))
00128                 volt_values.append(volt_v)
00129 
00130     time_values[:] = [x - time_values[0] for x in time_values]
00131     time_values = time_values[::-1]
00132     
00133 ####################
00134 # Plotting graphics for the Voltage vs Time
00135 ####################
00136 
00137     pylab.figure(1)
00138 
00139     pylab.plot(volt_values, time_values)
00140     pylab.ylabel("Time elapsed(seconds)")
00141     pylab.xlabel("Voltage(mV)")
00142     pylab.title("Time x Volt,file="+ filename.replace('.csv',''))
00143     pylab.grid(True)
00144     
00145     secArray = np.asarray(time_values)
00146     voltArray = np.asarray(volt_values)
00147     
00148     # Polyfit for the voltage values
00149     z1 = np.polyfit(voltArray, secArray,1)
00150     z2 = np.polyfit(voltArray, secArray,2)
00151     z3 = np.polyfit(voltArray, secArray,3)
00152     
00153     # Linear space for better visualization
00154     xp = np.linspace(49000, 43000, 100)
00155     
00156     # Generating the polynomial function from the fit
00157     p1 = np.poly1d(z1)
00158     p2 = np.poly1d(z2)
00159     p3 = np.poly1d(z3)
00160     
00161     pylab.plot(xp, p1(xp), 'r-', xp, p2(xp), 'g-', xp, p3(xp), 'm-')
00162 
00163     pylab.text(46000, 11900, 'p1=' + p1.__str__(), bbox=dict(facecolor='red', alpha=0.5))
00164     pylab.text(46000, 11600, 'p2=' + p2.__str__(), bbox=dict(facecolor='green', alpha=0.5))
00165     pylab.text(46000, 11200, 'p3=' + p3.__str__(), bbox=dict(facecolor='magenta', alpha=0.5))
00166     
00167     pylab.savefig(filename.replace('.csv',''), format="pdf")
00168     #pylab.show()
00169 
00170 ####################
00171 # Residuals Analysis
00172 ####################
00173 
00174     pylab.figure(2)
00175     
00176     pylab.ylabel("Residuals(s)")
00177     pylab.xlabel("Voltage(mV)")
00178     pylab.title("Residuals x Voltage,file="+ filename.replace('.csv',''))
00179     
00180     #Evaluating the polynomial through all the volt values
00181     z1_val = np.polyval(z1, volt_values)
00182     z2_val = np.polyval(z2, volt_values)
00183     z3_val = np.polyval(z3, volt_values)
00184     
00185    # Getting the residuals from the fit functions compared to the real values
00186     z1_res = time_values - z1_val
00187     z2_res = time_values - z2_val
00188     z3_res = time_values - z3_val
00189     
00190     pylab.plot(time_values, z1_res, time_values, z2_res, time_values, z3_res)
00191     
00192     pylab.grid()
00193     
00194     pylab.legend(('Residuals 1st order', 'Residuals 2nd order', 'Residuals 3rd order'))
00195     
00196     pylab.savefig(filename.replace('.csv','')+'_res', format="pdf")
00197     
00198 ###################
00199 # Savitzky Golay Filter Applied to the Battery Voltage
00200 ###################
00201     
00202     values_filt = sg.filter(voltArray)
00203     
00204     pylab.figure(3)
00205     
00206     pylab.subplot(211)
00207     
00208     pylab.plot(voltArray, time_values)
00209     
00210     pylab.grid(True)
00211     pylab.title('Comparison between real and filtered data')
00212     pylab.ylabel('Real Values(mV)')
00213     
00214     pylab.subplot(212)
00215     
00216     pylab.plot(values_filt, time_values)
00217     
00218     pylab.grid(True)
00219     pylab.ylabel('Filtered Values(mV)')
00220     pylab.xlabel('Time(s)')
00221     
00222 #####    
00223 
00224 ###################
00225 # Filtered fits
00226 ###################
00227     pylab.figure(4)
00228 
00229     pylab.plot(values_filt, time_values)
00230     pylab.ylabel("Time elapsed(seconds)")
00231     pylab.xlabel("Voltage(mV)")
00232     pylab.title("Time x Volt,file="+ filename.replace('.csv',''))
00233     pylab.grid(True)
00234     
00235     secArray = np.asarray(time_values)
00236     
00237     # Polyfit for the voltage values
00238     z1 = np.polyfit(values_filt, secArray,1)
00239     z2 = np.polyfit(values_filt, secArray,2)
00240     z3 = np.polyfit(values_filt, secArray,3)
00241 
00242     if (mode=="initial"):
00243         z3_l = []
00244         
00245         for el in z3:
00246             z3_l.append((float)(el))
00247             
00248         abcd = z3_l    
00249         yl["abcd"] = z3_l
00250         yl["theta"] = 0.
00251         yl["off_y"] = 0.  
00252     
00253     # Linear space for better visualization
00254     xp = np.linspace(49000, 43000, 100)
00255     
00256     # Generating the polynomial function from the fit
00257     p1 = np.poly1d(z1)
00258     p2 = np.poly1d(z2)
00259     p3 = np.poly1d(z3)
00260     
00261     pylab.plot(xp, p1(xp), 'r-', xp, p2(xp), 'g-', xp, p3(xp), 'm-')
00262 
00263     pylab.text(46000, 11900, 'p1=' + p1.__str__(), bbox=dict(facecolor='red', alpha=0.5))
00264     pylab.text(46000, 11600, 'p2=' + p2.__str__(), bbox=dict(facecolor='green', alpha=0.5))
00265     pylab.text(46000, 11200, 'p3=' + p3.__str__(), bbox=dict(facecolor='magenta', alpha=0.5))
00266 
00267 ####################
00268 # Residuals Analysis for the filtered Signal
00269 ####################
00270 
00271     pylab.figure(5)
00272     
00273     pylab.ylabel("Residuals(s)")
00274     pylab.xlabel("Voltage(mV)")
00275     pylab.title("Residuals x Voltage,file="+ filename.replace('.csv',''))
00276     
00277     #Evaluating the polynomial through all the time values
00278     z1_val = np.polyval(z1, values_filt)
00279     z2_val = np.polyval(z2, values_filt)
00280     z3_val = np.polyval(z3, values_filt)
00281     
00282    # Getting the residuals from the fit functions compared to the real values
00283     z1_res = time_values - z1_val
00284     z2_res = time_values - z2_val
00285     z3_res = time_values - z3_val
00286     
00287     pylab.plot(time_values, z1_res, time_values, z2_res, time_values, z3_res)
00288     
00289     pylab.grid()
00290     
00291     pylab.legend(('Residuals 1st order', 'Residuals 2nd order', 'Residuals 3rd order'))
00292     
00293 ####################
00294 # Polynomial Evaluation for the filtered signal and the function from the non-moving case
00295 ####################
00296 
00297     if(mode == "update"):
00298         pylab.figure(6)
00299 
00300         
00301         poly_vals = np.polyval(abcd, values_filt)
00302        
00303         
00304         pylab.plot(values_filt, poly_vals, values_filt, time_values)
00305 
00306         pylab.legend(('Polynomial', 'Real'))
00307         
00308         pylab.grid()
00309         #####
00310         pylab.figure(7)
00311         
00312         pylab.ylabel("Time available(seconds)")
00313         pylab.xlabel("Voltage(mV)")
00314         pylab.title("Time x Volt,file="+ filename.replace('.csv',''))
00315         pylab.grid(True)
00316 
00317         poly_vals = np.polyval(abcd, values_filt)
00318         
00319         ss = lambda y1, y2: ((y1-y2)**2).sum()
00320 
00321         #theta = -0.07
00322         #new_x = values_filt*cos(theta) - poly_vals*sin(theta)
00323         #new_y = values_filt*sin(theta) + poly_vals*cos(theta)
00324 
00325         theta = -0.2
00326         theta_values = []
00327         cost_values = []
00328         off_values = []
00329 
00330         while theta < 0.2:
00331             theta +=0.01
00332             new_x = values_filt*cos(theta) - poly_vals*sin(theta)
00333             new_y = values_filt*sin(theta) + poly_vals*cos(theta)
00334 
00335 
00336             off_y = -6000
00337 
00338             cost_values_i =[]
00339             off_y_values_i=[]
00340 
00341             while off_y < 6000:
00342                 off_y +=200
00343                 new_y_temp = new_y
00344                 new_y_temp = new_y_temp + off_y
00345 
00346                 ss1=ss(time_values,new_y_temp)
00347                 print ss1, off_y
00348 
00349                 cost_values_i.append(ss1)
00350                 off_y_values_i.append(off_y)
00351 
00352             #ss1=ss(time_values,new_y)
00353             #print ss1, theta
00354             #cost_values.append(ss1)
00355             theta_values.append(theta)
00356             cost_min = min(cost_values_i)
00357             cost_min_index = cost_values_i.index(cost_min)
00358             cost_values.append(cost_values_i[cost_min_index])
00359             off_values.append(off_y_values_i[cost_min_index])
00360 
00361         cost_min = min(cost_values)
00362         cost_min_index = cost_values.index(cost_min)
00363 
00364         theta = theta_values[cost_min_index]
00365         off_y = off_values[cost_min_index]
00366 
00367         new_x = values_filt*cos(theta) - poly_vals*sin(theta)
00368         new_y = values_filt*sin(theta) + poly_vals*cos(theta)
00369 
00370         new_y = new_y + off_y
00371         
00372         yl["abcd"] = abcd
00373         yl["theta"] = theta
00374         yl["off_y"] = off_y
00375         yl["maximum_time"] = (float)(new_y[0])
00376 
00377         pylab.plot(poly_vals, values_filt, time_values, values_filt, new_y, values_filt)
00378 
00379         pylab.legend(('Poly not moving', 'Real', 'Shifted Fit'))
00380     
00381     yaml.safe_dump(yl, yaml_file,default_flow_style=False)
00382     
00383     yaml_file.close()
00384 
00385     pylab.show()
00386 
00387 
00388    
00389 if __name__=="__main__":
00390     main(sys.argv[1:])


cob_voltage_control
Author(s): Alexander Bubeck
autogenerated on Thu Aug 27 2015 12:45:45