% run the gdxmrw_tr1 example

% In this example, we use a standard (non-indexed) GDX file created in
% Matlab via GDXMRW's wgdx() call to drive the transport model.  We
% read a similar file containing the solution back in to verify that
% the result is as expected.

clear all

% read in the raw data for the trnsport model
trdata

Is.name = 'I';
Is.ts   = 'canning plants';
Is.type = 'set';
Is.uels = {'seattle', 'san-diego'};

Js.name = 'J';
Js.ts   = 'markets';
Js.type = 'set';
Js.uels = {'new-york', 'chicago', 'topeka'};

caps.name = 'a';
caps.ts   = 'capacity of plant i in cases';
caps.type = 'parameter';
caps.val = cap';
caps.form = 'full';
caps.dim = 1;
caps.uels = Is.uels;

dems.name = 'b';
dems.ts   = 'demand at market j in cases';
dems.type = 'parameter';
dems.val = dem';
dems.form = 'full';
dems.dim = 1;
dems.uels = Js.uels;

dists.name = 'd';
dists.ts   = 'distance in thousands of miles';
dists.type = 'parameter';
dists.val = distance;
dists.form = 'full';
dists.dim = 2;
dists.uels{1} = Is.uels;
dists.uels{2} = Js.uels;

fs.name = 'f';
fs.ts   = 'freight in dollars per case per thousand miles';
fs.type = 'parameter';
fs.val = f;
fs.form = 'full';
fs.dim = 0;

wgdx ('trdat1', Is, Js, caps, dems, dists, fs);
fprintf('Matlab data written to GDX file trdat1\n');

solGDX = 'trsol1.gdx';
if exist(solGDX,'file')
  delete (solGDX);
end

flag = system ('gams gdxmrw_tr1 lo=2');

if flag ~= 0
  error('gams run failed: rc = %d', flag);
end
if ~ exist(solGDX,'file')
   error([ 'Results file ', solGDX, ' does not exist after gams run' ]);
end
fprintf('Model gdxmrw_tr1.gms finished\n');

% now get the outputs from the GDX file produced by the GAMS run
rs = struct('name','modelStat','form','full');
r = rgdx (solGDX, rs);
modelstat = r.val;

rs.name = 'solveStat';
r = rgdx (solGDX, rs);
solvestat = r.val;

fprintf('modelstat = %d (1 = optimal solution)\n', modelstat);
fprintf('solvestat = %d (1 = normal completion)\n\n', solvestat);

if (modelstat ~= 1) || (solvestat ~= 1)
  error ('Model not solved as expected')
end

rs.name = 'z';
rs.field = 'l';
r = rgdx (solGDX, rs);
z = r.val;

rs.name = 'x';
rs.uels{1} = Is.uels;
rs.uels{2} = Js.uels;
r = rgdx (solGDX, rs);
x = r.val;

fprintf('optimal value = %g\n\n', z);
