-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chicago.py
1761 lines (1320 loc) · 53.5 KB
/
Chicago.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
# coding: utf-8
# # Chicago: "we makin' cars"
# Implement the Formula SAE contectualized design problem from Zurita et al
# ## TO DO: CHECK UNITS
# everywhere, esp when importing tables
# In[95]:
import numpy as np
import pandas as pd
from scipy.stats import chi
# from opteval import benchmark_func as bf
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import copy
import time as timer
import threading
import pickle
# from sklearn import linear_model
# ## Helper Functions
# In[2]:
def cp(x): #make a copy instead of reference
return copy.deepcopy(x)
def isNumber(s):
try:
float(s)
return True
except ValueError:
return False
def isNaN(num):
return num != num
def mean(x):
return np.mean(x)
def norm(x):
return float(np.linalg.norm(x))
def dist(x,y):
return np.linalg.norm(np.array(x)-np.array(y))
def bounds(x,low,high):
if x > high:
return high
if x < low:
return low
return x
# In[3]:
def makeAiScore():
ai = np.random.normal(97,17)
ai = bounds(ai, 40,150)
return ai
def makeIqScore(): #this IQ ranges from 0 to 1, bc it is basically efficiency
iq = np.random.normal(0.5,0.2)
iq = bounds(iq, 0.1,1.0)
return iq
def pickWorseScore(betterScore,worseScore,temperature):
if temperature <=0: #never pick worse answers, and avoid devide by 0
return False
if np.random.uniform(0,1) < np.exp((betterScore-worseScore)/temperature): #
return True
return False
def calculateDecay(steps,T0=1.0,Tf=0.01):
if T0<=Tf or T0<=0:
return 0
return (Tf / float(T0) ) ** (1/steps)
def calculateAgentDecay(agent, steps):
E_N = normalizedE(agent.kai.E)
E_transformed = np.exp((E_N*-1)+3.3)
startEndRatio = bounds(1/E_transformed, 1E-10,1)
T0 = agent.temp
TF = T0 * startEndRatio
return calculateDecay(steps,T0,TF)
# ## constants and params
# In[4]:
complexSharing = True #if False, shareBasic() is used, eg strictly-greedy one-dimension jump
commBonus = 10 #increasing the communication bonus makes successful communication more likely
commSd = 20 #increasing standard deviation of communication succcess makes it less predictable
selfBias = 0 #increasing self bias will make agents choose their solutions more over others
startRange = 10
nDims = 2
SO_STRENGTH = 1
RG_STRENGTH = 1
TEAM_MEETING_COST = 1 #1 turn
ROUGHNESS = 0.02
VERBOSE = False
AVG_SPEED = 1
SD_SPEED = .5
MIN_SPEED = 0
AVG_TEMP = 1
SD_TEMP = 0.5
# ## Load Table of parameters
# In[5]:
#FIRST TIME:
paramsDF = pd.read_csv("./SAE/paramDB.csv")
paramsDF.columns = ['paramID','name','variable','team','kind','minV','maxV','used']
# paramsDF.at[3,"maxV"] = np.pi/4
# paramsDF.at[10,"maxV"] = np.pi/4
paramsDF.at[17,"maxV"] = np.pi /4
paramsDF.used = pd.to_numeric(paramsDF.used)
paramsDF = paramsDF.drop(columns=["paramID"],axis=1)
#remove unused variables... print(len(paramsDF))
paramsDF = paramsDF.loc[paramsDF.used > 0 ]
paramsDF.to_csv("./SAE/paramDBreduced.csv")
paramsDF = pd.read_csv("./SAE/paramDBreduced.csv")
print(len(paramsDF))
paramsDF = paramsDF.drop(["used"],axis=1)
paramsDF.head()
# In[6]:
paramsDF.loc[paramsDF.variable == "asw"]
# In[7]:
#logical vector for parameters with fixed min/max (TRUE), or min/max as f(p) (FALSE)
hasNumericBounds = [True if isNumber(row.minV) and isNumber(row.maxV) else False for i, row in paramsDF.iterrows()]
# In[8]:
# materialsDF = pd.read_csv("/Users/samlapp/Documents/THRED Lab/SAE/materials.csv")
# materialsDF.q = [int(1 + np.random.uniform(0.98,1.02)*materialsDF.iloc[i]['q']) for i in range(len(materialsDF))]
# materialsDF.to_csv("/Users/samlapp/Documents/THRED Lab/SAE/materialsTweaked.csv")
materialsDF = pd.read_csv("./SAE/materialsTweaked.csv")
materialsDF.head()
# In[9]:
tiresDF = pd.read_csv("./SAE/tires.csv")
tiresDF
# In[10]:
# motorsDF = pd.read_csv("/Users/samlapp/Documents/THRED Lab/SAE/motors.csv")
# # first time: we want to make motors with the same power slightly different:
# motorsDF.Power = [int(1 + np.random.uniform(0.98,1.02)*motorsDF.iloc[i]['Power']) for i in range(len(motorsDF))]
# motorsDF.to_csv("/Users/samlapp/Documents/THRED Lab/SAE/motorsTweaked.csv")
enginesDF = pd.read_csv("./SAE/motorsTweaked.csv")
print("unique" if len(enginesDF)-len(np.unique(enginesDF.Power)) == 0 else "not uniuqe")
enginesDF.columns = ["ind","id","name","le","we","he","me","Phi_e","T_e"]
enginesDF.head()
# In[11]:
# susDF = pd.read_csv("/Users/samlapp/Documents/THRED Lab/SAE/suspension.csv")
# susDF.krsp = [int(np.random.uniform(0.98,1.02)*susDF.iloc[i]['krsp']) for i in range(len(susDF))]
# susDF.kfsp = susDF.krsp
# susDF.to_csv("/Users/samlapp/Documents/THRED Lab/SAE/suspensionTweaked.csv")
susDF = pd.read_csv("./SAE/suspensionTweaked.csv")
print("unique" if len(susDF)-len(np.unique(susDF.krsp)) == 0 else "not uniuqe")
susDF = susDF.drop(columns=[susDF.columns[0]])
susDF.head()
# In[12]:
# brakesDF = pd.read_csv("/Users/samlapp/Documents/THRED Lab/SAE/brakes.csv")
# brakesDF.columns = [a.strip() for a in brakesDF.columns]
# brakesDF.rbrk = [np.random.uniform(0.98,1.02)*brakesDF.iloc[i]['rbrk'] for i in range(len(brakesDF))]
# brakesDF.to_csv("/Users/samlapp/Documents/THRED Lab/SAE/brakesTweaked.csv")
brakesDF = pd.read_csv("./SAE/brakesTweaked.csv")
print("unique" if len(brakesDF)-len(np.unique(brakesDF['rbrk'])) == 0 else "not uniuqe")
brakesDF = brakesDF.drop(columns=[brakesDF.columns[0]])
brakesDF.head()
# In[13]:
paramsDF.variable
# In[14]:
class Params:
def __init__(self,v = paramsDF):
self.vars = v.variable
self.team = v.team
for i, row in v.iterrows():
setattr(self, row.variable.strip(),-1)
p = Params()
for v in p.vars:
value = np.random.uniform()
setattr(p,v,value)
paramsDF.loc[paramsDF.variable=="hrw"]["team"][0]
teams = np.unique(paramsDF.team)
teamDimensions = [[row.team == t for i, row in paramsDF.iterrows()] for t in teams]
teamDictionary = {}
for i in range(len(teams)):
teamDictionary[teams[i]] = teamDimensions[i]
paramList = np.array(paramsDF.variable)
# In[15]:
#convert parameter vector to Parameter object
def asParameters(pList):
p = Params()
pNames = paramsDF.variable
for i in range(len(pList)):
pName = pNames[i]
pValue = pList[i]
setattr(p,pName,pValue)
return p
def asVector(params):
r = np.zeros(len(paramsDF))
for i in range(len(paramsDF)):
pName = paramsDF.variable[i]
pValue = getattr(params,pName)
r[i] = pValue
return r
# ## Objective Subfunctions
# ### constants
#
# The car’s top velocity vcar is 26.8 m/s (60 mph).
#
# The car’s engine speed x_e is 3600 rpm.
#
# The density of air q_air during the race is 1.225 kg/m3.
#
# The track radio of curvature r_track is 9 m.
#
# The pressure applied to the brakes Pbrk is 1x10^7 Pa
#
# In[16]:
#scale parameters to go between unit cube (approximately) and SI units
paramMaxValues = []
# In[17]:
v_car = 26.8 #m/s (60 mph)
w_e = 3600 * 60 * 2 *np.pi #rpm to radians/sec
rho_air = 1.225 #kg/m3.
r_track = 9 #m
P_brk = 10**7 #Pascals
C_dc = 0.04 #drag coefficient of cabin
gravity = 9.81 #m/s^2
# In[18]:
#mass (minimize)
def mrw(p):
return p.lrw * p.wrw *p.hrw * p.qrw
def mfw(p):
return p.lfw * p.wfw *p.hfw * p.qfw
def msw(p):
return p.lsw * p.wsw *p.hsw * p.qsw
def mia(p):
return p.lia * p.wia *p.hia * p.qia
def mc(p):
return 2*(p.hc*p.lc*p.tc + p.hc*p.wc*p.tc + p.lc*p.hc*p.tc)*p.qc
def mbrk(p):
#CHRIS missing parameters: how is mbrk calculated? assuming lrw*rho
return p.lbrk * p.wbrk * p.hbrk * p.qbrk
def mass(p): #total mass, minimize
mass = mrw(p) + mfw(p) + 2 * msw(p) + 2*p.mrt + 2*p.mft + p.me + mc(p) + mia(p) + 4*mbrk(p) + 2*p.mrsp + 2*p.mfsp
return mass
# In[19]:
#center of gravity height, minimize
def cGy(p):
t1 = (mrw(p)*p.yrw + mfw(p)*p.yfw+ p.me*p.ye + mc(p)*p.yc + mia(p)*p.yia) / mass(p)
t2 = 2* (msw(p)*p.ysw + p.mrt*p.rrt + p.mft*p.rft + mbrk(p)*p.rft + p.mrsp*p.yrsp + p.mfsp*p.yfsp) / mass(p)
return t1 + t2
# In[20]:
#Drag (minimize) and downforce (maximize)
def AR(w,alpha,l): #aspect ratio of a wing
return w* np.cos(alpha) / l
def C_lift(AR,alpha): #lift coefficient of a wing
return 2*np.pi* (AR / (AR + 2)) * alpha
def C_drag(C_lift, AR): #drag coefficient of wing
return C_lift**2 / (np.pi * AR)
def F_down_wing(w,h,l,alpha,rho_air,v_car): #total downward force of wing
wingAR = AR(w,alpha,l)
C_l = C_lift(wingAR, alpha)
return 0.5 * alpha * h * w * rho_air * (v_car**2) * C_l
def F_drag_wing(w,h,l,alpha,rho_air,v_car): #total drag force on a wing
wingAR = AR(w,alpha,l)
# print(wingAR)
C_l = C_lift(wingAR, alpha)
# print(C_l)
C_d = C_drag(C_l,wingAR)
# print(C_d)
return F_drag(w,h,rho_air,v_car,C_d)
def F_drag(w,h,rho_air,v_car,C_d):
return 0.5*w*h*rho_air*v_car**2*C_d
def F_drag_total(p): #total drag on vehicle
cabinDrag = F_drag(p.wc,p.hc,rho_air,v_car,C_dc)
rearWingDrag = F_drag_wing(p.wrw,p.hrw,p.lrw,p.arw,rho_air,v_car)
frontWingDrag = F_drag_wing(p.wfw,p.hfw,p.lfw,p.afw,rho_air,v_car)
sideWingDrag = F_drag_wing(p.wsw,p.hsw,p.lsw,p.asw,rho_air,v_car)
return rearWingDrag + frontWingDrag + 2* sideWingDrag + cabinDrag
def F_down_total(p): #total downforce
downForceRearWing = F_down_wing(p.wrw,p.hrw,p.lrw,p.arw,rho_air,v_car)
downForceFrontWing = F_down_wing(p.wfw,p.hfw,p.lfw,p.afw,rho_air,v_car)
downForceSideWing = F_down_wing(p.wsw,p.hsw,p.lsw,p.asw,rho_air,v_car)
return downForceRearWing + downForceFrontWing + 2*downForceSideWing
# In[21]:
#acceleration (maximize)
def rollingResistance(p,tirePressure,v_car):
C = .005 + 1/tirePressure * (.01 + .0095 * (v_car**2))
return C * mass(p) * gravity
def acceleration(p):
mTotal = mass(p)
tirePressure = p.Prt #CHRIS should it be front or rear tire pressure?
total_resistance = F_drag_total(p) + rollingResistance(p, tirePressure,v_car)
w_wheels = v_car / p.rrt #rotational speed of rear tires
efficiency = total_resistance * v_car / p.Phi_e
torque = p.T_e
#converted units of w_e from rpm to rad/s !!!
F_wheels = torque * efficiency * w_e /(p.rrt * w_wheels)
return (F_wheels - total_resistance) / mTotal
# acceleration(p)
# In[22]:
#crash force (minimize)
def crashForce(p):
return np.sqrt(mass(p) * v_car**2 * p.wia * p.hia * p.Eia / (2*p.lia))
# In[23]:
#impact attenuator volume (minimize)
def iaVolume(p):
return p.lia*p.wia*p.hia
# In[24]:
#corner velocity (maximize)
y_suspension = 0.05 # m
dydt_suspension = 0.025 #m/s
def suspensionForce(k,c):
return k*y_suspension + c*dydt_suspension
def cornerVelocity(p):
F_fsp = suspensionForce(p.kfsp,p.cfsp)
F_rsp = suspensionForce(p.krsp,p.crsp)
downforce = F_down_total(p)
mTotal = mass(p)
#CHRIS again, rear tire pressure?
C = rollingResistance(p,p.Prt,v_car)
forces = downforce+mTotal*gravity-2*F_fsp-2*F_rsp
if forces < 0:
return 0
return np.sqrt( forces * C * r_track / mTotal )
# cornerVelocity(p)
# In[25]:
#breaking distance (minimize)
def breakingDistance(p):
mTotal = mass(p)
C = rollingResistance(p,p.Prt,v_car)
#CHRIS need c_brk break friction coef, and A_brk (rectangle or circle?)
#breaking torque
A_brk = p.hbrk * p.wbrk
c_brk = .37 #? most standard brake pads is usually in the range of 0.35 to 0.42
Tbrk = 2 * c_brk * P_brk * A_brk * p.rbrk
#y forces:
F_fsp = suspensionForce(p.kfsp,p.cfsp)
F_rsp = suspensionForce(p.krsp,p.crsp)
Fy = mTotal*gravity + F_down_total(p) - 2 * F_rsp - 2*F_fsp
#breaking accelleration
#CHRIS front and rear tire radius are same? (rrt and rft)
a_brk = Fy * C / mTotal + 4*Tbrk*C/(p.rrt*mTotal)
#breaking distance
return v_car**2 / (2*a_brk)
# breakingDistance(p)
# In[26]:
#suspension acceleration (minimize)
def suspensionAcceleration(p):
Ffsp = suspensionForce(p.kfsp,p.cfsp)
Frsp = suspensionForce(p.krsp,p.crsp)
mTotal = mass(p)
Fd = F_down_total(p)
return (2*Ffsp - 2*Frsp - mTotal*gravity - Fd)/mTotal
# suspensionAcceleration(p)
# In[27]:
#pitch moment (minimize)
def pitchMoment(p):
Ffsp = suspensionForce(p.kfsp,p.cfsp)
Frsp = suspensionForce(p.krsp,p.crsp)
downForceRearWing = F_down_wing(p.wrw,p.hrw,p.lrw,p.arw,rho_air,v_car)
downForceFrontWing = F_down_wing(p.wfw,p.hfw,p.lfw,p.afw,rho_air,v_car)
downForceSideWing = F_down_wing(p.wsw,p.hsw,p.lsw,p.asw,rho_air,v_car)
#CHRIS assuming lcg is lc? and lf is ?
lcg = p.lc
lf = 0.5
return 2*Ffsp*lf + 2*Frsp*lf + downForceRearWing*(lcg - p.lrw) - downForceFrontWing*(lcg-p.lfw) - 2*downForceSideWing*(lcg-p.lsw)
# pitchMoment(p)
# ## Global Objective
# In[28]:
#Global objective: linear sum of objective subfunctions
#sub-objectives to maximize will be mirrored *-1 to become minimizing
subObjectives = [mass,cGy,F_drag_total,F_down_total,acceleration,crashForce,iaVolume,cornerVelocity,breakingDistance,suspensionAcceleration,pitchMoment]
alwaysMinimize = [1,1,1,-1,-1,1,1,-1,1,1,1] #1 for minimizing, -1 for maximizing
weightsNull = np.ones(len(subObjectives)) / len(subObjectives)
weights1 = np.array([14,1,20,30,10,1,1,10,10,2,1])/100
weights2 = np.array([25,1,15,20,15,1,1,15,5,1,1])/100
weights3 = np.array([14,1,20,15,25,1,1,10,10,2,1])/100
weightsCustom = np.array([14,1,20,30,11,1,1,10,10,2,0])/100 #pitch moment is zero bc incorrect eqn
def objectiveDetailedNonNormalized(p,weights):
score = 0
subscores = []
for i in range(len(subObjectives)):
obj = subObjectives[i]
subscore = obj(p)
subscores.append(subscore)
score += weights[i]*alwaysMinimize[i]*subscore
return score,subscores
# subscoreMean = np.zeros(len(subObjectives))
# subscoreSd = np.ones(len(subObjectives))
def objective(p,weights):
score = 0
for i in range(len(subObjectives)):
obj = subObjectives[i]
subscore= obj(p)
normalizedSubscore = (subscore - subscoreMean[i]) / subscoreSd[i]
score += weights[i]*alwaysMinimize[i]*normalizedSubscore
return score
def objectiveDetailed(p,weights):
score = 0
subscores = []
for i in range(len(subObjectives)):
obj = subObjectives[i]
subscore= obj(p)
normalizedSubscore = (subscore - subscoreMean[i]) / subscoreSd[i]
subscores.append(normalizedSubscore)
score += weights[i]*alwaysMinimize[i]*normalizedSubscore
return score, subscores
# ## Constraints
# ## constraints not done
# I didnt actually do the constraint functions yet just bounds
#
# In[29]:
#a list with all the min-max functions (!) which can be called to return max and min value as f(p)
minMaxParam = [None for i in range(len(paramsDF))]
def wrw(p):
minV = 0.300
maxV = r_track - 2 * p.rrt
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="wrw"].index[0]] = wrw
# def xrw(p):
# minV = p.lrw / 2
# maxV = .250 - minV
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xrw"].index[0]] = xrw
def yrw(p):
minV = .5 + p.hrw / 2
maxV = 1.2 - p.hrw / 2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="yrw"].index[0]] = yrw
wheelSpace = .1 #?? don't have an equation for this rn, min is .075
aConst = wheelSpace
def lfw(p):
minV = .05
maxV = .7 - aConst
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="lfw"].index[0]] = lfw
f_track = 3 # bounds: 3, 2.25 m
def wfw(p):
minV = .3
maxV = f_track
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="wfw"].index[0]] = wfw
# def xfw(p):
# minV = p.lrw + p.rrt + p.lc + p.lia + p.lfw/2
# maxV = .25 + p.rrt + p.lc + p.lia + p.lfw/2
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xfw"].index[0]] = xfw
xConst = .030 #ground clearance 19 to 50 mm
def yfw(p):
minV = xConst + p.hfw / 2
maxV = .25 - p.hfw/2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="yfw"].index[0]] = yfw
# def xsw(p):
# minV = p.lrw + 2*p.rrt + aConst + p.lsw / 2
# maxV = .250 + 2*p.rrt + aConst + p.lsw / 2
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xsw"].index[0]] = xsw
def ysw(p):
minV = xConst + p.hsw/2
maxV = .250 - p.hsw/2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="ysw"].index[0]] = ysw
# def xrt(p):
# minV = p.lrw + p.rrt
# maxV = .250 + p.rrt
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xrt"].index[0]] = xrt
# def xft(p):
# minV = p.lrw + p.rrt + p.lc
# maxV = .250 + p.rrt + p.lc
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xft"].index[0]] = xft
# def xe(p):
# minV = p.lrw + p.rrt - p.le / 2
# maxV = p.lrw + aConst + p.rrt - p.le / 2
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xe"].index[0]] = xe
def ye(p):
minV = xConst + p.he / 2
maxV = .5 - p.he / 2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="ye"].index[0]] = ye
def hc(p):
minV = .500
maxV = 1.200 - xConst
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="hc"].index[0]] = hc
# def xc(p):
# minV = p.lrw + p.rrt + p.lc / 2
# maxV = .250 + p.rrt + p.lc / 2
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xc"].index[0]] = xc
def yc(p):
minV = xConst + p.hc / 2
maxV = 1.200 - p.hc / 2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="yc"].index[0]] = yc
def lia(p):
minV = .2
maxV = .7 - p.lfw # what is l_fr?
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="lia"].index[0]] = lia
# def xia(p):
# minV = p.lrw + p.rrt + p.lc + p.lia / 2
# maxV = .250 + p.rrt + p.lc + p.lia/ 2
# return minV, maxV
# minMaxParam[paramsDF.loc[paramsDF.variable=="xia"].index[0]] = xia
def yia(p):
minV = xConst + p.hia / 2
maxV = 1.200 - p.hia / 2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="yia"].index[0]] = yia
def yrsp(p):
minV = p.rrt
maxV = p.rrt * 2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="yrsp"].index[0]] = yrsp
def yfsp(p):
minV = p.rft
maxV = p.rft * 2
return minV, maxV
minMaxParam[paramsDF.loc[paramsDF.variable=="yfsp"].index[0]] = yfsp
#test:
# for f in minMaxParam:
# if f is not None:
# print(f(p))
# In[30]:
def getAttr(obj):
return [a for a in dir(obj) if not a.startswith('__')]
# In[31]:
def findMaterialByDensity(rho):
differences = abs(np.array(materialsDF.q) - rho)
material = materialsDF.iloc[np.argmin(differences)]
return material.Code, material.q, material.E
def findTireByRadius(radius):
differences = abs(np.array(tiresDF.radius) - radius)
tire = tiresDF.iloc[np.argmin(differences)]
return tire.ID, tire.radius, tire.mass
def findEngineByPower(power):
differences = abs(np.array(enginesDF.Phi_e) - power)
engine = enginesDF.loc[np.argmin(differences)]
return engine
def findSuspensionByK(k):
differences = abs(np.array(susDF.krsp) - k)
sus = susDF.loc[np.argmin(differences)]
return sus
def findBrakesByR(r): #what is the driving variable for brakes??? r?
differences = abs(np.array(brakesDF.rbrk) - r)
brakes = brakesDF.loc[np.argmin(differences)]
return brakes
# In[34]:
def constrain(p,dimsToConstrain=np.ones(len(paramsDF))):
# p_attribute = getAttr(p)
paramIndices = [i for i in range(len(dimsToConstrain)) if dimsToConstrain[i] ==1]
for i in paramIndices: #range(len(paramsDF)): # we need to do the equations bounds last
# if not dimsToConstrain[i]: #we don't need to check this dimension, it didn't change
# continue
param = paramsDF.loc[i]
variable = param.variable
value = getattr(p,variable)
if param.kind == 1: #continuous param with min and max
if hasNumericBounds[i]:
newValue = bounds(value,float(param["minV"]),float(param["maxV"]))
setattr(p,variable,newValue)
#do the equation ones after setting all other parameters
elif param.kind == 2: #choose a material based on density
materialID,density,modulusE = findMaterialByDensity(value)
setattr(p,variable,density)
#find other variables that are driven by this one:
for i, otherParam in paramsDF[paramsDF.team == variable].iterrows():#dimension is driven by this one
setattr(p,otherParam.variable,modulusE)
elif param.kind == 3: #choose tires
tireID,radius,weight = findTireByRadius(value)
setattr(p,variable,radius)
#find other variables that are driven by this one:
for i, otherParam in paramsDF[paramsDF.team == variable].iterrows():
setattr(p,otherParam.variable,weight)
elif param.kind == 4: #choose motor
tableRow= findEngineByPower(value) #Phi_e,l_e,w_e,h_e,T_e,m_e
setattr(p,variable,tableRow[variable])
#find other variables that are driven by this one:
for i, otherParam in paramsDF[paramsDF.team == variable].iterrows():
setattr(p,otherParam.variable,tableRow[otherParam.variable])
elif param.kind == 5: #choose brakes
tableRow = findBrakesByR(value) # r is driving variable
setattr(p,variable,tableRow[variable]) #df columns need to be same as variable names
#find other variables that are driven by this one:
for i, otherParam in paramsDF[paramsDF.team == variable].iterrows():
#their "team" is THIS VAR: dimension is driven by this
setattr(p,otherParam.variable,tableRow[otherParam.variable])
elif param.kind == 6: #choose suspension
tableRow = findSuspensionByK(value) #kfsp, cfsp, mfsp
setattr(p,variable,tableRow[variable])
#find other variables that are driven by this one:
for i, otherParam in paramsDF[paramsDF.team == variable].iterrows():#their "team" is THIS VAR: dimension is driven by this
setattr(p,otherParam.variable,tableRow[otherParam.variable])
#now we can do the ones that depend on other variables
for i in paramIndices:
param = paramsDF.loc[i]
variable = param.variable
value = getattr(p,variable)
if param.kind == 1 and not hasNumericBounds[i]:
f = minMaxParam[i] #list of minMax functions for each variable
minV, maxV = f(p)
newValue = bounds(value,minV,maxV)
setattr(p,variable,newValue)
return p
# ## create the scaling vector
# In[35]:
pVmax = asParameters([1e30 for i in range(len(paramsDF))])
maxVals = pVmax
maxVals = constrain(pVmax)
scalingVector = asVector(maxVals) #this acts as a scaling vector to map SI unit values to ~unit cube
# paramsDF.iloc[11]
# ## create realistic starting values
# In[36]:
def startParams(returnParamObject=True):
nParams = len(paramsDF)
pV = np.random.uniform(0,1,nParams) * scalingVector
p = constrain(asParameters(pV))
# print(asVector(p))
return p if returnParamObject else asVector(p)
# objective(p,weightsCustom)
# In[37]:
# p = startParams()
# constrained = asVector(p)
# # constrained/ scalingVector
# for i, row in paramsDF.iterrows():
# print(row[1] + " : \t"+str(constrained[i]))
# ### run random possible start values through objectives to get distribution of outputs
# In[40]:
# subscores = []
# for i in range(2000):
# p = startParams()
# _,ss = objectiveDetailedNonNormalized(p,weightsNull)
# subscores.append(ss)
# s = np.array(subscores)
# In[41]:
# x = s[:,7]
# s[:,7 ] = [3000 if isNaN(x[i]) else x[i] for i in range(len(x)) ]
# ### capture the mean and standard deviations of subscores
# so that we can normalize them assuming Normal dist.
# Now, the objective function will fairly weight sub-objectives using custom weights
# In[42]:
# #FIRST TIME, need to run this if we don't have the file with saved values
# subscoreMean = []
# subscoreSd = []
# for i in range(len(subscores[0])):
# subscoreMean.append(np.mean(s[:,i]))
# subscoreSd.append(np.std(s[:,i]))
# subscoreStatsDF = pd.DataFrame(columns=["subscoreMean","subscoreSD"],data=np.transpose([subscoreMean,subscoreSd]))
# subscoreStatsDF.to_csv("./SAE/subscoreStatsDF.csv")
# # plt.hist((np.array(s[:,i]) - subscoreMean[i])/subscoreSd[i])
# # plt.show()
# In[43]:
subscoreStatsDF = pd.read_csv("./SAE/subscoreStatsDF.csv")
subscoreMean = list(subscoreStatsDF.subscoreMean)
subscoreSd = list(subscoreStatsDF.subscoreSD)
# In[44]:
objective(startParams(),weightsNull)
# # Create Virtual Population with represntative KAI scores
# based on KAI score and subscore dataset provided by Dr. J
# In[45]:
kaiDF_DATASET = pd.read_csv("./KAI/KAI_DATA_2018_07_09.csv")
kaiDF_DATASET.columns = ["KAI","SO","E","RG"]
def makeKAI(n=1,asDF=True):
pop = np.random.multivariate_normal(kaiDF_DATASET.mean(),kaiDF_DATASET.cov(),n)
if asDF:
popDF = pd.DataFrame(pop)
popDF.columns = kaiDF_DATASET.columns
return popDF if n>1 else popDF.loc[0]
else:
return pop if n>1 else pop[0]
# def makeSubscores(kai,n=1,asDF=True):
# pop = np.random.multivariate_normal(kaiDF_DATASET.mean(),kaiDF_DATASET.cov(),n)
kaiPopulation = makeKAI(100000)
kaiPopulation=kaiPopulation.round()
# In[46]:
def findAiScore(kai):
kai = int(kai)
a = kaiPopulation.loc[kaiPopulation['KAI'] == kai]
ind = np.random.choice(a.index)
me = kaiPopulation.loc[ind]
return KAIScore(me) #this is a KAIScore object
# In[47]:
def normalizedAI(ai):
return (ai - kaiDF_DATASET.mean().KAI)/kaiDF_DATASET.std().KAI
def normalizedRG(rg):
return (rg - kaiDF_DATASET.mean().RG)/kaiDF_DATASET.std().RG
def normalizedE(E):
return (E - kaiDF_DATASET.mean().E)/kaiDF_DATASET.std().E
def normalizedSO(SO):
return (SO - kaiDF_DATASET.mean().SO)/kaiDF_DATASET.std().SO
# In[48]:
kaiDF_DATASET.mean().E
kaiDF_DATASET.std().E
# In[49]:
def dotNorm(a,b): #return normalized dot product (how parallel 2 vectors are, -1 to 1)
if norm(a) <= 0 or norm(b)<= 0:
# print("uh oh, vector was length zero")
return 0
a = np.array(a)
b = np.array(b)
dotAB = np.sum(a*b)
normDotAB = dotAB / (norm(a)*norm(b))
return normDotAB
# In[50]:
def plotCategoricalMeans(x,y):
categories = np.unique(x)
means = []
sds = []
for c in categories:
yc = [y[i] for i in range(len(y)) if x[i] == c]
means.append(np.mean(yc))
sds.append(np.std(yc))
plt.errorbar(categories,means,yerr=sds,marker='o',ls='none')
return means
# In[51]:
#speed distributions:
df=1.9
def travelDistance(speed): #how far do we go? chi distribution, but at least go 0.1 * speed
r = np.max([chi.rvs(df),0.1])
return r * speed
# In[52]:
def memoryWeightsPrimacy(n):
if n==1:
return np.array([1])
weights = np.arange(n-1,-1,-1)**3*0.4 + np.arange(0,n,1)**3
weights = weights / np.sum(weights)
return weights
# In[53]: