-
Notifications
You must be signed in to change notification settings - Fork 0
/
measure_optimize.py
2649 lines (2319 loc) · 112 KB
/
measure_optimize.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
"""
Measurement optimization tool
@University of Notre Dame
"""
import numpy as np
import pandas as pd
import pyomo.environ as pyo
from pyomo.opt import SolverStatus, TerminationCondition
from greybox_generalize import LogDetModel
from pyomo.contrib.pynumero.interfaces.external_grey_box import (
ExternalGreyBoxModel,
ExternalGreyBoxBlock,
)
from enum import Enum
from dataclasses import dataclass
import pickle
from scipy.spatial import cKDTree
import cvxpy as cp
class CovarianceStructure(Enum):
"""Covariance definition
if identity: error covariance matrix is an identity matrix
if variance: a numpy vector, each element is the corresponding variance, a.k.a. diagonal elements.
Shape: Sum(Nt)
if time_correlation: a 3D numpy array, each element is the error covariances
This option assumes covariances not between measurements, but between timepoints for one measurement
Shape: Nm * (Nt_m * Nt_m)
if measure_correlation: a 2D numpy array, covariance matrix for a single time steps
This option assumes the covariances between measurements at the same timestep in a time-invariant way
Shape: Nm * Nm
if time_measure_correlation: a 2D numpy array, covariance matrix for the flattened measurements
Shape: sum(Nt) * sum(Nt)
"""
identity = 0
variance = 1
time_correlation = 2
measure_correlation = 3
time_measure_correlation = 4
@classmethod
def has_value(cls, value):
return value in cls._value2member_map_
class ObjectiveLib(Enum):
"""
Objective function library
if A: minimize the trace of FIM
if D: minimize the determinant of FIM
"""
A = 0
D = 1
E = 2
@classmethod
def has_value(cls, value):
return value in cls._value2member_map_
class SensitivityData:
""""""
def __init__(self, filename, Nt) -> None:
"""
Read, convert the format, and sotre the sensitivity information (Jacobian).
Only process a certain format of CSV file.
Assume every measurement has the same number of time points: Nt
Arguments
---------
:param filename: a string of the csv file name
:param Nt: number of timepoints is needed to split Q for each measurement.
Assume all measurements have the same number of time points of Nt.
This csv file should have the following format:
columns: parameters to be estimated
(An extra first column is added for index)
rows: measurement timepoints
data: Jacobian values
The csv file example:
Column index | Parameter 1 | Parameter 2 | ... | Parameter P
measurement 1 | number | number | ... | number
measurement 2 | number | number | ... | number
...
measurement N | number | number | ... | number
Number according to measurement i, parameter j is
the gradient of measurement i w.r.t parameter j
Returns
------
None
"""
# store the number of time points for each measurement
self.Nt = Nt
# read Jacobian from .csv file
self._read_from_csv(filename)
def _read_from_csv(self, filename):
"""Read Jacobian from csv file
Arguments
---------
:param filename: a string of the csv file name
This csv file structure is explained in the class doc string.
Returns
------
None
"""
# first column is index column, indicated here. If you have different column as the index column, indicate here.
jacobian_info = pd.read_csv(filename, index_col=[0])
# convert Jacobian matrix from Pandas DataFrame to numpy array
jacobian_array = np.asarray(jacobian_info)
# check if the number of rows in this array is a multiple of Nt
if len(jacobian_array) % self.Nt != 0:
raise ValueError(
"The number of rows in this Jacobian matrix is not a multiple of Nt."
)
# infer the number of parameters from the shape of jacobian
self.n_parameters = len(jacobian_array[0])
# store the original Jacobian matrix in object
self.jacobian = jacobian_array
def get_jac_list(self, static_measurement_idx, dynamic_measurement_idx):
"""Combine Jacobian Q for each measurement to be in one Jacobian Q.
Through _split_jacobian we get a numpy array for Jacobian Q,
each list contains an Nt*n_parameters elements, which is the sensitivity matrix Q for measurement m
We aim to convert this list of arrays to Q, a numpy array containing Jacobian matrix of the shape N_total_m * Np
Jacobian Q structure:
[ \partial y1(t1)/ \partial p1, ..., \partial y1(t1)/ \partial pN,
\partial y1(t2)/ \partial p1, ..., \partial y1(t2)/ \partial pN,
...,
\partial y1(tN)/ \partial p1, ..., \partial y1(tN)/ \partial pN,
\partial y2(t1)/ \partial p1, ..., \partial y2(t1)/ \partial pN,
...,
\partial yN(tN)/ \partial p1, ..., \partial yN(tN)/ \partial pN,]
Arguments
---------
:param static_measurement_idx: list of the index for static measurements
:param dynamic_measurement_idx: list of the index for dynamic measurements
Returns
-------
self.jac: Jacobian information for main class use, a 2D numpy array
"""
# get the maximum index from index set
# why not sum up static index number and dynamic index number? because they can overlap
max_measure_idx = max(max(static_measurement_idx), max(dynamic_measurement_idx))
# the total rows of Q should be equal or more than the number of maximum index given by the argument
if len(self.jacobian) < max_measure_idx * self.Nt:
raise ValueError(
"Inconsistent Jacobian matrix shape. Expecting at least "
+ str(max_measure_idx * self.Nt)
+ " rows in Jacobian matrix Q."
)
# if one measurement is in both SCM indices and DCM indices, its Jacobian is included twice (overlap is allowed)
# compute how many measurements as SCM
if static_measurement_idx:
static_idx_len = len(static_measurement_idx)
# if given None, this variable is given 0 (len(None) gives error message)
else:
static_idx_len = 0
# compute how many measurements as DCM
if dynamic_measurement_idx:
dynamic_idx_len = len(dynamic_measurement_idx)
# if given None, this variable is given 0 (len(None) gives error message)
else:
dynamic_idx_len = 0
# compute N_total_measure, including both SCMs and DCMs. store for later use
self.total_measure_idx = static_idx_len + dynamic_idx_len
# all measurements have Nt time points
total_measure_len = (static_idx_len + dynamic_idx_len) * self.Nt
# initialize Jacobian Q as numpy array
# here we stack the Jacobian Q according to the orders the user provides SCM and DCM index
# jac: Jacobian matrix of shape N_total_measure * Np
jac = np.zeros((total_measure_len, self.n_parameters))
# update row number counter in the reassembled jac
# starts from -1 because we add one every time before giving it a value
update_row_counter = -1
# if there is static-cost measurements
if static_measurement_idx is not None:
# loop over SCM indices
for i in static_measurement_idx:
# loop over time points
for t in range(self.Nt):
# locate the row number in the original Jacobian information
row_number = i * self.Nt + t
# update the row number in the assembled Jacobian matrix
update_row_counter += 1
# loop over columns, i.e. parameters
for p in range(self.n_parameters):
jac[update_row_counter][p] = self.jacobian[row_number][p]
# if there is dynamic-cost measurements
if dynamic_measurement_idx is not None:
# loop over DCM indices
for j in dynamic_measurement_idx:
# loop over time points
for t in range(self.Nt):
# locate the row number in the origianl Jacobian information
row_number = j * self.Nt + t
# update row number in assembled Jacobian matrix
update_row_counter += 1
# loop over columns, i.e. parameters
for p in range(self.n_parameters):
jac[update_row_counter][p] = self.jacobian[row_number][p]
self.jac = jac
@dataclass
class MeasurementData:
"""
containing measurement related information.
:param name: a list of strings, the measurement names
:param jac_index: a list of int, the indices of measurements in the Jacobian matrix
:param static_cost: a list of float, the static cost of measurements
:param dynamic_cost: a list of float, the dynamic cost of measurements
:param min_time_interval: float, the minimal time interval between two sampled time points
:param max_num_sample: int, the maximum number of samples for each measurement
:param total_max_num_sample: int, the maximum number of samples for all measurements
"""
name: list
jac_index: list
static_cost: list
dynamic_cost: list
min_time_interval: float
max_num_sample: int
total_max_num_sample: int
def _check_if_input_is_valid(self):
"""This function is to check if the input types are consistent with what this class expects.
Adapted from: https://stackoverflow.com/questions/50563546/validating-detailed-types-in-python-dataclasses
from the answer of @Arne
"""
# loop over all names of this dataclass
for field_name, field_def in self.__dataclass_fields__.items():
# get the type the input it should be
data_type = field_def.type
# get the actual type we get from the user's input
input_type = type(getattr(self, field_name))
# check if the actual type is the same with what we expect
if input_type != field_def.type:
raise ValueError(
"Instead of getting type ", data_type, ", the input is ", input_type
)
def __post_init__(self):
"""This is added for error checking."""
# if one input is not the type it is supposed to be, throw error
self._check_if_input_is_valid()
class MeasurementOptimizer:
def __init__(
self,
sens_info,
measure_info,
error_cov=None,
error_opt=CovarianceStructure.identity,
print_level=0,
):
"""
Arguments
---------
:param sens_info: the SensitivityData object
containing Jacobian matrix jac and the number of timepoints Nt
jac contains m lists, m is the number of meausrements
Each list contains an N_t_m*n_parameters elements, which is the sensitivity matrix Q for measurement m
:param measure_info: the MeasurementData object
containing the string names of measurements, indices of measurements in the Jacobian matrix,
the static costs and dynamic costs of the measurements,
minimal interval time between two sample points, and the maximum number of samples.
:param error_cov: a numpy array
defined error covariance matrix here
if CovarianceStructure.identity: error covariance matrix is an identity matrix
if CovarianceStructure.variance: a numpy vector, each element is the corresponding variance, a.k.a. diagonal elements.
Shape: Sum(Nt)
if CovarianceStructure.time_correlation: a 3D numpy array, each element is the error covariances
This option assumes covariances not between measurements, but between timepoints for one measurement
Shape: Nm * (Nt_m * Nt_m)
if CovarianceStructure.measure_correlation: a 2D numpy array, covariance matrix for a single time steps
This option assumes the covariances between measurements at the same timestep in a time-invariant way
Shape: Nm * Nm
if CovarianceStructure.time_measure_correlation: a 2D numpy array, covariance matrix for the flattened measurements
Shape: sum(Nt) * sum(Nt)
:param: error_opt: CovarianceStructure
can choose from identity, variance, time_correlation, measure_correlation, time_measure_correlation. See above comments.
:param print_level: int
indicate what statements are printed for debugging at the pre-computation stage
0 (default): no extra printing
1: print to show it is working
2: print for debugging
3: print everything that could help with debugging
Returns
-------
None
"""
# print_level received here is for the pre-computation stage
self.precompute_print_level = print_level
# threshold used to round the fractional number to be integer
self.near_1_threshold = 0.99
self.near_0_threshold = 0.01
## parse sensitivity info from SensitivityData
# get total measurement number from the shape of Q
self.n_total_measurements = len(sens_info.jac)
# store the sens object
self.sens_info = sens_info
## parse measurement info from MeasurementData
self.measure_info = measure_info
# parse measure_info information
self._parse_measure_info()
# check if SensitivityData and MeasurementData provide consistent inputs
self._check_consistent_sens_measure()
# flattened Q and indexes
self._dynamic_flatten(sens_info.jac)
# build and check PSD of Sigma
# check sigma inputs
self._check_sigma(error_cov, error_opt)
# build the Sigma and Sigma_inv (error covariance matrix and its inverse matrix)
Sigma = self._build_sigma(error_cov, error_opt)
# split Sigma_inv to DCM-DCM error, DCM-SCM error vector, SCM-SCM error matrix
self._split_sigma(Sigma)
def _parse_measure_info(self):
"""
This function decodes information from measure_info object.
"""
# indices of static and dynamic measurements, stored in lists
static_measurement_idx, dynamic_measurement_idx = [], []
# dynamic_cost_measure_info stores the static costs of dynamic-cost measurements
# static_cost_measure_info stores the static costs of static-cost measurements
dynamic_cost_measure_info, static_cost_measure_info = [], []
# loop over the number of measurements
for i in range(len(self.measure_info.dynamic_cost)):
# if there is no dynamic costs, this is a static-cost measurement
if self.measure_info.dynamic_cost[i] == 0:
# add to static-cost measurment indices list
static_measurement_idx.append(i)
# add its static cost to the static-cost measurements' cost list
static_cost_measure_info.append(self.measure_info.static_cost[i])
# if there are dynamic costs, this is a dynamic-cost measurement
else:
# add to dynamic-cost measurement indices list
dynamic_measurement_idx.append(i)
# add its static cost to the dynamic-cost measurements' cost list
dynamic_cost_measure_info.append(self.measure_info.static_cost[i])
if self.precompute_print_level == 3:
print("Static-cost measurement idx:", static_measurement_idx)
print("Dynamic-cost measurement idx:", dynamic_measurement_idx)
# number of SCMs
self.n_static_measurements = len(static_measurement_idx)
# SCM indices
self.static_measurement_idx = static_measurement_idx
# number of DCMs
self.n_dynamic_measurements = len(dynamic_measurement_idx)
# DCM indices
self.dynamic_measurement_idx = dynamic_measurement_idx
# static-cost measurements' cost list
self.cost_list = static_cost_measure_info
# dynamic-cost measurements' cost list
self.dynamic_cost_measure_info = dynamic_cost_measure_info
# get DCM installation costs
self.dynamic_install_cost = [
self.measure_info.static_cost[i] for i in dynamic_measurement_idx
]
# parse measurement names
self.measure_name = self.measure_info.name # measurement name list
# add dynamic-cost measurements list
# loop over DCM index list
for i in self.dynamic_measurement_idx:
# loop over dynamic-cost measurements time points
for _ in range(self.sens_info.Nt):
self.cost_list.append(self.measure_info.dynamic_cost[i])
# total number of all measurements and all time points
self.total_num_time = self.sens_info.Nt * (
self.n_static_measurements + self.n_dynamic_measurements
)
# min time interval, only for dynamic-cost measurements
# if there is no min time interval, it is 0
self.min_time_interval = self.measure_info.min_time_interval
# each manual number, for one measurement, how many time points can be chosen at most
# if this number is >= Nt, then there is no limitation to how many of them can be chosen
self.each_manual_number = self.measure_info.max_num_sample
# the maximum number of time points can be chosen for all DCMs
self.manual_number = self.measure_info.total_max_num_sample
if self.precompute_print_level >= 2:
print("Minimal time interval between two samples:", self.min_time_interval)
print(
"Maximum number of samples for each measurement:",
self.each_manual_number,
)
print("Maximum number of samples for all measurements:", self.manual_number)
if self.precompute_print_level == 3:
# print measurement information
print(
"cost list of all measurements, including SCMs and time points for DCMs:",
self.cost_list,
)
print("DCMs installation costs:", self.dynamic_cost_measure_info)
def _check_consistent_sens_measure(self):
"""This function checks if SensitivityData and MeasurementData provide consistent inputs"""
# check if the index list of MeasurementData is in the range of SensitivityData
if (
max(self.measure_info.jac_index) + 1
) * self.sens_info.Nt > self.n_total_measurements:
raise ValueError(
"The measurement index is out of the range of the given Jacobian matrix"
)
def _check_sigma(self, error_cov, error_option):
"""Check sigma inputs shape and values
Arguments
---------
:param error_cov: if error_cov is None, return an identity matrix
option 1: a numpy vector, each element is the corresponding variance, a.k.a. diagonal elements.
Shape: Sum(Nt)
option 2: a 3D numpy array, each element is the error covariances
This option assumes covariances not between measurements, but between timepoints for one measurement
Shape: Nm * (Nt_m * Nt_m)
option 3: a 2D numpy array, covariance matrix for a single time steps
This option assumes the covariances between measurements at the same timestep in a time-invariant way
Shape: Nm * Nm
option 4: a 2D numpy array, covariance matrix for the flattened measurements
Shape: sum(Nt) * sum(Nt)
:param: error_opt: CovarianceStructure
can choose from identity, variance, time_correlation, measure_correlation, time_measure_correlation. See above comments.
Returns
-------
None
"""
# identity matrix
if (error_option == CovarianceStructure.identity) or (
error_option == CovarianceStructure.variance
):
# if None, it means identity matrix
# if not None, need to check shape
if error_cov is not None:
if len(error_cov) != self.total_num_time:
raise ValueError(
"error_cov must have the same length as total_num_time. Expect length:"
+ str(self.total_num_time)
)
elif error_option == CovarianceStructure.time_correlation:
# check the first dimension (length of DCMs)
if len(error_cov) != self.n_total_measurements:
raise ValueError(
"error_cov must have the same length as n_total_measurements. Expect length:"
+ str(self.n_total_measurements)
)
# check the time correlation matrice shape for each DCM
# loop over the index of DCM to retrieve the number of time points for DCM
for i in range(self.n_total_measurements):
# check row number
if len(error_cov[0]) != self.sens_info.Nt:
raise ValueError(
"error_cov[i] must have the shape Nt*Nt. Expect number of rows:"
+ str(self.sens_info.Nt)
)
# check column number
if len(error_cov[0][0]) != self.sens_info.Nt:
raise ValueError(
"error_cov[i] must have the shape Nt*Nt. Expect number of columns:"
+ str(self.sens_info.Nt)
)
elif error_option == CovarianceStructure.measure_correlation:
# check row number
if len(error_cov) != self.sens_info.total_measure_idx:
raise ValueError(
"error_cov must have the same length as total_measure_idx. Expect number of rows:"
+ str(self.sens_info.total_measure_idx)
)
# check column number
if len(error_cov[0]) != self.sens_info.total_measure_idx:
raise ValueError(
"error_cov[i] must have the same length as total_measure_idx. Expect number of columns:"
+ str(self.sens_info.total_measure_idx)
)
elif error_option == CovarianceStructure.time_measure_correlation:
# check row number
if len(error_cov) != self.total_num_time:
raise ValueError(
"error_cov must have the shape total_num_time*total_num_time. Expect number of rows:"
+ str(self.total_num_time)
)
# check column number
if len(error_cov[0]) != self.total_num_time:
raise ValueError(
"error_cov must have the shape total_num_time*total_num_time. Expect number of columns:"
+ str(self.total_num_time)
)
def _dynamic_flatten(self, jac):
"""Update dynamic flattened matrix index.
Arguments
---------
:param jac: Jacobian information for main class use, a 2D array of shape [N_total_meausrements * Np]
Returns
-------
dynamic_flatten matrix: flatten dynamic-cost measurements, not flatten static-costs, [s1, d1|t1, ..., d1|tN, s2]
Flatten matrix: flatten dynamic-cost and static-cost measuremenets
"""
### dynamic_flatten: to be decision matrix
jac_dynamic_flatten = []
# position index in jac_dynamic_flatten where each measurement starts
# key: measurement name. value: its first index in jac_dynamic_flatten
self.first_pos_dynamic_flatten = {}
# all static measurements index after dynamic_flattening
self.static_idx_dynamic_flatten = []
self.dynamic_idx_dynamic_flatten = []
### flatten: flatten all measurement all costs
jac_flatten = []
# position index in jac_flatten where each measurement starts
# key: measurement name. value: it first position in jac_flatten
self.first_pos_flatten = {}
# all static measurements index after flatten
self.static_idx_flatten = []
# all dynamic measurements index after flatten
self.dynamic_idx_flatten = []
# map dynamic index to flatten index
# key: dynamic index, value: corresponding indexes in flatten matrix. For static, it's a list. For dynamic, it's a index value
self.dynamic_to_flatten = {}
# counter for dynamic_flatten
count1 = 0
# counter for flatten
count2 = 0
# loop over total measurement index
for i in range(self.sens_info.total_measure_idx):
if (
i in self.static_measurement_idx
): # static measurements are not flattened for dynamic flatten
if self.precompute_print_level == 3:
print("Static-cost measurement idx: ", i)
# dynamic_flatten for SCM
jacobian_static = []
# locate first row of the sensitivity for this measurement
first_row = i * self.sens_info.Nt
for t in range(self.sens_info.Nt):
jacobian_static.append(jac[first_row + t])
jac_dynamic_flatten.append(jacobian_static)
# map position index in jac_dynamic_flatten where each measurement starts
self.first_pos_dynamic_flatten[i] = count1
# store all static measurements index after dynamic_flattening
self.static_idx_dynamic_flatten.append(count1)
self.dynamic_to_flatten[count1] = (
[]
) # static measurement's dynamic_flatten index corresponds to a list of flattened index
# flatten
for t in range(self.sens_info.Nt):
jac_flatten.append(jac[first_row + t])
if t == 0:
self.first_pos_flatten[i] = count2
# all static measurements index after flatten
self.static_idx_flatten.append(count2)
# map all timepoints to the dynamic_flatten static index
self.dynamic_to_flatten[count1].append(count2)
count2 += 1
count1 += 1
elif i in self.dynamic_measurement_idx:
if self.precompute_print_level == 3:
print("Dynamic-cost measurement idx: ", i)
# dynamic measurements are flattend for both dynamic_flatten and flatten
# locate first row of the sensitivity for this measurement
first_row = i * self.sens_info.Nt
for t in range(self.sens_info.Nt):
jac_dynamic_flatten.append(jac[first_row + t])
if t == 0:
self.first_pos_dynamic_flatten[i] = count1
self.dynamic_idx_dynamic_flatten.append(count1)
jac_flatten.append(jac[first_row + t])
if t == 0:
self.first_pos_flatten[i] = count2
self.dynamic_to_flatten[count1] = count2
count2 += 1
count1 += 1
self.jac_dynamic_flatten = jac_dynamic_flatten
self.jac_flatten = jac_flatten
# dimension after dynamic_flatten
self.num_measure_dynamic_flatten = len(self.static_idx_dynamic_flatten) + len(
self.dynamic_idx_dynamic_flatten
)
# dimension after flatten
self.num_measure_flatten = len(self.static_idx_flatten) + len(
self.dynamic_idx_flatten
)
if self.precompute_print_level >= 2:
print("Number of binary decisions:", self.num_measure_dynamic_flatten)
if self.precompute_print_level == 3:
print(
"Dimension after dynamic flatten:", self.dynamic_idx_dynamic_flatten
)
print("Dimension after flatten:", self.dynamic_idx_flatten)
def _build_sigma(self, error_cov, error_option):
"""Build error covariance matrix
Arguments
---------
:param error_cov: if error_cov is None, return an identity matrix
option 1: a numpy vector, each element is the corresponding variance, a.k.a. diagonal elements.
Shape: Sum(Nt)
option 2: a 3D numpy array, each element is the error covariances
This option assumes covariances not between measurements, but between timepoints for one measurement
Shape: Nm * (Nt_m * Nt_m)
option 3: a 2D numpy array, covariance matrix for a single time steps
This option assumes the covariances between measurements at the same timestep in a time-invariant way
Shape: Nm * Nm
option 4: a 2D numpy array, covariance matrix for the flattened measurements
Shape: sum(Nt) * sum(Nt)
:param: error_opt: CovarianceStructure
can choose from identity, variance, time_correlation, measure_correlation, time_measure_correlation. See above comments.
Returns
-------
Sigma: a 2D numpy array, covariance matrix for the flattened measurements
Shape: sum(Nt) * sum(Nt)
"""
# initialize error covariance matrix, shape N_all_t * N_all_t
Sigma = np.zeros((self.total_num_time, self.total_num_time))
# identity matrix or only have variance
if (error_option == CovarianceStructure.identity) or (
error_option == CovarianceStructure.variance
):
# if given None, it means it is an identity matrix
if not error_cov:
# create identity matrix
error_cov = [1] * self.total_num_time
# loop over diagonal elements and change
for i in range(self.total_num_time):
# Sigma has 0 in all off-diagonal elements, error_cov gives the diagonal elements
Sigma[i, i] = error_cov[i]
if self.precompute_print_level >= 2:
print("Error covariance matrix option:", error_option)
if self.precompute_print_level == 3:
print("Error matrix:", Sigma)
# different time correlation matrix for each measurement
# no covariance between measurements
elif error_option == CovarianceStructure.time_correlation:
for i in range(self.n_total_measurements):
# give the error covariance to Sigma
# each measurement has a different time-correlation structure
# that is why this is a 3D matrix
sigma_i_start = self.first_pos_flatten[i]
# loop over all timepoints for measurement i
# for each measurement, the time correlation matrix is Nt*Nt
for t1 in range(self.sens_info.Nt):
for t2 in range(self.sens_info.Nt):
# for the ith measurement, the error matrix is error_cov[i]
Sigma[sigma_i_start + t1, sigma_i_start + t2] = error_cov[i][
t1
][t2]
if self.precompute_print_level >= 2:
print("Error covariance matrix option:", error_option)
if self.precompute_print_level == 3:
print("Error matrix:", Sigma)
# covariance between measurements
# the covariances between measurements at the same timestep in a time-invariant way
elif error_option == CovarianceStructure.measure_correlation:
# loop over number of measurements
for i in range(self.sens_info.total_measure_idx):
# loop over number of measurements
for j in range(self.sens_info.total_measure_idx):
# find the covariance term
cov_ij = error_cov[i][j]
# find the starting index for each measurement (each measurement i has Nt entries)
first_i = self.first_pos_flatten[i]
# starting index for measurement j
first_j = self.first_pos_flatten[j]
# i, j may have different timesteps
# we find the corresponding index by locating the starting indices
for t in range(self.sens_info.Nt):
Sigma[t + first_i, t + first_j] = cov_ij
if self.precompute_print_level >= 2:
print("Error covariance matrix option:", error_option)
if self.precompute_print_level == 3:
print("Error matrix:", Sigma)
# the full covariance matrix is given
elif error_option == CovarianceStructure.time_measure_correlation:
Sigma = np.asarray(error_cov)
if self.precompute_print_level >= 2:
print("Error covariance matrix option:", error_option)
if self.precompute_print_level == 3:
print("Error matrix:", Sigma)
self.Sigma = Sigma
return Sigma
def _split_sigma(self, Sigma):
"""Split the error covariance matrix to be used for computation
They are split to DCM-DCM (scalar) covariance, DCM-SCM (vector) covariance, SCCM-SCM (matrix) covariance
We inverse the Sigma for the computation of FIM
Arguments
---------
:param Sigma: a 2D numpy array, covariance matrix for the flattened measurements
Shape: sum(Nt) * sum(Nt)
Returns
-------
None
"""
# Inverse of covariance matrix is used
# pinv is used to avoid ill-conditioning issues
Sigma_inv = np.linalg.pinv(Sigma)
self.Sigma_inv_matrix = Sigma_inv
# Use a dicionary to store the inverse of sigma as either scalar number, vector, or matrix
# key: a tuple (i,j), i, j are the measurement indices in jac_sens.
# value: value of the covariance of these two measurements.
self.Sigma_inv = {}
# between static and static: (Nt_i+Nt_j)*(Nt_i+Nt_j) matrix
for i in self.static_idx_dynamic_flatten: # loop over static measurement index
for (
j
) in self.static_idx_dynamic_flatten: # loop over static measurement index
# should be a (Nt_i+Nt_j)*(Nt_i+Nt_j) matrix
sig = np.zeros((self.sens_info.Nt, self.sens_info.Nt))
# row [i, i+Nt_i], column [i, i+Nt_i]
for ti in range(self.sens_info.Nt): # loop over time points
for tj in range(self.sens_info.Nt): # loop over time points
sig[ti, tj] = Sigma_inv[
self.first_pos_flatten[i] + ti, self.first_pos_flatten[j] + tj
]
self.Sigma_inv[(i, j)] = sig
# between static and dynamic: Nt*1 matrix
for i in self.static_idx_dynamic_flatten: # loop over static measurement index
for (
j
) in (
self.dynamic_idx_dynamic_flatten
): # loop over dynamic measuremente index
# should be a vector, here as a Nt*1 matrix
sig = np.zeros((self.sens_info.Nt, 1))
# row [i, i+Nt_i], col [j]
for t in range(self.sens_info.Nt): # loop over time points
# print(i,j)
# print(t, self.first_pos_flatten[i], self.dynamic_to_flatten[j])
sig[t, 0] = Sigma_inv[
self.first_pos_flatten[i] + t, self.dynamic_to_flatten[j]
]
self.Sigma_inv[(i, j)] = sig
# between static and dynamic: Nt*1 matrix
for (
i
) in self.dynamic_idx_dynamic_flatten: # loop over dynamic measurement index
for (
j
) in self.static_idx_dynamic_flatten: # loop over static measurement index
# should be a vector, here as Nt*1 matrix
sig = np.zeros((self.sens_info.Nt, 1))
# row [j, j+Nt_j], col [i]
for t in range(self.sens_info.Nt): # loop over time
sig[t, 0] = Sigma_inv[
self.first_pos_flatten[j] + t, self.dynamic_to_flatten[i]
]
self.Sigma_inv[(i, j)] = sig
# between dynamic and dynamic: a scalar number
for (
i
) in self.dynamic_idx_dynamic_flatten: # loop over dynamic measurement index
for (
j
) in (
self.dynamic_idx_dynamic_flatten
): # loop over dynamic measurement index
# should be a scalar number
self.Sigma_inv[(i, j)] = Sigma_inv[
self.dynamic_to_flatten[i], self.dynamic_to_flatten[j]
]
def assemble_unit_fims(self):
"""
compute a list of FIM.
unit FIMs include DCM-DCM FIM, DCM-SCM FIM, SCM-SCM FIM
"""
self.unit_fims = []
# loop over measurement index
for i in range(self.num_measure_dynamic_flatten):
# loop over measurement index
for j in range(self.num_measure_dynamic_flatten):
# static*static
if (
i in self.static_idx_dynamic_flatten
and j in self.static_idx_dynamic_flatten
):
# print("static * static, cov:", self.Sigma_inv[(i,j)])
unit = (
np.asarray(self.jac_dynamic_flatten[i]).T
@ self.Sigma_inv[(i, j)]
@ np.asarray(self.jac_dynamic_flatten[j])
)
# consider both i=SCM, j=DCM scenario and i=DCM, j=SCM scenario
# static*dynamic
elif (
i in self.static_idx_dynamic_flatten
and j in self.dynamic_idx_dynamic_flatten
):
# print("static*dynamic, cov:", self.Sigma_inv[(i,j)])
unit = (
np.asarray(self.jac_dynamic_flatten[i]).T
@ self.Sigma_inv[(i, j)]
@ np.asarray(self.jac_dynamic_flatten[j]).reshape(
1, self.sens_info.n_parameters
)
)
# static*dynamic
elif (
i in self.dynamic_idx_dynamic_flatten
and j in self.static_idx_dynamic_flatten
):
# print("static*dynamic, cov:", self.Sigma_inv[(i,j)])
unit = (
np.asarray(self.jac_dynamic_flatten[i])
.reshape(1, self.sens_info.n_parameters)
.T
@ self.Sigma_inv[(i, j)].T
@ np.asarray(self.jac_dynamic_flatten[j])
)
# dynamic*dynamic
else:
# print("dynamic*dynamic, cov:", self.Sigma_inv[(i,j)])
unit = (
self.Sigma_inv[(i, j)]
* np.asarray(self.jac_dynamic_flatten[i])
.reshape(1, self.sens_info.n_parameters)
.T
@ np.asarray(self.jac_dynamic_flatten[j]).reshape(
1, self.sens_info.n_parameters
)
)
# check if unitFIM is symmetric
# Note: I removed this function because unit FIM doesn't need to be symmetric
# f not np.allclose(unit, unit.T):
# if self.precompute_print_level == 3:
# print("Index ",i,j, "has not symmetric FIM:", unit)
# raise ValueError("The unit FIM is not symmetric with index:", i, j)
# store unit FIM following this order
self.unit_fims.append(unit.tolist())
if self.precompute_print_level >= 1:
print("Number of unit FIMs:", len(self.unit_fims))
def _measure_matrix(self, measurement_vector):
"""
This is a helper function, when giving a vector of solutions, it converts this vector into a 2D array
This is needed for validating the solutions after the optimization,
since we only computes the half diagonal of the measurement matrice and flatten it.
Arguments
---------
:param measurement_vector: a vector of measurement weights solution
Returns
-------
measurement_matrix: a full measurement matrix, construct the weights for covariances
"""
# check if measurement vector legal
if len(measurement_vector) != self.num_measure_dynamic_flatten:
raise ValueError(
"Measurement vector is of wrong shape, expecting length of"
+ str(self.num_measure_dynamic_flatten)
)
# initialize measurement matrix as a 2D array
measurement_matrix = np.zeros((self.num_measure_dynamic_flatten, self.num_measure_dynamic_flatten))
# loop over total measurement index
for i in range(self.num_measure_dynamic_flatten):
for j in range(self.num_measure_dynamic_flatten):
measurement_matrix[i, j] = min(
measurement_vector[i], measurement_vector[j]
)
return measurement_matrix
def _continuous_optimization(
self,
mixed_integer=False,
fixed_nlp=False,
fix=False,
upper_diagonal_only=False,
num_dynamic_t_name=None,
budget=100,
init_cov_y=None,
initial_fim=None,
dynamic_install_initial=None,
total_measure_initial=1,
static_dynamic_pair=None,
time_interval_all_dynamic=False,
total_manual_num_init=10,
cost_initial=100,
fim_diagonal_small_element=0,
print_level=0,
):
"""Continuous optimization problem formulation.
Arguments
---------
:param mixed_integer: boolean
not relaxing integer decisions
:param fixed_nlp: boolean
if True, the problem is formulated as a fixed NLP
:param fix: boolean
if solving as a square problem or with DOFs
:param upper_diagonal_only: boolean
if using upper_diagonal_only set to define decisions and FIM, or not
:param num_dynamic_t_name: list
a list of the exact time points for the dynamic-cost measurements time points
:param budget: integer
total budget
:param init_cov_y: list of lists
initialize decision variables
:param initial_fim: list of lists
initialize FIM
:param dynamic_install_initial: list
initialize if_dynamic_install
:param total_measure_initial: integer
initialize the total number of measurements chosen
:param static_dynamic_pair: list of lists
a list of the name of measurements, that are selected as either dynamic or static measurements.