%***********************************************************************
%
%	COMPUTES THE AFFINE TRANSFORMATION USED IN BATTERY CURRENT AND
%       VOLTAGE MEASUREMENTS USING THE DATA PROVIDED IN A FILE
%
%	By	:	Haldun KOMSUOGLU
%	Start	:	03/06/2002
%	Last	:	03/06/2002
%	Statue  :	DARPA Project Material
%
%       Inputs:
%
%       Outputs:
%
%       Notes:
%        1) Assumes that the data file is a text file with 4 columns where
%           the columns are ordered as follows:
%                   V_phy   V_meas   I_phy   I_meas
%
%***********************************************************************
function compute_power_calib;

% ### The experimental data on battery current and voltage and their
%     associated measurements
% ###
DATA = load( 'power.data' );
% ---- Battery voltage related measurements
Vbatt = DATA( :, 1 );
Vmeas = DATA( :, 2 );
% ---- Battery current related measurements
Ibatt = DATA( :, 3 );
Imeas = DATA( :, 4 );

% ### Using Linear Squares Fit find the affine maps from the measurements
%     to the real values
% ###
% ---- Compute affine map for the voltage
[Pv, Sv ] = polyfit( Vmeas, Vbatt, 1 );
% ---- Compute affine map for the current
[Pi, Si ] = polyfit( Imeas, Ibatt, 1 );

% ### Plot the data to show the fit performance
% ###
% ---- Plot the voltage data and the fit
figure( 1 );
hold on;
plot( Vmeas, Vbatt, 'r*' );
plot( Vmeas, polyval( Pv, Vmeas ), 'b-' );
grid;
title( 'Battery Voltage Calibration' ); 
xlabel( 'Vmeas' );
ylabel( 'Vbatt' );
% ---- Plot the current data and the fit
figure( 2 );
hold on;
plot( Imeas, Ibatt, 'r*' );
plot( Imeas, polyval( Pi, Imeas ), 'b-' );
grid;
title( 'Battery Current Calibration' ); 
xlabel( 'Imeas' );
ylabel( 'Ibatt' );


% ### Display the coefficients to be used in RHexLib
% ###
disp( 'RHexLib power measurment calibration settings' );
disp( '---------------------------------------------' );
% ---- Build the voltage measurment configuration line
V_text = sprintf( 'float batt_voltage_calib = %.5f %.5f ;', -Pv(2)/Pv(1), Pv(1)  );
disp( V_text );
% ---- Build the current measurment configuration line
I_text = sprintf( 'float batt_current_calib = %.5f %.5f;', -Pi(2)/Pi(1), Pi(1)  );
disp( I_text );


