forked from araujolma/SOAR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprobCart.py
452 lines (363 loc) · 13.3 KB
/
probCart.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 10:40:31 2017
@author: araujolma
A module for the cart problem:
get the cart from position 0 to position 1 in minimal time,
subject to restrictions on maximum acceleration and deceleration.
There are two subarcs, connected through the "middle", equaling position and
velocity.
"""
import numpy, utils
from sgra import sgra
import matplotlib.pyplot as plt
# TODO: these parameters really should go the external configuration file...
Kpf = 0.#10.#0.
# This is irrelevant if Kpf is zero
vLim = .5
class prob(sgra):
probName = 'probCart'
def initGues(self,opt={}):
# The parameters that go here are the ones that cannot be simply
# altered from an external configuration file... at least not
# without a big increase in the complexity of the code...
# matrix sizes
n = 2
m = 1
p = 2
q = 6#8
s = 2
self.n = n
self.m = m
self.p = p
self.q = q
self.s = s
self.Ns = 2*n*s + p
self.omit = True
# list of variations after omission
self.omitVarList = [2, 3, 4, 5, 6, 7, 8, 9, 10]
# matrix for omitting equations
mat = numpy.eye(self.q)
self.omitEqMat = mat[[2,3,4,5],:]
initMode = opt.get('initMode','default')
if initMode == 'default':
N = 3000+1#20000+1#2000+1
dt = 1.0/(N-1)
t = numpy.arange(0,1.0+dt,dt)
self.N = N
self.dt = dt
self.t = t
#prepare tolerances
tolP = 1.0e-4#7#8
tolQ = 1.0e-6#8#5
tol = dict()
tol['P'] = tolP
tol['Q'] = tolQ
self.tol = tol
self.constants['gradStepSrchCte'] = 1.0e-3
# Get initialization mode
x = numpy.zeros((N,n,s))
u = numpy.zeros((N,m,s))#5.0*numpy.ones((N,m,s))
#x[:,0,0] = t.copy()
#x[:,0,0] = .5*t
#x[:,0,1] = .5+.5*t
lam = 0.0*x
mu = numpy.zeros(q)
pi = 10.0*numpy.ones(p)
self.x = x
self.u = u
self.pi = pi
self.lam = lam
self.mu= mu
solInit = self.copy()
self.compWith(solInit,'Initial Guess')
self.log.printL("\nInitialization complete.\n")
return solInit
elif initMode == 'extSol':
inpFile = opt.get('confFile','')
# Get parameters from file
self.loadParsFromFile(file=inpFile)
# The actual "initial guess"
N,m,n,p,q,s = self.N,self.m,self.n,self.p,self.q,self.s
x = numpy.zeros((N,n,s))
u = numpy.zeros((N,m,s))
lam = 0.0*x.copy()
mu = numpy.zeros(q)
pi = numpy.array([1.0,1.0])
self.x = x
self.u = u
self.pi = pi
self.lam = lam
self.mu = mu
solInit = self.copy()
self.compWith(solInit,'Initial Guess')
self.log.printL("\nInitialization complete.\n")
return solInit
#%%
def calcPhi(self):
N = self.N
n = self.n
s = self.s
phi = numpy.empty((N,n,s))
x = self.x
u = self.u
pi = self.pi
for arc in range(s):
phi[:,0,arc] = pi[arc] * x[:,1,arc]
phi[:,1,arc] = pi[arc] * numpy.tanh(u[:,0,arc])
return phi
#%%
def calcGrads(self,calcCostTerm=False):
Grads = dict()
N,n,m,p,q,s = self.N,self.n,self.m,self.p,self.q,self.s
x,u,pi = self.x,self.u,self.pi
# Pre-assign functions
tanh = numpy.tanh
Grads['dt'] = 1.0/(N-1)
phix = numpy.zeros((N,n,n,s))
phiu = numpy.zeros((N,n,m,s))
if p>0:
phip = numpy.zeros((N,n,p,s))
else:
phip = numpy.zeros((N,n,1,s))
fx = numpy.zeros((N,n,s))
fu = numpy.zeros((N,m,s))
fp = numpy.zeros((N,p,s))
#psiy = numpy.eye(q,2*n*s)
psiy = numpy.zeros((q,2*n*s))
psiy[0,0] = 1.0
psiy[1,1] = 1.0
psiy[2,2] = 1.0; psiy[2,4] = -1.0
psiy[3,3] = 1.0; psiy[3,5] = -1.0
psiy[4,6] = 1.0
psiy[5,7] = 1.0
# psiy[0,0] = 1.0
# psiy[1,1] = 1.0
# psiy[1,2] = -1.0
# psiy[2,3] = 1.0
psip = numpy.zeros((q,p))
CostIncrActv = (self.x[:,1,:] >= vLim)
SpeedVio = (self.x[:,1,:]-vLim) * CostIncrActv
for arc in range(s):
tanh_u = tanh(u[:,0,arc])
phix[:,0,1,arc] = pi[arc] * numpy.ones(N)
phiu[:,1,0,arc] = pi[arc] * (1.0 - tanh_u**2)
phip[:,0,arc,arc] = x[:,1,arc]
phip[:,1,arc,arc] = tanh_u
fx[:,1,arc] = pi[arc] * 2. * Kpf * SpeedVio[:,arc]
fp[:,arc,arc] = 1. + Kpf * (SpeedVio[:,arc]**2)
# DynMat = array([[0.0,1.0],[0.0,0.0]])
# for k in range(N):
# for arc in range(s):
#
# phix[k,:,:,arc] = pi[arc] * DynMat
# phiu[k,:,:,arc] = pi[arc] * array([[0.0],\
# [1.0-tanh_u[k,0,arc]**2]])
# phip[k,:,arc,arc] = array([x[k,1,arc],\
# tanh_u[k,0,arc]])
# fp[k,:] = Idp
Grads['phix'] = phix
Grads['phiu'] = phiu
Grads['phip'] = phip
Grads['fx'] = fx
Grads['fu'] = fu
Grads['fp'] = fp
# Grads['gx'] = gx
# Grads['gp'] = gp
Grads['psiy'] = psiy
Grads['psip'] = psip
return Grads
#%%
def calcPsi(self):
x = self.x
N = self.N
# return numpy.array([x[0,0,0],x[0,1,0],x[N-1,0,0]-0.5,x[N-1,1,0],\
# x[0,0,1]-0.5,x[0,1,1],x[N-1,0,1]-1.0,x[N-1,1,1]])
return numpy.array([x[0,0,0],x[0,1,0],
x[N-1,0,0]-x[0,0,1],x[N-1,1,0]-x[0,1,1],
x[N-1,0,1]-1.0,x[N-1,1,1]])
def calcF(self):
N,s = self.N,self.s
f = numpy.empty((N,s))
CostIncrActv = (self.x[:, 1, :] >= vLim)
SpeedVio = (self.x[:, 1, :] - vLim) * CostIncrActv
for arc in range(s):
f[:,arc] = self.pi[arc] * (1. + Kpf*SpeedVio[:,arc]**2)
return f, f, 0.0*f
def calcI(self):
#N,s = self.N,self.s
#f, _, _ = self.calcF()
#Ivec = self.pi
# for arc in range(s):
# Ivec[arc] = .5*(f[0,arc]+f[N-1,arc])
# Ivec[arc] += f[1:(N-1),arc].sum()
# Ivec *= 1.0/(N-1)
Ivec = numpy.empty(self.s)
f,_,_ = self.calcF()
for arc in range(self.s):
Ivec[arc] = utils.simp(f[:,arc],self.N)
I = Ivec.sum()
return I, I, 0.0
#%%
def plotSol(self,opt={},intv=[],piIsTime=True,mustSaveFig=True,\
subPlotAdjs={}):
x = self.x
u = self.u
pi = self.pi
# if len(intv)==0:
# intv = numpy.arange(0,self.N,1,dtype='int')
# else:
# intv = list(intv)
if len(intv)>0:
self.log.printL("plotSol: Sorry, currently ignoring plotting range.")
if opt.get('mode','sol') == 'sol':
I, _, _ = self.calcI()
titlStr = "Current solution: I = {:.4E}".format(I) + \
" P = {:.4E} ".format(self.P) + " Q = {:.4E} ".format(self.Q)
titlStr += "\n(grad iter #" + str(self.NIterGrad) + ")"
plt.subplot2grid((4,1),(0,0),colspan=5)
self.plotCat(x[:,0,:])
plt.grid(True)
plt.ylabel("Position")
plt.title(titlStr)
plt.subplot2grid((4,1),(1,0),colspan=5)
self.plotCat(x[:,1,:],color='g')
plt.grid(True)
plt.ylabel("Speed")
plt.subplot2grid((4,1),(2,0),colspan=5)
self.plotCat(u[:,0,:],color='k')
plt.grid(True)
plt.ylabel("u1 [-]")
plt.subplot2grid((4,1),(3,0),colspan=5)
self.plotCat(numpy.tanh(u[:,0,:]),color='k')
plt.grid(True)
plt.ylabel('Acceleration')
plt.xlabel("Concat. adim. time [-]")
plt.subplots_adjust(0.0125,0.0,0.9,2.5,0.2,0.2)
self.savefig(keyName='currSol',fullName='solution')
self.log.printL("pi = "+str(pi))
elif opt['mode'] == 'var':
dx, du, dp = opt['x'], opt['u'], opt['pi']
titlStr = "Proposed variations (grad iter #" + \
str(self.NIterGrad+1) + ")\n"+"Delta pi: "
for i in range(self.p):
titlStr += "{:.4E}, ".format(dp[i])
plt.subplots_adjust(0.0125,0.0,0.9,2.5,0.2,0.2)
plt.subplot2grid((4,1),(0,0))
self.plotCat(dx[:,0,:])
plt.grid(True)
plt.ylabel("Position")
plt.title(titlStr)
plt.subplot2grid((4,1),(1,0))
self.plotCat(dx[:,1,:],color='g')
plt.grid(True)
plt.ylabel("Speed")
plt.subplot2grid((4,1),(2,0))
self.plotCat(du[:,0,:],color='k')
plt.grid(True)
plt.ylabel("u1 [-]")
new_u = self.u + du
acc = numpy.tanh(self.u)
new_acc = numpy.tanh(new_u)
dacc = new_acc-acc
plt.subplot2grid((4,1),(3,0))
self.plotCat(dacc[:,0,:],color='r')
plt.grid(True)
plt.xlabel("t")
plt.ylabel("Acceleration")
self.savefig(keyName='corr',fullName='corrections')
elif opt['mode'] == 'lambda':
titlStr = "Lambda for current solution"
titlStr += "\n(grad iter #" + str(self.NIterGrad) + ")"
plt.subplot2grid((4,1),(0,0),colspan=5)
self.plotCat(self.lam[:,0,:])
plt.grid(True)
plt.ylabel("lambda: Position")
plt.title(titlStr)
plt.subplot2grid((4,1),(1,0),colspan=5)
self.plotCat(self.lam[:,1,:],color='g')
plt.grid(True)
plt.ylabel("lambda: Speed")
plt.subplot2grid((4,1),(2,0),colspan=5)
self.plotCat(u[:,0,:],color='k')
plt.grid(True)
plt.ylabel("u1 [-]")
plt.subplot2grid((4,1),(3,0),colspan=5)
self.plotCat(numpy.tanh(u[:,0,:]),color='k')
plt.grid(True)
plt.ylabel('Acceleration')
plt.xlabel("Time [s]")
plt.subplots_adjust(0.0125,0.0,0.9,2.5,0.2,0.2)
self.savefig(keyName='currLamb',fullName='lambdas')
self.log.printL("mu = "+str(self.mu))
else:
titlStr = opt['mode']
def compWith(self,altSol,altSolLabl='altSol',mustSaveFig=True,\
piIsTime=True,
subPlotAdjs={'left':0.0,'right':1.0,'bottom':0.0,
'top':2.8,'wspace':0.2,'hspace':0.5}):
self.log.printL("\nComparing solutions...\n")
pi = self.pi
currSolLabl = 'Final solution'
# Plotting the curves
plt.subplots_adjust(**subPlotAdjs)
plt.subplot2grid((4,1),(0,0))
altSol.plotCat(altSol.x[:,0,:],mark='--',labl=altSolLabl)
self.plotCat(self.x[:,0,:],color='r',labl=currSolLabl)
plt.grid(True)
plt.ylabel("Position")
#titlStr = "Comparing solutions: " + currSolLabl + " and " + \
# altSolLabl
#titlStr += "\n(grad iter #" + str(self.NIterGrad) + ")"
#plt.title(titlStr)
plt.xlabel("Adimensional time")
plt.legend(loc="lower center",bbox_to_anchor=(0.5,1),ncol=2)
plt.subplot2grid((4,1),(1,0))
altSol.plotCat(altSol.x[:,1,:],mark='--',labl=altSolLabl)
self.plotCat(self.x[:,1,:],color='g',labl=currSolLabl)
plt.grid(True)
plt.ylabel("Speed")
plt.xlabel("Adimensional time")
plt.legend(loc="lower center",bbox_to_anchor=(0.5,1),ncol=2)
plt.subplot2grid((4,1),(2,0))
altSol.plotCat(altSol.u[:,0,:],mark='--',labl=altSolLabl)
self.plotCat(self.u[:,0,:],color='k',\
labl=currSolLabl)
plt.grid(True)
plt.ylabel("u1 [-]")
plt.xlabel("Adimensional time")
plt.legend(loc="lower center",bbox_to_anchor=(0.5,1),ncol=2)
plt.subplot2grid((4,1),(3,0))
altSol.plotCat(numpy.tanh(altSol.u[:,0,:]),mark='--',labl=altSolLabl)
self.plotCat(numpy.tanh(self.u[:,0,:]),color='k',labl=currSolLabl)
plt.grid(True)
plt.ylabel('Acceleration')
plt.xlabel("Adimensional time")
plt.legend(loc="lower center",bbox_to_anchor=(0.5,1),ncol=2)
self.savefig(keyName='comp',fullName='comparisons')
self.log.printL("pi = "+str(pi)+"\n")
#
if __name__ == "__main__":
print("\n\nRunning probCart.py!\n")
exmpProb = prob()
print("Initializing problem:")
exmpProb = exmpProb.initGues()
exmpProb.printPars()
s = exmpProb.s
print("Plotting current version of solution:")
exmpProb.plotSol()
print("Calculating f:")
f = exmpProb.calcF()
exmpProb.plotCat(f)
plt.grid(True)
plt.xlabel('Concat. adim. time')
plt.ylabel('f')
plt.show()
print("Calculating grads:")
Grads = exmpProb.calcGrads()
for key in Grads.keys():
print("Grads['",key,"'] = ",Grads[key])
print("Calculating I:")
I = exmpProb.calcI()
print("I = ",I)