%% MBD - EcoCAR 2
%Driver Model Initialization file
%David Ord

%% Vehicle Parameters

MDL.VehicleDynamics.M = 1700;           %vehicle mass [kg]
MDL.VehicleDynamics.Mi = 1.04*MDL.VehicleDynamics.M;        %intertial mass [kg]
MDL.VehicleDynamics.c_rr = 0.01;        %coefficient of rolling resistance
MDL.VehicleDynamics.r_w = 0.324;        %wheel radius [m]
MDL.VehicleDynamics.CdA = 0.76;         %Coefficient of drag mult. with frontal area [m^2]
MDL.VehicleDynamics.rho = 1.2;          %air density [kg/m^3]
MDL.VehicleDynamics.grade = 0;          %road grade [%]
MDL.VehicleDynamics.g = 9.81;           %gravitational constant [m/s^2]
MDL.VehicleDynamics.V_i = 0;            %initial velocity [m/s]

%% Engine Model Parameters

MDL.EngineModel.C0 = 20000;
MDL.EngineModel.C1 = 1.3;
MDL.EngineModel.C2 = 0.0042/1000;

MDL.EngineModel.AccyLoad = 600;
MDL.EngineModel.MaxPwr = 110000;

%% Driveline Model Parameters

MDL.DrivelineModel.C0 = 600;
MDL.DrivelineModel.C1 = 0.012;
MDL.DrivelineModel.C2 = 0.00000049;

MDL.DrivelineModel.Ftr_max = 8000;

%% Driver Model Parameters

MDL.DriverModel.Kp = 350;
MDL.DriverModel.Ki = 0;
MDL.DriverModel.Kd = 0;

MDL.DriverModel.BrakeGain = 100;
MDL.DriverModel.Ftr_Max = 8000;
MDL.DriverModel.Ptr_Max = 110000;

%% Load Drive Cycles from Excel File

MDL.DriveCycle.UDDS = xlsread('DriveCycles_Scaled.xls',2,'A4:B1376');
MDL.DriveCycle.DC505 = xlsread('DriveCycles_Scaled.xls',3,'A4:B509');
MDL.DriveCycle.FTP = xlsread('DriveCycles_Scaled.xls',4,'A4:B2481');
MDL.DriveCycle.HWFET = xlsread('DriveCycles_Scaled.xls',5,'A4:B769');
MDL.DriveCycle.US06 = xlsread('DriveCycles_Scaled.xls',6,'A4:B600');
MDL.DriveCycle.US06C = xlsread('DriveCycles_Scaled.xls',7,'A4:B236');
MDL.DriveCycle.US06H = xlsread('DriveCycles_Scaled.xls',9,'A4:B374');

%% Run and Plot results

DriveCycle = MDL.DriveCycle.UDDS;
MDL.VehicleDynamics.T = length(DriveCycle);

sim('NTER_Assign3_SOLUTION')

figure
hold on
grid on
box on
plot(0:1:MDL.VehicleDynamics.T-1, DriveCycle(:,2),'r','LineWidth',2)
plot(tout,yout(:,7)*2.23694)    %m/s to mph
title('Velocity vs. Time')
xlabel('Time, t (s)')
ylabel('Velocity, V (mph)')

figure
scatter(yout(:,7)*3.6,yout(:,1)/1000,'.')
grid on
box on
title('Tractive Force vs. Vehicle Speed')
xlabel('Vehicle Speed, V (kph)')
ylabel('Tractive Force, Ftr (kN)')

mpg = yout(end,9)*0.000621371/yout(end,2)
fuelmass = yout(end,3)
enginelosses = yout(end,4)/1000
drivelinelosses = yout(end,5)/1000
totalEtr = yout(end,17)/1000
posEtr = yout(end,18)/1000
negEtr = yout(end,19)/1000


