-
Notifications
You must be signed in to change notification settings - Fork 0
/
modpods.py
2450 lines (2131 loc) · 139 KB
/
modpods.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
import pandas as pd
import numpy as np
import pysindy as ps
import scipy.stats as stats
from scipy import signal
import matplotlib.pyplot as plt
import control as control
import networkx as nx
import sys
import pyswmm # not a requirement for any other function
import re
# delay model builds differential equations relating the dependent variables to transformations of all the variables
# if there are no independent variables, then dependent_columns should be a list of all the columns in the dataframe
# and independent_columns should be an empty list
# by default, only the independent variables are transformed, but if transform_dependent is set to True, then the dependent variables are also transformed
# REQUIRES:
# a pandas dataframe,
# the column names of the dependent and indepdent variables,
# the number of timesteps to "wind up" the latent states,
# the initial number of transformations to use in the optimization,
# the maximum number of transformations to use in the optimization,
# the maximum number of iterations to use in the optimization
# and the order of the polynomial to use in the optimization
# bibo_stable: if true, the highest order output autocorrelation term is constrained to be negative
# RETURNS:
# models for each number of transformations from min to max
# NOTE: this code works for MIMO models, however, if output variables are dependent on each other
# poor simulation fidelity is likely due to their errors contributing to each other
# if the learned dynamics are highly accurate such that errors do not grow too large in any dependent variable, a MIMO model should work fine
# if you anticipate significant errors in the simulation of any dependent variable, you should use multiple MISO models instead
# as the model predicts derivatives, system_data must represent a *causal* system
# that is, forcing and the response to that forcing cannot occur at the same timestep
# it may be necessary for the user to shift the forcing data back to make the system causal (especially for time aggregated data like daily rainfall-runoff)
# forcing_coef_constraints is a dictionary of column name and then a 1, 0, or -1 depending on whether the coefficients of that variable should be positive, unconstrained, or negative
def delay_io_train(system_data, dependent_columns, independent_columns,
windup_timesteps=0,init_transforms=1, max_transforms=4,
max_iter=250, poly_order=3, transform_dependent=False,
verbose=False, extra_verbose=False, include_bias=False,
include_interaction=False, bibo_stable = False,
transform_only = None, forcing_coef_constraints=None,
early_stopping_threshold = 0.005):
forcing = system_data[independent_columns].copy(deep=True)
orig_forcing_columns = forcing.columns
response = system_data[dependent_columns].copy(deep=True)
results = dict() # to store the optimized models for each number of transformations
if transform_dependent:
shape_factors = pd.DataFrame(columns = system_data.columns, index = range(init_transforms, max_transforms+1))
shape_factors.iloc[0,:] = 1 # first transformation is [1,1,0] for each input
scale_factors = pd.DataFrame(columns = system_data.columns, index = range(init_transforms, max_transforms+1))
scale_factors.iloc[0,:] = 1 # first transformation is [1,1,0] for each input
loc_factors = pd.DataFrame(columns = system_data.columns, index = range(init_transforms, max_transforms+1))
loc_factors.iloc[0,:] = 0 # first transformation is [1,1,0] for each input
elif transform_only is not None: # the user provided a list of columns to transform
shape_factors = pd.DataFrame(columns = transform_only, index = range(init_transforms, max_transforms+1))
shape_factors.iloc[0,:] = 1 # first transformation is [1,1,0] for each input
scale_factors = pd.DataFrame(columns = transform_only, index = range(init_transforms, max_transforms+1))
scale_factors.iloc[0,:] = 1 # first transformation is [1,1,0] for each input
loc_factors = pd.DataFrame(columns = transform_only, index = range(init_transforms, max_transforms+1))
loc_factors.iloc[0,:] = 0 # first transformation is [1,1,0] for each input
else:
# the transformation factors should be pandas dataframes where the index is which transformation it is and the columns are the variables
shape_factors = pd.DataFrame(columns = forcing.columns, index = range(init_transforms, max_transforms+1))
shape_factors.iloc[0,:] = 1 # first transformation is [1,1,0] for each input
scale_factors = pd.DataFrame(columns = forcing.columns, index = range(init_transforms, max_transforms+1))
scale_factors.iloc[0,:] = 1 # first transformation is [1,1,0] for each input
loc_factors = pd.DataFrame(columns = forcing.columns, index = range(init_transforms, max_transforms+1))
loc_factors.iloc[0,:] = 0 # first transformation is [1,1,0] for each input
#print(shape_factors)
#print(scale_factors)
#print(loc_factors)
# first transformation is [1,1,0] for each input
'''
shape_factors = np.ones(shape=(forcing.shape[1] , init_transforms) )
scale_factors = np.ones(shape=(forcing.shape[1] , init_transforms) )
loc_factors = np.zeros(shape=(forcing.shape[1] , init_transforms) )
'''
#speeds = list([500,200,50,10, 5,2, 1.1, 1.05,1.01])
speeds = list([100,50,20,10,5,2,1.1,1.05,1.01]) # I don't have a great idea of what good values for these are yet
if transform_dependent: # just trying something
improvement_threshold = 1.001 # when improvements are tiny, tighten up the jumps
else:
improvement_threshold = 1.0
for num_transforms in range(init_transforms,max_transforms + 1):
print("num_transforms")
print(num_transforms)
speed_idx = 0
speed = speeds[speed_idx]
if (not num_transforms == init_transforms): # if we're not starting right now
# start dull
shape_factors.iloc[num_transforms-1,:] = 10*(num_transforms-1) # start with a broad peak centered at ten timesteps
scale_factors.iloc[num_transforms-1,:] = 1
loc_factors.iloc[num_transforms-1,:] = 0
if verbose:
print("starting factors for additional transformation\nshape\nscale\nlocation")
print(shape_factors)
print(scale_factors)
print(loc_factors)
prev_model = SINDY_delays_MI(shape_factors, scale_factors, loc_factors, system_data.index,
forcing, response,extra_verbose, poly_order , include_bias,
include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
print("\nInitial model:\n")
try:
print(prev_model['model'].print(precision=5))
print("R^2")
print(prev_model['error_metrics']['r2'])
except Exception as e: # and print the exception:
print(e)
pass
print("shape factors")
print(shape_factors)
print("scale factors")
print(scale_factors)
print("location factors")
print(loc_factors)
print("\n")
if not verbose:
print("training ", end='')
#no_improvement_last_time = False
for iterations in range(0,max_iter ):
if not verbose and iterations % 5 == 0:
print(str(iterations)+".", end='')
if transform_dependent:
tuning_input = system_data.columns[(iterations // num_transforms) % len(system_data.columns)] # row = iter // width % height]
elif transform_only is not None:
tuning_input = transform_only[(iterations // num_transforms) % len(transform_only)]
else:
tuning_input = orig_forcing_columns[(iterations // num_transforms) % len(orig_forcing_columns)] # row = iter // width % height
tuning_line = iterations % num_transforms + 1 # col = % width (plus one because there's no zeroth transformation)
if verbose:
print(str("tuning input: {i} | tuning transformation: {l:g}".format(i=tuning_input,l=tuning_line)))
sooner_locs = loc_factors.copy(deep=True)
#sooner_locs[tuning_input][tuning_line] = float(loc_factors[tuning_input][tuning_line] - speed/10 )
sooner_locs.loc[tuning_line,tuning_input] = float(loc_factors.loc[tuning_line,tuning_input] - speed/10)
if ( sooner_locs[tuning_input][tuning_line] < 0):
sooner = {'error_metrics':{'r2':-1}}
else:
sooner = SINDY_delays_MI(shape_factors ,scale_factors ,sooner_locs,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
later_locs = loc_factors.copy(deep=True)
#later_locs[tuning_input][tuning_line] = float ( loc_factors[tuning_input][tuning_line] + 1.01*speed/10 )
later_locs.loc[tuning_line,tuning_input] = float(loc_factors.loc[tuning_line,tuning_input] + 1.01*speed/10)
later = SINDY_delays_MI(shape_factors , scale_factors,later_locs,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
shape_up = shape_factors.copy(deep=True)
#shape_up[tuning_input][tuning_line] = float ( shape_factors[tuning_input][tuning_line]*speed*1.01 )
shape_up.loc[tuning_line,tuning_input] = float(shape_factors.loc[tuning_line,tuning_input]*speed*1.01)
shape_upped = SINDY_delays_MI(shape_up , scale_factors, loc_factors,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
shape_down = shape_factors.copy(deep=True)
#shape_down[tuning_input][tuning_line] = float ( shape_factors[tuning_input][tuning_line]/speed )
shape_down.loc[tuning_line,tuning_input] = float(shape_factors.loc[tuning_line,tuning_input]/speed)
if (shape_down[tuning_input][tuning_line] < 1):
shape_downed = {'error_metrics':{'r2':-1}} # return a score of negative one as this is illegal
else:
shape_downed = SINDY_delays_MI(shape_down , scale_factors, loc_factors,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
scale_up = scale_factors.copy(deep=True)
#scale_up[tuning_input][tuning_line] = float( scale_factors[tuning_input][tuning_line]*speed*1.01 )
scale_up.loc[tuning_line,tuning_input] = float(scale_factors.loc[tuning_line,tuning_input]*speed*1.01)
scaled_up = SINDY_delays_MI(shape_factors , scale_up, loc_factors,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
scale_down = scale_factors.copy(deep=True)
#scale_down[tuning_input][tuning_line] = float ( scale_factors[tuning_input][tuning_line]/speed )
scale_down.loc[tuning_line,tuning_input] = float(scale_factors.loc[tuning_line,tuning_input]/speed)
scaled_down = SINDY_delays_MI(shape_factors , scale_down, loc_factors,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
# rounder
rounder_shape = shape_factors.copy(deep=True)
#rounder_shape[tuning_input][tuning_line] = shape_factors[tuning_input][tuning_line]*(speed*1.01)
rounder_shape.loc[tuning_line,tuning_input] = shape_factors.loc[tuning_line,tuning_input]*(speed*1.01)
rounder_scale = scale_factors.copy(deep=True)
#rounder_scale[tuning_input][tuning_line] = scale_factors[tuning_input][tuning_line]/(speed*1.01)
rounder_scale.loc[tuning_line,tuning_input] = scale_factors.loc[tuning_line,tuning_input]/(speed*1.01)
rounder = SINDY_delays_MI(rounder_shape , rounder_scale, loc_factors,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
# sharper
sharper_shape = shape_factors.copy(deep=True)
#sharper_shape[tuning_input][tuning_line] = shape_factors[tuning_input][tuning_line]/speed
sharper_shape.loc[tuning_line,tuning_input] = shape_factors.loc[tuning_line,tuning_input]/speed
if (sharper_shape[tuning_input][tuning_line] < 1):
sharper = {'error_metrics':{'r2':-1}} # lower bound on shape to avoid inf
else:
sharper_scale = scale_factors.copy(deep=True)
#sharper_scale[tuning_input][tuning_line] = scale_factors[tuning_input][tuning_line]*speed
sharper_scale.loc[tuning_line,tuning_input] = scale_factors.loc[tuning_line,tuning_input]*speed
sharper = SINDY_delays_MI(sharper_shape ,sharper_scale,loc_factors,
system_data.index, forcing, response, extra_verbose, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
scores = [prev_model['error_metrics']['r2'], shape_upped['error_metrics']['r2'], shape_downed['error_metrics']['r2'],
scaled_up['error_metrics']['r2'], scaled_down['error_metrics']['r2'], sooner['error_metrics']['r2'],
later['error_metrics']['r2'], rounder['error_metrics']['r2'], sharper['error_metrics']['r2'] ]
#print(scores)
if (sooner['error_metrics']['r2'] >= max(scores) and sooner['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = sooner.copy()
loc_factors = sooner_locs.copy(deep=True)
elif (later['error_metrics']['r2'] >= max(scores) and later['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = later.copy()
loc_factors = later_locs.copy(deep=True)
elif(shape_upped['error_metrics']['r2'] >= max(scores) and shape_upped['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = shape_upped.copy()
shape_factors = shape_up.copy(deep=True)
elif(shape_downed['error_metrics']['r2'] >=max(scores) and shape_downed['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = shape_downed.copy()
shape_factors = shape_down.copy(deep=True)
elif(scaled_up['error_metrics']['r2'] >= max(scores) and scaled_up['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = scaled_up.copy()
scale_factors = scale_up.copy(deep=True)
elif(scaled_down['error_metrics']['r2'] >= max(scores) and scaled_down['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = scaled_down.copy()
scale_factors = scale_down.copy(deep=True)
elif (rounder['error_metrics']['r2'] >= max(scores) and rounder['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = rounder.copy()
shape_factors = rounder_shape.copy(deep=True)
scale_factors = rounder_scale.copy(deep=True)
elif (sharper['error_metrics']['r2'] >= max(scores) and sharper['error_metrics']['r2'] > improvement_threshold*prev_model['error_metrics']['r2']):
prev_model = sharper.copy()
shape_factors = sharper_shape.copy(deep=True)
scale_factors = sharper_scale.copy(deep=True)
# the middle was best, but it's bad, tighten up the bounds (if we're at the last tuning line of the last input)
elif( num_transforms == tuning_line and tuning_input == shape_factors.columns[-1]): # no improvement transforming last column
#no_improvement_last_time=True
speed_idx = speed_idx + 1
if verbose:
print("\n\ntightening bounds\n\n")
'''
elif (num_transforms == tuning_line and tuning_input == orig_forcing_columns[0] and no_improvement_last_time): # no improvement next iteration (first column)
speed_idx = speed_idx + 1
no_improvement_last_time=False
if verbose:
print("\n\ntightening bounds\n\n")
'''
if (speed_idx >= len(speeds)):
print("\n\noptimization complete\n\n")
break
speed = speeds[speed_idx]
if (verbose):
print("\nprevious, shape up, shape down, scale up, scale down, sooner, later, rounder, sharper")
print(scores)
print("speed")
print(speed)
print("shape factors")
print(shape_factors)
print("scale factors")
print(scale_factors)
print("location factors")
print(loc_factors)
print("iteration no:")
print(iterations)
print("model")
try:
prev_model['model'].print(precision=5)
except Exception as e:
print(e)
print("\n")
final_model = SINDY_delays_MI(shape_factors, scale_factors ,loc_factors,system_data.index, forcing, response, True, poly_order ,
include_bias, include_interaction,windup_timesteps,bibo_stable,transform_dependent=transform_dependent,
transform_only=transform_only,forcing_coef_constraints=forcing_coef_constraints)
print("\nFinal model:\n")
try:
print(final_model['model'].print(precision=5))
except Exception as e:
print(e)
print("R^2")
print(prev_model['error_metrics']['r2'])
print("shape factors")
print(shape_factors)
print("scale factors")
print(scale_factors)
print("location factors")
print(loc_factors)
print("\n")
results[num_transforms] = {'final_model':final_model.copy(),
'shape_factors':shape_factors.copy(deep=True),
'scale_factors':scale_factors.copy(deep=True),
'loc_factors':loc_factors.copy(deep=True),
'windup_timesteps':windup_timesteps,
'dependent_columns':dependent_columns,
'independent_columns':independent_columns}
# check if the benefit from adding the last transformation is less than the early stopping threshold
if num_transforms > init_transforms and results[num_transforms]['final_model']['error_metrics']['r2'] - results[num_transforms-1]['final_model']['error_metrics']['r2'] < early_stopping_threshold:
print("Last transformation added less than ", early_stopping_threshold*100," % to R2 score. Terminating early.")
break
return results
def SINDY_delays_MI(shape_factors, scale_factors, loc_factors, index, forcing, response, final_run,
poly_degree, include_bias, include_interaction,windup_timesteps,bibo_stable=False,
transform_dependent=False,transform_only=None, forcing_coef_constraints=None):
if transform_only is not None:
transformed_forcing = transform_inputs(shape_factors, scale_factors,loc_factors, index, forcing.loc[:,transform_only])
untransformed_forcing = forcing.drop(columns=transform_only)
# combine forcing and transformed forcing column-wise
forcing = pd.concat((untransformed_forcing,transformed_forcing),axis='columns')
else:
forcing = transform_inputs(shape_factors, scale_factors,loc_factors, index, forcing)
feature_names = response.columns.tolist() + forcing.columns.tolist()
# SINDy
if (not bibo_stable and forcing_coef_constraints is None): # no constraints, normal mode
model = ps.SINDy(
differentiation_method= ps.FiniteDifference(),
feature_library=ps.PolynomialLibrary(degree=poly_degree,include_bias = include_bias, include_interaction=include_interaction),
optimizer = ps.STLSQ(threshold=0),
feature_names = feature_names
)
elif (forcing_coef_constraints is not None and not bibo_stable):
library = ps.PolynomialLibrary(degree=poly_degree,include_bias = include_bias, include_interaction=include_interaction)
total_train = pd.concat((response,forcing), axis='columns')
library.fit([ps.AxesArray(total_train,{"ax_sample":0,"ax_coord":1})])
n_features = library.n_output_features_
n_targets = len(response.columns)
constraint_rhs = np.zeros((n_features,)) # every feature is constrained
# one row per constraint, one column per coefficient
constraint_lhs = np.zeros((n_features , n_targets*n_features ) )
# now implement the forcing coefficient constraints
for i, col in enumerate(feature_names):
for key in forcing_coef_constraints.keys():
if key in col:
constraint_lhs[i, i] = -forcing_coef_constraints[key]
# invert the sign because the eqn is written as "leq 0"
model = ps.SINDy(
differentiation_method= ps.FiniteDifference(),
feature_library=ps.PolynomialLibrary(degree=poly_degree,include_bias = include_bias, include_interaction=include_interaction),
optimizer = ps.ConstrainedSR3(threshold=0, thresholder = "l2",constraint_lhs=constraint_lhs, constraint_rhs = constraint_rhs, inequality_constraints=True),
feature_names = feature_names
)
elif (bibo_stable): # highest order output autocorrelation is constrained to be negative
#import cvxpy
#run_cvxpy= True
# Figure out how many library features there will be
library = ps.PolynomialLibrary(degree=poly_degree,include_bias = include_bias, include_interaction=include_interaction)
total_train = pd.concat((response,forcing), axis='columns')
library.fit([ps.AxesArray(total_train,{"ax_sample":0,"ax_coord":1})])
n_features = library.n_output_features_
#print(f"Features ({n_features}):", library.get_feature_names(input_features=total_train.columns))
feature_names = library.get_feature_names(input_features=total_train.columns)
# Set constraints
n_targets = total_train.shape[1] # not sure what targets means after reading through the pysindy docs
#print("n_targets")
#print(n_targets)
constraint_rhs = np.zeros((len(response.columns),1))
# one row per constraint, one column per coefficient
constraint_lhs = np.zeros((len(response.columns) , n_features ))
#print(constraint_rhs)
#print(constraint_lhs)
# constrain the highest order output autocorrelation to be negative
# this indexing is only right for include_interaction=False, include_bias=False, and pure polynomial library
# for more complex libraries, some conditional logic will be needed to grab the right column
constraint_lhs[:,-len(forcing.columns)-len(response.columns):-len(forcing.columns)] = 1
# leq 0
#print("constraint lhs")
#print(constraint_lhs)
# forcing_coef_constraints only implemented for bibo stable MISO models right now
if forcing_coef_constraints is not None:
n_targets = len(response.columns)
constraint_rhs = np.zeros((n_features,)) # every feature is constrained
# one row per constraint, one column per coefficient
constraint_lhs = np.zeros((n_features , n_targets*n_features ) )
# bibo stability, set the highest order output autocorrelation to be negative for each response variable
# the index corresponds to the last entry in "feature_names" which includes the name of the response column
highest_power_col_idx = 0
for i, col in enumerate(feature_names):
if response.columns[0] in col:
highest_power_col_idx = i
constraint_lhs[0, highest_power_col_idx] = 1 # first row, highest power of the response variable
# now implement the forcing coefficient constraints
for i, col in enumerate(feature_names):
for key in forcing_coef_constraints.keys():
if key in col:
constraint_lhs[i, i] = -forcing_coef_constraints[key]
# invert the sign because the eqn is written as "leq 0"
''''
print(forcing.columns)
forcing_constraints_array = np.ndarray(shape=(1,len(forcing.columns)))
for i, col in enumerate(forcing.columns):
if col in forcing_coef_constraints.keys(): # invert the sign because the eqn is written as "leq 0"
forcing_constraints_array[0,i] = -forcing_coef_constraints[col]
elif str(col).replace('_tr_1','') in forcing_coef_constraints.keys():
forcing_constraints_array[0,i] = -forcing_coef_constraints[str(col).replace('_tr_1','')]
elif str(col).replace('_tr_2','') in forcing_coef_constraints.keys():
forcing_constraints_array[0,i] = -forcing_coef_constraints[str(col).replace('_tr_2','')]
elif str(col).replace('_tr_3','') in forcing_coef_constraints.keys():
forcing_constraints_array[0,i] = -forcing_coef_constraints[str(col).replace('_tr_3','')]
else:
forcing_constraints_array[0,i] = 0
for row in range(n_targets, n_features):
constraint_lhs[row, row] = forcing_constraints_array[0,row - n_targets]
'''
# constrain the highest order output autocorrelation to be negative
# this indexing is only right for include_interaction=False, include_bias=False, and pure polynomial library
# for more complex libraries, some conditional logic will be needed to grab the right column
#constraint_lhs[:n_targets,-len(forcing.columns)-len(response.columns):-len(forcing.columns)] = 1
#print(forcing_constraints_array)
#print('constraint lhs')
#print(constraint_lhs)
#print('constraint rhs')
#print(constraint_rhs)
model = ps.SINDy(
differentiation_method= ps.FiniteDifference(),
feature_library=ps.PolynomialLibrary(degree=poly_degree,include_bias = include_bias, include_interaction=include_interaction),
optimizer = ps.ConstrainedSR3(threshold=0, thresholder = "l2",constraint_lhs=constraint_lhs, constraint_rhs = constraint_rhs, inequality_constraints=True),
feature_names = feature_names
)
if transform_dependent:
# combine response and forcing into one dataframe
total_train = pd.concat((response,forcing), axis='columns')
total_train = transform_inputs(shape_factors, scale_factors,loc_factors, index, total_train)
# remove the columns in total_train that are already in response (just want to keep the transformed forcing)
total_train = total_train.drop(columns = response.columns)
feature_names = response.columns.tolist() + total_train.columns.tolist()
# need to add constraints such that variables don't depend on their own past values (but they can have autocorrelations)
library = ps.PolynomialLibrary(degree=poly_degree,include_bias = include_bias, include_interaction=include_interaction)
library_terms = pd.concat((total_train,response), axis='columns')
library.fit([ps.AxesArray(library_terms,{"ax_sample":0,"ax_coord":1})])
n_features = library.n_output_features_
#print(f"Features ({n_features}):", library.get_feature_names())
# Set constraints
n_targets = response.shape[1] # not sure what targets means after reading through the pysindy docs
constraint_rhs = np.zeros((n_targets,))
# one row per constraint, one column per coefficient
constraint_lhs = np.zeros((n_targets , n_features*n_targets))
# for bibo stability, starting guess is that each dependent variable is negatively autocorrelated and depends on no other variable
if bibo_stable:
initial_guess = np.zeros((n_targets,n_features))
for idx in range(0,n_targets):
initial_guess[idx,idx] = -1
else:
initial_guess = None
#print(constraint_rhs)
#print(constraint_lhs)
# set the coefficient on a variable's own transformed value to 0
for idx in range(0,n_targets):
constraint_lhs[idx,(idx+1)*n_features - n_targets + idx] = 1
#print("constraint lhs")
#print(constraint_lhs)
model = ps.SINDy(
differentiation_method= ps.FiniteDifference(),
feature_library=library,
optimizer = ps.ConstrainedSR3(threshold=0, thresholder = "l0",
nu = 10e9, initial_guess = initial_guess,
constraint_lhs=constraint_lhs,
constraint_rhs = constraint_rhs,
inequality_constraints=False,
max_iter=10000),
feature_names = feature_names
)
try:
# windup latent states (if your windup is too long, this will error)
model.fit(response.values[windup_timesteps:,:], t = np.arange(0,len(index),1)[windup_timesteps:], u = total_train.values[windup_timesteps:,:])
r2 = model.score(response.values[windup_timesteps:,:],t=np.arange(0,len(index),1)[windup_timesteps:],u=total_train.values[windup_timesteps:,:]) # training data score
except Exception as e: # and print the exception
print("Exception in model fitting, returning r2=-1\n")
print(e)
error_metrics = {"MAE":[False],"RMSE":[False],"NSE":[False],"alpha":[False],"beta":[False],"HFV":[False],"HFV10":[False],"LFV":[False],"FDC":[False],"r2":-1}
return {"error_metrics": error_metrics, "model": None, "simulated": False, "response": response, "forcing": forcing, "index": index,"diverged":False}
else:
try:
# windup latent states (if your windup is too long, this will error)
model.fit(response.values[windup_timesteps:,:], t = np.arange(0,len(index),1)[windup_timesteps:], u = forcing.values[windup_timesteps:,:])
r2 = model.score(response.values[windup_timesteps:,:],t=np.arange(0,len(index),1)[windup_timesteps:],u=forcing.values[windup_timesteps:,:]) # training data score
except Exception as e: # and print the exception
print("Exception in model fitting, returning r2=-1\n")
print(e)
error_metrics = {"MAE":[False],"RMSE":[False],"NSE":[False],"alpha":[False],"beta":[False],"HFV":[False],"HFV10":[False],"LFV":[False],"FDC":[False],"r2":-1}
return {"error_metrics": error_metrics, "model": None, "simulated": False, "response": response, "forcing": forcing, "index": index,"diverged":False}
# r2 is how well we're doing across all the outputs. that's actually good to keep model accuracy lumped because that's what makes most sense to drive the optimization
# even though the metrics we'll want to evaluate models on are individual output accuracy
#print("training R^2", r2)
#model.print(precision=5)
# return false for things not evaluated / don't exist
error_metrics = {"MAE":[False],"RMSE":[False],"NSE":[False],"alpha":[False],"beta":[False],"HFV":[False],"HFV10":[False],"LFV":[False],"FDC":[False],"r2":r2}
simulated = False
if (final_run): # only simulate final runs because it's slow
try: #once in high volume training put this back in, but want to see the errors during development
if transform_dependent:
simulated = model.simulate(response.values[windup_timesteps,:],t=np.arange(0,len(index),1)[windup_timesteps:],u=total_train.values[windup_timesteps:,:])
else:
simulated = model.simulate(response.values[windup_timesteps,:],t=np.arange(0,len(index),1)[windup_timesteps:],u=forcing.values[windup_timesteps:,:])
mae = list()
rmse = list()
nse = list()
alpha = list()
beta = list()
hfv = list()
hfv10 = list()
lfv = list()
fdc = list()
for col_idx in range(0,len(response.columns)): # univariate performance metrics
error = response.values[windup_timesteps+1:,col_idx]-simulated[:,col_idx]
#print("error")
#print(error)
# nash sutcliffe efficiency between response and simulated
mae.append(np.mean(np.abs(error)))
rmse.append(np.sqrt(np.mean(error**2 ) ))
#print("mean measured = ", np.mean(response.values[windup_timesteps+1:,col_idx] ))
#print("sum of squared error between measured and model = ", np.sum((error)**2 ))
#print("sum of squared error between measured and mean of measured = ", np.sum((response.values[windup_timesteps+1:,col_idx]-np.mean(response.values[windup_timesteps+1:,col_idx] ) )**2 ))
nse.append(1 - np.sum((error)**2 ) / np.sum((response.values[windup_timesteps+1:,col_idx]-np.mean(response.values[windup_timesteps+1:,col_idx] ) )**2 ) )
alpha.append(np.std(simulated[:,col_idx])/np.std(response.values[windup_timesteps+1:,col_idx]))
beta.append(np.mean(simulated[:,col_idx])/np.mean(response.values[windup_timesteps+1:,col_idx]))
hfv.append(100*np.sum(np.sort(simulated[:,col_idx])[-int(0.02*len(index)):]-np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.02*len(index)):])/np.sum(np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.02*len(index)):]))
hfv10.append(100*np.sum(np.sort(simulated[:,col_idx])[-int(0.1*len(index)):]-np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.1*len(index)):])/np.sum(np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.1*len(index)):]))
lfv.append(100*np.sum(np.sort(simulated[:,col_idx])[-int(0.3*len(index)):]-np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.3*len(index)):])/np.sum(np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.3*len(index)):]))
fdc.append(100*(np.log10(np.sort(simulated[:,col_idx])[int(0.2*len(index))])
- np.log10(np.sort(simulated[:,col_idx])[int(0.7*len(index))])
- np.log10(np.sort(response.values[windup_timesteps+1:,col_idx])[int(0.2*len(index))])
+ np.log10(np.sort(response.values[windup_timesteps+1:,col_idx])[int(0.7*len(index))]) )
/ np.log10(np.sort(response.values[windup_timesteps+1:,col_idx])[int(0.2*len(index))])
- np.log10(np.sort(response.values[windup_timesteps+1:,col_idx])[int(0.7*len(index))]))
print("MAE = ", mae)
print("RMSE = ", rmse)
print("NSE = ", nse)
# alpha nse decomposition due to gupta et al 2009
print("alpha = ", alpha)
print("beta = ", beta)
# top 2% peak flow bias (HFV) due to yilmaz et al 2008
print("HFV = ", hfv)
# top 10% peak flow bias (HFV) due to yilmaz et al 2008
print("HFV10 = ", hfv10)
# 30% low flow bias (LFV) due to yilmaz et al 2008
print("LFV = ", lfv)
# bias of FDC midsegment slope due to yilmaz et al 2008
print("FDC = ", fdc)
# compile all the error metrics into a dictionary
error_metrics = {"MAE":mae,"RMSE":rmse,"NSE":nse,"alpha":alpha,"beta":beta,"HFV":hfv,"HFV10":hfv10,"LFV":lfv,"FDC":fdc,"r2":r2}
except Exception as e: # and print the exception:
print("Exception in simulation\n")
print(e)
error_metrics = {"MAE":[np.NAN],"RMSE":[np.NAN],"NSE":[np.NAN],"alpha":[np.NAN],"beta":[np.NAN],"HFV":[np.NAN],"HFV10":[np.NAN],"LFV":[np.NAN],"FDC":[np.NAN],"r2":r2}
return {"error_metrics": error_metrics, "model": model, "simulated": response[1:], "response": response, "forcing": forcing, "index": index,"diverged":True}
return {"error_metrics": error_metrics, "model": model, "simulated": simulated, "response": response, "forcing": forcing, "index": index,"diverged":False}
#return [r2, model, mae, rmse, index, simulated , response , forcing]
def transform_inputs(shape_factors, scale_factors, loc_factors,index, forcing):
# original forcing columns -> columns of forcing that don't have _tr_ in their name
orig_forcing_columns = [col for col in forcing.columns if "_tr_" not in col]
#print("original forcing columns = ", orig_forcing_columns)
# how many rows of shape_factors do not contain NaNs?
num_transforms = shape_factors.count().iloc[0]
#print("num_transforms = ", num_transforms)
#print("forcing at beginning of transform inputs")
#print(forcing)
shape_time = np.arange(0,len(index),1)
for input in orig_forcing_columns: # which input are we talking about?
for transform_idx in range(1,num_transforms + 1): # which transformation of that input are we talking about?
# if the column doesn't exist, create it
if (str(str(input) + "_tr_" + str(transform_idx)) not in forcing.columns):
forcing.loc[:,str(str(input) + "_tr_" + str(transform_idx))] = 0.0
# now, fill it with zeros (need to reset between different transformation shape factors)
forcing[str(str(input) + "_tr_" + str(transform_idx))].values[:] = float(0.0)
#print(forcing)
for idx in range(0,len(index)): # timestep
if (abs(forcing[input].iloc[idx]) > 10**-6): # when nonzero forcing occurs
if (idx == int(0)):
forcing[str(str(input) + "_tr_" + str(transform_idx))].values[idx:] += forcing[input].values[idx]*stats.gamma.pdf(shape_time, shape_factors[input][transform_idx], scale=scale_factors[input][transform_idx], loc = loc_factors[input][transform_idx])
else:
forcing[str(str(input) + "_tr_" + str(transform_idx))].values[idx:] += forcing[input].values[idx]*stats.gamma.pdf(shape_time[:-idx], shape_factors[input][transform_idx], scale=scale_factors[input][transform_idx], loc = loc_factors[input][transform_idx])
#print("forcing at end of transform inputs")
#print(forcing)
# assert there are no NaNs in the forcing
assert(forcing.isnull().values.any() == False)
return forcing
# REQUIRES: the output of delay_io_train, starting value of otuput, forcing timeseries
# EFFECTS: returns a simulated response given forcing and a model
# REQUIRED EDITS: not written to accomodate transform_dependent yet
def delay_io_predict(delay_io_model, system_data, num_transforms=1,evaluation=False , windup_timesteps=None):
if windup_timesteps is None: # user didn't specify windup timesteps, use what the model trained with.
windup_timesteps = delay_io_model[num_transforms]['windup_timesteps']
forcing = system_data[delay_io_model[num_transforms]['independent_columns']].copy(deep=True)
response = system_data[delay_io_model[num_transforms]['dependent_columns']].copy(deep=True)
transformed_forcing = transform_inputs(shape_factors=delay_io_model[num_transforms]['shape_factors'],
scale_factors=delay_io_model[num_transforms]['scale_factors'],
loc_factors=delay_io_model[num_transforms]['loc_factors'],
index=system_data.index,forcing=forcing)
try:
prediction = delay_io_model[num_transforms]['final_model']['model'].simulate(system_data[delay_io_model[num_transforms]['dependent_columns']].iloc[windup_timesteps,:],
t=np.arange(0,len(system_data.index),1)[windup_timesteps:],
u=transformed_forcing[windup_timesteps:])
except Exception as e: # and print the exception:
print("Exception in simulation\n")
print(e)
print("diverged.")
error_metrics = {"MAE":[np.NAN],"RMSE":[np.NAN],"NSE":[np.NAN],"alpha":[np.NAN],"beta":[np.NAN],"HFV":[np.NAN],"HFV10":[np.NAN],"LFV":[np.NAN],"FDC":[np.NAN]}
return {'prediction':np.NAN*np.ones(shape=response[windup_timesteps+1:].shape), 'error_metrics':error_metrics,"diverged":True}
# return all the error metrics if the prediction is being evaluated against known measurements
if (evaluation):
try:
mae = list()
rmse = list()
nse = list()
alpha = list()
beta = list()
hfv = list()
hfv10 = list()
lfv = list()
fdc = list()
for col_idx in range(0,len(response.columns)): # univariate performance metrics
error = response.values[windup_timesteps+1:,col_idx]-prediction[:,col_idx]
initial_error_length = len(error)
error = error[~np.isnan(error)]
if (len(error) < 0.75*initial_error_length):
print("WARNING: More than 25% of the entries in error were NaN")
#print("error")
#print(error)
# nash sutcliffe efficiency between response and prediction
mae.append(np.mean(np.abs(error)))
rmse.append(np.sqrt(np.mean(error**2 ) ))
#print("mean measured = ", np.mean(response.values[windup_timesteps+1:,col_idx] ))
#print("sum of squared error between measured and model = ", np.sum((error)**2 ))
#print("sum of squared error between measured and mean of measured = ", np.sum((response.values[windup_timesteps+1:,col_idx]-np.mean(response.values[windup_timesteps+1:,col_idx] ) )**2 ))
nse.append(1 - np.sum((error)**2 ) / np.sum((response.values[windup_timesteps+1:,col_idx]-np.mean(response.values[windup_timesteps+1:,col_idx] ) )**2 ) )
alpha.append(np.std(prediction[:,col_idx])/np.std(response.values[windup_timesteps+1:,col_idx]))
beta.append(np.mean(prediction[:,col_idx])/np.mean(response.values[windup_timesteps+1:,col_idx]))
hfv.append(np.sum(np.sort(prediction[:,col_idx])[-int(0.02*len(system_data.index)):])/np.sum(np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.02*len(system_data.index)):]))
hfv10.append(np.sum(np.sort(prediction[:,col_idx])[-int(0.1*len(system_data.index)):])/np.sum(np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.1*len(system_data.index)):]))
lfv.append(np.sum(np.sort(prediction[:,col_idx])[:int(0.3*len(system_data.index))])/np.sum(np.sort(response.values[windup_timesteps+1:,col_idx])[:int(0.3*len(system_data.index))]))
fdc.append(np.mean(np.sort(prediction[:,col_idx])[-int(0.6*len(system_data.index)):-int(0.4*len(system_data.index))])/np.mean(np.sort(response.values[windup_timesteps+1:,col_idx])[-int(0.6*len(system_data.index)):-int(0.4*len(system_data.index))]))
print("MAE = ", mae)
print("RMSE = ", rmse)
print("NSE = ", nse)
# alpha nse decomposition due to gupta et al 2009
print("alpha = ", alpha)
print("beta = ", beta)
# top 2% peak flow bias (HFV) due to yilmaz et al 2008
print("HFV = ", hfv)
# top 10% peak flow bias (HFV) due to yilmaz et al 2008
print("HFV10 = ", hfv10)
# 30% low flow bias (LFV) due to yilmaz et al 2008
print("LFV = ", lfv)
# bias of FDC midsegment slope due to yilmaz et al 2008
print("FDC = ", fdc)
# compile all the error metrics into a dictionary
error_metrics = {"MAE":mae,"RMSE":rmse,"NSE":nse,"alpha":alpha,"beta":beta,"HFV":hfv,"HFV10":hfv10,"LFV":lfv,"FDC":fdc}
# omit r2 here because it doesn't mean the same thing as it does for training, would be misleading.
# r2 in training expresses how much of the derivative is predicted by the model, whereas in evaluation it expresses how much of the response is predicted by the model
return {'prediction':prediction, 'error_metrics':error_metrics,"diverged":False}
except Exception as e: # and print the exception:
print(e)
print("Simulation diverged.")
error_metrics = {"MAE":[np.NAN],"RMSE":[np.NAN],"NSE":[np.NAN],"alpha":[np.NAN],"beta":[np.NAN],"HFV":[np.NAN],"HFV10":[np.NAN],"LFV":[np.NAN],"FDC":[np.NAN],"diverged":True}
return {'prediction':prediction, 'error_metrics':error_metrics}
else:
error_metrics = {"MAE":[np.NAN],"RMSE":[np.NAN],"NSE":[np.NAN],"alpha":[np.NAN],"beta":[np.NAN],"HFV":[np.NAN],"HFV10":[np.NAN],"LFV":[np.NAN],"FDC":[np.NAN]}
return {'prediction':prediction, 'error_metrics':error_metrics,"diverged":False}
### the functions below are for generating LTI systems directly from data (aka system identification)
# the function below returns an LTI system (in the matrices A, B, and C) that mimic the shape of a given gamma distribution
# scaling should be correct, but need to verify that
# max state dim, resolution, and max iterations could be icnrased to improve accuracy
def lti_from_gamma(shape, scale, location,dt=0,desired_NSE = 0.999,verbose=False,
max_state_dim=50,max_iterations=200, max_pole_speed = 5, min_pole_speed = 0.01):
# a pole of speed -5 decays to less than 1% of it's value after one timestep
# a pole of speed -0.01 decays to more than 99% of it's value after one timestep
# i've assumed here that gamma pdf is defined the same as in matlab
# if that's not true testing will show it soon enough
t50 = shape*scale + location # center of mass
skewness = 2 / np.sqrt(shape)
total_time_base = 2*t50 # not that this contains the full shape, but if we fit this much of the curve perfectly we'll be close enough
#resolution = (t50)/((skewness + location)) # make this coarser for faster debugging
resolution = (t50)/(10*(skewness + location)) # production version
#resolution = 1/ skewness
decay_rate = 1 / resolution
decay_rate = np.clip(decay_rate ,min_pole_speed, max_pole_speed)
state_dim = int(np.floor(total_time_base*decay_rate)) # this keeps the time base fixed for a given decay rate
if state_dim > max_state_dim:
state_dim = max_state_dim
decay_rate = state_dim / total_time_base
resolution = 1 / decay_rate
if state_dim < 1:
state_dim = 1
decay_rate = state_dim / total_time_base
resolution = 1 / decay_rate
decay_rate = np.clip(decay_rate ,min_pole_speed, max_pole_speed)
if verbose:
print("state dimension is ",state_dim)
print("decay rate is ",decay_rate)
print("total time base is ",total_time_base)
print("resolution is", resolution)
# make the timestep one so that the relative error is correct (dt too small makes error bigger than written)
#t = np.linspace(0,3*total_time_base,1000)
#desired_error = desired_error / dt
'''
if dt > 0: # true if numeric
t = np.arange(0,2*total_time_base,dt)
else:
t= np.linspace(0,2*total_time_base,num=200)
'''
t = np.linspace(0,2*total_time_base,num=200)
#if verbose:
# print("dt is ",dt)
# print("scaled desired error is ",desired_error)
gam = stats.gamma.pdf(t,shape,location,scale)
# A is a cascade with the appropriate decay rate
A = decay_rate*np.diag(np.ones((state_dim-1)) , -1) - decay_rate*np.diag(np.ones((state_dim)),0)
# influence enters at the top state only
B = np.concatenate((np.ones((1,1)),np.zeros((state_dim-1,1))))
# contributions of states to the output will be scaled to match the gamma distribution
C = np.ones((1,state_dim))*max(gam)
lti_sys = control.ss(A,B,C,0)
lti_approx = control.impulse_response(lti_sys,t)
'''
error = np.sum(np.abs(gam - lti_approx.y))
if(verbose):
print("initial error")
print(error)
#print("desired error")
#print(max(gam))
#print(desired_error)
'''
NSE = 1 - (np.sum(np.square(gam - lti_approx.y)) / np.sum(np.square(gam - np.mean(gam)) ))
# if NSE is nan, set to -10e6
if np.isnan(NSE):
NSE = -10e6
if verbose:
print("initial NSE")
print(NSE)
print("desired NSE")
print(desired_NSE)
iterations = 0
speeds = [10,5,2,1.1,1.05,1.01,1.001]
speed_idx = 0
leap = speeds[speed_idx]
# the area under the curve is normalized to be one. so rather than basing our desired error off the
# max of the distribution, it might be better to make it a percentage error, one percent or five percent
while (NSE < desired_NSE and iterations < max_iterations):
og_was_best = True # start each iteration assuming that the original is the best
# search across the C vector
for i in range(C.shape[1]-1,int(-1),int(-1)): # accross the columns # start at the end and come back
#for i in range(int(0),C.shape[1],int(1)): # accross the columns, start at the beginning and go forward
og_approx = control.ss(A,B,C,0)
og_y = np.ndarray.flatten(control.impulse_response(og_approx,t).y)
og_error = np.sum(np.abs(gam - og_y))
og_NSE = 1 - (np.sum((gam - og_y)**2) / np.sum((gam - np.mean(gam))**2))
Ctwice = np.array(C, copy=True)
Ctwice[0,i] = leap*C[0,i]
twice_approx = control.ss(A,B,Ctwice,0)
twice_y = np.ndarray.flatten(control.impulse_response(twice_approx,t).y)
twice_error = np.sum(np.abs(gam - twice_y))
twice_NSE = 1 - (np.sum((gam - twice_y)**2) / np.sum((gam - np.mean(gam))**2))
Chalf = np.array(C,copy=True)
Chalf[0,i] = (1/leap)*C[0,i]
half_approx = control.ss(A,B,Chalf,0)
half_y = np.ndarray.flatten(control.impulse_response(half_approx,t).y)
half_error = np.sum(np.abs(gam - half_y))
half_NSE = 1 - (np.sum((gam - half_y)**2) / np.sum((gam - np.mean(gam))**2))
'''
Cneg = np.array(C,copy=True)
Cneg[0,i] = -C[0,i]
neg_approx = control.ss(A,B,Cneg,0)
neg_y = np.ndarray.flatten(control.impulse_response(neg_approx,t).y)
neg_error = np.sum(np.abs(gam - neg_y))
neg_NSE = 1 - (np.sum((gam - neg_y)**2) / np.sum((gam - np.mean(gam))**2))
'''
faster = np.array(A,copy=True)
faster[i,i] = A[i,i]*leap # faster decay
if abs(faster[i,i]) < abs(max_pole_speed):
if i > 0: # first reservoir doesn't receive contribution from another reservoir. want to keep B at 1 for scaling
faster[i,i-1] = A[i,i-1]*leap # faster rise
faster_approx = control.ss(faster,B,C,0)
faster_y = np.ndarray.flatten(control.impulse_response(faster_approx,t).y)
faster_error = np.sum(np.abs(gam - faster_y))
faster_NSE = 1 - (np.sum((gam - faster_y)**2) / np.sum((gam - np.mean(gam))**2))
else:
faster_NSE = -10e6 # disallowed because the pole is too fast
slower = np.array(A,copy=True)
slower[i,i] = A[i,i]/leap # slower decay
if abs(slower[i,i]) > abs(min_pole_speed):
if i > 0:
slower[i,i-1] = A[i,i-1]/leap # slower rise
slower_approx = control.ss(slower,B,C,0)
slower_y = np.ndarray.flatten(control.impulse_response(slower_approx,t).y)
slower_error = np.sum(np.abs(gam - slower_y))
slower_NSE = 1 - (np.sum((gam - slower_y)**2) / np.sum((gam - np.mean(gam))**2))
else:
slower_NSE = -10e6 # disallowed because the pole is too slow
#all_errors = [og_error, twice_error, half_error, faster_error, slower_error]
all_NSE = [og_NSE, twice_NSE, half_NSE, faster_NSE, slower_NSE]# , neg_NSE]
if (twice_NSE >= max(all_NSE) and twice_NSE > og_NSE):
C = Ctwice
if twice_NSE > 1.001*og_NSE: # an appreciable difference
og_was_best = False # did we change something this iteration?
elif (half_NSE >= max(all_NSE) and half_NSE > og_NSE):
C = Chalf
if half_NSE > 1.001*og_NSE: # an appreciable difference
og_was_best = False # did we change something this iteration?
elif (slower_NSE >= max(all_NSE) and slower_NSE > og_NSE):
A = slower
if slower_NSE > 1.001*og_NSE: # an appreciable difference
og_was_best = False # did we change something this iteration?
elif (faster_NSE >= max(all_NSE) and faster_NSE > og_NSE):
A = faster
if faster_NSE > 1.001*og_NSE: # an appreciable difference
og_was_best = False # did we change something this iteration?
'''
elif (neg_NSE >= max(all_NSE) and neg_NSE > og_NSE):
C = Cneg
if neg_NSE > 1.001*og_NSE:
og_was_best = False
'''
NSE = og_NSE
error = og_error
iterations += 1 # this shouldn't be the termination condition unless the resolution is too coarse
# normally the optimization should exit because the leap has become too small
if og_was_best: # the original was the best, so we're going to tighten up the optimization
speed_idx += 1
if speed_idx > len(speeds)-1:
break # we're done
leap = speeds[speed_idx]
# print the iteration count every ten
# comment out for production
if (iterations % 2 == 0 and verbose):
print("iterations = ", iterations)
print("error = ", error)
print("NSE = ", NSE)
print("leap = ", leap)
lti_approx = control.ss(A,B,C,0)
y = np.ndarray.flatten(control.impulse_response(og_approx,t).y)
error = np.sum(np.abs(gam - og_y))
print("LTI_from_gamma final NSE")
print(NSE)
if (verbose):
print("final system\n")
print("A")
print(A)
print("B")
print(B)
print("C")
print(C)
print("\nfinal error")
print(error)
# are any of the final eigenvalues outside the bounds specified?
E = np.linalg.eigvals(A)
if (np.any(np.abs(E) > max_pole_speed) or np.any(np.abs(E) < min_pole_speed)):
print("WARNING: final eigenvalues are outside the bounds specified")
return {"lti_approx":lti_approx, "lti_approx_output":y, "error":error, "t":t, "gamma_pdf":gam}
# this function takes the system data and the causative topology and returns an LTI system
# if the causative topology isn't already defined, it needs to be created using infer_causative_topology
def lti_system_gen(causative_topology, system_data,independent_columns,dependent_columns,max_iter=250,
swmm=False,bibo_stable = False,max_transition_state_dim=50, max_transforms = 1, early_stopping_threshold = 0.005):
# cast the columns and indices of causative_topology to strings so sindy can run properly
# We need the tuples to link the columns in system_data to the object names in the swmm model
# so we'll cast these back to tuples once we're done
if swmm:
causative_topology.columns = causative_topology.columns.astype(str)
causative_topology.index = causative_topology.index.astype(str)
print("causative topology \n")
print(causative_topology.index)
print(causative_topology.columns)
# do the same for dependent_columns and independent_columns
dependent_columns = [str(col) for col in dependent_columns]
independent_columns = [str(col) for col in independent_columns]
print(dependent_columns)
print(independent_columns)
# do the same for the columns of system_data
system_data.columns = system_data.columns.astype(str)
print(system_data.columns)
A = pd.DataFrame(index=dependent_columns, columns=dependent_columns)
B = pd.DataFrame(index=dependent_columns, columns=independent_columns)
C = pd.DataFrame(index=dependent_columns,columns=dependent_columns)
C.loc[:,:] = np.diag(np.ones(len(dependent_columns))) # these are the states which are observable