-
Notifications
You must be signed in to change notification settings - Fork 4
/
Ksysid.m
2166 lines (1854 loc) · 102 KB
/
Ksysid.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 Ksysid
%Ksysid: Class for doing Koopman-based sysid
% Constructed from a sample set of data from an experiment or simulation.
properties
params struct; % sysid parameters
lift struct; % contains matlab generated lifting functions
basis struct; % contains the observables for the system
model; % contains the bese lifted system model of system (chosen from candidates)
candidates; % candidate models trained with different lasso params
koopData; % info related to the training of koopman operator
scaledown; % contains scaling functions for y,u,zeta to lie in [-1,1]
scaleup; % contains scaling from [-1,1] to real life range
% properties that can be set using Name,Value pair input to constructor
isupdate; % true if this should overwrite an existing model when saving, false otherwise
obs_type; % cell array of the types of observables to include in model
obs_degree; % array of the degree/complexity of each type of observable
snapshots; % number of snapshot pairs to use in training
lasso; % lasso L1 regularization penalty weight
delays; % number of delays to include
liftinput; % if 1, input is lifted along with state, yielding nonlinear model
model_type; % 'linear' or 'nonlinear'
loaded; % true or false. Does the system include loads?
dim_red; % true or false. Should SVD dimensional reduction be performed?
time_type; % 'discrete' or 'continuous'
traindata; % scaled exp/sim data for training the model
valdata; % scaled exp/sim data for validating the model
snapshotPairs; % snapshot pairs extracted from training data
end
methods
function obj = Ksysid( data4sysid , varargin )
%CLASS CONSTRUCTOR
% data - struct with fields t,x,u,y. Contains results of a
% simuation or experiment of the system to be identified
% (note: this is not necessarily the same data to be used for
% sysid, it just provides the dimensions of the state, input,
% etc.)
% verify that data4sysid has required fields
if ~isfield( data4sysid , 'train' ) || ~isfield( data4sysid , 'val' )
error('Input must have *train* and *val* fields of type cell array');
end
% isolate one trial to extract some model parameters
data = data4sysid.train{1};
data4train = data4sysid.train;
data4val = data4sysid.val;
% set param values based on the data
obj.params = struct; % initialize params struct
obj.params.n = size( data.y , 2 ); % dimension of measured state
obj.params.m = size( data.u , 2 ); % dimension of input
obj.params.Ts = mean( data.t(2:end) - data.t(1:end-1) ); % sampling time
obj.params.isfake = false; % assume system is real
% if data has a params field save it as sysParams
if isfield( data , 'params' )
obj.params.sysParams = data.params;
obj.params.isfake = true; % if params field exist the system is fake
end
% initialize structs
obj.lift = struct; % initialize lift struct
obj.basis = struct; % initialize basis struct
% set defualt values of Name, Value optional arguments
obj.isupdate = false;
obj.obs_type = { 'poly' };
obj.obs_degree = [ 1 ];
obj.snapshots = Inf;
obj.lasso = [ 1e6 ]; % default is least squares solution
obj.delays = 0; % default 0 (was 1 to ensure model is dynamic)
obj.model_type = 'linear';
obj.loaded = false;
obj.time_type = 'discrete';
% replace default values with user input values
obj = obj.parse_args( varargin{:} );
obj.params.nd = obj.delays; % saves copy in params (for consistency with mpc class)
obj.params.nzeta = obj.params.n * ( obj.delays + 1 ) + obj.params.m * obj.delays;
% specify dimension of the loading condition
if obj.loaded && isfield( data , 'w' )
obj.params.nw = size( data.w , 2 );
else
obj.params.nw = 0;
end
% verify specified model type is valid
if strcmp( obj.model_type , 'linear' )
obj.liftinput = 0; % default is not to lift input
elseif strcmp( obj.model_type , 'nonlinear' )
obj.liftinput = 1; % lift the input
elseif strcmp( obj.model_type , 'bilinear' )
obj.liftinput = 2; % lift the input (try to avoid using this parameter)
else
error('Invalid model_type chosen. Must be linear, bilinear, or nonlinear.');
end
% make sure if user specifies a "loaded" model the data has a load field (w)
if obj.loaded && ~isfield( data , 'w' )
error('You have specified a loaded system, but your training data does not have the required load field (w)');
end
% define the dictionary of observables
if obj.loaded % observables must include loads
obj = obj.def_observables_loaded( obj.obs_type , obj.obs_degree );
else
obj = obj.def_observables( obj.obs_type , obj.obs_degree );
end
% merge the training data into a single big file (requred for training function to work)
data4train_merged = obj.merge_trials( data4train );
% scale data to be in range [-1 , 1]
[ traindata , obj ] = obj.get_scale( data4train_merged );
valdata = cell( size( data4val ) );
for i = 1 : length( data4val )
valdata{i} = obj.scale_data( data4val{i} );
end
obj.traindata = traindata;
obj.valdata = valdata;
% % To suppress scaling, comment this in and comment out above 2 lines
% obj.traindata = data4train_merged;
% obj.valdata = data4val;
% get shapshot pairs from traindata
obj.snapshotPairs = obj.get_snapshotPairs( obj.traindata , obj.snapshots );
% perform dimension reduction on dictionary if user wants it
if ~obj.dim_red % don't perform dimensional reduction
Px = []; % null value, doesn't matter
else % do perform dimensional reduction
Px = obj.lift_snapshots( obj.snapshotPairs );
end
obj = obj.get_econ_observables( Px );
disp(['Number of basis functions: ' , num2str( obj.params.N ) ]);
end
% parse_args: Parses the Name, Value pairs in varargin
function obj = parse_args( obj , varargin )
%parse_args: Parses the Name, Value pairs in varargin of the
% constructor, and assigns property values
for idx = 1:2:length(varargin)
obj.(varargin{idx}) = varargin{idx+1} ;
end
% If lasso is set to Inf, replace it with a valid large number
if obj.lasso == Inf
obj.lasso = 1e6;
end
end
% loop_progress: visually display the progress of a for loop
function loop_progress( obj, now , total )
%loop_progress: display progress in execution of for loop
prog = now / total;
numdots = floor( prog * 10 );
if prog <= 0.1 % empty progress bar
fprintf(['Loop progress: [' , repmat('.',1,10) , ']\n']);
elseif prog >= 0.9 % last progress bar
fprintf(repmat('\b',1,28));
fprintf(['Loop progress: [' , repmat('#',1,10) , repmat('.',1,10-10) , ']\n']);
else
fprintf(repmat('\b',1,28));
fprintf(['Loop progress: [' , repmat('#',1,numdots) , repmat('.',1,10-numdots) , ']\n']);
end
end
%% operations on simulation/experimental data (some are redundant and found in the data class)
function [ data_scaled , obj ] = get_scale( obj , data )
%scale: Scale sim/exp data to be in range [-1 , 1]
% Also creates scaleup/scaledown matrices and saves as params
% data - struct containing fields t , y , u (at least)
% data_scaled - struct containing t , y , u , x (optional)
% get min/max values in each dimension
y_min = min( data.y );
u_min = min( data.u );
y_max = max( data.y );
u_max = max( data.u );
% calculate centers of range
y_dc = ( y_max + y_min ) ./ 2;
u_dc = ( u_max + u_min ) ./ 2;
% calculate scaling factors
scale_y = ( y_max - y_min ) ./ 2;
for i = find( scale_y == 0 ) % avoids Inf issue for constant states
scale_y(i) = 1;
end
scale_u = ( u_max - u_min ) ./ 2;
for i = find( scale_u == 0 ) % avoids Inf issue for constant input trials
scale_u(i) = 1;
end
% shift and scale the data
data_scaled = struct; % initialize
data_scaled.t = data.t; % time is not scaled
data_scaled.y = ( data.y - y_dc ) ./ scale_y;
data_scaled.u = ( data.u - u_dc ) ./ scale_u;
% save scaling functions
y = sym( 'y' , [ 1 , obj.params.n ] );
u = sym( 'u' , [ 1 , obj.params.m ] );
y_scaledown = ( y - y_dc ) ./ scale_y;
u_scaledown = ( u - u_dc ) ./ scale_u;
obj.scaledown.y = matlabFunction( y_scaledown , 'Vars' , {y} );
obj.scaledown.u = matlabFunction( u_scaledown , 'Vars' , {u} );
y_scaleup = ( y .* scale_y ) + y_dc;
u_scaleup = ( u .* scale_u ) + u_dc;
obj.scaleup.y = matlabFunction( y_scaleup , 'Vars' , {y} );
obj.scaleup.u = matlabFunction( u_scaleup , 'Vars' , {u} );
% save scaling factors
obj.params.scale.y_factor = scale_y;
obj.params.scale.y_offset = y_dc;
obj.params.scale.u_factor = scale_u;
obj.params.scale.u_offset = u_dc;
% do same for x if it is part of data struct
if ismember( 'x' , fields(data) )
x_min = min( data.x );
x_max = max( data.x );
x_dc = ( x_max + x_min ) ./ 2;
scale_x = ( x_max - x_min ) ./ 2;
data_scaled.x = ( data.x - x_dc ) ./ scale_x;
x = sym( 'x' , [ 1 , size(data.x,2) ] );
x_scaledown = ( x - x_dc ) ./ scale_x;
obj.scaledown.x = matlabFunction( x_scaledown , 'Vars' , {x} );
x_scaleup = ( x .* scale_x ) + x_dc;
obj.scaleup.x = matlabFunction( x_scaleup , 'Vars' , {x} );
end
% do same for w if it is part of data struct
if ismember( 'w' , fields(data) )
w = sym( 'w' , [ 1 , size(data.w,2) ] );
w_min = min( data.w );
w_max = max( data.w );
w_dc = ( w_max + w_min ) ./ 2;
w_nonconst_ind = find( w_min ~= w_max ); % find non-constant load parameters
% if load is constant just shift to zero
w_scaledown = w - w_dc;
w_scaleup = w + w_dc;
% otherwise shift and scale it between [-1,1]
for i = w_nonconst_ind
scale_w = ( w_max(i) - w_min(i) ) ./ 2;
w_scaledown(i) = ( w(i) - w_dc(i) ) ./ scale_w;
w_scaleup(i) = ( w(i) .* scale_w ) + w_dc(i);
end
obj.scaledown.w = matlabFunction( w_scaledown , 'Vars' , {w} );
obj.scaleup.w = matlabFunction( w_scaleup , 'Vars' , {w} );
data_scaled.w = obj.scaledown.w( data.w );
end
% create scaling functions for zeta
zeta = sym( 'zeta' , [ 1 , obj.params.nzeta ] );
zeta_scaledown = sym( zeros( size(zeta) ) );
zeta_scaleup = sym( zeros( size(zeta) ) );
zeta_scaledown(1:obj.params.n) = obj.scaledown.y( zeta(1:obj.params.n) );
zeta_scaleup(1:obj.params.n) = obj.scaleup.y( zeta(1:obj.params.n) );
for i = 1 : obj.delays % for y delays
range = obj.params.n * i + 1 : obj.params.n * (i+1);
zeta_scaledown(range) = obj.scaledown.y( zeta(range) );
zeta_scaleup(range) = obj.scaleup.y( zeta(range) );
end
for i = 1 : obj.delays % for u delays
endy = obj.params.n * ( obj.delays + 1 );
range = endy + obj.params.m * (i-1) + 1 : endy + obj.params.m * i;
zeta_scaledown(range) = obj.scaledown.u( zeta(range) );
zeta_scaleup(range) = obj.scaleup.u( zeta(range) );
end
obj.scaledown.zeta = matlabFunction( zeta_scaledown , 'Vars' , {zeta} );
obj.scaleup.zeta = matlabFunction( zeta_scaleup , 'Vars' , {zeta} );
end
% resample (resamples data with a desired time step)
function data_resampled = resample( obj , data , Ts )
%resample: resamples sim/exp data with a desired timestep
% data - struct with fields t, y, x (optional)
% Ts - the desired sampling period
% get query points
tq = ( data.t(1) : Ts : data.t(end) )';
data_resampled.t = tq;
data_resampled.u = interp1( data.t , data.u , tq );
data_resampled.y = interp1( data.t , data.y , tq );
if ismember( 'x' , fields(data) )
data_resampled.x = interp1( data.t , data.x , tq );
end
if ismember( 'w' , fields(data) )
data_resampled.w = interp1( data.t , data.w , tq );
end
end
% scale_data (scale sim/exp data to be in range [-1 , 1])
function data_scaled = scale_data( obj , data , down )
%scale: Scale sim/exp data based on the scalefactors set in
% get_scale.
% data - struct containing fields t , y , u (at least)
% data_scaled - struct containing t , y , u , x (optional)
% down - boolean. true to scale down, false to scale up.
if nargin < 3
down = true; % default is to scale down
end
% scale the data
if down
data_scaled = struct; % initialize
data_scaled.t = data.t; % time is not scaled
data_scaled.y = obj.scaledown.y( data.y ); %data.y * obj.params.scaledown.y;
data_scaled.u = obj.scaledown.u( data.u ); %data.u * obj.params.scaledown.u;
if ismember( 'x' , fields(data) )
data_scaled.x = obj.scaledown.x( data.x ); %data.x * obj.params.scaledown.x;
end
if ismember( 'w' , fields(data) )
data_scaled.w = obj.scaledown.w( data.w );
end
else
data_scaled = struct; % initialize
data_scaled.t = data.t; % time is not scaled
data_scaled.y = obj.scaleup.y( data.y ); %data.y * obj.params.scaleup.y;
data_scaled.u = obj.scaleup.u( data.u ); %data.u * obj.params.scaleup.u;
if ismember( 'x' , fields(data) )
data_scaled.x = data.scaleup.x( data.x ); %data.x * obj.params.scaleup.x;
end
if ismember( 'w' , fields(data) )
data_scaled.w = data.scaleup.w( data.w ); %data.x * obj.params.scaleup.x;
end
end
end
% chop (chop data into several trials)
function data_chopped = chop( obj , data , num , len )
%chop: chop data into num trials of lenght len
% data - struct with fields t , y , (x)
% data_chopped - cell array containing the chopped datas
% determine length of timestep
Ts = mean( data.t(2:end) - data.t(1:end-1) ); % take mean in case they're not quite uniform
% find maximum length of each chop for given num
maxlen = data.t(end) / num;
if len > maxlen
len = maxlen;
disp([ 'Maximum trial length is ' , num2str(maxlen) , 's. Using this value instead.' ]);
end
% set length of the chops in terms of time steps
lenk = length( find( data.t < len ) );
maxlenk = length( find( data.t < maxlen ) );
data_chopped = cell( 1 , num );
for i = 1 : num
index = (i-1) * maxlenk + ( 1 : lenk );
% chop the data
data_chopped{i}.t = ( ( 1 : lenk ) - 1 ) * Ts;
data_chopped{i}.y = data.y( index , : );
data_chopped{i}.u = data.u( index , : );
if ismember( 'x' , fields(data) )
data_chopped{i}.x = data.x( index , : );
end
end
end
% merge_trials (merge cell array containing several sim/exp trials into one data struct)
function data_merged = merge_trials( obj , data )
%merge_trials: Merge cell array containing several sim/exp trials into one data struct
% data - cell array where each cell is a data struct with
% fields t, y, u, (x), (params), ...
% data_merged: data struct with the same fields
% confirm that data is a cell array (i.e. contains several trials)
% If so, concatenate all trials into a single data struct
if iscell( data )
data_merged = data{1}; % initialize the merged data struct
for i = 2 : length( data )
data_fields = fields( data{i} );
for j = 1 : length( data_fields )
if isa( data{i}.( data_fields{j} ) , 'numeric' )
data_merged.( data_fields{j} ) = [ data_merged.( data_fields{j} ) ; data{i}.( data_fields{j} ) ];
end
end
end
else
data_merged = data; % if not a cell array, do nothing
end
end
%% save the class object
% save_class
function obj = save_class( obj , model_id )
%save_class: Saves the class as a .mat file
% If class is from a simulated system, it is saved in the
% subfolder corresponding to that system.
% If class if from a real system, it is saved in the generic
% folder /systems/fromData/.
% varargin = isupdate - indicates whether this is an update of a
% previously saved class (1) or a new class (0).
% shorthand
isupdate = obj.isupdate;
% if no model id is provided, save the first candidate model
if nargin < 2 && ~iscell(obj.candidates)
obj.model = obj.candidates;
elseif nargin < 2
obj.model = obj.candidates{1};
else
obj.model = obj.candidates{model_id};
end
% set the class name based on its parameters
if isupdate
classname = obj.params.classname;
else
dateString = datestr(now , 'yyyy-mm-dd_HH-MM'); % current date/time
classname = [ obj.model_type , '_' , obj.obs_type{1} , '-' , num2str(obj.obs_degree) ,'_n-' , num2str( obj.params.n ) , '_m-' , num2str( obj.params.m ) , '_del-' , num2str( obj.params.nd ) , '_' , dateString ];
obj.params.classname = classname; % create classname parameter
end
% save the class file
sysid_class = obj;
if obj.params.isfake % check if class was created from simulated system
dirname = [ 'systems' , filesep , obj.params.sysParams.sysName , filesep , 'models'];
if ~isupdate
mkdir( dirname );
end
fname = [ dirname , filesep , classname, '.mat' ];
save( fname , 'sysid_class' );
else
dirname = [ 'systems' , filesep , 'fromData' ];
fname = [ dirname , filesep , classname, '.mat' ];
save( fname , 'sysid_class' , '-v7.3' );
end
end
%% defining observables
% def_observables (define the basis of observable functions)
function obj = def_observables( obj , type , degree )
% def_observables: Defines the set of nonlinear observable
% functions that will act as basis of Koopman subspace
% type - Type of functions, [cell array of strings].
% 'armshape' - coefficients of shape polynomial
% 'poly' - monomials
% ... more to be added over time
% degree - Maximum degree/complexity of functions, [vector].
% check that the type and degree have same dimension
if size(type) ~= size(degree)
error('inputs must be of the same size');
end
% define the low dimensional state with delays, called zeta
x = sym('x', [obj.params.n, 1] , 'real'); % state variable x
xd = sym('xd', [obj.params.nd * obj.params.n, 1] , 'real'); % state delays i.e. for 2 delays: [x_i-1, x_i-2]'
ud = sym('ud', [obj.params.nd * obj.params.m, 1] , 'real'); % input delays i.e. for 2 delays: [u_i-1, u_i-2]'
zeta = [x ; xd; ud]; % state variable with delays
u = sym('u', [obj.params.m, 1] , 'real'); % input vector u
if strcmp( obj.model_type , 'nonlinear' ) % if the includes input in unlifted state
zeta = [ zeta ; u ]; % just so lifting function works
end
obj.params.zeta = zeta; % needed for defining lifting function
obj.params.x = x;
obj.params.u = u;
disp('Defining initial set of observables...');
% construct the observables
fullBasis = zeta; % first nzeta observables should always be the measured state and delays
for i = 1 : length(degree)
if strcmp( type{i} , 'poly' )
obj = obj.def_polyLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.poly( size(zeta,1)+1 : end ) ]; % don't include first nzeta states because they will be repeats
elseif strcmp( type{i} , 'fourier' )
obj = obj.def_fourierLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.fourier ];
elseif strcmp( type{i} , 'fourier_sparser' )
obj = obj.def_fourierLift_sparser( degree(i) );
fullBasis = [ fullBasis ; obj.basis.fourier_sparser ];
elseif strcmp( type{i} , 'gaussian' )
obj = obj.def_gaussianLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.gaussian ];
elseif strcmp( type{i} , 'hermite' )
obj = obj.def_hermiteLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.hermite ];
end
end
% add a constant term to the end of the set
fullBasis = [ fullBasis ; sym(1) ];
% BILINEAR LIFT: multiply input by monomials of state, but no powers of input
if strcmp( obj.model_type , 'bilinear' )
% modify basis to include inputs
basis_diag = kron( eye(obj.params.m) , fullBasis );
fullBasis_input = [ fullBasis ; basis_diag * u ];
% save basis and function to class
obj.basis.full_input = fullBasis_input; % symbolic expression
obj.lift.full_input = matlabFunction( fullBasis_input , 'Vars' , { zeta , u } ); % lifting function
end
% remove current input from zeta
if strcmp( obj.model_type , 'nonlinear' )
zeta = zeta(1 : obj.params.nzeta);
end
% multiply by smooth bump function to bound magnitude TEST
% (DOESN't SEEM TO HELP WITH EXPLODING SIMULATIONS)
% (I THINK THIS SHOULD ONLY WORK FOR CTS MODELS)
% (DOESN'T WORK UNLESS RELIFTING AT EACH TIME STEP)
% fullBasis = fullBasis * exp(-( norm(zeta) )^2 / 1);
% fullBasis = fullBasis * exp(-( norm(zeta) )^10 / 100);
% define outputs
obj.params.zeta = zeta;
obj.basis.full = fullBasis;
obj.lift.full = matlabFunction( fullBasis , 'Vars' , { [ zeta ; u ] } );
obj.params.N = length( fullBasis ); % the dimension of the lifted state
end
% def_observables_loaded (define the basis of observable functions)
function obj = def_observables_loaded( obj , type , degree )
% def_observables_loaded: Defines the set of nonlinear observable
% functions that will act as basis of Koopman subspace, when
% the model includes loads.
% type - Type of functions, [cell array of strings].
% 'armshape' - coefficients of shape polynomial
% 'poly' - monomials
% ... more to be added over time
% degree - Maximum degree/complexity of functions, [vector].
% check that the type and degree have same dimension
if size(type) ~= size(degree)
error('inputs must be of the same size');
end
% define the low dimensional state with delays, called zeta
x = sym('x', [obj.params.n, 1] , 'real'); % state variable x
xd = sym('xd', [obj.params.nd * obj.params.n, 1] , 'real'); % state delays i.e. for 2 delays: [x_i-1, x_i-2]'
ud = sym('ud', [obj.params.nd * obj.params.m, 1] , 'real'); % input delays i.e. for 2 delays: [u_i-1, u_i-2]'
zeta = [x ; xd; ud]; % state variable with delays
u = sym('u', [obj.params.m, 1] , 'real'); % input vector u
w = sym('w', [obj.params.nw, 1] , 'real'); % load vector w
if strcmp( obj.model_type , 'nonlinear' ) % if the includes input in unlifted state
zeta = [ zeta ; u ]; % just so lifting function works
end
obj.params.zeta = zeta; % needed for defining lifting function
obj.params.x = x;
obj.params.u = u;
obj.params.w = w;
disp('Defining initial set of observables...');
% construct the observables
fullBasis = zeta; % first nzeta observables should always be the measured state and delays
for i = 1 : length(degree)
if strcmp( type{i} , 'poly' )
obj = obj.def_polyLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.poly( size(zeta,1)+1 : end ) ]; % don't include first nzeta states because they will be repeats
elseif strcmp( type{i} , 'fourier' )
obj = obj.def_fourierLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.fourier ];
elseif strcmp( type{i} , 'fourier_sparser' )
obj = obj.def_fourierLift_sparser( degree(i) );
fullBasis = [ fullBasis ; obj.basis.fourier_sparser ];
elseif strcmp( type{i} , 'gaussian' )
obj = obj.def_gaussianLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.gaussian ];
elseif strcmp( type{i} , 'hermite' )
obj = obj.def_hermiteLift( degree(i) );
fullBasis = [ fullBasis ; obj.basis.hermite ];
end
end
% add a constant term to the end of the set
fullBasis = [ fullBasis ; sym(1) ];
% incorporate the loads into the basis set
zw = [ 1 ; w ]; % load vector, with 1 appended to beginning
fullBasis_loaded = fullBasis;% different version, doesn't requare large symbolic matrices
for i = 1 : obj.params.nw
fullBasis_loaded = [ fullBasis_loaded ; w(i) * fullBasis ];
end
% BILINEAR LIFT: multiply input by monomials of state, but no powers of input
if strcmp( obj.model_type , 'bilinear' )
% modify basis to include inputs
basis_diag = kron( eye(obj.params.m) , fullBasis_loaded );
fullBasis_loaded_input = [ fullBasis_loaded ; basis_diag * u ]; % save to class
% save basis and function to class
obj.basis.full_loaded_input = fullBasis_loaded_input; % symbolic expression
obj.lift.full_loaded_input = matlabFunction( fullBasis_loaded_input , 'Vars' , { zeta , w , u} ); % lifting function
end
% remove current input from zeta
if strcmp( obj.model_type , 'nonlinear' )
zeta = zeta(1 : obj.params.nzeta);
end
% define outputs
obj.params.zeta = zeta;
obj.params.zw = zw;
obj.basis.full = fullBasis;
obj.basis.full_loaded = fullBasis_loaded;
obj.lift.full = matlabFunction( fullBasis , 'Vars' , { [ zeta ; u ] } );
obj.lift.full_loaded = matlabFunction( fullBasis_loaded , 'Vars' , { [ zeta ; u ] , w } );
obj.params.N = length( fullBasis ); % the dimension of the lifted state
end
% def_polyLift (defines polynomial basis functions)
function [ obj , polyBasis ] = def_polyLift( obj , degree )
%def_polyLift: Defines the lifting function that lifts state variable x to
% space spanned by monomials with total degree less than or equal to
% max_degree.
% e.g. 1 x1 x2 x1^2 x1x2 x2^2 ...
zeta = obj.params.zeta; % get the symbolic unlifted state
nzeta = length(zeta);
maxDegree = degree;
% Number of mononials, i.e. dimenstion of p(x)
% N = factorial(nzeta + maxDegree) / ( factorial(nzeta) * factorial(maxDegree) );
N = prod( ( nzeta + 1) : ( nzeta + maxDegree ) ) / factorial(maxDegree); % avoids Infs for really big factorials
% matrix of exponents (N x naug). Each row gives exponents for 1 monomial
exponents = [];
for i = 1:maxDegree
exponents = [exponents; partitions(i, ones(1,nzeta))];
end
% exponents = [exponents ; zeros(1,nzeta)]; % put constant at end of basis so state can be the first nzeta elements
% create vector of orderd monomials (column vector)
for i = 1:N-1
polyBasis(i,1) = obj.get_monomial(zeta, exponents(i,:));
end
% % define matrix of exponents: columns=monomial term, rows=dimension of x
% psi = exponents';
% create the lifting function: zeta -> p(zeta)
obj.lift.poly = matlabFunction(polyBasis, 'Vars', {zeta});
%
% % define derivative of lifted state with respect to x
% dlift = jacobian(polyBasis,x);
% matlabFunction(dlift, 'File', 'jacobianLift', 'Vars', {zeta});
% output variables
obj.basis.poly = polyBasis; % symbolic vector of basis monomials, p(x)
% ams.jacobianBasis = dlift;
% params.N = N; % dimension of polyBasis (including the state itself)
% params.Np = N + p; % dimension of the lifted state
% params.psi = psi; % monomial exponent index function
% params.x = x; % symbolic state variable
% params.u = u; % symbolic input variable
% params.xd = xd; % symbolic state delays
% params.ud = ud; % symbolic input delays
end
% get_monomial (builds a monomial)
function [ monomial ] = get_monomial( obj, x, exponents )
%get_monomial: builds a monomial from symbolic vector x and a vector of
%exponents
% e.g. x = [x1 x2]; exponents = [1 2]; => monomial = x1^1 * x2^2
n = length(x);
monomial = x(1)^exponents(1);
for i = 2:n
monomial = monomial * x(i)^exponents(i);
end
end
% def_fourierLift (defines sin/cos basis functions)
function [ obj , fourierBasis ] = def_fourierLift( obj , degree )
%def_fourierLift: Defines fourier basis functions
% shorthand variable names
n = obj.params.n;
p = obj.params.m;
zeta = obj.params.zeta; % get the symbolic unlifted state
nzeta = length(zeta);
maxDegree = degree;
% Number of basis elements, i.e. dimenstion of p(x)
Nfourier = nzeta + (1 + 2*maxDegree)^nzeta;
% create sines of cosines of all the states
poop = sym( zeros(1+2*maxDegree , nzeta) );
for i = 1 : nzeta
poop(1,i) = 1;
for j = 1 : maxDegree
poop(2*j,i) = cos(2*pi*j*zeta(i));
poop(2*j+1,i) = sin(2*pi*j*zeta(i));
end
end
% define fourier basis vector
fourierBasis = poop(:,1);
for i = 2 : nzeta
fourierBasis = kron(fourierBasis, poop(:,i));
end
% remove the constant element from the basis
fourierBasis = fourierBasis( 2 : end );
% create the lifting function: zeta -> fourier(zeta)
obj.lift.fourier = matlabFunction(fourierBasis, 'Vars', {zeta});
% output variables
obj.basis.fourier = fourierBasis; % symbolic vector
end
% def_fourierLift_sparser (defines sin/cos basis functions)
function [ obj , fourierBasis ] = def_fourierLift_sparser( obj , degree )
%def_fourierLift_sparser: Defines fourier basis functions, but
% not as many as def_fourierLift (i.e. not every combination of
% a suitable degree)
% shorthand variable names
n = obj.params.n;
p = obj.params.m;
zeta = obj.params.zeta; % get the symbolic unlifted state
nzeta = length(zeta);
maxDegree = degree;
% matrix of exponents (N x naug). Each row gives exponents for 1 monomial
multipliers = zeros(1,2*nzeta);
for i = 1:maxDegree
multipliers = [multipliers; partitions(i, ones(1, 2*nzeta))];
end
multipliers = multipliers( 2 : end , : ); % remove 1st row which is a constant
% Number of basis elements, i.e. dimenstion of p(x)
N = nzeta + size(multipliers , 1);
% create vector of sines and cosines with multipliers
fourierBasis = sym('fourierBasis', [N-nzeta,1]);
for i = 1:N-nzeta
fourierBasis(i,1) = obj.get_sinusoid(zeta, multipliers(i,:));
end
% create the lifting function: zeta -> fourier_sparser(zeta)
obj.lift.fourier_sparser = matlabFunction(fourierBasis, 'Vars', {zeta});
% output variables
obj.basis.fourier_sparser = fourierBasis; % symbolic vector
end
% get_sinusoid (builds a sinusoid from symbolic vector x and a vector of multipliers)
function [ sinusoid ] = get_sinusoid( obj , x , multiplier )
%get_sinusoid: builds a sinusoid from symbolic vector x and a vector of multipliers
% e.g. x = []
n = length(multiplier); % vector of multipliers
sinusoid = sym(1); % initialize as a symbolic variable
for i = 1 : n/2
if multiplier(i) ~= 0
sinusoid = sinusoid * sin(2*pi*multiplier(i)*x(i));
end
end
for j = n/2 + 1 : n
if multiplier(j) ~= 0
sinusoid = sinusoid * cos(2*pi*multiplier(j)*x(j - n/2));
end
end
end
% def_gaussianLift (defines gaussian basis functions)
function [ obj , gaussianBasis ] = def_gaussianLift( obj , degree )
%def_gaussianLift: Defines a set of randomly distributed
%gaussian basis functions
% shorthand variable names
n = obj.params.n;
p = obj.params.m;
zeta = obj.params.zeta; % get the symbolic unlifted state
nzeta = length(zeta);
maxDegree = degree;
% create basis functions with random centers in interval [-1 , 1]
gaussianBasis = sym('gaussianBasis', [maxDegree , 1]);
zeta0 = (2*rand([nzeta,maxDegree]) - 1); % columns are random centers
for i = 1 : maxDegree
radius = norm( zeta - zeta0(:,i) );
gaussianBasis(i,:) = exp(-( 1 * radius )^2) ;
% % I think this might work faster
% radius = sum( ( zeta - zeta0(:,i) ).^2 );
% psi(i,:) = exp( -radius );
end
% create the lifting function: zeta -> fourier_sparser(zeta)
obj.lift.gaussian = matlabFunction(gaussianBasis, 'Vars', {zeta});
% output variables
obj.basis.gaussian = gaussianBasis; % symbolic vector
end
% get_hermite (builds a product of hermite polynomials)
function [ hermite ] = get_hermite( obj, x, orders )
%get_monomial: builds a monomial from symbolic vector x and a vector of
%exponents
% e.g. x = [x1 x2]; exponents = [1 2]; => monomial = hermiteH(1,x1) * hermiteH(2,x2)
n = length(x);
hermite = hermiteH( orders(1) , x(1) );
for i = 2:n
hermite = hermite * hermiteH( orders(i) , x(i) );
end
end
% def_polyLift (defines polynomial basis functions)
function [ obj , hermiteBasis ] = def_hermiteLift( obj , degree )
%def_polyLift: Defines the lifting function that lifts state variable x to
% space spanned by monomials with total degree less than or equal to
% max_degree.
% e.g. 1 x1 x2 x1^2 x1x2 x2^2 ...
zeta = obj.params.zeta; % get the symbolic unlifted state
nzeta = length(zeta);
maxDegree = degree;
% Number of mononials, i.e. dimenstion of p(x)
N = factorial(nzeta + maxDegree) / ( factorial(nzeta) * factorial(maxDegree) );
% matrix of exponents (N x naug). Each row gives exponents for 1 monomial
exponents = [];
for i = 1:maxDegree
exponents = [exponents; partitions(i, ones(1,nzeta))];
end
% create vector of orderd monomials (column vector)
for i = 1:N-1
hermiteBasis(i,1) = obj.get_hermite(zeta, exponents(i,:));
end
% create the lifting function: zeta -> p(zeta)
obj.lift.hermite = matlabFunction(hermiteBasis, 'Vars', {zeta});
% output variables
obj.basis.hermite = hermiteBasis; % symbolic vector of basis monomials, p(x)
end
%% fitting Koopman operator and A,B,C system matrices
% get_zeta (adds a zeta field to a test data struct)
function [ data_out , zeta ] = get_zeta( obj , data_in )
%get_zeta: Adds a zeta field to a test data struct
% data_in - struct with t , x , y , u fields
% zeta - [ y , yd1 , yd2 , ... , ud1 , ud2 , ... ]
data_out = data_in;
if obj.delays ~= 0
% add the zeta field
for i = obj.params.nd + 1 : size( data_in.y , 1 )
ind = i - obj.params.nd; % current timestep index
y = data_in.y( i , : );
u = data_in.u( i , : );
ydel = zeros( 1 , obj.params.nd * obj.params.n );
udel = zeros( 1 , obj.params.nd * obj.params.m );
for j = 1 : obj.params.nd
fillrange_y = obj.params.n * (j - 1) + 1 : obj.params.n * j;
fillrange_u = obj.params.m * (j - 1) + 1 : obj.params.m * j;
ydel(1 , fillrange_y) = data_in.y( i - j , : );
udel(1 , fillrange_u) = data_in.u( i - j , : );
end
zetak = [ y , ydel , udel ];
% if strcmp( obj.model_type , 'nonlinear' ) % include input in zeta
% zetak = [ zetak , u ];
% end
data_out.zeta( ind , : ) = zetak;
data_out.uzeta( ind , : ) = data_in.u( i , : ); % current timestep with zeta (input starting at current timestep)
if isfield( data_in , 'w' )
data_out.wzeta( ind , : ) = data_in.w( i , : );
end
end
else
data_out.zeta = data_in.y; % if no delays, zeta is equal to y
data_out.uzeta = data_in.u;
if isfield( data_in , 'w' )
data_out.wzeta = data_in.w;
end
end
zeta = data_out.zeta;
end
% get_snapshotPairs (convert time-series data into snapshot pairs)
function snapshotPairs = get_snapshotPairs( obj , data , varargin )
%get_snapshotPairs: Convert time-series data into a set of num
%snapshot pairs.
% data - struct with fields x , y , u , t , (zeta) OR cell
% array containing cells which contain those fields
% varargin = num - number of snapshot pairs to be taken
disp('Constructing snapshots...');
% check wheter data is a cell array (i.e. contains several trials)
% If so, concatenate all trials into a single data struct
if iscell( data )
data_merged = obj.merge_trials( data );
data = data_merged; % replace cell array with merged data struct
end
% check if data has a zeta field, create one if not
if ~ismember( 'zeta' , fields(data) )
data = obj.get_zeta( data );
end
% If snapshots are already defined in data file use those
if ismember( 'snapshots' , fields(data) )
snapshotPairs.alpha = data.snapshots.alpha;
snapshotPairs.beta = data.snapshots.beta;
snapshotPairs.u = data.snapshots.u;
if ismember( 'w' , fields(data.snapshots) )
snapshotPairs.w = data.snapshots.w;
end
else % otherwise, construct them from time-series data
% separate data into 'before' and 'after' time step
before.t = data.t( obj.params.nd + 1 : end-1 );
before.zeta = data.zeta( 1:end-1 , : );
after.t = data.t( obj.params.nd + 2 : end );
after.zeta = data.zeta( 2:end , : );
u = data.uzeta( 1:end-1 , : ); % input that happens between before.zeta and after.zeta
% remove pairs that fall at the boundary between sim/exp trials
goodpts = find( before.t < after.t );
before.zeta = before.zeta( goodpts , : );
after.zeta = after.zeta( goodpts , : );
u = u( goodpts , : );
% if system is loaded, include the load
if isfield( data , 'w' )
w = data.wzeta( 1:end-1 , : ); % load that happens between before.zeta and after.zeta
w = w( goodpts , : );
end
% set the number of snapshot pairs to be taken
num_max = size( before.zeta , 1 ) - 1; % maximum number of snapshot pairs
if length(varargin) == 1
num = varargin{1};
if num > num_max - 1
message = [ 'Number of snapshot pairs cannot exceed ' , num2str(num_max) , '. Taking ' , num2str(num_max) , ' pairs instead.' ];
disp(message);
num = num_max;
end
else
num = num_max;
end
% randomly select num snapshot pairs
total = num_max;
s = RandStream('mlfg6331_64');
index = datasample(s , 1:total, num , 'Replace' , false);
snapshotPairs.alpha = before.zeta( index , : );
snapshotPairs.beta = after.zeta( index , : );
snapshotPairs.u = u( index , : );
if isfield( data , 'w' )
snapshotPairs.w = w( index , : );
end
end
end
% get_Koopman (Find the best possible koopman operator from snapshot pairs)
function [ koopData , K ] = get_Koopman( obj , snapshotPairs , varargin )
%get_KoopmanConstGen: Find the best possible koopman operator given
%snapshot pairs using constraint generation to deal with large data sets.
% varargin = lasso weighting parameter. lasso >> 1 approaches least squares solution
if length(varargin) == 1
if isempty( varargin{1} )
lasso = 1e4 * obj.params.N; % defualt value of the lasso parameter (should emulate least squares)
else
lasso = varargin{1} * obj.params.N;
end
else
lasso = 1e4 * obj.params.N; % defualt value of the lasso parameter (should emulate least squares)
end