-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodpods.py
More file actions
4390 lines (4053 loc) · 199 KB
/
modpods.py
File metadata and controls
4390 lines (4053 loc) · 199 KB
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 re
import warnings
from typing import Any
import control
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import pysindy as ps
import pyswmm # not a requirement for any other function
import scipy.stats as stats
from pysindy.optimizers._constrained_sr3 import ConstrainedSR3 as _ConstrainedSR3
# Suppress the specific AxesWarning from pysindy after import
warnings.filterwarnings(
"ignore", message=".*axes labeled for array with.*", module="pysindy"
)
# 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),
)
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=_ConstrainedSR3(
reg_weight_lam=0,
regularizer="l2",
constraint_lhs=constraint_lhs,
constraint_rhs=constraint_rhs,
inequality_constraints=True,
),
)
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=_ConstrainedSR3(
reg_weight_lam=0,
regularizer="l2",
constraint_lhs=constraint_lhs,
constraint_rhs=constraint_rhs,
inequality_constraints=True,
),
)
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=_ConstrainedSR3(
reg_weight_lam=0,
regularizer="l0",
relax_coeff_nu=10e9,
initial_guess=initial_guess,
constraint_lhs=constraint_lhs,
constraint_rhs=constraint_rhs,
inequality_constraints=False,
max_iter=10000,
),
)
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])
)