-
Notifications
You must be signed in to change notification settings - Fork 1
/
functionfile_speedygreedy.py
2272 lines (1886 loc) · 118 KB
/
functionfile_speedygreedy.py
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
# Copyright 2023, Karthik Ganapathy
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”),
# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import numpy as np
import networkx as netx
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
from matplotlib.ticker import MaxNLocator, FuncFormatter, LogFormatter, LogLocator, NullFormatter
from time import process_time
from copy import deepcopy as dc
import pandas as pd
import dbm
import shelve
import itertools
import concurrent.futures
import os
import socket
from tqdm.autonotebook import tqdm
matplotlib.rcParams['axes.titlesize'] = 12
matplotlib.rcParams['xtick.labelsize'] = 12
matplotlib.rcParams['ytick.labelsize'] = 12
matplotlib.rcParams['axes.labelsize'] = 12
matplotlib.rcParams['legend.fontsize'] = 10
matplotlib.rcParams['legend.title_fontsize'] = 10
matplotlib.rcParams['legend.framealpha'] = 0.5
matplotlib.rcParams['lines.markersize'] = 5
matplotlib.rcParams['image.cmap'] = 'Blues'
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['savefig.bbox'] = 'tight'
matplotlib.rcParams['savefig.format'] = 'pdf'
# matplotlib.rcParams['axes.autolimit_mode'] = 'round_numbers'
# Error handling
class ArchitectureError(Exception):
"""Raise when architecture is not B or C"""
def __init__(self, value='Check architecture type'):
self.value = value
def __str__(self):
return repr(self.value)
class SecondOrderError(Exception):
"""Raise when second order or type is not specified accurately"""
def __init__(self, value='Check second order type'):
self.value = value
def __str__(self):
return repr(self.value)
class ClassError(Exception):
"""Raise when variable is not of the correct class/variable type"""
def __init__(self, value='Check class data type'):
self.value = value
def __str__(self):
return repr(self.value)
class Experiment:
"""
Manage experiment parameters - save/load from csv file
Wrapper to simulate and plot objects of System class
"""
def __init__(self):
self.parameters_save_filename = "experiment_parameters.csv" # File name for experiment parameters
# Dictionary of parameter names and default value with data-type
self.default_parameter_datatype_map = {'experiment_no': int(1),
'test_model': str(None),
'test_parameter': int(0),
'number_of_nodes': int(20),
'network_model': str('rand'),
'network_parameter': float(0),
'rho': float(1),
'second_order': False,
'second_order_network': int(0),
'initial_architecture_size': int(5),
'architecture_constraint_min': int(5),
'architecture_constraint_max': int(5),
'second_order_architecture': int(0),
'Q_cost_scaling': float(1),
'R_cost_scaling': float(1),
'B_run_cost': float(1),
'C_run_cost': float(1),
'B_switch_cost': float(1),
'C_switch_cost': float(1),
'W_scaling': float(1),
'V_scaling': float(1),
'disturbance_model': str(None),
'disturbance_step': int(0),
'disturbance_number': int(0),
'disturbance_magnitude': int(0),
'prediction_time_horizon': int(10),
'X0_scaling': float(1),
'multiprocessing': False}
self.parameter_keys = list(self.default_parameter_datatype_map.keys()) # Strip parameter names from dict
self.parameter_datatypes = {k: type(self.default_parameter_datatype_map[k]) for k in
self.default_parameter_datatype_map} # Strip parameter data types from dict
# Parameters and simulation systems for current experiment
self.exp_no = 1
self.parameter_values = []
# System dictionaries: key = 0 for single exp, model_id for statistical
self.S = {0: System()} # Dictionary of generated systems
self.S_1 = {} # Dictionary of first system to compare
self.S_2 = {} # Dictionary of second system to compare
self.process_pool_workers = None # number of workers for processpool: none=max
self.datadump_folder_path = 'DataDump/'
self.image_save_folder_path = 'Images/'
# Saved experiment data parse
self.parameter_table = pd.DataFrame() # Parameter table from csv
self.experiments_list = [] # List of experiments
self.read_table_from_file()
# Plot parameters
self.plot_title_check = True
# Simulation function mapper
self.experiment_modifications_mapper = {
'fixed_vs_self_tuning': self.simulate_experiment_fixed_vs_self_tuning,
'self_tuning_number_of_changes': self.simulate_experiment_self_tuning_number_of_changes,
'self_tuning_prediction_horizon': self.simulate_experiment_self_tuning_prediction_horizon,
'self_tuning_architecture_cost': self.simulate_experiment_self_tuning_architecture_cost,
'pointdistribution_openloop': self.simulate_experiment_fixed_vs_self_tuning_pointdistribution_openloop,
'self_tuning_architecture_cost_no_lim': self.simulate_experiment_self_tuning_architecture_cost_no_lim,
'self_tuning_architecture_constraints': self.simulate_experiment_self_tuning_architecture_constraints
}
self.experiment_mapper_statistics = {
'statistics_fixed_vs_self_tuning': 'fixed_vs_self_tuning',
'statistics_self_tuning_number_of_changes': 'self_tuning_number_of_changes',
'statistics_self_tuning_prediction_horizon': 'self_tuning_prediction_horizon',
'statistics_self_tuning_architecture_cost': 'self_tuning_architecture_cost',
'statistics_self_tuning_architecture_cost_no_lim': 'self_tuning_architecture_cost_no_lim',
'statistics_pointdistribution_openloop': 'pointdistribution_openloop',
'statistics_self_tuning_architecture_constraints': 'self_tuning_architecture_constraints'
}
def initialize_table(self) -> None:
# Initialize parameter csv file from nothing - FOR BUGFIXING ONLY
print('Initializing table with default parameters')
self.parameter_values = [[k] for k in self.default_parameter_datatype_map.values()]
self.parameter_table = pd.DataFrame(dict(zip(self.parameter_keys, self.parameter_values)))
self.parameter_table.set_index(self.parameter_keys[0], inplace=True)
self.write_table_to_file()
def check_dimensions(self, print_check=False) -> None:
# Ensure dimensions match
if len(self.parameter_values) == len(self.parameter_datatypes) == len(self.parameter_keys):
if print_check:
print('Dimensions agree: {} elements'.format(len(self.parameter_keys)))
else:
raise Exception("Dimension mismatch - values: {}, datatype: {}, keys: {}".format(len(self.parameter_values), len(self.parameter_datatypes), len(self.parameter_keys)))
def check_experiment_number(self) -> None:
# Ensure experiment number is in the tables list
if self.exp_no not in self.experiments_list:
raise Exception('Invalid experiment number')
def read_table_from_file(self) -> None:
# Read table from file
if not os.path.exists(self.parameters_save_filename):
raise Warning('File does not exist')
else:
self.parameter_table = pd.read_csv(self.parameters_save_filename, index_col=0, dtype=self.parameter_datatypes)
self.parameter_table.replace({np.nan: None}, inplace=True)
self.experiments_list = self.parameter_table.index
def read_parameters_from_table(self) -> None:
# Read parameters from table
if not isinstance(self.parameter_table, pd.DataFrame):
raise Exception('Not a pandas frame')
self.parameter_values = [self.exp_no] + [k for k in self.parameter_table.loc[self.exp_no]]
def parameter_value_map(self) -> None:
# Mapping list for parameters to manage default csv values to python values
self.parameter_values = [list(map(d, [v]))[0] if v is not None else None for d, v in
zip(self.parameter_datatypes, self.parameter_values)]
def write_parameters_to_table(self) -> None:
# Write a parameter dictionary to an experiment table - FOR BUGFIXING ONLY
if len(self.parameter_values) == 0:
raise Exception('No experiment parameters provided')
self.check_dimensions()
self.parameter_value_map()
append_check = True
for i in self.experiments_list:
if [k for k in self.parameter_table.loc[i]][:] == self.parameter_values[1:]:
print('Duplicate experiment at : {}'.format(i))
append_check = False
break
if append_check:
self.parameter_table.loc[max(self.experiments_list) + 1] = self.parameter_values[1:]
self.experiments_list = self.parameter_table.index
self.write_table_to_file()
def write_table_to_file(self) -> None:
# Write an experiment table to csv - FOR BUGFIXING ONLY
self.parameter_table.to_csv(self.parameters_save_filename)
print('Printing done')
# def return_keys_values(self):
# return self.parameter_values, self.parameter_keys
def display_test_parameters(self) -> None:
# Print parameter table
print(self.parameter_table)
def initialize_system_from_experiment_number(self, exp_no=None) -> None:
# Define model S[0] for given experiment number
if exp_no is not None:
self.exp_no = exp_no
self.check_experiment_number()
self.read_parameters_from_table()
self.S[0] = System()
self.S[0].initialize_system_from_experiment_parameters(self.parameter_values, self.parameter_keys)
if self.S[0].sim.test_model not in self.experiment_modifications_mapper and self.S[0].sim.test_model not in self.experiment_mapper_statistics:
raise Exception('Experiment not defined')
def retrieve_experiment(self, exp_no=None) -> None:
# Retrieve simulated experiment from datadump
if exp_no is None:
exp_no = self.exp_no
self.initialize_system_from_experiment_number(exp_no)
self.system_model_from_memory_sim_model(self.S[0].model_name)
if self.S_1[0].plot is None:
self.S_1[0].plot = PlotParameters()
if self.S_2[0].plot is None:
self.S_2[0].plot = PlotParameters()
def system_model_to_memory_gen_model(self) -> None:
# Store model generated from experiment parameters
shelve_filename = self.datadump_folder_path + 'gen_' + self.S[0].model_name
with shelve.open(shelve_filename, writeback=True) as shelve_data:
shelve_data['s'] = self.S[0]
print('\nShelving gen model: {}'.format(shelve_filename))
def system_model_from_memory_gen_model(self, model, print_check=False):
# Retrieve model generated from experiment parameters
shelve_filename = self.datadump_folder_path + 'gen_' + model
if print_check:
print('\nReading gen model: {}'.format(shelve_filename))
with shelve.open(shelve_filename, flag='r') as shelve_data:
self.S[0] = shelve_data['s']
if not isinstance(self.S[0], System):
raise Exception('System model error')
def system_model_to_memory_sim_model(self) -> None:
# Store simulated models
shelve_filename = self.datadump_folder_path + 'sim_' + self.S[0].model_name
print('\nShelving sim model: {}'.format(shelve_filename))
with shelve.open(shelve_filename, writeback=True) as shelve_data:
shelve_data['s'] = self.S[0]
shelve_data['s1'] = self.S_1[0]
shelve_data['s2'] = self.S_2[0]
def system_model_from_memory_sim_model(self, model):
# Retrieve simulated models
shelve_filename = self.datadump_folder_path + 'sim_' + model
print('\nReading sim model: {}'.format(shelve_filename))
with shelve.open(shelve_filename, flag='r') as shelve_data:
self.S[0] = shelve_data['s']
self.S_1[0] = shelve_data['s1']
self.S_2[0] = shelve_data['s2']
if not isinstance(self.S[0], System) or not isinstance(self.S_1[0], System) or not isinstance(self.S_2[0], System):
raise Exception('Data type mismatch')
self.S[0].plot = PlotParameters()
self.S_1[0].plot = PlotParameters(1)
self.S_2[0].plot = PlotParameters(2)
def system_model_to_memory_statistics(self, model_id: int, print_check: bool = False) -> None:
# Store simulated statistics model to memory
shelve_filename = self.datadump_folder_path + 'statistics/' + self.S[0].model_name
if not os.path.isdir(shelve_filename):
os.makedirs(shelve_filename)
shelve_filename = shelve_filename + '/model_' + str(model_id)
with shelve.open(shelve_filename, writeback=True) as shelve_data:
shelve_data['s'] = self.S[model_id]
shelve_data['s1'] = self.S_1[model_id]
shelve_data['s2'] = self.S_2[model_id]
if print_check:
print('\nShelving model: {}'.format(shelve_filename))
def data_from_memory_statistics(self, model_id: int = None, print_check=False):
# Retrieve simulated statistics model from memory
if self.exp_no is None:
raise Exception('Experiment not provided')
shelve_filename = self.datadump_folder_path + 'statistics/' + self.S[0].model_name + '/model_' + str(model_id)
with shelve.open(shelve_filename, flag='r') as shelve_data:
self.S[model_id] = shelve_data['s']
self.S_1[model_id] = shelve_data['s1']
self.S_2[model_id] = shelve_data['s2']
if not isinstance(self.S[model_id], System) or not isinstance(self.S_1[model_id], System) or not isinstance(self.S_2[model_id], System):
raise Exception('Data type mismatch')
if print_check:
print('\nModel read done: {}'.format(shelve_filename))
def dict_memory_clear(self, model_id : int = 0):
# Clear up memory after using statistics model
for S in (self.S, self.S_1, self.S_2):
if model_id in S:
del S[model_id]
def simulate_experiment_wrapper(self, exp_no=None, print_check: bool = False) -> None:
# Wrapper function to simulate experiment based on specified test_model
self.initialize_system_from_experiment_number(exp_no=exp_no)
print('\nSimulating Exp No: {}'.format(self.exp_no))
if self.S[0].sim.test_model in self.experiment_modifications_mapper:
self.simulate_experiment(print_check=print_check)
elif self.S[0].sim.test_model in self.experiment_mapper_statistics:
self.simulate_statistics_experiment(print_check=print_check)
else:
raise Exception('Experiment not defined')
def simulate_experiment(self, statistics_model: int = 0, print_check: bool = False, tqdm_check: bool = True) -> None:
# Experiment wrapper to create + modify, simulate and save test cases
if self.S[0].sim.test_model in self.experiment_modifications_mapper:
sim_function = self.experiment_modifications_mapper[self.S[0].sim.test_model]
else:
sim_function = self.experiment_modifications_mapper[self.experiment_mapper_statistics[self.S[0].sim.test_model]]
if statistics_model > 0 and self.S[0].sim.test_model not in ['pointdistribution_openloop']:
self.S[statistics_model] = System()
self.initialize_system_from_experiment_number()
if self.S[0].sim.test_model == 'pointdistribution_openloop' or self.S[0].sim.test_model in self.experiment_mapper_statistics:
sim_function(statistics_model=statistics_model, print_check=print_check)
else:
sim_function(print_check=print_check)
self.S_1[statistics_model].simulate(print_check=print_check, tqdm_check=tqdm_check)
self.S_2[statistics_model].simulate(print_check=print_check, tqdm_check=tqdm_check)
if statistics_model == 0:
self.system_model_to_memory_sim_model()
self.dict_memory_clear(model_id=0)
else:
self.system_model_to_memory_statistics(statistics_model)
self.dict_memory_clear(model_id=statistics_model)
def simulate_statistics_experiment(self, print_check: bool = False, start_idx: int = 1, number_of_samples: int = 100) -> None:
# wrapper to simulate statistics experiments sequentially using a loop or in parallel using a ProcessPoolExecutor
if self.S[0].sim.test_model == 'statistics_pointdistribution_openloop':
self.system_model_to_memory_gen_model()
idx_range = list(range(1, 1 + self.S[0].number_of_states))
else:
idx_range = list(range(start_idx, number_of_samples + start_idx))
self.S[0].sim.test_model = self.experiment_mapper_statistics[self.S[0].sim.test_model]
if self.S[0].sim.multiprocess_check:
tqdm_check = False
with tqdm(total=len(idx_range), ncols=100, desc='Model ID', leave=True) as pbar:
with concurrent.futures.ProcessPoolExecutor(max_workers=self.process_pool_workers) as executor:
for _ in executor.map(self.simulate_experiment, idx_range, itertools.repeat(print_check),
itertools.repeat(tqdm_check)):
pbar.update()
else:
for test_no in tqdm(idx_range, desc='Simulations', ncols=100, position=0, leave=True):
self.simulate_experiment(statistics_model=test_no, print_check=print_check, tqdm_check=True)
def simulate_experiment_fixed_vs_self_tuning(self, statistics_model: int = 0, print_check: bool = False) -> None:
# test_parameter is the number of optimizing greedy swap changes for self-tuning architecture
if statistics_model > 0:
self.S[statistics_model].initialize_system_from_experiment_parameters(self.parameter_values, self.parameter_keys)
self.S[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_1[statistics_model] = dc(self.S[statistics_model])
self.S_1[statistics_model].sim.sim_model = "fixed"
self.S_1[statistics_model].plot_name = 'fixed arch'
self.S_2[statistics_model] = dc(self.S[statistics_model])
self.S_2[statistics_model].sim.self_tuning_parameter = None if self.S_2[statistics_model].sim.test_parameter == 0 else self.S_2[statistics_model].sim.test_parameter
self.S_2[statistics_model].sim.sim_model = "self_tuning"
self.S_2[statistics_model].plot_name = 'self_tuning arch'
def simulate_experiment_fixed_vs_self_tuning_pointdistribution_openloop(self, statistics_model: int = 0, print_check: bool = False) -> None:
# test fixed vs self-tuning after setting the true initial state based on the statistics model
# test_parameter is the number of optimizing greedy swap changes for self-tuning architecture
self.S[statistics_model] = dc(self.S[0])
self.S[statistics_model].initialize_trajectory(statistics_model - 1)
self.S[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_1[statistics_model] = dc(self.S[statistics_model])
self.S_1[statistics_model].sim.sim_model = "fixed"
self.S_1[statistics_model].plot_name = 'fixed arch'
self.S_2[statistics_model] = dc(self.S[statistics_model])
self.S_2[statistics_model].sim.sim_model = "self_tuning"
self.S_2[statistics_model].sim.self_tuning_parameter = None if self.S[statistics_model].sim.test_parameter == 0 else self.S[statistics_model].sim.test_parameter
self.S_2[statistics_model].plot_name = 'self_tuning arch'
def simulate_experiment_self_tuning_number_of_changes(self, statistics_model: int = 0, print_check: bool = False) -> None:
# compare 1 vs test_parameter number of changes for self-tuning architecture
if statistics_model > 0:
self.S[statistics_model].initialize_system_from_experiment_parameters(self.parameter_values, self.parameter_keys)
self.S[statistics_model].sim.sim_model = "self_tuning"
self.S[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_1[statistics_model] = dc(self.S[statistics_model])
self.S_1[statistics_model].sim.self_tuning_parameter = 1
self.S_1[statistics_model].plot_name = 'self_tuning 1change'
self.S_2[statistics_model] = dc(self.S[statistics_model])
self.S_2[statistics_model].sim.self_tuning_parameter = None if self.S[statistics_model].sim.test_parameter == 0 else self.S[statistics_model].sim.test_parameter
self.S_2[statistics_model].plot_name = 'self_tuning bestchange' if self.S_2[statistics_model].sim.self_tuning_parameter is None else f"self_tuning {self.S_2[statistics_model].sim.self_tuning_parameter}changes"
def simulate_experiment_self_tuning_prediction_horizon(self, statistics_model: int = 0, print_check: bool = False) -> None:
# compare Tp vs test_parameter*Tp simulation horizon for self-tuning architecture
if statistics_model > 0:
self.S[statistics_model].initialize_system_from_experiment_parameters(self.parameter_values, self.parameter_keys)
self.S[statistics_model].sim.sim_model = "self_tuning"
self.S[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_1[statistics_model] = dc(self.S[statistics_model])
self.S_1[statistics_model].plot_name = 'self_tuning Tp' + str(self.S_1[statistics_model].sim.t_predict)
self.S_2[statistics_model] = dc(self.S[statistics_model])
self.S_2[statistics_model].sim.t_predict *= 2 if self.S[statistics_model].sim.test_parameter is None else self.S[statistics_model].sim.test_parameter
self.S_2[statistics_model].plot_name = 'self_tuning Tp' + str(self.S_2[statistics_model].sim.t_predict)
def simulate_experiment_self_tuning_architecture_cost(self, statistics_model: int = 0, print_check: bool = False) -> None:
# compare base vs test_parameter*base running and switching costs
# Check if base-costs are non-zero for valid scaling
if statistics_model > 0:
self.S[statistics_model].initialize_system_from_experiment_parameters(self.parameter_values, self.parameter_keys)
self.S[statistics_model].sim.sim_model = "self_tuning"
self.S_1[statistics_model] = dc(self.S[statistics_model])
self.S_1[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_1[statistics_model].plot_name = 'self_tuning base arch cost'
self.S_2[statistics_model] = dc(self.S[statistics_model])
self.S_2[statistics_model].scalecost_by_test_parameter()
self.S_2[statistics_model].optimize_initial_architecture(print_check=print_check)
def simulate_experiment_self_tuning_architecture_cost_no_lim(self, statistics_model: int = 0, print_check: bool = False) -> None:
# compare base vs test_parameter*base running and switching costs for unconstrainted architecture
if statistics_model > 0:
self.S[statistics_model].initialize_system_from_experiment_parameters(self.parameter_values, self.parameter_keys)
self.S[statistics_model].sim.sim_model = "self_tuning"
self.S[statistics_model].sim.self_tuning_parameter = None
self.S_1[statistics_model] = dc(self.S[statistics_model])
self.S_1[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_1[statistics_model].plot_name = 'self_tuning base arch cost'
self.S_2[statistics_model] = dc(self.S[statistics_model])
self.S_2[statistics_model].scalecost_by_test_parameter()
self.S_2[statistics_model].optimize_initial_architecture(print_check=print_check)
def simulate_experiment_self_tuning_architecture_constraints(self, statistics_model: int = 0, print_check: bool = False) -> None:
# compare [base,high] vs [test_parameter*base,high] architecture constraints
if statistics_model > 0:
self.S[statistics_model].initialize_system_from_experiment_parameters(self.parameter_values, self.parameter_keys)
self.S[statistics_model].sim.sim_model = "self_tuning"
self.S[statistics_model].sim.self_tuning_parameter = None
# print('Check 1')
self.S_1[statistics_model] = dc(self.S[statistics_model])
self.S_1[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_1[statistics_model].plot_name = r"self_tuning $|$arch$|\in [${},{}$]$".format(self.S_1[statistics_model].B.min, self.S_1[statistics_model].B.max)
# print(f"1: {self.S_1[statistics_model].B.min} | {self.S_1[statistics_model].B.max}")
self.S_2[statistics_model] = dc(self.S[statistics_model])
self.S_2[statistics_model].architecture_limit_set(min_set=self.S_2[statistics_model].sim.test_parameter)
self.S_2[statistics_model].optimize_initial_architecture(print_check=print_check)
self.S_2[statistics_model].plot_name = r"self_tuning $|$arch$|\in [${},{}$]$".format(self.S_2[statistics_model].B.min, self.S_2[statistics_model].B.max)
# print(f"2: {self.S_2[statistics_model].B.min} | {self.S_2[statistics_model].B.max}")
def plot_experiment(self, exp_no=None) -> None:
# Plotting wrapper for experiments
self.initialize_system_from_experiment_number(exp_no=exp_no)
print('\nPlotting Experiment No: {}'.format(self.exp_no))
if self.S[0].sim.test_model in self.experiment_modifications_mapper:
self.retrieve_experiment()
self.plot_comparison_exp_no()
elif self.S[0].sim.test_model in self.experiment_mapper_statistics:
self.plot_statistics_exp_no()
else:
raise Exception('Experiment not defined')
def plot_comparison_exp_no(self) -> None:
# Plot wrapper for a single experiment
fig = plt.figure(figsize=(6, 8), tight_layout=True)
outer_grid = gs.GridSpec(2, 2, figure=fig, height_ratios=[1, 7], width_ratios=[1, 1])
ax_exp_legend = fig.add_subplot(outer_grid[0, 0])
ax_eval = fig.add_subplot(outer_grid[0, 1])
time_grid = gs.GridSpecFromSubplotSpec(7, 1, subplot_spec=outer_grid[1, :], hspace=0.2, height_ratios=[1, 1, 1, 0.7, 1, 0.7, 0.7])
ax_cost = fig.add_subplot(time_grid[0, 0])
ax_state = fig.add_subplot(time_grid[1, 0], sharex=ax_cost)
ax_B_scatter = fig.add_subplot(time_grid[2, 0], sharex=ax_cost)
ax_B_count = fig.add_subplot(time_grid[3, 0], sharex=ax_cost)
ax_C_scatter = fig.add_subplot(time_grid[4, 0], sharex=ax_cost)
ax_C_count = fig.add_subplot(time_grid[5, 0], sharex=ax_cost)
ax_compute_time = fig.add_subplot(time_grid[6, 0], sharex=ax_cost)
self.S_1[0].plot_openloop_eigvals(ax_in=ax_eval)
self.S_1[0].plot_cost(ax_in=ax_cost)
self.S_2[0].plot_cost(ax_in=ax_cost, set_details_flag=True)
ax_cost.tick_params(axis="x", labelbottom=False)
# ax_cost.yaxis.set_major_locator(MaxNLocator(2))
plt_title = None if not self.plot_title_check else f"Experiment No: {self.exp_no}"
ax_exp_legend.legend(handles=[mpatches.Patch(color=self.S_1[0].plot.plot_parameters[self.S_1[0].plot.plot_system]['c'], label=self.S_1[0].plot_name),
mpatches.Patch(color=self.S_2[0].plot.plot_parameters[self.S_2[0].plot.plot_system]['c'], label=self.S_2[0].plot_name)],
loc='center', ncol=1, title=plt_title)
ax_exp_legend.axis('off')
self.S_1[0].plot_states(ax_in=ax_state)
self.S_2[0].plot_states(ax_in=ax_state, set_details_flag=True)
ax_state.tick_params(axis="x", labelbottom=False)
self.S_1[0].plot_architecture_history(arch='B', ax_in=ax_B_scatter)
self.S_2[0].plot_architecture_history(arch='B', ax_in=ax_B_scatter)
ax_B_scatter.set_ylabel('Actuator\nPosition\n' + r'$\mathcal{A}_t$')
ax_B_scatter.tick_params(axis="x", labelbottom=False)
self.S_1[0].plot_architecture_history(arch='C', ax_in=ax_C_scatter)
self.S_2[0].plot_architecture_history(arch='C', ax_in=ax_C_scatter)
ax_C_scatter.set_ylabel('Sensor\nPosition\n' + r'$S_t$')
ax_C_scatter.tick_params(axis="x", labelbottom=False)
for lim_val in [self.S[0].B.min, self.S[0].B.max]:
ax_B_count.axhline(y=lim_val, color='tab:gray', ls='dashdot', alpha=0.5)
ax_C_count.axhline(y=lim_val, color='tab:gray', ls='dashdot', alpha=0.5)
self.S_1[0].plot_architecture_count(ax_in=ax_B_count, arch='B')
self.S_2[0].plot_architecture_count(ax_in=ax_B_count, arch='B')
ax_B_count.set_ylabel('Actuator\nCount\n' + r'$|\mathcal{A}_t|$')
ax_B_count.tick_params(axis="x", labelbottom=False)
self.S_1[0].plot_architecture_count(ax_in=ax_C_count, arch='C')
self.S_2[0].plot_architecture_count(ax_in=ax_C_count, arch='C')
ax_C_count.set_ylabel('Sensor\nCount\n' + r'$|S_t|$')
ax_C_count.tick_params(axis="x", labelbottom=False)
self.S_1[0].plot_compute_time(ax_in=ax_compute_time)
self.S_2[0].plot_compute_time(ax_in=ax_compute_time)
ax_compute_time.set_yscale('log')
y_lims = list(ax_compute_time.get_ylim())
ax_compute_time.locator_params(axis='y', subs=(1, ))
ax_compute_time.set_ylim(10 ** np.floor(np.log10(y_lims[0])), 10 ** np.ceil(np.log10(y_lims[1])))
# ax_compute_time.yaxis.set_major_locator(MaxNLocator(2))
ax_compute_time.set_ylabel('Compute\nTime (s)')
ax_compute_time.set_xlabel(r'Time $t$')
ax_compute_time.set_xlim(0, self.S[0].sim.t_simulate)
plt.show()
save_path = self.image_save_folder_path + 'exp' + str(self.exp_no) + '.pdf'
fig.savefig(save_path, dpi=fig.dpi)
print('\nImage saved: {}\n'.format(save_path))
def plot_statistics_exp_no(self) -> None:
# Plot wrapper for statistics experiment
self.initialize_system_from_experiment_number()
sim_range = range(1, self.S[0].number_of_states + 1) if self.S[0].sim.test_model == 'statistics_pointdistribution_openloop' else range(1, 100 + 1)
fig = plt.figure(tight_layout=True)
grid_outer = gs.GridSpec(2, 1, figure=fig, height_ratios=[3, 1])
grid_inner = gs.GridSpecFromSubplotSpec(2, 2, subplot_spec=grid_outer[0, 0], hspace=0.2, width_ratios=[1, 1], height_ratios=[1, 2])
ax_exp_legend = fig.add_subplot(grid_inner[0, 0])
ax_eigmodes = fig.add_subplot(grid_inner[0, 1])
ax_cost = fig.add_subplot(grid_inner[1, :])
grid_architecture = gs.GridSpecFromSubplotSpec(1, 5, subplot_spec=grid_outer[1, :], hspace=0)
ax_architecture_B_count = fig.add_subplot(grid_architecture[0, 0])
ax_architecture_C_count = fig.add_subplot(grid_architecture[0, 1], sharey=ax_architecture_B_count)
ax_architecture_B_change = fig.add_subplot(grid_architecture[0, 2], sharey=ax_architecture_B_count)
ax_architecture_C_change = fig.add_subplot(grid_architecture[0, 3], sharey=ax_architecture_B_count)
ax_architecture_compute_time = fig.add_subplot(grid_architecture[0, 4], sharey=ax_architecture_B_count)
cstyle = ['tab:blue', 'tab:orange', 'black']
lstyle = ['dashdot', 'dashed']
mstyle = ['o', '+', 'x']
cost_min_1, cost_min_2 = np.inf * np.ones(self.S[0].sim.t_simulate), np.inf * np.ones(self.S[0].sim.t_simulate)
cost_max_1, cost_max_2 = np.zeros(self.S[0].sim.t_simulate), np.zeros(self.S[0].sim.t_simulate)
sample_cost_1, sample_cost_2 = np.zeros(self.S[0].sim.t_simulate), np.zeros(self.S[0].sim.t_simulate)
compute_time_1, compute_time_2 = [], []
sample_eig = np.zeros(self.S[0].number_of_states)
arch_change_1 = {'B': [], 'C': []}
arch_change_2 = {'B': [], 'C': []}
arch_count_1 = {'B': [], 'C': []}
arch_count_2 = {'B': [], 'C': []}
m1_name, m2_name = '', ''
sample_ID = np.random.choice(sim_range)
for model_no in tqdm(sim_range, ncols=100, desc='Model ID'):
self.data_from_memory_statistics(model_no)
cost_min_1, cost_max_1, compute_time_1, arch_change_1, arch_count_1 = statistics_data_parser(self.S_1[model_no], cost_min_1, cost_max_1, compute_time_1, arch_change_1, arch_count_1)
cost_min_2, cost_max_2, compute_time_2, arch_change_2, arch_count_2 = statistics_data_parser(self.S_2[model_no], cost_min_2, cost_max_2, compute_time_2, arch_change_2, arch_count_2)
ax_eigmodes.scatter(range(1, self.S[model_no].number_of_states + 1), np.sort(np.abs(self.S[model_no].A.open_loop_eig_vals)),
marker=mstyle[0], s=10, color=cstyle[0], alpha=float(1 / self.S[0].number_of_states))
if sample_ID == model_no:
sample_cost_1 = list(
itertools.accumulate(self.S_1[model_no].list_from_dict_key_time(self.S_1[model_no].trajectory.cost.true)))
sample_cost_2 = list(
itertools.accumulate(self.S_2[model_no].list_from_dict_key_time(self.S_2[model_no].trajectory.cost.true)))
sample_eig = np.sort(np.abs(self.S[model_no].A.open_loop_eig_vals))
m1_name = self.S_1[model_no].plot_name
m2_name = self.S_2[model_no].plot_name
self.dict_memory_clear(model_id=model_no)
plt_title = None if not self.plot_title_check else f"Experiment No: {self.exp_no}"
ax_exp_legend.legend(handles=[mpatches.Patch(color=cstyle[0], label=r'$M_1$:' + m1_name),
mpatches.Patch(color=cstyle[1], label=r'$M_2$:' + m2_name)],
loc='center', title = plt_title)
ax_exp_legend.axis('off')
ax_cost.fill_between(range(0, self.S[0].sim.t_simulate), cost_min_1, cost_max_1, color=cstyle[0], alpha=0.4)
ax_cost.fill_between(range(0, self.S[0].sim.t_simulate), cost_min_2, cost_max_2, color=cstyle[1], alpha=0.4)
ax_cost.plot(range(0, self.S[0].sim.t_simulate), sample_cost_1, color=cstyle[2], ls=lstyle[0], linewidth=1)
ax_cost.plot(range(0, self.S[0].sim.t_simulate), sample_cost_2, color=cstyle[2], ls=lstyle[1], linewidth=1)
ax_cost.legend(handles=[mlines.Line2D([], [], color=cstyle[2], ls=lstyle[0], label='Sample ' + r'$M_1$'),
mlines.Line2D([], [], color=cstyle[2], ls=lstyle[1], label='Sample ' + r'$M_2$')],
loc='upper left', ncols=2)
ax_cost.set_yscale('log')
ax_cost.set_xlabel(r'Time $t$')
ax_cost.set_ylabel(r'Cost $J_t$')
ax_cost.set_xlim(0, self.S[0].sim.t_simulate)
ax_eigmodes.scatter(range(1, self.S[0].number_of_states + 1), sample_eig, marker=mstyle[2], color=cstyle[2], s=10)
ax_eigmodes.hlines(1, xmin=1, xmax=self.S[0].number_of_states, colors=cstyle[2], ls=lstyle[1])
# ax_eigmodes.set_xlabel('Mode ' + r'$i$')
ax_eigmodes.set_ylabel(r'$|\lambda_i(A)|$')
ax_eigmodes.tick_params(top=False, labeltop=False, bottom=False, labelbottom=False)
ax_eigmodes.legend(
handles=[mlines.Line2D([], [], color=cstyle[2], marker=mstyle[2], linewidth=0, label='Sample'),
mlines.Line2D([], [], color=cstyle[0], marker=mstyle[0], linewidth=0, label='Modes')],
loc='upper left')
a1 = ax_architecture_B_change.boxplot([arch_change_2['B'], arch_change_1['B']],
labels=[r'$M_2$', r'$M_1$'], vert=False, widths=0.5)
a2 = ax_architecture_C_change.boxplot([arch_change_2['C'], arch_change_1['C']],
labels=[r'$M_2$', r'$M_1$'], vert=False, widths=0.5)
a3 = ax_architecture_B_count.boxplot([arch_count_2['B'], arch_count_1['B']],
labels=[r'$M_2$', r'$M_1$'], vert=False, widths=0.5)
a4 = ax_architecture_C_count.boxplot([arch_count_2['C'], arch_count_1['C']],
labels=[r'$M_2$', r'$M_1$'], vert=False, widths=0.5)
a5 = ax_architecture_compute_time.boxplot([compute_time_2, compute_time_1],
labels=[r'$M_2$', r'$M_1$'], vert=False, widths=0.5)
for ax in (ax_architecture_B_count, ax_architecture_C_count):
ax.xaxis.set_major_locator(MaxNLocator(min_n_ticks=1, integer=True))
for ax in (ax_architecture_B_change, ax_architecture_C_change):
ax.xaxis.set_major_locator(MaxNLocator(min_n_ticks=1, integer=True))
for bplot in (a1, a2, a3, a4, a5):
for patch, color in zip(bplot['medians'], [cstyle[1], cstyle[0]]):
patch.set_color(color)
# for a in (ax_architecture_B_count, ax_architecture_C_count, ax_architecture_B_change, ax_architecture_C_change):
# x_lim_g = a.get_xlim()
# a.set_xlim(np.floor(x_lim_g[0]), np.ceil(x_lim_g[1]))
for a in (ax_architecture_C_count, ax_architecture_B_change, ax_architecture_C_change, ax_architecture_compute_time):
a.tick_params(axis='y', labelleft=False, left=False)
ax_architecture_compute_time.set_xscale('log')
x_lims = list(ax_architecture_compute_time.get_xlim())
# ax_architecture_compute_time.locator_params(axis='x', subs=(1, ))
ax_architecture_compute_time.set_xlim(10 ** np.floor(np.log10(x_lims[0])), 10 ** np.ceil(np.log10(x_lims[1])))
# ax_architecture_compute_time.xaxis.set_major_locator(LogLocator(base=10, subs=(1.0,), numticks=2))
# ax_architecture_compute_time.xaxis.set_major_formatter(LogFormatter(labelOnlyBase=True))
ax_architecture_compute_time.set_xticks([10 ** np.floor(np.log10(x_lims[0])), 10 ** np.ceil(np.log10(x_lims[1]))])
ax_architecture_compute_time.xaxis.set_minor_formatter(NullFormatter())
ax_architecture_B_count.set_xlabel('Avg ' + r'$\mathcal{A}_t$' + '\nSize')
ax_architecture_C_count.set_xlabel('Avg ' + r'$S_t$' + '\nSize')
ax_architecture_B_change.set_xlabel('Avg ' + r'$\mathcal{A}_t - \mathcal{A}_{t-1}$' + '\nChanges')
ax_architecture_C_change.set_xlabel('Avg ' + r'$S_t - S_{t-1}$' + '\nChanges')
ax_architecture_compute_time.set_xlabel('Avg Compute \n Time (s)')
plt.show()
save_path = self.image_save_folder_path + 'exp' + str(self.exp_no) + '.pdf'
fig.savefig(save_path, dpi=fig.dpi)
print('\nImage saved: {}\n'.format(save_path))
def coin_toss() -> bool:
# Generate True/False with equal probability
return np.random.default_rng().random() > 0.5
def compare_lists(list1: list, list2: list) -> dict:
# Find elements unique to each list and common to both lists
return {'only1': [k for k in list1 if k not in list2], 'only2': [k for k in list2 if k not in list1],
'both': [k for k in list1 if k in list2]}
def architecture_iterator(arch=None) -> list:
# Iterate over either B, C or both
if type(arch) == list and len(arch) == 1:
arch = arch[0]
arch = [arch] if arch in ['B', 'C'] else ['B', 'C'] if (
arch is None or arch == ['B', 'C']) else [] if arch == 'skip' else 'Error'
if arch == 'Error':
raise ArchitectureError
return arch
def normalize_columns_of_matrix(A_mat: np.ndarray) -> np.ndarray:
# Normalize columns of a matrix - used for eigenvector matrix normalization
for i in range(0, np.shape(A_mat)[0]):
if np.linalg.norm(A_mat[:, i]) != 0:
A_mat[:, i] /= np.linalg.norm(A_mat[:, i])
return A_mat
class PlotParameters:
# Plot values and parameters - updated when simulated systems are read from memory
def __init__(self, sys_stage: int = 0):
self.plot_system = sys_stage
self.predicted_cost, self.true_cost = [], []
self.x_2norm, self.x_estimate_2norm, self.error_2norm = [], [], []
self.plot_parameters = \
{1: {'node': 'tab:blue', 'B': 'tab:orange', 'C': 'tab:green', 'm': 'x', 'c': 'tab:blue', 'ms': 20,
'ls': 'solid'},
2: {'node': 'tab:blue', 'B': 'tab:orange', 'C': 'tab:green', 'm': 'o', 'c': 'tab:orange', 'ms': 20,
'ls': 'dashed'}}
self.network_plot_limits = []
self.B_history = [[], []]
self.C_history = [[], []]
self.states_graph, self.state_positions = netx.DiGraph(), {}
self.actutator_positions, self.sensor_positions = {}, {}
class System:
class Dynamics:
def __init__(self):
# Parameters assigned from function file
self.rho = 1 # Scaling factor for eigenvalues
self.network_model = 'rand' # Network adjacency matrix
self.network_parameter = 0 # Parameter for network adjacency matrix
self.second_order = False # Check for second order states - each node has 2 states associated with it
self.second_order_scaling_factor = 1 # Scaling factor for second order equation
self.second_order_network_type = 1 # Network type of second order states
# Default parameter
self.self_loop = True # Self-loops within the adjacency matrix
# Evaluated
self.open_loop_eig_vals = 0 # Vector of second order states
self.open_loop_eig_vecs = np.zeros((0, 0))
self.adjacency_matrix = 0 # Adjacency matrix
self.number_of_non_stable_modes = 0 # Number of unstable modes with magnitude >= 1
self.A_mat = np.zeros((0, 0)) # Open-loop dynamics matrix
self.A_augmented_mat = np.zeros((0, 0)) # Open-loop augmented dynamics matrix for current t
def display_values(self) -> None:
for var, value in vars(self).items():
print(f"{var} = {value}")
class Architecture:
def __init__(self):
# Parameters assigned from function file
self.second_order_architecture_type = 0 # Type of second-order architecture - which states do it control or estimate
self.min = 1 # Minimum architecture bounds
self.max = 1 # Maximum architecture bounds
self.R2 = 0 # Cost on running architecture
self.R3 = 0 # Cost on switching architecture
# Calculated terms
self.available_indices = [] # Indices of available architecture
self.available_vectors = {} # Vectors associated with available architecture
self.number_of_available = 0 # Count of available architecture
self.active_set = [] # Set of indices of active architecture
self.active_matrix = np.zeros((0, 0)) # Matrix of active architecture
self.Q = np.zeros((0, 0)) # Cost on states/Process noise covariance
self.R1 = np.zeros((0, 0)) # Cost on active actuators/Measurement noise covariance
self.R1_reference = np.zeros((0, 0)) # Cost on available actuators
self.indicator_vector_current = np.zeros(
self.number_of_available) # {1, 0} binary vector of currently active architecture - to compute running/switching costs
self.indicator_vector_history = np.zeros(
self.number_of_available) # {1, 0} binary vector of previously active architecture - to compute switching costs
self.history_active_set = {} # Record of active architecture over simulation horizon
self.change_count = 0 # Count of number of changes in architecture over simulation horizon
self.active_count = [] # Count size of active architecture at each timestep of the simulation horizon
self.recursion_matrix = {} # Recursive cost matrix/estimation error covariance over the prediction horizon
self.gain = {} # Gains calculated over the prediction horizon for the fixed architecture
def display_values(self) -> None:
for var, value in vars(self).items():
print(f"{var} = {value}")
class Disturbance:
def __init__(self):
# Parameters assigned from function file
self.W_scaling = 1 # Scaling factor for process noise covariance
self.V_scaling = 1 # Scaling factor for measurement noise covariance
self.noise_model = None # Noise model for targeted un-modelled disturbances
self.disturbance_step = 0 # Number of steps between un-modelled disturbances
self.disturbance_number = 0 # Number of states affected by un-modelled disturbances
self.disturbance_magnitude = 0 # Scaling factor of un-modelled disturbances
# Calculated terms
self.W = np.zeros((0, 0)) # Process noise covariance
self.V = np.zeros((0, 0)) # Measurement noise covariance
self.w_gen = {} # Realization of process noise
self.v_gen = {} # Realization of measurement noise
self.F_augmented = np.zeros((0, 0)) # augmented matrix for noise at current time
def display_values(self) -> None:
for var, value in vars(self).items():
print(f"{var} = {value}")
class Simulation:
def __init__(self):
# Parameters assigned from function file
self.experiment_number = 0 # Experiment number based on parameter sheet
self.t_predict = int(10) # Prediction time horizon
self.sim_model = None # Simulation model of architecture
self.self_tuning_parameter = 1 # Number of self tuning changes per step
self.test_model = None # Test case
self.test_parameter = None # Test case
self.multiprocess_check = False # Boolean to determine if multiprocess mapping is used or not for choices
# Constant parameters
self.t_simulate = int(100) # Simulation time horizon
self.t_current = 0 # Current time-step of simulation
def display_values(self) -> None:
for var, value in vars(self).items():
print(f"{var} = {value}")
class Trajectory:
def __init__(self):
# Parameters assigned from function file
self.X0_scaling = 1 # Scaling factor of initial state
# Calculated terms
self.X0_covariance = np.zeros((0, 0)) # Initial state covariance
self.x = {} # True state trajectory
self.x_estimate = {} # Estimates state trajectory
self.X_augmented = {} # augmented state trajectory
self.error = {} # Estimation error trajectory
self.control_cost_matrix = {} # Control cost matrix at each timestep
self.estimation_matrix = {} # Estimation error covariance matrix at each timestep
self.error_2norm = {} # 2-norm of estimation error trajectory
self.cost = System.Cost() # Cost variables
self.computation_time = {} # Computation time for greedy optimization at each simulation timestep
def display_values(self) -> None:
for var, value in vars(self).items():
print(f"{var} = {value}")
class Cost:
def __init__(self):
# Parameters assigned from function file
self.metric_control = 1 # Metric function to evaluate control costs
self.metric_running = 1 # Metric function to evaluate running costs
self.metric_switching = 1 # Metric function to evaluate switching costs
# Calculated terms
self.running = 0 # Running cost at current timestep
self.switching = 0 # Switching cost at current timestep
self.control = 0 # Control cost at current timestep
self.predicted = {} # Predicted total stage cost trajectory
self.true = {} # True total stage cost trajectory
self.initial = [] # Costs for initial architecture optimization
self.predicted_matrix = {} # Cost matrix over the prediction horizon
def display_values(self) -> None:
for var, value in vars(self).items():
print(f"{var} = {value}")
def __init__(self):
self.number_of_nodes = 20 # Number of nodes in the network
self.number_of_states = 20 # Number of state in the network (affected by second_order dynamics)
self.A = self.Dynamics()
self.B = self.Architecture()
self.C = self.Architecture()
self.disturbance = self.Disturbance()
self.sim = self.Simulation()
self.trajectory = self.Trajectory()
self.plot = None
self.model_name = ''
self.plot_name = None
def copy_from_system(self, ref_sys):
# Dict based deep copy from ref_sys
if not isinstance(ref_sys, System):
raise Exception('Check system')
self.__dict__.update(ref_sys.__dict__)
def initialize_system_from_experiment_parameters(self, experiment_parameters, experiment_keys) -> None:
# Create model from experiment parameters
parameters = dict(zip(experiment_keys, experiment_parameters))
self.sim.experiment_number = parameters['experiment_no']
self.number_of_nodes = parameters['number_of_nodes']
self.number_of_states = parameters['number_of_nodes']
self.A.rho = parameters['rho']
self.A.network_model = parameters['network_model']
self.A.network_parameter = parameters['network_parameter']
self.adjacency_matrix_initialize()
self.A.second_order = parameters['second_order']
if self.A.second_order:
self.number_of_states = self.number_of_nodes * 2
self.A.second_order_network_type = parameters['second_order_network']
self.B.second_order_architecture_type = parameters['second_order_architecture']
self.C.second_order_architecture_type = parameters['second_order_architecture']
self.rescale_wrapper()
self.sim.t_predict = parameters['prediction_time_horizon']
self.sim.multiprocess_check = parameters['multiprocessing']
self.sim.test_model = None if parameters['test_model'] == 'None' else parameters['test_model']
self.sim.test_parameter = None if parameters['test_parameter'] == 0 else int(parameters['test_parameter'])
parameters['disturbance_model'] = None if parameters['disturbance_model'] == 'None' else parameters[
'disturbance_model']
self.disturbance.W_scaling = parameters['W_scaling']
self.disturbance.V_scaling = parameters['V_scaling']
self.disturbance.noise_model = parameters['disturbance_model']
if self.disturbance.noise_model is not None:
self.disturbance.disturbance_step = parameters['disturbance_step']
self.disturbance.disturbance_number = parameters['disturbance_number']
self.disturbance.disturbance_magnitude = parameters['disturbance_magnitude']
self.initialize_disturbance()
self.B.R2 = parameters['B_run_cost']
self.C.R2 = parameters['C_run_cost']
self.B.R3 = parameters['B_switch_cost']
self.C.R3 = parameters['C_switch_cost']
self.architecture_limit_set(min_set=parameters['architecture_constraint_min'],
max_set=parameters['architecture_constraint_max'])
self.initialize_available_vectors_as_basis_vectors()