-
Notifications
You must be signed in to change notification settings - Fork 5
/
grad_sgra.py
1824 lines (1599 loc) · 74.5 KB
/
grad_sgra.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 27 14:39:08 2017
@author: levi
"""
import numpy #, time
#from utils import testAlgn
from utils import simp, testAlgn
import matplotlib.pyplot as plt
eps = 1e-20 # this is for avoiding == 0.0 (float) comparisons
LARG = 1e100 # this is for a "random big number"
class stepMngr:
""" Class for the step manager, the object used to calculate the step
value for the gradient phase. The step is chosen through (rudimentary)
minimization of an objective function "Obj".
For now, the objective function looks only into J, the extended cost
functional."""
def __init__(self, log, ctes, corr, pi, prevStepInfo, prntCond=False):
self.cont = -1 # number of objective function evaluation counter
self.cont_exp = -1 # number of objective function evaluation estimation
# TODO: maybe pre-allocating numpy arrays performs better!!
self.histStep = list()
self.histI = list()
self.histP = list()
self.histObj = list()
#Overall parameters
self.tolP = ctes['tolP'] #from sgra already
self.limP = ctes['limP'] #1e5 * tolP seems ok
# for stopping conditions
self.stopStepLimTol = ctes['stopStepLimTol'] # been using 1e-4
self.stopObjDerTol = ctes['stopObjDerTol'] # been using 1e-4
self.stopNEvalLim = ctes['stopNEvalLim'] # been using 100
# for findStepLim
self.findLimStepTol = ctes['findLimStepTol'] # been using 1e-2
self.piLowLim = ctes['piLowLim']
self.piHighLim = ctes['piHighLim']
# New: dJ/dAlfa
self.dJdStepTheo = corr['dJdStepTheo']
self.corr = corr
self.log = log
self.mustPrnt = prntCond
self.best = {'step':0.0, # this is for the best step so far
'obj': None, # this is for the best object so far
'limP': -1.} # this is for the smallest distance to P limit
self.maxGoodStep = 0.0
self.minBadStep = LARG
# Previous step information
self.prevStepInfo = prevStepInfo
self.isDecr = True # the obj function is monotonic until proven otherwise
self.pLimSrchStopMotv = 0 # reason for abandoning the P lim step search.
# TODO: these parameters should go to the config file...
self.tolStepObj = 1e-2
self.tolStepLimP = 1e-2
self.tolLimP = 1e-2
self.epsStep = 1e-10#min(self.tolStepObj,self.tolStepLimP) / 100.
self.sortIndxHistStep = list()
# Try to find a proper limit for the step
# initialize arrays with -1
alfaLimLowPi = numpy.zeros_like(self.piLowLim) - 1.
alfaLimHighPi = numpy.zeros_like(self.piHighLim) - 1.
# Find the limit with respect to the pi Limits (lower and upper)
# pi + alfa * corr['pi'] = piLim => alfa = (piLim-pi)/corr['pi']
p = min((len(self.piLowLim), len(corr['pi'])))
for i in range(p):
if self.piLowLim[i] is not None and corr['pi'][i] < 0.:
alfaLimLowPi[i] = (self.piLowLim[i] - pi[i]) / corr['pi'][i]
if self.piHighLim[i] is not None and self.corr['pi'][i] > 0.:
alfaLimHighPi[i] = (self.piHighLim[i] - pi[i]) / corr['pi'][i]
noLimPi = True
alfaLimPi = alfaLimLowPi[0]
for alfa1, alfa2 in zip(alfaLimLowPi, alfaLimHighPi):
if alfa1 > 0.:
if alfa1 < alfaLimPi or noLimPi:
alfaLimPi = alfa1
noLimPi = False
if alfa2 > 0.:
if alfa2 < alfaLimPi or noLimPi:
alfaLimPi = alfa2
noLimPi = False
if self.mustPrnt:
if noLimPi:
msg = "\n> No limit in step due to pi conditions. Moving on."
else:
msg = "\n> Limit in step due to pi conditions: " + \
"{}".format(alfaLimPi)
self.log.printL(msg)
# convention: 0: pi limits,
# 1: P < limP,
# 2: Obj <= Obj0,
# 3: Obj >= 0
if noLimPi:
self.StepLimActv = [False, True, True, True]
# lowest step that violates each condition
self.StepLimUppr = [LARG, LARG, LARG, LARG]
# highest step that does NOT violate each condition
self.StepLimLowr = [0., 0., 0., 0.]
else:
self.StepLimActv = [True, True, True, True]
# lowest step that violates each condition
self.StepLimUppr = [alfaLimPi, LARG, LARG, LARG]
# highest step that does NOT violate each condition
self.StepLimLowr = [alfaLimPi, 0., 0., 0.]
# "Stop motive" codes: 0 - step rejected
# 1 - local min found
# 2 - step limit hit
# 3 - too many evals
self.stopMotv = -1 # placeholder, this will be updated later.
self.P0, self.I0, self.J0, self.Obj0 = 1., 1., 1., 1.
# this is for the P regression
self.PRegrAngCoef = 0.
self.PRegrLinCoef = 0.
# this is for the "trissection" search
self.trio = {'obj': [0.,0.,0.],
'step': [0.,0.,0.]} # placeholder values; these don't make sense
self.isTrioSet = False # True when the trio is set
@staticmethod
def calcObj(P, I, J):
"""This is the function which defines the objective function."""
# TODO: Find a way to properly parametrize this so that the user can
# set the objective function by setting numerical (or enumerable)
# parameters in the .its file.
return J
# return (I + (self.k)*P)
# if P > self.tolP:
# return (I + (self.k)*(P-self.tolP))
# else:
# return I
def getLast(self):
""" Get the attributes for the last applied step. """
P = self.histP[self.cont]
I = self.histI[self.cont]
Obj = self.histObj[self.cont]
return P, I, Obj
def check(self,alfa,Obj,P,pi):
""" Perform a validity check in this step value, updating the limit
values for searching step values if it is the case.
Conditions checked: - limits in each of the pi parameters
- P <= limP
- Obj <= Obj0
- Obj >= 0 [why?]
If any of these conditions are not met, the actual obtained value of Obj
is not meaningful. Hence, the strategy adopted is to artificially increase
the Obj value if any of the conditions (except the third, of course) is not
met.
"""
# Check for violations on the pi conditions.
# Again, some limit is 'None' when it is not active.
PiCondVio = False
for i in range(len(pi)):
# violated here in lower limit condition
if self.piLowLim[i] is not None and pi[i] < self.piLowLim[i]:
PiCondVio = True; break # already violated, no need to continue
# violated here in upper limit condition
if self.piHighLim[i] is not None and pi[i] > self.piHighLim[i]:
PiCondVio = True; break # already violated, no need to continue
#
# "Bad point" conditions:
BadPntCode = False; BadPntMsg = ''
ObjRtrn = 1.1 * self.Obj0
# condition 0
if PiCondVio:
BadPntCode = True
BadPntMsg += ("\n- piLowLim: " + str(self.piLowLim) +
"\n pi: " + str(pi) +
"\n piHighLim: " + str(self.piHighLim))
# no need for checking since the pi limits are known beforehand
# condition 1
if P >= self.limP:
BadPntCode = True
BadPntMsg += ("\n- P = {:.4E}".format(P) +
" > {:.4E} = limP".format(self.limP))
if alfa < self.StepLimUppr[1]:
self.StepLimUppr[1] = alfa
else:
if alfa > self.StepLimLowr[1]:
self.StepLimLowr[1] = alfa
# condition 2
if Obj > self.Obj0:
BadPntCode = True
BadPntMsg += ("\n- Obj-Obj0 = {:.4E}".format(Obj-self.Obj0) +
" > 0")
ObjRtrn = Obj
if alfa < self.StepLimUppr[2]:
self.StepLimUppr[2] = alfa
else:
if alfa > self.StepLimLowr[2]:
self.StepLimLowr[2] = alfa
# condition 3
if Obj < 0.0:
BadPntCode = True
BadPntMsg += ("\n- Obj = {:.4E} < 0".format(Obj))
if alfa < self.StepLimUppr[3]:
self.StepLimUppr[3] = alfa
else:
if alfa > self.StepLimLowr[3]:
self.StepLimLowr[3] = alfa
# look for limits that are no longer active, deactivate them
domMsg = ''
for i in range(4):
if self.StepLimActv[i]:
for j in range(4):
if not (j == i):
if self.StepLimUppr[j] <= self.StepLimLowr[i]:
domMsg += "\nIndex {} was ".format(i) + \
"dominated by index {}".format(j) + \
". No longer active."
self.StepLimActv[i] = False
break
if BadPntCode:
# Bad point! Return saturated version of Obj (if necessary)
if self.mustPrnt:
self.log.printL("> In check. Got a bad point," + \
BadPntMsg + "\nwith alfa = " + str(alfa) + \
", Obj = "+str(Obj)+domMsg)
# update minimum bad step, if necessary
if alfa < self.minBadStep:
self.minBadStep = alfa
stat = False
else:
# Good point; update maximum good step, if necessary
if alfa > self.maxGoodStep:
self.maxGoodStep = alfa
stat = True
ObjRtrn = Obj
if self.mustPrnt:
msg = "\n StepLimLowr = "+str(self.StepLimLowr)
msg += "\n StepLimUppr = " + str(self.StepLimUppr)
msg += "\n StepLimActv = " + str(self.StepLimActv)
self.log.printL(msg)
return stat, ObjRtrn
def calcBase(self,sol,P0,I0,J0):
""" Calculate the baseline values, that is, the functions P, I, J for
the solution with no correction applied.
Please note that there is no need for this P0, I0 and J0 to come from
outside of this function... this is only here to avoid calculating
these guys twice. """
Obj0 = self.calcObj(P0,I0,J0)
if self.mustPrnt:
self.log.printL("> I0 = {:.4E}, ".format(I0) + \
"Obj0 = {:.4E}".format(Obj0))
self.log.printL("\n> Setting Obj0 to "+str(Obj0))
self.P0, self.I0, self.J0, self.Obj0 = P0, I0, J0, Obj0
self.best['obj'] = Obj0
self.trio['obj'][0] = Obj0
return Obj0
def testDecr(self,alfa:float,Obj:float):
"""
Test if the decrescent behavior of the objective as a function of the step
is still maintained.
This is implemented by keeping ordered lists of the steps and the
corresponding objective values.
Only the valid (non-violating) steps are kept, of course.
:return: None
"""
isMonoLost = False
ins = len(self.sortIndxHistStep)
# test if non-ascending monotonicity is maintained
if ins > 0:
# the test is different depending on the position of the current
# step in respect to the list of previous steps.
if alfa > self.histStep[self.sortIndxHistStep[-1]]:
# step bigger than all previous steps
ind = ins
if self.isDecr:
if Obj > self.histObj[self.sortIndxHistStep[-1]]:
isMonoLost = True
self.isDecr = False
elif alfa < self.histStep[self.sortIndxHistStep[0]]:
# step smaller than all previous steps
ind = 0
if self.isDecr:
if Obj < self.histObj[self.sortIndxHistStep[0]]:
isMonoLost = True
self.isDecr = False
else:
# step is in between. Find proper values of steps for comparison
for i, indx_alfa_ in enumerate(self.sortIndxHistStep):
alfa_ = self.histStep[indx_alfa_]
if alfa_ <= alfa <= self.histStep[self.sortIndxHistStep[i + 1]]:
ind = i
break
else:
# this condition should never be reached!
msg = "Something is very weird here. Debugging is recommended."
raise (Exception(msg))
if self.isDecr:
if Obj < self.histObj[self.sortIndxHistStep[ind + 1]] or \
Obj > self.histObj[self.sortIndxHistStep[ind]]:
isMonoLost = True
self.isDecr = False
# insert the current step at the proper place in the sorted list
self.sortIndxHistStep.insert(ind, ins)
# insert the objective in the corresponding place
# Display message if and only if the monotonicity was lost right now
if isMonoLost and self.mustPrnt:
self.log.printL("\n> Monotonicity was just lost...")
else:
self.sortIndxHistStep.append(ins)
#self.log.printL("\nLeaving testDecr, these are the sorted lists:")
#self.log.printL("SortHistStep = {}\nSortHistObj = "
# "{}".format(self.sortHistStep,self.sortHistObj))
def isNewStep(self, alfa):
"""Check if the step alfa is a new one (not previously tried).
The (relative) tolerance is self.epsStep.
"""
for alfa_ in self.histStep:
if abs(alfa_-alfa) < self.epsStep * alfa:
return False
else:
return True
def tryNewStep(self, sol, alfa, ovrdSort=False, plotSol=False, plotPint=False):
""" Similar to tryStep(), but making sure it is a new step
:param sol: sgra
:param alfa: the step to be tried
:param ovrdSort: flag for overriding the sorting (sort it regardless)
:param plotSol: flag for plotting the solution with the correction
:param plotPint: flag for plotting the P_int with the correction
:return: P, I, Obj just like tryStep()
"""
if self.isNewStep(alfa):
P, I, Obj = self.tryStep(sol, alfa, ovrdSort=ovrdSort,
plotSol=plotSol, plotPint=plotPint)
return P, I, Obj
else:
alfa0 = alfa.copy()
keepSrch = True
while keepSrch:
# TODO: this scheme is more than too simple...
alfa *= 1.01
keepSrch = not self.isNewStep(alfa)
if self.mustPrnt:
msg = "\n> Changing step from {} to {}".format(alfa0,alfa) + \
" due to conflict."
self.log.printL(msg)
P, I, Obj = self.tryStep(sol, alfa, ovrdSort=ovrdSort, plotSol=plotSol,
plotPint=plotPint)
return P, I, Obj
def tryStep(self, sol, alfa, ovrdSort=False, plotSol=False, plotPint=False):
""" Try this given step value.
It returns the values of P, I and Obj associated* with the tried step (alfa).
Some additional procedures are performed, though:
- update "best step" record ...
- update the lower and upper bounds (via self.check())
- assemble/update the trios for searching the minimum obj"""
# Increment evaluation counter
self.cont += 1
if not self.isNewStep(alfa):
self.log.printL("\n> Possible conflict over here! Debugging is "
"recommended...")
if self.mustPrnt:
self.log.printL("\n> Trying alfa = {:.4E}".format(alfa))
# Apply the correction
newSol = sol.copy()
newSol.aplyCorr(alfa,self.corr)
if plotSol:
newSol.plotSol()
# Get corresponding P, I, J, etc
P,_,_ = newSol.calcP(mustPlotPint=plotPint)
J,_,_,I,_,_ = newSol.calcJ()
JrelRed = 100.*((J - self.J0)/alfa/self.dJdStepTheo)
IrelRed = 100.*((I - self.I0)/alfa/self.dJdStepTheo)
Obj = self.calcObj(P,I,J)
# Record on the spreadsheets (if it is the case)
if self.log.xlsx is not None:
col, row = self.prevStepInfo['NIterGrad']+1, self.cont+1
self.log.xlsx['step'].write(row,col,alfa)
self.log.xlsx['P'].write(row,col,P)
self.log.xlsx['I'].write(row,col,I)
self.log.xlsx['J'].write(row,col,J)
self.log.xlsx['obj'].write(row,col,Obj)
# check if it is a good step, etc
isOk, Obj = self.check(alfa, Obj, P, newSol.pi)
# update trios for objective "trissection"
if self.isTrioSet:
# compare current step with the trio's middle step
if alfa < self.trio['step'][1]:
# new step is less than the middle step
if alfa > self.trio['step'][0]:
# new step is between the left and middle step.
if Obj < self.trio['obj'][1]:
# shift middle and right steps to the left
self.trio['step'][1], \
self.trio['step'][2] = alfa, self.trio['step'][1]
self.trio['obj'][1], \
self.trio['obj'][2] = Obj, self.trio['obj'][1]
else:
# shift the left step to the right
self.trio['step'][0] = alfa
self.trio['obj'][0] = Obj
else:
# new step is greater than the middle step
if alfa < self.trio['step'][2]:
# new step is between the middle and right step.
if Obj < self.trio['obj'][1]:
# shift left and middle steps to the right
self.trio['step'][0], \
self.trio['step'][1] = self.trio['step'][1], alfa
self.trio['obj'][0], \
self.trio['obj'][1] = self.trio['obj'][1], Obj
else:
# shift the right step to the left
self.trio['step'][2] = alfa
self.trio['obj'][2] = Obj
if self.mustPrnt:
self.log.printL("\n> New trios:\n {}".format(self.trio))
resStr = ''
if isOk:
# update the step closest to P limit, if still applicable.
# Just the best distance is kept, the best step is necessarily
# StepLimLowr[1]
if self.StepLimActv[1]:
distP = 1. - P / self.limP
if self.mustPrnt:
msg = "\n> Current distP = {}.\n".format(distP)
else:
msg = ''
if self.best['limP'] < 0.:
self.best['limP'] = distP
if self.mustPrnt:
msg += " First best steplimP: {}.".format(alfa)
else:
if distP < self.best['limP']:
self.best['limP'] = distP
if self.mustPrnt:
msg += " Updating best steplimP: {}.".format(alfa)
if self.mustPrnt:
self.log.printL(msg)
if not self.isTrioSet:
if len(self.sortIndxHistStep) == 0:
# This is the first valid step ever!
# Put it in the middle of the trio
self.trio['step'][1] = alfa
self.trio['obj'][1] = Obj
# entry 1 is set. Check entry 2 before switching the 'ready' flag
if self.trio['step'][2] > eps:
# entry 2 had already been set. Switch the flag!
self.isTrioSet = True
if self.mustPrnt:
self.log.printL("\n> Middle entry was just set, "
"trios are ready.")
# Update best value (if it is the case)
if self.best['obj'] > Obj:
self.best['step'], self.best['obj'] = alfa, Obj
if self.mustPrnt:
self.log.printL("\n> Best result updated!")
#
if self.mustPrnt:
resStr = "\n- Results (good point):\n" + \
"step = {:.4E} P = {:.4E} I = {:.4E}".format(alfa,P,I) + \
" J = {:.7E} Obj = {:.7E}\n ".format(J,Obj) + \
" Rel. reduction of J = {:.1F}%,".format(JrelRed) + \
" Rel. reduction of I = {:.1F}%".format(IrelRed)
# test the non-ascending monotonicity of Obj = f(step).
if self.isDecr or ovrdSort:
# no need to keep testing if the monotonicity is not kept!
self.testDecr(alfa,Obj)
else:
# not a valid step.
if not self.isTrioSet:
if self.trio['step'][2] < eps or alfa < self.trio['step'][2]:
# this means the final position of the trio gets the smallest
# non-valid step to be found before the trio is set.
self.trio['step'][2] = alfa
self.trio['obj'][2] = Obj
# entry 2 is set. Check entry 1 before switching the 'ready' flag
if self.trio['step'][1] > eps:
# entry 1 had already been set. Switch the flag!
self.isTrioSet = True
if self.mustPrnt:
self.log.printL("\n> Final entry was just set, trios are "
"ready.")
if self.mustPrnt:
resStr = "\n- Results (bad point):\n" + \
"step = {:.4E} P = {:.4E} I = {:.4E}".format(alfa,P,I) + \
" J = {:.7E} CorrObj = {:.7E}\n ".format(J,Obj) + \
" J reduction eff. = {:.1F}%,".format(JrelRed) + \
" I reduction eff. = {:.1F}%".format(JrelRed)
#
if self.mustPrnt:
resStr += "\n- Evaluation #" + str(self.cont) + ",\n" + \
"- BestStep: {:.6E}, ".format(self.best['step']) + \
"BestObj: {:.6E}".format(self.best['obj']) + \
"\n- MaxGoodStep: {:.6E}".format(self.maxGoodStep) + \
"\n- MinBadStep: {:.6E}".format(self.minBadStep)
self.log.printL(resStr)
#
self.histStep.append(alfa)
self.histP.append(P)
self.histI.append(I)
self.histObj.append(Obj)
if self.mustPrnt:
msg = "Steps: {}\n Objs: {}\n " \
"Ps: {}".format(self.histStep, self.histObj, self.histP)
msg += "\n\nstepTrio = {}\nobjTrio = {}".format(self.trio['step'],
self.trio['obj'])
self.log.printL(msg)
return P, I, Obj#self.getLast()
def tryStepSens(self,sol,alfa,plotSol=False,plotPint=False):
""" Try a given step and the sensitivity as well. """
da = self.findLimStepTol * .1
NotAlgn = True
P, I, Obj = self.tryStep(sol, alfa, plotSol=plotSol, plotPint=plotPint)
outp = {}
while NotAlgn:
stepArry = numpy.array([alfa*(1.-da), alfa, alfa*(1.+da)])
Pm, Im, Objm = self.tryStep(sol, stepArry[0])
PM, IM, ObjM = self.tryStep(sol, stepArry[2])
dalfa = stepArry[2] - stepArry[0]
gradP = (PM-Pm) / dalfa
gradI = (IM-Im) / dalfa
gradObj = (ObjM-Objm) / dalfa
outp = {'P': numpy.array([Pm,P,PM]), 'I': numpy.array([Im,I,IM]),
'obj': numpy.array([Objm,Obj,ObjM]), 'step': stepArry,
'gradP': gradP, 'gradI': gradI, 'gradObj': gradObj}
algnP = testAlgn(stepArry,outp['P'])
algnI = testAlgn(stepArry,outp['I'])
algnObj = testAlgn(stepArry,outp['obj'])
# Test alignment; if not aligned, keep lowering
if max([abs(algnP),abs(algnI),abs(algnObj)]) < 1.0e-10:
NotAlgn = False
da *= .1
#
return outp
def showTrios(self):
msg = "\nStepTrio: {}\n ObjTrio: {}".format(self.trio['step'],
self.trio['obj'])
self.log.printL(msg)
def adjsTrios(self,sol):
if self.mustPrnt:
self.log.printL("\n> Adjusting trios...")
self.showTrios()
# TODO: 1 decade is probably too much! Make this less aggressive
if self.trio['obj'][1] > self.trio['obj'][2]:
if self.mustPrnt:
self.log.printL("\n> Moving to the right!")
self.log.printL(" Steps:" + str(self.histStep))
self.log.printL(" Objs:" + str(self.histObj))
# the right objective is less than the middle one:
# move the middle one to the right, keep searching to
# the right until the objective rises
Obj, alfa = self.trio['obj'][2], self.trio['step'][2]
while Obj <= self.trio['obj'][1]:
if self.mustPrnt:
self.log.printL("\n Moving the right point of the trio 1 "
"decade to the right.")
objMid, stepMid = self.trio['obj'][1], self.trio['step'][1]
if objMid < self.trio['obj'][0]:
# The middle objective is lesser than the left one;
# move the latter to the right as well!
self.trio['step'][0], self.trio['obj'][0] = stepMid, objMid
if self.mustPrnt:
self.log.printL("\n Moving the left point of the trio to"
" the place of the previous middle point.")
self.trio['obj'][1] = self.trio['obj'][2]
self.trio['step'][1] = self.trio['step'][2]
alfa *= 10.
P, I, Obj = self.tryStep(sol, alfa)
self.trio['obj'][2] = Obj
self.trio['step'][2] = alfa
if self.trio['obj'][1] > self.trio['obj'][0]:
if self.mustPrnt:
self.log.printL("\n> Moving to the left!")
self.log.printL(" Steps:" + str(self.histStep))
self.log.printL(" Objs:" + str(self.histObj))
# the left objective is less than the middle one:
# move the middle one to the left, keep searching to
# the left until the objective rises
Obj, alfa = self.trio['obj'][0], self.trio['step'][0]
while Obj <= self.trio['obj'][1]:
if self.mustPrnt:
self.log.printL("\n Moving left element of the trio 1 decade"
" to the left.")
objMid, stepMid = self.trio['obj'][1], self.trio['step'][1]
if objMid < self.trio['obj'][2]:
# The middle objective is lesser than the right one;
# move the latter to the left as well!
self.trio['step'][2], self.trio['obj'][2] = stepMid, objMid
if self.mustPrnt:
self.log.printL("\n Moving the right point of the trio to"
" the place of the previous middle point.")
self.trio['obj'][1] = self.trio['obj'][0]
self.trio['step'][1] = self.trio['step'][0]
alfa /= 10.
P, I, Obj = self.tryStep(sol, alfa)
self.trio['obj'][0] = Obj
self.trio['step'][0] = alfa
def keepSrchPLim(self):
""" Decide to keep looking for P step limit or not.
keepLookCode is 0 for keep looking. Other values correspond to different
exit conditions:
1 - P limit is not active
2 - upper and lower bounds for P step limit are within tolerance
3 - monotonic (descent) behavior was lost, obj min is before P limit
4 - too many objective function evaluations
5 - P limit is within tolerance"""
if not self.StepLimActv[1]:
keepLoopCode = 1
elif (self.StepLimUppr[1] - self.StepLimLowr[1]) < \
self.StepLimLowr[1] * self.tolStepLimP:
keepLoopCode = 2
elif not self.isDecr:
keepLoopCode = 3
elif self.cont >= self.stopNEvalLim:
keepLoopCode = 4
elif self.tolLimP > self.best['limP'] > 0.:
keepLoopCode = 5
else:
keepLoopCode = 0
self.pLimSrchStopMotv = keepLoopCode
def srchStep(self,sol):
"""The ultimate step search.
First of all, the algorithm tries to find a step value for which
P = limP; called AlfaLimP. This is because of the almost linear
behavior of P with step in loglog plot.
This AlfaLimP search is conducted until the value is found (with a
given tolerance, of course) or if Obj > Obj0 before P = limP.
The second part concerns the min Obj search itself. Ideally, some
step values have already been tried in the previous search.
The search is performed by "trissection"; we have 3 ascending values
of step with the corresponding values of Obj. If the middle point
corresponds to the lowest value (V condition), the trissection
begins. Else, the search point moves left of right until the V
condition is met.
"""
if self.mustPrnt:
self.log.printL("\n> Entering ULTIMATE STEP SEARCH!\n")
# PART 1: alfa_limP search
# 1.0: Get the stop motive of the previous grad iteration, if it exists
prevStopMotv = self.prevStepInfo.get('stopMotv', -1)
# 1.0.1: Get the best step from the previous grad iteration
prevBest = self.prevStepInfo.get('best', None)
if prevBest is not None:
alfa = prevBest['step']
if self.mustPrnt:
msg = "\n> First of all, let's try the best step of " \
"the previous run,\n alfa = {}".format(alfa)
self.log.printL(msg)
self.tryStep(sol, alfa)
# 1.0.2: Decide the mode for P limit search, default or not
if prevStopMotv == 1 or prevStopMotv == 2 or prevStopMotv == 3:
isPLimSrchDefault = False
else:
isPLimSrchDefault = True
# 1.0.3: If the previous P limit fit is to be used, check validity first
if not isPLimSrchDefault:
a = self.prevStepInfo['PRegrAngCoef']
#b = self.prevStepInfo['PRegrLinCoef']
if a < eps:
# Fit is not good, override and return to default
if self.mustPrnt:
self.log.printL("\n> Overriding P limit search to default"
" mode.")
isPLimSrchDefault = True
# 1.0.4: calculate P target (just below P limit, but still within tolerance)
P_targ = self.limP * (1. - self.tolLimP / 2.)
# ^ This is so that abs(P_targ / self.limP - 1.) = tolLimP/2
logP_targ = numpy.log(P_targ)
if isPLimSrchDefault:
# 1.1: Start with alfa = 1, unless the pi conditions don't allow it
if self.StepLimActv[0]:
alfa1 = min([1., self.StepLimLowr[0]*.9])
else:
alfa1 = 1.
if self.mustPrnt:
self.log.printL("\n> Going for default P limit search.")
P1, I1, Obj1 = self.tryNewStep(sol, alfa1)
alfa1 = self.histStep[-1]
if self.cont > 0:
# 1.2: If more than 1 step has been tried, make a line
y1, y2 = numpy.log(self.histP[-1]), numpy.log(self.histP[-2])
x1 = numpy.log(self.histStep[-1])
x2 = numpy.log(self.histStep[-2])
a = (y2 - y1) / (x2 - x1) # angular coefficient
b = y1 - x1 * a # linear coefficient
self.PRegrAngCoef, self.PRegrLinCoef = a, b # store them
alfaLimP = numpy.exp((logP_targ - b) / a)
if self.mustPrnt:
msg = "\n> Ok, that did not work. " \
"Let's try alfa = {} (linear fit from" \
" the latest tries).".format(alfaLimP)
self.log.printL(msg)
else:
# 1.2 (alt): first model for alfa with P(0) and P(alfa1) only
# was actually very bad. Let's go with +- 10%...
if P1 > P_targ:
alfaLimP = alfa1 * 0.9
else:
alfaLimP = alfa1 * 1.1
if self.mustPrnt:
msg = "\n> AlfaLimP = {} (by first model**)".format(alfaLimP)
self.log.printL(msg)
# Proceed with this value, unless the pi conditions don't allow it
if self.StepLimActv[0]:
alfaLimP = min([alfaLimP, self.StepLimLowr[0]*.99])
# 1.3: update P limit search status
self.keepSrchPLim()
else:
if self.pLimSrchStopMotv == 0:
# 1.1 (alt): Start with the fit provided by the last grad step
a = self.prevStepInfo['PRegrAngCoef']
b = self.prevStepInfo['PRegrLinCoef']
alfaLimP = numpy.exp((logP_targ - b) / a)
# ... unless the pi conditions don't allow it
if self.StepLimActv[0]:
alfaLimP = min([alfaLimP, self.StepLimLowr[0] * .9])
if self.mustPrnt:
msg = "\n> Using the fit from the previous step search,\n" \
" (a = {}, b = {}),\n let's try alfa".format(a, b) + \
" = {} to hit P target = {}.".format(alfaLimP, P_targ)
self.log.printL(msg)
# Try alfaLimP, but there can be a conflict...
P, I, Obj = self.tryNewStep(sol, alfaLimP)
# 1.2 (alt) Checking if we must proceed...
self.keepSrchPLim()
else:
alfaLimP, P = 1., 1. # These values will not be used.
# 1.3 (alt): The fit was not that successful... carry on
if self.pLimSrchStopMotv == 0:
if self.cont > 0:
# 1.3.1 (alt1): If more than 1 step was tried, make a line!
y1, y2 = numpy.log(self.histP[-1]), numpy.log(self.histP[-2])
x1 = numpy.log(self.histStep[-1])
x2 = numpy.log(self.histStep[-2])
a = (y2-y1)/(x2-x1) # angular coefficient
b = y1 - x1 * a # linear coefficient
self.PRegrAngCoef, self.PRegrLinCoef = a, b # store them
alfaLimP = numpy.exp((logP_targ - b) / a)
if self.mustPrnt:
msg = "\n> Ok, that did not work. "\
"Let's try alfa = {} (linear fit from" \
" the latest tries).".format(alfaLimP)
self.log.printL(msg)
else:
# 1.3.1 (alt2): Unable to fit, let's go with +/-10%...
if P > P_targ:
alfaLimP *= 0.9 # 10% lower
msg = "\n> Ok, that did not work. Let's try" \
" alfa = {} (10% lower).".format(alfaLimP)
else:
alfaLimP *= 1.1 # 10% higher
msg = "\n> Ok, that did not work. Let's try" \
" alfa = {} (10% higher).".format(alfaLimP)
if self.mustPrnt:
self.log.printL(msg)
# 1.3: Main loop for P limit search
while self.pLimSrchStopMotv == 0:
# 1.3.1: Safety in alfaLimP: make sure the guess is in the right
# interval
if alfaLimP > self.minBadStep or alfaLimP < self.StepLimLowr[1]:
alfaLimP = .5 * (self.StepLimLowr[1] + self.minBadStep)
msg = "\n> Model has retrieved a bad guess for alfaLimP..." \
"\n Let's go with {} instead.".format(alfaLimP)
self.log.printL(msg)
# 1.3.2: try newest step value
self.tryStep(sol, alfaLimP)
# 1.3.3: keep in loop or not
self.keepSrchPLim()
# 1.3.4: perform regression (if it is the case)
if self.pLimSrchStopMotv == 0:
# 1.3.4.1: assemble log arrays for regression
logStep = numpy.log(numpy.array(self.histStep))
logP = numpy.log(numpy.array(self.histP))
n = len(self.histStep)
# 1.3.4.2: perform actual regression
X = numpy.ones((n, 2))
X[:, 0] = logStep
# weights for regression: priority to points closer to the P limit
W = numpy.zeros((n, n))
logLim = numpy.log(self.limP)
for i, logP_ in enumerate(logP):
W[i, i] = 1. / (logP_ - logLim) ** 2. # inverse
mat = numpy.dot(X.transpose(), numpy.dot(W, X))
a, b = numpy.linalg.solve(mat,
numpy.dot(X.transpose(),
numpy.dot(W, logP)))
self.PRegrAngCoef, self.PRegrLinCoef = a, b
# 1.3.4.3: calculate alfaLimP according to current regression, P
# target just below the P limit, in order to try to get a point
# in the tolerance
alfaLimP = numpy.exp((logP_targ - b) / a)
if self.mustPrnt:
msg = "\n> Performed fit with n = {} points:\n" \
" Steps: {}\n Ps: {}\n Weights: {}\n" \
" a = {}, b = {}\n" \
" alfaLimP = {}".format(n, numpy.exp(logStep),
numpy.exp(logP), W,
a, b, alfaLimP)
self.log.printL(msg)
# DEBUG PLOT
# plt.loglog(self.histStep, self.histP, 'o', label='P')
# model = numpy.exp(b) * numpy.array(self.histStep) ** a
# plt.loglog(self.histStep, model, '--', label = 'model')
# plt.loglog(self.histStep,
# self.limP * numpy.ones_like(self.histP), label='limP')
# plt.loglog(alfaLimP, self.limP, 'x', label='Next guess')
# plt.grid()
# plt.title("P vs step behavior")
# plt.xlabel('Step')
# plt.ylabel('P')
# plt.legend()
# plt.show()
if self.mustPrnt:
msg = '\n> Stopping alfa_limP search: '
if self.pLimSrchStopMotv == 1:
msg += "P limit is no longer active." + \
"\n Local min is likely before alfa_limP."
elif self.pLimSrchStopMotv == 2:
msg += "P limit step tolerance is met."
elif self.pLimSrchStopMotv == 3:
msg += "Monotonicity in objective was lost." + \
"\n Local min is likely before alfa_limP."
elif self.pLimSrchStopMotv == 4:
msg += "Too many Obj evals. Debugging is recommended."
elif self.pLimSrchStopMotv == 5:
msg += "P limit tolerance is met."
self.log.printL(msg)
# 1.4: If the loop was abandoned because of too many evals, leave now.
alfa = self.best['step']
if self.pLimSrchStopMotv == 4:
msg = "\n> Leaving step search due to excessive evaluations." + \
"\n Debugging is recommended."
self.log.printL(msg)
self.stopMotv = 3
return alfa
# PART 2: min Obj search
# 2.0: Bad condition: Obj>Obj0 in all tested steps
if alfa < eps: # alfa is essentially 0 in this case
if self.isTrioSet:
raise(Exception("grad_sgra: No good step but the trios are set."
"\nDebug this now!"))
if self.mustPrnt:
msg = "\n\n> Bad condition! Obj>Obj0 in all tested steps."
self.log.printL(msg)
# 2.0.1: Get latest tried step
Obj, alfa = self.histObj[-1], self.histStep[-1]
# 2.0.2: Go back a few times. We will need 3 points
while Obj > self.Obj0 or self.cont < 2:
alfa /= 10.
P, I, Obj = self.tryStep(sol,alfa)
# 2.0.3: Assemble the trios
self.trio['obj'] = [self.histObj[-1],
self.histObj[-2],
self.histObj[-3]]
self.trio['step'] = [self.histStep[-1],
self.histStep[-2],
self.histStep[-3]]
if self.mustPrnt:
self.log.printL("\n> Finished looking for valid objs.")
self.showTrios()
# 2.0.4: Trios are set
self.isTrioSet = True
# DEBUG PLOTS
# plt.semilogx(self.histStep, self.histObj, 'o', label='Obj')
# plt.semilogx(self.histStep,
# self.Obj0 * numpy.ones_like(self.histStep),
# label='Obj0')
# plt.grid()
# plt.title("Obj vs step behavior")
# plt.xlabel('Step')
# plt.ylabel('Obj')
# plt.legend()
# plt.show()
# 2.1 shortcut: step limit was found, objective seems to be
# descending with step. Abandon ship with the best step so far and
# that's it.
alfa, Obj = self.best['step'], self.best['obj']
if self.isDecr and not(self.StepLimActv[2]):
# calculate the gradient at this point
if self.mustPrnt:
self.log.printL("\n> It seems the minimum obj is after the P "
"limit.\n Testing gradient...")
# TODO: this hardcoded value can cause issues in super sensitive
# problems...
alfa_ = alfa * .999
P_,I_,Obj_ = self.tryStep(sol,alfa_)
grad = (Obj-Obj_)/(alfa-alfa_)
if grad < 0.:
if self.mustPrnt:
msg = "\n> Objective seems to be descending with step.\n" + \
" Leaving calcStepGrad with alfa = {}\n".format(alfa)
self.log.printL(msg)
self.stopMotv = 2 # step limit hit