function parameterEstimationSdoBattery_setup(p)
%PARAMETERESTIMATIONSDOBATTERY_SETUP
%
% Solve a parameter estimation problem for the sdoBattery model.
%
% The function sets up an estimation problem to be solved in deployed mode.
%
% The input argument, p, defines the model parameters to estimate,
% if omitted the parameters specified in the function body are estimated.
%
% Modify the function to include or exclude new experiments, or
% to change the estimation options.
%

% Copyright 2020 The MathWorks, Inc.


%% Open the model.
open_system('sdoBattery')


%% Specify Model Parameters to Estimate
%
if nargin < 1 || isempty(p)
    p = sdo.getParameterFromModel('sdoBattery',{'K','Loss','Qmax','Q0','V'});
    p(1).Value = 0.32;
    p(1).Free = 0;
    p(2).Value = 0.012;
    p(2).Free = 0;
    p(3).Value = 250;
    p(3).Minimum = 0;
    p(3).Scale = 256;
    p(4).Value = 150;
    p(4).Minimum = 0;
    p(4).Scale = 256;
    p(5).Value = 400;
    p(5).Free = 0;
end


%%
% Update Parameters for this Vehicle in the Database
vin = "4DEF";
load sdoBatteryVinDatabase vinDatabase
carData =  vinDatabase(vin);
for ct = 1:width(carData)
    variableName = carData.Properties.VariableNames{ct};
    bIdx = strcmp(variableName,{p.Name});
    carData{'CurrentValue',variableName} = p(bIdx).Value;
end
vinDatabase(vin) = carData;


%% Define the Estimation Experiments
%

% Load the experiment data
data = readtable('sdoBattery_Data1.csv');

% Create the experiment
Exper = sdo.Experiment('sdoBattery');

%%
% Specify the experiment input data used to generate the output.
Exper_Sig_Input = Simulink.SimulationData.Signal;
Exper_Sig_Input.Values    = timeseries(data.Current,data.Time);
Exper_Sig_Input.BlockPath = 'sdoBattery/Current';
Exper_Sig_Input.PortType  = 'outport';
Exper_Sig_Input.PortIndex = 1;
Exper_Sig_Input.Name      = 'Current';
Exper.InputData = Exper_Sig_Input;

%%
% Specify the measured experiment output data.
Exper_Sig_Output = Simulink.SimulationData.Signal;
Exper_Sig_Output.Values    = timeseries(data.Voltage,data.Time);
Exper_Sig_Output.BlockPath = 'sdoBattery/SOC -> Voltage';
Exper_Sig_Output.PortType  = 'outport';
Exper_Sig_Output.PortIndex = 1;
Exper_Sig_Output.Name      = 'sdoBattery/SOC -> Voltage:1';
Exper.OutputData = Exper_Sig_Output;


%% Configure objects for deployment and save to a MATLAB file
%
Exper = prepareToDeploy(Exper);
%
Simulator = createSimulator(Exper);
Simulator = prepareToDeploy(Simulator,p);
save sdoBatteryObjectsToDeploy Exper Simulator p vinDatabase
end