-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathGAMS.m
1721 lines (1498 loc) · 73.8 KB
/
GAMS.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef GAMS < handle
%GAMS Interface class to call GAMS models from within Matlab
% This class can be used for quick scenario generation and result
% analysis for GAMS models. Call 'help GAMS.method_name' for information
% on individual methods. Get started by: set, param, getGDX, putGDX and
% getXLS.
%
% Methods
% g = GAMS constructor, set paths
% g.setPath set paths to GAMS, model, result
% g.setMail set preferences
% g.run execute GAMS
%
% Static methods
%
% GAMS.set create set
% GAMS.param create parameter
%
% GAMS.getGDX read a symbol from GDX file
% GAMS.putGDX write set or parameter to GDX file
% GAMS.globGDX read symbol from multiple GDX files
% GAMS.getXLS read entity from XLS file
% GAMS.putXLS write sets, params, variables to XLS file
%
% GAMS.rectify make data structure compliant to given uels
% GAMS.merge merge contents of two data structures into one
% GAMS.sum summarize multi-dimensional data structures
%
% GAMS.to_uels creates uels {'1' '2' '3'} from [1:3]
% GAMS.uel_to_ids create ids from uels
% GAMS.full_to_sparse convert value matrix form
% GAMS.sparse_to_full convert value matrix from
%
% GAMS.GDX2MDB convert GDX file to MS Access MDB
%
% Example
% [set_node att_node db_node] = GAMS.getXLS('input.xlsx', 'Node');
% GAMS.putGDX('node.gdx',set_node,att_node,db_node);
% g = GAMS(struct('model','fuelstation.gms'));
% g.run();
% total_cost = GAMS.getGDX('result.gdx','z');
%
properties
path % paths for GAMS binary and model file
status % return code of last GAMS run
result % stdout of last GAMS run
end
methods
function obj = GAMS(path) % constructor initialises variables
%GAMS.GAMS constructs a GAMS object
%
% Usage
% obj = GAMS(path)
%
% Parameters
% path struct with the following fields
% gams path to GAMS executable ('gams.exe')
% model path to model file ('model.gms')
% result path to result file ('result.gdx')
% missing fields are replaced by the default
% values (in parenthesis above)
%
% Returns
% obj GAMS object
%
% create empty struct if called without input parameter
if nargin == 0, path = struct(); end
obj.setPath(path);
end
function [status, result] = run(obj, verbose)
%GAMS.run calls GAMS and collects return code
% Executes 'gams model.gms', where both path to gams
% and to model file are taken from the objects property path.
%
% Usage
% [status, result] = G.run(verbose)
%
% Parameters
% verbose (optional) integer, specifies how many
% lines of the GAMS stdout to be displayed in
% the command window
% default: 0 (=off)
%
% Returns
% status Return code. Non-zero values indicate errors
% result STDOUT GAMS output, different from *.lst!
%
if nargin < 2, verbose = 0; end
% create run command
if isfield(obj.path,'result')
gams_command = sprintf('"%s" "%s" -GDX="%s" -lo=3\n', obj.path.gams, obj.path.model, obj.path.result);
else
gams_command = sprintf('"%s" "%s" -lo=3\n', obj.path.gams, obj.path.model);
end
% execute command
tstart = tic;
[status, result] = system(gams_command);
telapsed = toc(tstart);
% catch status and result
dlmwrite(strrep(obj.path.model,'.gms','.log'), result, 'delimiter', '', 'newline', 'pc');
obj.result = regexp(result, '[\f\n\r]', 'split');
obj.status = status;
result = char(obj.result);
% optional: display last lines of output
if verbose > 0
verbose = min(size(result,1)-1, verbose);
disp(result(end-verbose:end,:));
end
end
function setPath(obj, path)
%GAMS.setPath sets path property
%
% Usage
% g.setPath(path)
%
% Parameters
% path struct with the following fields
% gams path to GAMS executable ('gams.exe')
% model path to model file ('model.gms')
% result path to result file ('result.gdx')
% missing fields are replaced by the default
% values (in parenthesis above)
%
% Returns
% nothing
%
% set up struct with default values
defaultpath = struct(...
'gams','gams.exe',...
'model','model.gms',...
'result','result.gdx');
% now fill up missing values in path structure with defaults
fns = fieldnames(defaultpath);
for fn=fns'
fn=char(fn); %#ok<FXSET>
% checks, whether fn exists as field in parameter path
if sum(strcmp(fieldnames(path),fn)) == 0
% if not, copy default value
path.(fn) = defaultpath.(fn);
% warn if no model filename was given
if strcmp(fn,'model_file'), warning(WrongNumberOfArguments,['No model file given, default ''' defaultpath.model_file ''' is used.']); end
end
end
% assign path structure to created object that is returned
obj.path = path;
end
end
methods (Static)
function Gset = set(name, vals, onsets, form)
%GAMS.set creates GAMS set data structure
% Used to create one- and multi-dimensional sets from MATLAB
% data structure
% Example
% g_sites = GAMS.set('Site', {'AT', 'DE'});
%
% Usage
% S = GAMS.set(name, vals, onsets, form)
%
% Parameters
% name name of set (string)
% vals list of values (cell array of elements;
% element may be a string [one-dimensional]
% or a cell array of strings [multi-dimensional])
% alternative: logical incidence matrix
% onsets list of domain sets for multi-dimensional
% (cell array of cell arrays like vals)
% form (optional) 'full' or 'sparse' (default: 'full')
% try sparse when using extremely huge
% datasets with very few existing
% (onset-)combinations
%
% Returns
% S.name name of variable, equation, parameter
% S.type 'set'
% S.val incidence matrix (nd-array)
% S.form 'full' or 'sparse'
% S.uels cell array of dimension labels
% S.ids structures with dimension labels as fieldnames
%
% Advanced examples
% % multi-dimensional sets
% node = {'AT' 'DE' 'FR' 'ES'};
% edge = {{'AT' 'DE'} {'DE' 'FR'} {'FR' 'ES'}};
% g_node = GAMS.set('Node',node);
% g_edge = GAMS.set('Edge',edge,{node node});
% GAMS.putGDX('grid.gdx',g_node,g_edge);
%
% % sets with numeric entries are possible, but must
% % be converted to cell arrays when used as onsets
% t = 1:5; % main set
% t0 = 1; % subset
% g_time = GAMS.set('Time',t);
% g_t0 = GAMS.set('T0',t0,g_time.uels); % domain check
% GAMS.putGDX('time.gdx',g_time,g_t0);
%
% sparse option checking
if nargin < 4, form = 'full'; end
if sum(strcmp({'full' 'sparse'}, form)) ~= 1
error('GAMS:set:WrongForm', 'Optional rgument form must be ''full'' (default) or ''sparse''');
end
% convert numeric inputs to cell array of strings
if isnumeric(vals)
vals = reshape(vals,numel(vals),1);
vals = cellstr(num2str(vals,'%-g'))';
end
if nargin > 2 % multi-dimensional sets or one-dimensional subsets
% handle dimensions defined by number of onsets
dimensionality = cellfun(@(x) size(x,2), onsets);
if numel(dimensionality) == 1
dimensionality = [1 dimensionality];
end
% create onset ids
ids = cell(1,length(onsets));
for d=1:length(onsets), ids{d} = GAMS.uel_to_ids(onsets{d}); end
if prod(dimensionality) > 1e8 || strcmp(form,'sparse')
% create sparse matrix
% incidence_matrix
incidence_matrix = zeros(numel(vals), length(dimensionality));
for k = 1:numel(vals)
el = vals(k);
if iscell(el{1}) % if element is multi-dimensional
el = el{:}; % unpack cell array wrapping around the element
end
indices = zeros(1,length(el));
for dim = 1:length(el) % for each dimension of the element
% determine subscripts of el in corresponding onset
matching_index = find(strcmp(onsets{dim},el{dim}));
% basic domain checking
if isempty(matching_index)
error(['GAMS.set: No matching ''' el{dim} ''' found in onset dimension ' num2str(dim) '!']);
end
indices(dim) = matching_index;
end
incidence_matrix(k,:) = indices;
end
Gset = struct(...
'name',name,...
'type','set',...
'val',incidence_matrix,...
'form','sparse',...
'dim',length(onsets),...
'uels',{onsets},...
'ids',{ids}...
);
else
% create full incidence matrix
% prepare incidence matrix
incidence_matrix = zeros(dimensionality);
if islogical(vals)
% special case: vals is already an incidence matrix
incidence_matrix = double(vals);
else
% now cycle through values and fill incidence matrix
for el = vals
if iscell(el{1}) % if element is multi-dimensional
el = el{:}; %#ok<FXSET> % unpack cell array wrapping around the element
end
indices = zeros(1,length(el));
for dim = 1:length(el) % for each dimension of the element
% determine subscripts of el in corresponding onset
matching_index = find(strcmp(onsets{dim},el{dim}));
% basic domain checking
if isempty(matching_index)
error(['GAMS.set: No matching ''' el{dim} ''' found in onset dimension ' num2str(dim) '!']);
end
indices(dim) = matching_index;
end
% and, because Matlab does not support indexing by vector
% of subscripts, convert the vector to a numeric cell array
% and use that to convert indices to a linear index using
% sub2ind.
indices_as_cell = num2cell(indices);
indices_linear = sub2ind(size(incidence_matrix),indices_as_cell{:});
incidence_matrix(indices_linear) = 1;
end
end
Gset = struct(...
'name',name,...
'type','set',...
'val',incidence_matrix,...
'form','full',...
'dim',length(onsets),...
'uels',{onsets},...
'ids',{ids}...
);
end
else % one-dimensional sets
% make every input a row vector of elements (=flat list)
vals = reshape(vals,1,numel(vals));
ids = GAMS.uel_to_ids(vals);
% create set data structure
Gset = struct(...
'name',name,...
'type','set',...
'val',ones(size(vals)),...
'form','full',...
'dim',1,...
'uels',{{vals}},...
'ids',{{ids}}...
);
end
end
function Gparam = param(name, vals, onsets, form)
%GAMS.set creates GAMS set data structure
% Used to create one- and multi-dimensional sets from MATLAB
% data structure
% Example
% g_param = GAMS.param('myParam', 5);
%
% Usage
% P = GAMS.param(name, vals, onsets, form)
%
% Parameters
% name name of parameter (string)
% vals matrix of values
% onsets list of domain set(s)
% (cell array of cell arrays)
% form (optional) 'full' or 'sparse' (default: 'full')
% try sparse when using extremely huge
% datasets with very few non-zero
% (onset-)combinations of values
%
% Returns
% P.name name of variable, equation, parameter
% P.type 'parameter'
% P.val value matrix (full: nd-array, sparse: matrix)
% P.uels cell array of dimension labels
% P.ids structures with dimension labels as fieldnames
% P.form 'full' or 'sparse'
% P.dim number of dimensions
%
%
% More examples
% % scalar parameter
% scalar = GAMS.param('scalar',5);
%
% % 1D parameter
% domain = {'a' 'b' 'c' 'd'};
% vals = [ 1 2 3 4];
% param = GAMS.param('param',vals,{domain});
%
% % 2D parameter on (node,atts)
% node = {'AT' 'DE' 'FR' 'ES'};
% atts = { 'demand' 'price' };
% vals = [ 100 5; 200 4; 300 2; 400 1 ];
% db_node = GAMS.param('db_node',vals,{node atts});
%
% % 3D parameter on (node,node,atts)
% edge = {{'AT' 'DE'} {'DE' 'FR'} {'FR' 'ES'}};
% atts = { 'length' 'capacity' };
% vals = [ 600 1; 800 3; 200 10 ];
% db_edge = GAMS.param('db_edge',vals,{edge atts});
%
% Last changed
% 2011-08-26 13:00 GMT+2 added this documentation
if nargin < 4, form = 'full'; end
if sum(strcmp({'full' 'sparse'}, form)) ~= 1
error('GAMS:param:WrongForm', 'Optional rgument form must be ''full'' (default) or ''sparse''');
end
if nargin == 2 % scalar parameer
Gparam = struct(...
'name',name,...
'type','parameter',...
'val', vals, ...
'form', 'full', ...
'dim', 0 ...
);
return
end
if ~iscell(onsets{1}{1}) % elementary onsets
% arbitrary number of dimensions (<20) allowed
value_matrix = vals;
ids = cell(1,length(onsets));
for d=1:length(onsets)
ids{d} = GAMS.uel_to_ids(onsets{d});
end
Gparam = struct(...
'name',name,...
'type','parameter',...
'val',value_matrix,...
'form','full',...
'dim',length(onsets),...
'uels',{onsets},...
'ids',{ids}...
);
else % multi-dimensional onsets{1}
% then onsets{2} is required and must be elementary
% initialise uels
Ndim = length(onsets{1}{1});
uels = cell(1,Ndim+1); % +1 for attribute dimension (from onsets{2})
% declare sparse 2D value matrix
[Nrows,Ncols] = size(vals);
value_matrix = zeros(numel(vals),Ndim+1);
% extract uels from onsets{1} by dimension, extract unique
% identifiers and assign positional references (using
% ismember) used in value_matrix
for k = 1:Ndim
uels_for_vals = cellfun(@(x) x{k},onsets{1},'UniformOutput',false);
uels{k} = unique(uels_for_vals);
% assign positional references to uels
% uels_for_vals = {'DE' 'AT' 'AT' 'DE' 'FR' }
% uels{k} = {'AT' 'DE' 'FR}
% --> loc = [2 1 1 2 3]
[~,loc] = ismember(uels_for_vals, uels{k});
% repeat each entry of loc Ncols times (one time for
% each attribute)
loc = repmat(loc, Ncols, 1);
value_matrix(:,k) = loc(:);
end
% increment Ndim by one to include the additional dimension
% spawned by attributes, add them to the uels cell array
% and add references (just repeating 1:Ncols for each row
% of vals) to the value_matrix
Ndim = Ndim + 1;
uels{Ndim} = onsets{2};
value_matrix(:, Ndim) = repmat(1:Ncols,1,Nrows);
% finally: copy attribute values to value_matrix
% reshape required for keeping right order (line by line,
% left to right), while a simple vals(:) would concatenate
% column by column
value_matrix(:, Ndim+1) = reshape(vals', [], 1);
% convert uels to ids
ids = cell(1,length(uels));
for d=1:length(uels)
ids{d} = GAMS.uel_to_ids(uels{d});
end
% create output data structure
Gparam = struct(...
'name',name,...
'type','parameter',...
'val',value_matrix,...
'form','sparse',...
'dim',Ndim,...
'uels',{uels},...
'ids',{ids}...
);
% and convert to full form if desired (default behaviour)
% and feasible (dimensionality in range)
if strcmp(form, 'full')
if prod(cellfun(@(x) size(x,2), Gparam.uels)) < 1e8
Gparam = GAMS.sparse_to_full(Gparam);
elseif nargin > 3
% warn if full data structure was desired
warning('GAMS:param:TooBigForFull',['Data structure ''' name ''' too big for full value matrix, fallback to sparse output.']);
end
end
end
end
function Gdata = rectify(Gdata, uels)
%GAMS.rectify makes variable or parameter conform to given uels
% Data delivered from GAMS.getGDX often has missing elements
% in some dimensions due to the sparse data structure that is
% handed back by rgdx. This helper functions automatically
% adds or removes values from Gdata in order to make it the
% size specified by the parameter uels. Missing entries are
% filled up with zeros in the value matrix, while superfluous
% entries are removed, issuing a warning.
% This function also sorts entries in value matrices, so
% that uels for all dimensions match after rectification.
% Example
% estocon = GAMS.getGDX('result.gdx','e_sto_con');
% estoin = GAMS.getGDX('result.gdx','e_sto_in');
% % estoin.uels{1} (timesteps) has missing elements, so
% % dimensions of value matrices do not match
% estoin = GAMS.rectify(estoin,estcon.uels);
% % now estoin.uels is identical to estocon.uels
%
% Usage
% Gdata = GAMS.rectify(Gdata, uels)
%
% Parameters
% Gdata a GAMS set, parameter or variable
% uels cell array of cell arrays of the desired uels;
% usually taken from (an)other Gdata object that
% is deemed complete in all dimensions
%
% Returns
% Gdata the rectified input parameter
%
if nargin ~= 2, error('GAMS:rectify:WrongNumberOfArguments','Wrong number of arguments.'); end
if length(uels) ~= length(Gdata.uels), error('GAMS:rectify:DifferentDimensions','Gdata and uels must have same number of dimensions.'); end
% initialize variables
Ndim = Gdata.dim;
[uels_to_copy, uels_to_remove, new_idx, old_idx, ids] = deal(cell(1,Ndim));
[dims, delete_count] = deal(zeros(1,Ndim)); % dimensionality vector, delete count
% Loop through each dimension
for d=1:Ndim
% calculate size of new value matrix
dims(d) = length(uels{d});
% convert uels to ids
ids{d} = GAMS.uel_to_ids(uels{d});
% determine which uels from Gdata will be kept and removed
uels_to_copy{d} = intersect(Gdata.uels{d}, uels{d});
uels_to_remove{d} = setdiff(Gdata.uels{d}, uels{d});
% from uels_to_copy, derive indexes for both old (Gdata)
% and new value matrix
new_idx{d} = zeros(1,length(uels_to_copy{d}));
for i=1:length(new_idx{d}), new_idx{d}(i) = find(strcmp(uels_to_copy{d}(i),uels{d})); end
old_idx{d} = zeros(1,length(uels_to_copy{d}));
for i=1:length(old_idx{d}), old_idx{d}(i) = find(strcmp(uels_to_copy{d}(i),Gdata.uels{d})); end
% from uels_to_remove, count
delete_count(d) = sum(cellfun(@(x) ~isempty(x),uels_to_remove{d}));
end
if sum(delete_count) > 0
if sum(delete_count) == 1
warning('GAMS:rectify:EntriesRemoved',['1 uel is removed from data structure ''' Gdata.name '''.']);
else
warning('GAMS:rectify:EntriesRemoved',[num2str(sum(delete_count)) ' uels are removed from data structure ''' Gdata.name '''.']);
end
end
% for vectors, value matrix becomes column vector
if length(dims) == 1, dims = [dims 1]; end
A = zeros(dims); % initialize new value matrix
A(new_idx{:}) = Gdata.val(old_idx{:}); % copy values
% create output data structure
Gdata.val = A;
Gdata.uels = uels;
Gdata.ids = ids;
end
function Gdata = merge(g1, g2)
%GAMS.merge merge contents of two data structures into one
% Data from two sets, variables or parameters are copied into
% one data structure that contains the contents of both
% inputs.
% Both inputs must be full (as in "not sparse") and have
% the same number of dimensions and type (set, parameter,
% variable or equation). Values of g2 overwrite values of g1.
% For scalar (zero-dimensional) data structures, merge
% falls back to adding the values of g1 and g2.
% Usage
% Gdata = GAMS.merge(g1, g2)
%
% Parameters
% g1 first GAMS data structure
% g2 second GAMS data structure
%
% Returns
% Gdata result GAMS data structure
% skip merge if one argument is empty
if isempty(g1) || isempty(g2)
if isempty(g2), Gdata = g1; end
if isempty(g1), Gdata = g2; end
return;
end
% error checking
if ~strcmp(g1.type, g2.type)
error('GAMS:merge:TypeMismatch','Both inputs must be of same type.');
end
if g1.dim ~= g2.dim
error('GAMS:merge:DimMismatch','Both inputs must have the same number of dimensions.');
end
if ~strcmp(g1.form,'full') || ~strcmp(g2.form,'full')
error('GAMS:merge:OnlyFull','Only full data structures can be merged. Please contact GAMS class maintainer if you need merging for sparse structures.');
end
% initialise temporary variables
[new_uels, new_ids, g1_idx, g2_idx] = deal(cell(1, g1.dim));
new_dims = zeros(1, g1.dim);
for d=1:g1.dim
% determine result uels, ids and size of value matrix
new_uels{d} = union(g1.uels{d}, g2.uels{d});
new_ids{d} = GAMS.uel_to_ids(new_uels{d});
new_dims(d) = length(new_uels{d});
if isnumeric(new_ids{d})
% if ids are a matrix, uels are numeric. In that case, sort
% them by value, not by literal
[new_ids{d}, sort_order] = sort(new_ids{d});
new_uels{d} = new_uels{d}(sort_order);
% determine indices in matrix A for copying values
[~, g1_idx{d}] = intersect(new_uels{d}, g1.uels{d});
[~, g2_idx{d}] = intersect(new_uels{d}, g2.uels{d});
% determine correct sort order
[~, g1_sort] = sort(new_ids{d}(g1_idx{d}));
[~, g2_sort] = sort(new_ids{d}(g2_idx{d}));
% and sort g1/g2_idx accordingly
g1_idx{d} = g1_idx{d}(g1_sort);
g2_idx{d} = g2_idx{d}(g2_sort);
% and clean up those sort vectors
clear sort_order g1_sort g2_sort;
else
% default behaviour for textual uels
% determine indices in matrix A for copying values
[~, g1_idx{d}] = intersect(new_uels{d}, g1.uels{d});
[~, g2_idx{d}] = intersect(new_uels{d}, g2.uels{d});
end
end
% for vectors, value matrix becomes column vector
if length(new_dims) == 1
new_dims = [new_dims 1];
g1.val = g1.val(:);
g2.val = g2.val(:);
end
if isempty(new_dims) % i.e. new_dims has length 0
% scalars are merged by adding their values
A = g1.val + g2.val;
else
% create value matrix
A = zeros(new_dims);
% copy values from g1
A(g1_idx{:}) = g1.val;
% copy values from g2
if strcmp(g1.type,'set')
% for sets, perform logical or "+" on set elements
A(g2_idx{:}) = A(g2_idx{:}) + g2.val;
A = min(1, A); % remove value 2 from incidence matrix
else
% for parameters, variables and equations,
% g2.val replaces an identical g1.val
A(g2_idx{:}) = g2.val;
end
end
% determine new name for data structure
if strcmp(g1.name, g2.name)
% keep original name if both are identical
new_name = g1.name;
else
% append names if names don't match
new_name = [g1.name '_' g2.name];
end
% construct result data structure
Gdata.name = new_name;
Gdata.type = g1.type;
Gdata.dim = g1.dim;
Gdata.val = A;
Gdata.uels = new_uels;
Gdata.ids = new_ids;
Gdata.form = g1.form;
% append field 'field' if inputs are variable or equation
if sum(strcmp(g1.type,{'variable' 'equation'})) > 0
Gdata.field = g1.field;
end
end
function Gdata = sum(Gdata, dims)
%GAMS.sum calculates sum for given dimensions
% Calculates sum of values for a given GAMS data structure.
% uels and ids are automatically adapted to match the
% result.
% Usage
% Gdata = GAMS.sum(Gdata, dims)
%
% Example
% % CO2Out(time, site, pro, coin, coout)
% co2_by_site = GAMS.sum(CO2Out, [1 3:5]);
%
% Parameters
% Gdata original data structure
% dims vector of dimensions
%
% Returns
% Gdata summarized data structure
%
if ~strcmp(Gdata.form,'full')
error('GAMS:sum:OnlyFull','Only full data structures can be summed. Please contact your GAMS class maintainer if you need summing for sparse structures.');
end
if max(dims) > Gdata.dim
error('GAMS:sum:WrongDimensions', ...
'Parameter dims contains wrong dimensions.');
end
% sort dimensions in descending order
dims = sort(dims(:),'descend')';
% vector of remaining dimensions
remaining_dims = setdiff(1:Gdata.dim, dims);
% sum value matrix...
for d=dims
Gdata.val = sum(Gdata.val, d);
end
% ... squeeze out any singleton dimensions...
Gdata.val = squeeze(Gdata.val);
% ... and change dim, uels and ids accordingly
Gdata.dim = length(remaining_dims);
Gdata.uels = Gdata.uels(remaining_dims);
Gdata.ids = Gdata.ids(remaining_dims);
end
function ids = uel_to_ids(uels)
%GAMS.uel_to_ids creates lookup structure for non-numeric uels
% This internal helper function creates a struct from a one-
% dimensional cell array, using its contents as fieldnames
% and their position 1..N as values. In case of numeric uels,
% this function returns the numeric array.
% Usage
% ids = GAMS.uel_to_ids(uels)
%
% Example
% ids = GAMS.uel_to_ids({'a' 'b' 'c'})
% % returns struct('a',1,'b',2,'c',3)
%
% Parameters
% uels one-dimensional cell array of uels
%
% Returns
% ids struct with uels as fieldnames or numeric array
%
if sum(isnan(str2double(uels))) == 0
% convert numeric uels
ids = str2double(uels);
else % provide id structure for easier access to named entries
uels = regexprep(uels,'[^A-Za-z0-9]','_');
uels = regexprep(uels,'^(\d|_)','x\1'); % if uel starts with a digit (\d) or underscore, prepend it with a character (here: x)
ids = cell2struct(num2cell(1:length(uels)),uels,2);
end
end
function uels = to_uels(vector)
%GAMS.to_uels converts a numeric vector to cell array of strings
% Usage
% uels = GAMS.to_uels(vector)
%
% Example
% uels = GAMS.to_uels(1:4)
% % returns {'1', '2', '3', '4'}
%
vals = reshape(vector,numel(vector),1);
uels = cellstr(num2str(vals,'%-g'))';
end
function Gparam = sparse_to_full(Gparam)
%GAMS.sparse_to_full converts sparse value matrix to full form
% This internal helper function is needed to convert sparse
% data structures as delivered from rgdx to the compact
% internal representations with nd-arrays.
% Usage
% param_full = GAMS.sparse_to_full(param_sparse)
%
% Parameters
% param_sparse sparse data structure
%
% Returns
% param_full full data structure
%
if ~(strcmp(Gparam.form,'sparse') && strcmp(Gparam.type,'parameter'))
error('GAMS:sparse_to_full:WrongType','Argument either no parameter or not sparse.');
end
% determine dimensionality of output
Ndim = length(Gparam.uels);
dims = zeros(1,Ndim);
% initialise value matrix
for k=1:Ndim
dims(k) = length(Gparam.uels{k});
end
value_matrix = zeros(dims);
% loop through values
for v=1:size(Gparam.val,1)
% convert subscript vector to cell array
idx = num2cell(Gparam.val(v,1:Ndim));
% use subscript vector for position addressing in value matrix
value_matrix(idx{:}) = Gparam.val(v,Ndim+1);
end
% create output
Gparam.val = value_matrix;
Gparam.form = 'full';
end
function Gparam = full_to_sparse(Gparam)
%GAMS.full_to_sparse converts full value matrix to sparse form
% This function converts the value matrix of a (default) full
% GAMS data structure to the 2-dimension sparse form.
% Supported data structures are sets, parameters and
% variables. Equations might work as well (untested).
% Usage
% Gdata_sparse = GAMS.full_to_sparse(Gdata_full)
%
% Parameters
% Gdata_full full data structure
%
% Returns
% Gdata_sparse sparse data structure
%
if ~(strcmp(Gparam.form,'full'))
error('GAMS:full_to_sparse:WrongType','Argument not full.');
end
% fix for row vector value matrices that acutally should be
% column vectors according to its uels. Example:
% name: 'x'
% type: 'parameter'
% val: [1 2 3]
% form: 'full'
% dim: 2
% uels: {{'a' 'b' 'c'} {'one'}}
% In this case and this case only, the value matrix is brought
% to column vector form.
if Gparam.dim == 2 && size(Gparam.val,1) == 1 && length(Gparam.uels{2}) == 1
Gparam.val = Gparam.val(:);
end
% find positions (linear index) of non-zero entries
non_zero_entries = find(Gparam.val);
% derive size of sparse value matrix
Ndim = Gparam.dim;
Nval = numel(non_zero_entries);
dims = size(Gparam.val);
idx = cell(1,Ndim);
value_matrix = zeros(Nval, Ndim+1);
% loop through all non-zero values
for v=1:Nval
% create subscript vector idx from linear index
[idx{:}] = ind2sub(dims, non_zero_entries(v));
% write idx to first Ndim columns of value matrix
value_matrix(v,1:Ndim) = cell2mat(idx);
% add value to last column
value_matrix(v,Ndim+1) = Gparam.val(non_zero_entries(v));
end
% special set treatment
if strcmp(Gparam.type, 'set')
% remove incidence column
Gparam.val = value_matrix(:,1:end-1);
else % parameter, variable, equation
Gparam.val = value_matrix;
end
% create output
Gparam.form = 'sparse';
Gparam.val = sortrows(Gparam.val);
end
% GDX import/export
function Gdata = getGDX(filename, var, form, field)
%GAMS.getGDX Reads GDX file to compact value array
% GAMS.getGDX is a wrapper function for rgdx, returning a
% structure read from a GDX file.
% Example
% EprOut = GAMS.getGDX('result.gdx', 'eprout')
%
% Usage
% G = GAMS.getGDX(filename, name, form, field)
%
% Parameters
% filename file name of GDX file to be read
% name name of variable, equation, set or parameter
% form (optional) form of output data structure
% possible: 'full' or 'sparse'
% default: 'full' if possible, 'sparse' else
% field (optional) field to be read. l is level or
% actual value, m is marginal value, lo and
% up are the boundaries of a value
% possible: 'l', 'm', 'lo', 'up'
% default: 'l'
%
% Returns
% G.name name of variable, equation, parameter
% G.type type ('variable', 'equation', ...) of name
% G.dim array of dimension size, same as SIZE(G.val)
% G.val nd-array of values
% G.uels cell array of dimension labels
% G.ids structures with dimension labels as fieldnames
% G.form form of value matrix: 'full' or 'sparse'
% G.field field of value matrix: 'l', 'm', 'lo' or 'up'
%
if nargin < 2, error('Wrong number of arguments: getGDX(filename[, var][, form][, field])'); end
if isempty(dir(filename)), error('File not found.'); end
if length(strfind(filename,'.')) ~= 1
% rgdx() cannot handle filenames with more than one '.'.
% Those files are temporarily copied in order to generate
% a save name ... (1)
tempdire = tempname('C:');
mkdir(tempdire);
tempfile = [tempname(tempdire) '.gdx'];
copyfile(filename, tempfile);
rgdxfn = tempfile;
else
rgdxfn = filename;
end
if nargin < 3 || strcmp(form,''), form = 'full'; end
if nargin < 4, field = 'l'; end
% read GDX file using rgdx()
rgdxopt = struct('name', var, 'compress', true);
if nargin > 3, rgdxopt.field = field; end
g = rgdx(rgdxfn, rgdxopt);
if length(strfind(filename,'.')) ~= 1
% (1) ... and deleted afterwards
delete(tempfile);
rmdir(tempdire);
end
% UELS AND IDENTIFIERS
C = cell(1, g.dim); % uels
I = cell(1, g.dim); % ids
dims = zeros(1, g.dim); % vector of lengths per dimension
for k=1:g.dim
dims(k) = length(g.uels{k});
C{k} = g.uels{k};
if sum(isnan(str2double(g.uels{k}))) == 0 % convert numeric uels