forked from araujolma/SOAR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprobRock.py
executable file
·2698 lines (2362 loc) · 104 KB
/
probRock.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 13:25:28 2017
@author: levi
"""
import numpy, itsme
from sgra import sgra
from atmosphere import rho, rhoSGRA
import matplotlib.pyplot as plt
from utils import simp#, getNowStr
from naivRock import naivGues
d2r = numpy.pi / 180.0
class prob(sgra):
probName = 'probRock'
def storePars(self,inputDict,inputFile):
"""Get parameters from dictionary, load them into self properly."""
# For lazy referencing here
n = self.n
# Payload mass
self.mPayl = inputDict['Mu']
# Earth constants
r_e, GM = inputDict['R'], inputDict['GM']
grav_e = GM / r_e / r_e
# Target heights for separation.
# This is only here because the Isp, Thrust and s_f arrays must be
# padded to put the extra arcs there.
TargHeig = numpy.array(inputDict['TargHeig'])
# Number of additional arcs:
addArcs = len(TargHeig); self.addArcs = addArcs
# Number of arcs:
s = inputDict['NStag'] + addArcs; self.s = s
# Extra arcs go in the beginning only.
isStagSep = numpy.ones(s, dtype='bool')
for i in range(addArcs):
isStagSep[i] = False
self.isStagSep = isStagSep
# There are always as many pi's as there are arcs
p = s; self.p = p
# n + n-1: beginning and end conditions (free final mass);
# n*(s-addArcs-1) are for "normal" arc interfaces
# [hf=hi,vf=vi,gf=gi,mf=mi or mf=mi+jettisoned mass];
# (n+1)* addArcs are for additional arc interfaces
# [hf=hTarg,hi=hTarg,vf=vi,gf=gi,mf=mi]
q = (n + n - 1) + n * (s - addArcs - 1) + (n + 1) * addArcs
self.q = q
# This is the 'N' variable in Miele (2003)
self.Ns = 2 * n * s + p
# rocket constants
ones = numpy.ones(s)
if 'Isplist' in inputDict.keys():
Isp = numpy.array(inputDict['Isplist'])
Isp = numpy.pad(Isp, (addArcs, 0),
'constant', constant_values=Isp[0])
else:
Isp = inputDict['Isp'] * numpy.ones(s)
Thrust = numpy.array(inputDict['Tlist'])
Thrust = numpy.pad(Thrust, (addArcs, 0),
'constant', constant_values=Thrust[0])
s_f = numpy.array(inputDict['efflist'])
s_f = numpy.pad(s_f, (addArcs, 0),
'constant', constant_values=s_f[0])
CL0, CL1 = inputDict['CL0'] * ones, inputDict['CL1'] * ones
CD0, CD2 = inputDict['CD0'] * ones, inputDict['CD2'] * ones
s_ref = inputDict['s_ref'] * ones
DampCent, DampSlop = inputDict['DampCent'],inputDict['DampSlop']
acc_max = inputDict['acc_max'] * grav_e # in km/s²
# Penalty function settings
# This approach to Kpf is that if, in any point during flight, the
# acceleration exceeds the limit by acc_max_tol, then the penalty
# function at that point is PFtol times greater than the maximum
# value of the original cost functional.
PFmode = inputDict['PFmode']
costFuncVals = Thrust / grav_e / Isp / (1.0 - s_f)
PFtol = inputDict['PFtol']
acc_max_relTol = inputDict['acc_max_relTol']
acc_max_tol = acc_max_relTol * acc_max
if PFmode == 'lin':
Kpf = PFtol * max(costFuncVals) / acc_max_tol
elif PFmode == 'quad':
Kpf = PFtol * max(costFuncVals) / (acc_max_tol ** 2)
elif PFmode == 'tanh':
Kpf = PFtol * max(costFuncVals) / numpy.tanh(acc_max_relTol)
else:
self.log.printL('Error: unknown PF mode "' + str(PFmode) + '"')
raise KeyError
constants = {'grav_e': grav_e, 'Thrust': Thrust,
'Isp': Isp, 's_f': s_f,
'r_e': r_e, 'GM': GM,
'CL0': CL0, 'CL1': CL1, 'CD0': CD0, 'CD2': CD2,
's_ref': s_ref,
'DampCent': DampCent, 'DampSlop': DampSlop,
'PFmode': PFmode, 'Kpf': Kpf}
self.constants = constants
# boundary conditions
h_final = inputDict['h_final']
V_final = numpy.sqrt(GM / (r_e + h_final)) # km/s
missDv = numpy.sqrt((GM / r_e) * (2.0 - r_e / (r_e + h_final)))
self.boundary = {'h_initial': inputDict['h_initial'],
'V_initial': inputDict['V_initial'],
'gamma_initial': inputDict['gamma_initial'],
'm_initial': 0., # Just a place holder!
'h_final': h_final,
'V_final': V_final,
'gamma_final': inputDict['gamma_final'],
'mission_dv': missDv,
'TargHeig': TargHeig}
# restrictions
alpha_max = inputDict['AoAmax'] * d2r * ones # in rads
alpha_min = -alpha_max # in rads
self.restrictions = {'alpha_min': alpha_min,
'alpha_max': alpha_max,
'beta_min': 0.0 * ones,
'beta_max': ones,
'acc_max': acc_max}
# Load remaining parameters:
# - Time discretization,
# - P and Q tolerances,
# - Gradient step search options [constants]
# - Time (pi) limitations [restrictions]
self.loadParsFromFile(file=inputFile)
def initGues(self,opt={}):
# matrix sizes
n, m = 4, 2
self.n, self.m = n, m
# Get initialization mode
initMode = opt.get('initMode','default'); self.initMode = initMode
if initMode == 'default' or initMode == 'naive':
N = 500+1
self.N = N
dt = 1.0/(N-1)
t = numpy.arange(0,1.0+dt,dt)
self.dt = dt
self.t = t
s = 2
addArcs = 0
p = s
self.s = s
self.addArcs = addArcs
self.p = p
self.Ns = 2*n*s + p
q = 2*n - 1 + n * (s-1)
self.q = q
x = numpy.zeros((N,n,s))
u = numpy.zeros((N,m,s))
#prepare tolerances
tolP = 1.0e-5
tolQ = 1.0e-7
tol = dict()
tol['P'] = tolP
tol['Q'] = tolQ
self.tol = tol
# Earth constants
r_e = 6371.0 # km
GM = 398600.4415 # km^3 s^-2
grav_e = GM/r_e/r_e #9.8e-3 km/s^2
# Payload mass
self.mPayl = 100
# rocket constants
Thrust = 300*numpy.ones(s) # kg km/s² [= kN]
Kpf = 100.0 # First guess........
DampCent = 0
DampSlop = 0
PFmode = 'quad'
gradStepSrchCte = 1.0e-4
Isp = 300.0*numpy.ones(s) # s
s_f = 0.05*numpy.ones(s)
CL0 = 0.0*numpy.ones(s) # (B0 Miele 1998)
CL1 = 0.8*numpy.ones(s) # (B1 Miele 1998)
CD0 = 0.05*numpy.ones(s) # (A0 Miele 1998)
CD2 = 0.5*numpy.ones(s) # (A2 Miele 1998)
s_ref = (numpy.pi*(0.0005)**2)*numpy.ones(s) # km^2
# boundary conditions
h_initial = 0.0 # km
V_initial = 1e-6 # km/s
gamma_initial = numpy.pi/2 # rad
m_initial = 20000 # kg
h_final = 463.0 # km
V_final = numpy.sqrt(GM/(r_e+h_final))#7.633 # km/s
gamma_final = 0.0 # rad
boundary = dict()
boundary['h_initial'] = h_initial
boundary['V_initial'] = V_initial
boundary['gamma_initial'] = gamma_initial
boundary['m_initial'] = m_initial
boundary['h_final'] = h_final
boundary['V_final'] = V_final
boundary['gamma_final'] = gamma_final
boundary['mission_dv'] = numpy.sqrt((GM/r_e)*\
(2.0-r_e/(r_e+h_final)))
self.boundary = boundary
constants = dict()
constants['grav_e'] = grav_e
constants['Thrust'] = Thrust
constants['Isp'] = Isp
constants['r_e'] = r_e
constants['GM'] = GM
constants['s_f'] = s_f
constants['CL0'] = CL0
constants['CL1'] = CL1
constants['CD0'] = CD0
constants['CD2'] = CD2
constants['s_ref'] = s_ref
constants['DampCent'] = DampCent
constants['DampSlop'] = DampSlop
constants['PFmode'] = PFmode
constants['Kpf'] = Kpf
constants['gradStepSrchCte'] = gradStepSrchCte
self.constants = constants
# restrictions
alpha_min = -2 * d2r # in rads
alpha_max = 2 * d2r # in rads
beta_min = 0.0
beta_max = 1.0
acc_max = 3.0 * grav_e
pi_min = numpy.zeros(s)
pi_max = numpy.empty_like(pi_min)
for k in range(s):
pi_max[k] = None
#pi_max = numpy.array([None])
restrictions = dict()
restrictions['alpha_min'] = alpha_min
restrictions['alpha_max'] = alpha_max
restrictions['beta_min'] = beta_min
restrictions['beta_max'] = beta_max
restrictions['acc_max'] = acc_max
restrictions['pi_min'] = pi_min
restrictions['pi_max'] = pi_max
self.restrictions = restrictions
PFtol = 1.0e-2
acc_max_relTol = 0.1
costFuncVals = Thrust/grav_e/Isp/(1.0-s_f)
acc_max_tol = acc_max_relTol * acc_max
if PFmode == 'lin':
Kpf = PFtol * max(costFuncVals) / (acc_max_tol)
elif PFmode == 'quad':
Kpf = PFtol * max(costFuncVals) / (acc_max_tol**2)
elif PFmode == 'tanh':
Kpf = PFtol * max(costFuncVals) / numpy.tanh(acc_max_relTol)
else:
self.log.printL('Error: unknown PF mode "' + str(PFmode) + '"')
raise KeyError
if initMode == 'default':
############### Artesanal handicraft with L and D (Miele 2003)
arclen = numpy.floor(len(t)/s).astype(int)
remainder = len(t) % arclen
tarc = numpy.zeros((arclen,s+1))
for k in range(s):
tarc[:,k] = t[k*arclen:(k+1)*arclen]
for r in range(remainder):
tarc[r,s] = t[s*arclen+r]
t_complete = numpy.zeros(((s+1)*arclen,s+1))
for k in range(s+1):
t_complete[:,k] = numpy.pad(tarc[:,k],
(k*arclen,(s-k)*arclen),'constant')
for arc in range(s):
for line in range(N):
x[line,0,arc] = h_final * \
numpy.sin(0.5*numpy.pi*t_complete[line,arc])
x[line,1,arc] = V_final * \
numpy.sin(numpy.pi*t_complete[line,arc]/2)
x[line,2,arc] = (numpy.pi/2) * \
(numpy.exp(-(t_complete[line,arc]**2)/0.017))+\
0.0#+0.06419
expt = numpy.exp(-(t_complete[line,arc]**2)/0.02)
x[line,3,arc] = m_initial*((0.7979* expt) +
0.1901*numpy.cos(t_complete[line,arc]))
#x[:,1,arc] = 1.0e3*(-0.4523*tarc[:,arc]**5 + \
#1.2353*tarc[:,arc]**4 + \
#-1.1884*tarc[:,arc]**3 + \
#0.4527*tarc[:,arc]**2 + \
#-0.0397*tarc[:,arc])
#x[:,1,arc] = 3.793*numpy.exp(0.7256*tarc[:,arc]) + \
#-1.585 + \
#-3.661*numpy.cos(3.785*tarc[:,arc]+ \
#0.9552)
#x[:,3,arc] = m_initial*(1.0-0.89*tarc[:,arc])
#x[:,3,arc] = m_initial*(-2.9*tarc[:,arc]**3 + \
#6.2*tarc[:,arc]**2 + \
#- 4.2*tarc[:,arc] + 1)
pi_time = 200
total_time = pi_time*s
for k in range(N):
if total_time*t[k]<200:
u[k,1,:] = (numpy.pi/2)
elif total_time*t[k]>600:
u[k,1,:] = (numpy.pi/2)*0.27
pi = pi_time*numpy.ones(p)
else:
############### Naive
t_shaped = numpy.reshape(t,(N,1))
t_matrix = t_shaped*numpy.ones((N,s))
t_flip_shaped = numpy.flipud(numpy.reshape(t,(N,1)))
#t_flip_matrix = t_flip_shaped*numpy.ones((N,s))
x[:,0,:] = h_final*t_matrix
x[:,1,:] = V_final*t_matrix
x[:,2,:] = gamma_initial*t_flip_shaped
x[:,3,:] = (m_initial)*t_flip_shaped
# x[:,0,:] = (numpy.pi/4)*numpy.ones((N,s))
# x[:,1,:] = V_final*numpy.ones((N,s))
# x[:,2,:] = (numpy.pi/4)*(numpy.ones((N,s)))
# x[:,3,:] = (m_initial)*numpy.ones((N,s))
u[:,0,:] = (0.005)*numpy.ones((N,s))
u[:,1,:] = (0.5)*numpy.ones((N,s))
pi = 500*numpy.ones(s)
#
elif initMode == 'naive2':
inpFile = opt.get('confFile','defaults/probRock.its')
sol = naivGues(inpFile,extLog=self.log)
# Get the parameters from the sol object
self.constants = sol.constants
self.restrictions = sol.restrictions
self.boundary = sol.boundary
self.mPayl = sol.mPayl
self.isStagSep = sol.isStagSep
self.addArcs = sol.addArcs
self.N, self.p, self.q, self.s = sol.N, sol.p, sol.q, sol.s
self.dt, self.t = sol.dt, sol.t
self.Ns = sol.Ns
self.tol = sol.tol
# These go outside because of the bypass that comes later
x, pi = sol.x, sol.pi
# Doing here just to undo later. Counter-productive, I know.
u = numpy.empty((self.N,self.m,self.s))
u[:,0,:], u[:,1,:] = sol.calcDimCtrl()
# all info retrieved; the sol object can now be safely deleted
del sol
elif initMode == 'extSol':
###################################################################
# STEP 1: run itsme
inpFile = opt.get('confFile','defaults/probRock.its')
self.log.printL("Starting ITSME with input = " + inpFile)
t_its, x_its, u_its, tabAlpha, tabBeta, inputDict, tphases, \
mass0, massJet = itsme.sgra(inpFile)
# 'inputDict' corresponds to the 'con' dictionary from itsme.
self.log.printL("\nITSME was run sucessfully, " + \
"proceding adaptations...")
###################################################################
# STEP 2: Load constants from file (actually, via inputDict)
self.storePars(inputDict,inpFile)
# This is specific to this initMode (itsme)
self.boundary['m_initial'] = x_its[0, 3]
# For lazy referencing below:
N, addArcs, s = self.N, self.addArcs, self.s
TargHeig = self.boundary['TargHeig']
constants = self.constants
###################################################################
# STEP 3: Set up the arcs, handle stage separation points
# Find indices for beginning of arc
arcBginIndx = numpy.empty(s+1,dtype='int')
arc = 0; arcBginIndx[arc] = 0
nt = len(t_its)
# The goal here is to find the indexes in the x_its array that
# correspond to where the arcs begin, hence, assembling the
# 'arcBginIndx' array.
# First, find the times for the targeted heights:
j = 0
for hTarg in TargHeig:
# search for target height
keepLook = True
while keepLook and (j < nt):
if x_its[j,0] > hTarg:
# Found the index!
arc += 1; arcBginIndx[arc] = j; keepLook = False
#
j+=1
#
#
# Second, search for the times with jettisoned masses:
nmj = len(massJet)
for i in range(nmj):
if massJet[i] > 0.0:
# Jettisoned mass found!
arc += 1; tTarg = tphases[i]; keepLook = True
while keepLook and (j < nt):
if abs(t_its[j]-tTarg) < 1e-10:
# TODO: this hardcoded 1e-10 may cause problems...
# Found the proper time!
# get the next time for proper initial conditions
j += 1; arcBginIndx[arc] = j; keepLook = False
#
j += 1
#
#
#
# Finally, set the array of interval lengths
pi = numpy.empty(s)
for arc in range(s):
pi[arc] = t_its[arcBginIndx[arc+1]] - t_its[arcBginIndx[arc]]
# Set up the variation omission configuration:
# list of variations after omission
mat = numpy.eye(self.q)
# matrix for omitting equations
# Assemble the list of equations to be omitted (start by omitting none)
omitEqMatList = list(range(self.q))
# Omit one equation for each assigned state (height)
Ns = 2 * self.n * self.s + self.p
for arc in range(addArcs-1,-1,-1):
i = 5 + 5 * arc
#psi[i + 1] = x[0, 0, arc + 1] - TargHeig[arc]
omitEqMatList.pop(i)
# Removing the first n elements, corresponding to the initial states
for i in range(self.n):
omitEqMatList.pop(0)
self.omitEqMat = mat[omitEqMatList, :]
# list of variations after omission
omitVarList = list(range(Ns + 1))
# this is how it works with 1 added arc
#self.omitVarList = [ # states for 1st arc (all omitted)
# 4, 5, 6, 7, # Lambdas for 1st arc
# 9, 10, 11, # states for 2nd arc (height omitted)
# 12, 13, 14, 15, # Lambdas for 2nd arc
# 16, 17, # pi's, 1st and 2nd arc
# 18] # final variation
for arc in range(addArcs - 1, -1, -1):
i = 2 * self.n * (arc+1)
# states in order: height (2x), speed, flight angle and mass
# psi[i + 1] = x[0, 0, arc + 1] - TargHeig[arc]
omitVarList.pop(i)
# Removing the first n elements, corresponding to the initial states
for i in range(self.n):
omitVarList.pop(0)
self.omitVarList = omitVarList
self.omit = True
###################################################################
# STEP 4: Re-integrate the differential equation with a fixed step
self.log.printL("Re-integrating ITSME solution with fixed " + \
"step scheme...")
# Re-integration of proposed solution (RK4)
# Only the controls are used, not the integrated state itself
x = numpy.zeros((N,n,s)); u = numpy.zeros((N,m,s))
for arc in range(s):
# dtd: dimensional time step
dtd = pi[arc]/(N-1); dtd6 = dtd/6.0
x[0,:,arc] = x_its[arcBginIndx[arc],:]
t0arc = t_its[arcBginIndx[arc]]
uip1 = numpy.array([tabAlpha.value(t0arc),
tabBeta.value(t0arc)])
# td: dimensional time (for integration)
for i in range(N-1):
td = t0arc + i * dtd
ui = uip1
u[i,:,arc] = ui
uipm = numpy.array([tabAlpha.value(td+.5*dtd),
tabBeta.value(td+.5*dtd)])
uip1 = numpy.array([tabAlpha.value(td+dtd),
tabBeta.value(td+dtd)])
# this bypass just ensures consistency for control
if i == N-2 and arc == s-1:
uip1 = ui
x1 = x[i,:,arc]
f1 = calcXdot(td,x1,ui,constants,arc)
tdm = td+.5*dtd # time at half the integration interval
x2 = x1 + .5 * dtd * f1 # x at half step, with f1
f2 = calcXdot(tdm,x2,uipm,constants,arc)
x3 = x1 + .5 * dtd * f2 # x at half step, with f2
f3 = calcXdot(tdm,x3,uipm,constants,arc)
x4 = x1 + dtd * f3 # x at next step, with f3
f4 = calcXdot(td+dtd,x4,uip1,constants,arc)
x[i+1,:,arc] = x1 + dtd6 * (f1+f2+f2+f3+f3+f4)
#
u[N-1,:,arc] = u[N-2,:,arc]
#
lam = numpy.zeros((self.N,n,self.s))
mu = numpy.zeros(self.q)
# Bypass
ones = numpy.ones(self.s)
self.restrictions['alpha_min'] = -3.0*numpy.pi/180.0 * ones
self.restrictions['alpha_max'] = 3.0*numpy.pi/180.0 * ones
# ThrustFactor = 2.0#500.0/40.0
# self.constants['Thrust'] *= ThrustFactor
# # Re-calculate the Kpf, since it scales with Thrust...
# #self.constants['Kpf'] *= ThrustFactor
# u[:,1,:] *= 1.0/ThrustFactor
u = self.calcAdimCtrl(u[:,0,:],u[:,1,:])
self.x, self.u, self.pi = x, u, pi
self.lam, self.mu = lam, mu
solInit = self.copy()
# This segment does the alterations on itsme solution to yield the
# Miele ratios (TWR=1.3, WL = 1890.)
# self.log.printL("\nRestoring initial solution.")
# self.calcP()
# while self.P > self.tol['P']:
# self.rest(parallelOpt={'restLMPBVP':True})
# self.log.printL("\nSolution was restored. ")
#
# TWR = self.constants['Thrust'][0] / self.boundary['m_initial'] / self.constants['grav_e']
# TWR_targ = 1.3
# dm = (TWR/TWR_targ) * self.boundary['m_initial']/30.
# sign = 1.
# while abs(TWR-TWR_targ)>0.0001:
# self.log.printL("TWR = {:.4G}. Time to change that mass!".format(TWR))
# #input("\nI am about to mess things up. Be careful. ")
# #dm = 10.
# #self.x[:,3,:] += dm
# if sign * (TWR - TWR_targ) < 0:
# dm = -dm/2.
# sign *= -1.
# self.boundary['m_initial'] += dm
# self.log.printL("\nDone. Let's restore it again.")
# self.calcP()
# while self.P > self.tol['P']:
# self.rest(parallelOpt={'restLMPBVP':True})
# TWR = self.constants['Thrust'][0] / self.boundary['m_initial'] / self.constants['grav_e']
#
# #self.compWith(solInit,altSolLabl='itsme',piIsTime=False)
#
# S = self.constants['s_ref'][0] # km²
# WL_targ = 1890. # kgf/m²
# S_targ = (self.boundary['m_initial'] / WL_targ) * 1e-6 # km²
# dS = (S_targ - S) / 10. # km²
# print("S = {:.4G} km², S_targ = {:.4G} km²".format(S, S_targ))
# sign = 1.
# while abs(S - S_targ) > S_targ * 1e-8:
# self.log.printL(
# "WL = {:.4G} kgf/m². Time to change that area!".format(self.boundary['m_initial'] / (S * 1e6)))
# # input("\nI am about to mess things up. Be careful. ")
# # dm = 10.
# # self.x[:,3,:] += dm
# if sign * (S_targ - S) < 0:
# dS = -dS / 2.
# sign *= -1.
# self.constants['s_ref'] += dS
# S = self.constants['s_ref'][0]
# self.log.printL("\nDone. Let's restore it again.")
# self.calcP()
# while self.P > self.tol['P']:
# self.rest(parallelOpt={'restLMPBVP': True})
# # self.compWith(solInit,altSolLabl='itsme',piIsTime=False)
#
# plt.plot(self.t * self.pi[0], self.x[:, 2, 0] / d2r)
# plt.xlabel('t [s]')
# plt.ylabel('gamma [deg]')
# plt.grid()
# plt.show()
#
# self.plotTraj(mustSaveFig=False)
# =============================================================================
# # Basic desaturation:
#
# # TODO: This hardcoded bypass MUST be corrected in later versions.
if initMode == 'extSol':
msg = "\n!!!\nHeavy hardcoded bypass here:\n" + \
"Control limits are being switched;\n" + \
"Controls themselves are being 'desaturated'.\n" + \
"Check code for the values, and be careful!\n"
self.log.printL(msg)
bat = 1.5
for arc in range(self.s):
for k in range(self.N):
if u[k,1,arc] < -bat:
u[k,1,arc] = -bat
if u[k,1,arc] > bat:
u[k,1,arc] = bat
# This was a test for a "super honest" desaturation, so that the
# program would not know when to do the coasting a priori.
# It turns out this does not actually happen because the "coasting
# information" is already "encoded" in the states (h,v,gama,m); so
# probably the restoration simply puts the coasting back. Hence,
# there is this...
# TODO: Try to put this before the RK4 re-integration. If this works,
# it would be a great candidate to a less-naive method.
# =============================================================================
self.u = u
self.compWith(solInit,'Initial guess')
self.plotSol(piIsTime=False)
self.plotSol()#opt={'mode':'orbt'})
self.plotF()
self.log.printL("\nInitialization complete.\n")
return solInit
#%%
def calcDimCtrl(self,ext_u = None):
"""Calculate variables alpha (angle of attack) and beta (thrust), from
either the object's own control (self.u) or external control
(additional parameter needed)."""
restrictions = self.restrictions
alpha_min = restrictions['alpha_min']
alpha_max = restrictions['alpha_max']
beta_min = restrictions['beta_min']
beta_max = restrictions['beta_max']
alfa = numpy.empty((self.N,self.s))
beta = numpy.empty((self.N,self.s))
if ext_u is None:
for arc in range(self.s):
alfa[:,arc] = .5*((alpha_max[arc] + alpha_min[arc]) +
(alpha_max[arc] - alpha_min[arc]) *
numpy.tanh(self.u[:,0,arc]))
beta[:,arc] = .5*((beta_max[arc] + beta_min[arc]) +
(beta_max[arc] - beta_min[arc]) *
numpy.tanh(self.u[:,1,arc]))
else:
for arc in range(self.s):
alfa[:,arc] = .5*((alpha_max[arc] + alpha_min[arc]) +
(alpha_max[arc] - alpha_min[arc]) *
numpy.tanh(ext_u[:,0,arc]))
beta[:,arc] = .5*((beta_max[arc] + beta_min[arc]) +
(beta_max[arc] - beta_min[arc]) *
numpy.tanh(ext_u[:,1,arc]))
return alfa, beta
def calcAdimCtrl(self,alfa,beta):
"""Calculate adimensional control 'u' based on external arrays for
alpha (ang. of attack) and beta (thrust). """
Nu = len(alfa)
s = self.s
u = numpy.empty((Nu,2,s))
alpha_min = self.restrictions['alpha_min']
alpha_max = self.restrictions['alpha_max']
beta_min = self.restrictions['beta_min']
beta_max = self.restrictions['beta_max']
a1 = .5*(alpha_max + alpha_min)
a2 = .5*(alpha_max - alpha_min)
b1 = .5*(beta_max + beta_min)
b2 = .5*(beta_max - beta_min)
for arc in range(self.s):
alfa[:,arc] -= a1[arc]
alfa[:,arc] *= 1.0/a2[arc]
beta[:,arc] -= b1[arc]
beta[:,arc] *= 1.0/b2[arc]
u[:,0,:] = alfa.copy()
u[:,1,:] = beta.copy()
sat = 0.99999
# Basic saturation
for arc in range(s):
for j in range(2):
for k in range(Nu):
if u[k,j,arc] > sat:
u[k,j,arc] = sat
elif u[k,j,arc] < -sat:
u[k,j,arc] = -sat
u = numpy.arctanh(u)
return u
def calcPhi(self):
N,n,s = self.N,self.n,self.s
constants = self.constants
grav_e = constants['grav_e']
Thrust = constants['Thrust']
Isp = constants['Isp']
r_e = constants['r_e']
GM = constants['GM']
CL0 = constants['CL0']
CL1 = constants['CL1']
CD0 = constants['CD0']
CD2 = constants['CD2']
s_ref = constants['s_ref']
DampCent = constants['DampCent']
DampSlop = constants['DampSlop']
sin, cos = numpy.sin, numpy.cos
alpha,beta = self.calcDimCtrl()
x, pi = self.x, self.pi
# calculate variables CL and CD
CL = numpy.empty_like(alpha)
CD = numpy.empty_like(alpha)
for arc in range(s):
CL[:,arc] = CL0[arc] + CL1[arc]*alpha[:,arc]
CD[:,arc] = CD0[arc] + CD2[arc]*(alpha[:,arc]**2)
# calculate L and D
# TODO: making atmosphere.rho vectorized (array compatible) would
# increase performance significantly!
dens = numpy.empty((N,s))
for arc in range(s):
dens[:,arc] = rhoSGRA(x[:,0,arc])
pDynTimesSref = numpy.empty_like(CL)
for arc in range(s):
pDynTimesSref[:,arc] = .5 * dens[:,arc] * \
(x[:,1,arc]**2) * s_ref[arc]
L = CL * pDynTimesSref
D = CD * pDynTimesSref
# calculate r
r = r_e + x[:,0,:]
# calculate grav
grav = GM/r/r
# calculate phi:
phi = numpy.empty((N,n,s))
sinGama = sin(x[:,2,:]); cosGama = cos(x[:,2,:])
sinAlfa = sin(alpha); cosAlfa = cos(alpha)
accDimTime = 0.0
for arc in range(s):
td = accDimTime + pi[arc] * self.t # Dimensional time
phi[:,0,arc] = x[:,1,arc] * sinGama[:,arc]
phi[:,1,arc] = (beta[:,arc] * Thrust[arc] * cosAlfa[:,arc] +
- D[:,arc])/x[:,3,arc] \
- grav[:,arc] * sinGama[:,arc]
phi[:,2,arc] = ((beta[:,arc] * Thrust[arc] * sinAlfa[:,arc] +
+ L[:,arc])/(x[:,3,arc] * x[:,1,arc]) +
cosGama[:,arc] * ( x[:,1,arc]/r[:,arc] +
- grav[:,arc]/x[:,1,arc] )) * \
.5*(1.0+numpy.tanh(DampSlop*(td-DampCent)))
phi[:,3,arc] = - (beta[:,arc] * Thrust[arc])/(grav_e * Isp[arc])
phi[:,:,arc] *= pi[arc]
accDimTime += pi[arc]
return phi
def calcAcc(self):
""" Calculate tangential acceleration."""
acc = numpy.empty((self.N,self.s))
phi = self.calcPhi()
for arc in range(self.s):
acc[:,arc] = phi[:,1,arc] / self.pi[arc]
return acc
#%%
def calcGrads(self,calcCostTerm=True):
# Pre-assign functions
sin = numpy.sin; cos = numpy.cos; tanh = numpy.tanh
# Load constants
N, n, m, p, q, s = self.N, self.n, self.m, self.p, self.q, self.s
addArcs = self.addArcs
constants = self.constants
grav_e = constants['grav_e']; MaxThrs = constants['Thrust']
Isp = constants['Isp']; g0Isp = Isp * grav_e
r_e = constants['r_e']; GM = constants['GM']
CL0 = constants['CL0']; CL1 = constants['CL1']
CD0 = constants['CD0']; CD2 = constants['CD2']
s_ref = constants['s_ref']
DampCent = constants['DampCent']; DampSlop = constants['DampSlop']
Kpf = constants['Kpf']; PFmode = constants['PFmode']
restrictions = self.restrictions
alpha_min = restrictions['alpha_min']
alpha_max = restrictions['alpha_max']
beta_min = restrictions['beta_min']
beta_max = restrictions['beta_max']
acc_max = restrictions['acc_max']
# Load states, controls
u1 = self.u[:,0,:]; u2 = self.u[:,1,:]
tanhU1 = tanh(u1); tanhU2 = tanh(u2)
pi = self.pi
acc = self.calcAcc()
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))
fOrig_u = numpy.zeros((N,m,s)); fPF_u = numpy.empty_like(fu)
## Psi derivatives
# For reference:
# y = [x[0,:,0],\
# x[N-1,:,0],\
# x[0,:,1],\
# x[N-1,:,0],\
# ...,\
# x[0,:,s-1],
# x[N-1,:,s-1]]
# first arc - second arc
#psi[4] = x[N-1,0,0] - 50.0e-3
#psi[5] = x[0,0,1] - 50.0e-3
#psi[6] = x[0,1,1] - x[N-1,1,0]
#psi[7] = x[0,2,1] - x[N-1,2,0]
#psi[8] = x[0,3,1] - x[N-1,3,0]
# second arc - third arc
#psi[9] = x[N-1,0,1] - 2.
#psi[10] = x[0,0,2] - 2.
#psi[11] = x[0,1,2] - x[N-1,1,1]
#psi[12] = x[0,2,2] - x[N-1,2,1]
#psi[13] = x[0,3,2] - x[N-1,3,1]
# y = [h(t=0,s=0), 0
# v(t=0,s=0), 1
# g(t=0,s=0), 2
# m(t=0,s=0), 3
# h(t=1,s=0), 4
# v(t=1,s=0), 5
# g(t=1,s=0), 6
# m(t=1,s=0), 7
# h(t=0,s=1), 8
# v(t=0,s=1), 9
# g(t=0,s=1), 10
# m(t=0,s=1), 11
# h(t=1,s=1), 12
# v(t=1,s=1), 13
# g(t=1,s=1), 14
# m(t=1,s=1), 15
# h(t=0,s=2), 16
# v(t=0,s=2), 17
# g(t=0,s=2), 18
# m(t=0,s=2), 19
# h(t=1,s=2), 20
# v(t=1,s=2), 21
# g(t=1,s=2), 22
# m(t=1,s=2)] 23
psiy = numpy.zeros((q,2*n*s))
s_f = self.constants['s_f']
# First n rows: all states have assigned values
for ind in range(n):
psiy[ind,ind] = 1.0
# Intermediate conditions: extra arcs
i0 = n; j0 = n
for arc in range(addArcs):
# This loop sets the interfacing conditions between all states
# in 'arc' and 'arc+1' (that's why it only goes up to s-1)
#self.log.printL("arc = "+str(arc))
# For height:
psiy[i0,j0] = 1.0 # height, this arc
#self.log.printL("Writing on ["+str(i0)+","+str(j0)+"] : 1.0")
psiy[i0+1,j0+n] = 1.0 # height, next arc
#self.log.printL("Writing on ["+str(i0+1)+","+str(j0+n)+"] : 1.0")
# For speed, angle and mass:
for stt in range(1,n):
psiy[i0+stt+1,j0+stt] = -1.0 #this state, this arc (end cond)
#self.log.printL("Writing on ["+str(i0+stt+1)+","+\
#str(j0+stt)+"] : -1.0")
psiy[i0+stt+1,j0+stt+n] = 1.0 #this state, next arc (init cond)
#self.log.printL("Writing on ["+str(i0+stt+1)+","+\
#str(j0+stt+n)+"] : 1.0")
i0 += n + 1
j0 += 2*n
#
# Intermediate conditions
#self.log.printL("End of first for, i0 = "+str(i0)+", j0 = "+str(j0))
for arc in range(addArcs,s-1):
# This loop sets the interfacing conditions between all states
# in 'arc' and 'arc+1' (that's why it only goes up to s-1)
# For height, speed and angle:
for stt in range(n-1):
psiy[i0+stt,j0+stt] = -1.0 # this state, this arc (end cond)
#self.log.printL("Writing on ["+str(i0+stt)+","+\
#str(j0+stt)+"] : -1.0")
psiy[i0+stt,j0+stt+n] = 1.0 # this state, next arc (init cond)
#self.log.printL("Writing on ["+str(i0+stt)+","+\
#str(j0+stt+n)+"] : 1.0")
# For mass:
stt = n-1
#initMode = self.initMode
#if initMode == 'extSol':
if self.isStagSep[arc]:
# mass, next arc (init cond)
psiy[i0+stt,j0+stt+n] = 1.0
#self.log.printL("Writing on ["+str(i0+stt)+","+\
#str(j0+stt+n)+"] : 1.0")
# mass, this arc (end cond):
psiy[i0+stt,j0+stt] = -1.0/(1.0-s_f[arc])
#self.log.printL("Writing on ["+str(i0+stt)+","+\
#str(j0+stt)+"] : -1/(1-e)...")
# mass, this arc (init cond):
psiy[i0+stt,j0+stt-n] = s_f[arc]/(1.0-s_f[arc])
#self.log.printL("Writing on ["+str(i0+stt)+","+\
#str(j0+stt-n)+"] : +e/(1-e)...")
else:
psiy[i0+stt,j0+stt] = -1.0 # mass, this arc (end cond)
#self.log.printL("Writing on ["+str(i0+stt)+","+\
#str(j0+stt)+"] : -1.0")
psiy[i0+stt,j0+stt+n] = 1.0 # mass, next arc (init cond)
#self.log.printL("Writing on ["+str(i0+stt)+","+\
#str(j0+stt+n)+"] : 1.0")
i0 += n
j0 += 2*n
#
# Last n-1 rows (no mass eq for end condition of final arc):
for ind in range(n-1):
psiy[q-1-ind,2*n*s-2-ind] = 1.0
psip = numpy.zeros((q,p))
# calculate r, V, etc
r = r_e + self.x[:,0,:]; r2 = r * r; r3 = r2 * r
V = self.x[:,1,:]; V2 = V * V
# GAMMA FACTOR (fdg)
fdg = numpy.empty_like(r)
td0 = 0.0
for arc in range(s):
td = td0 + self.t * pi[arc] # dimensional time
fdg[:,arc] = .5*(1.0+tanh(DampSlop*(td-DampCent)))
td0 += pi[arc]
m = self.x[:,3,:]
m2 = m * m
sinGama, cosGama = sin(self.x[:,2,:]), cos(self.x[:,2,:])
# Calculate variables (arrays) alpha and beta
# TODO: change calcDimCtrl so that the derivatives
# DAlfaDu1 and DBetaDu2 are also calculated there...
# (with an optional command so that these are not calculated all the
# time, of course!)
alpha,beta = self.calcDimCtrl()
sinAlpha, cosAlpha = sin(alpha), cos(alpha)
# Derivatives
DAlfaDu1 = .5 * (alpha_max - alpha_min) * (1.0 - tanhU1**2)
DBetaDu2 = .5 * (beta_max - beta_min) * (1.0 - tanhU2**2)