%% Generate Feed-Forward Flux Parameters
%
% Using MathWorks tools, you can create lookup tables for an interior
% permanent magnet synchronous motor (PMSM) controller that characterizes 
% the d-axis and q-axis flux as a function of d-axis and q-axis currents.  
% |VisualizeFluxSurface| loads the flux data and calls |interp2| to 
% interpolate the table data using a spline. Spline interpolation increases 
% table and breakpoint resolution.  

% Copyright 2017-2018 The MathWorks, Inc.
%% Step 1: Load and Preprocess Data
%
% Load the data from a |mat| file captured from a dynamometer or 
% another CAE tool.
load FEAdata.mat;

% Load the data matrix.
lambda_d = FEAdata.flux.d;
lambda_q = FEAdata.flux.q;
id = FEAdata.current.d;
iq = FEAdata.current.q;

%% Step 2: Generate Evenly Spaced Data
%
% The flux tables flux_d and flux_q can have different step sizes for id
% and iq because id is primarily dependent on d-axis flux and iq is
% primarily dependent on q-axis flux. Evenly spacing the rows and columns
% helps improve interpolation accuracy.

% Set the spacing for the table rows and columns 
flux_d_size = 50;
flux_q_size = 50;

% Use spline interpolation to get higher resolution
id_new = linspace(min(id),max(id),flux_d_size);
iq_new = linspace(min(iq),max(iq),flux_q_size);
lambda_d_new = interp2(id',iq,lambda_d,id_new',iq_new,'spline');
lambda_q_new = interp2(id',iq,lambda_q,id_new',iq_new,'spline');

%Visualize the flux surface
figure;
mesh(id_new,iq_new,lambda_d_new);
xlabel('I_d [A]')
ylabel('I_q [A]')
title('\lambda_d'); grid on;

figure;
mesh(id_new,iq_new,lambda_q_new);
xlabel('I_d [A]')
ylabel('I_q [A]')
title('\lambda_q'); grid on;

%% Step 3: Set Block Parameters
%
% Set MATLAB workspace variables that you can use
% for the Flux-Based PM Controller block parameters.

% Set the breakpoints
id_index=id_new;
iq_index=iq_new;

% Set the table data
lambda_d=lambda_d_new;
lambda_q=lambda_q_new;
