forked from pfyhr/evReqGen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdragraceSim.py
208 lines (173 loc) · 6.86 KB
/
dragraceSim.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
import sympy as sym
from sympy.solvers.solveset import linsolve
import numpy as np
import matplotlib.pyplot as plt
#import pandas as pd
import csv
import time
def topGradeSpeed(Cd, Cr, g, rhoAir, frontArea, mass, grade, velocity, wheelRadius):
Froll = Cr * mass * g
Fdrag = Cd*frontArea*rhoAir*(velocity)**2/2
Fincl = mass * g * grade
Ftrac = Froll + Fdrag + Fincl
wheelTorque = Ftrac*wheelRadius
return wheelTorque
def tractionMax(mass, g, wtRearFrac, wheelbase, cgh, driveWheel, muTire):
Fr = sym.Symbol('Fr')
Ff = sym.Symbol('Ff')
Fa = sym.Symbol('Fa')
if driveWheel == 'AWD':
print('AWD')
wheelForceMax = mass*g*muTire
elif driveWheel == 'FWD':
print('FWD')
eq1 = Fr + Ff - mass*g
eq2 = Fr*(1-wtRearFrac)*wheelbase - Ff*wtRearFrac*wheelbase - Fa*cgh
eq3 = Fa - Ff*muTire
X = linsolve([eq1, eq2, eq3], (Fr, Ff, Fa))
# extract the solution for eq3
wheelForceMax = X.args[0][2]
else: #RWD case
eq1 = Fr + Ff - mass*g
eq2 = Fr*(1-wtRearFrac)*wheelbase - Ff*wtRearFrac*wheelbase - Fa*cgh
eq3 = Fa - Fr*muTire
X = linsolve([eq1, eq2, eq3], (Fr, Ff, Fa))
# extract the solution for eq3
wheelForceMax = X.args[0][2]
# cast to float for speed
return float(wheelForceMax)
def accelerateVehicle(Cd, frontArea, mass, grade, v0, v1, cgh, wtRearFrac, wheelbase, driveWheel,
desiredAccTime, muTire, wheelRadius):
# some constantas
rhoAir = 1.2
g = 9.81
Cr = 0.01
transLoss = 0.99**3
# limit v1 max to
vmax = 151.0/3.6
if v1 > vmax:
v1 = vmax
#call tractionForceMax
wheelForceMax = tractionMax(mass, g, wtRearFrac, wheelbase, cgh, driveWheel, muTire)
#wheelTorqueMax = wheelForceMax * wheelRadius
# start search for optimal wheeltorque curve given constraints.
# initialize power and time with some gues values, maybe
# here the guess should be based on one run...
# the while loop below should be broken out into a function.
# that removes the optimizing bit and just runs "a vehicle" with
# whatever power is chosen.
power = 5e3
simAccTime = 1e2
timeTol = 0.01
timeStep = 0.01
while abs(simAccTime - desiredAccTime) > timeTol:
# initialize temporary variables
iterStep = 1
vCur = v0
pCar = 0. #position!
#try to come up with some nicer way to converge to the correct solution
#store two previous powers, and use some linear extrapolation from that
#some ratio of the previous and most recently tried power
#below will be some factor with sign if power should increase or decrease
timeratio = (simAccTime - desiredAccTime)/desiredAccTime
#store back prev before overwriting
prevpower = power
power = prevpower + (prevpower * timeratio)
print('power=', power*1e-3)
times = []
velocities = []
torques = []
while vCur < v1:
if vCur > 0:
wheelForce = np.minimum(wheelForceMax, power/vCur)
else:
wheelForce = wheelForceMax
tGS = topGradeSpeed(Cd, Cr, g, rhoAir, frontArea,
mass, grade, vCur, wheelRadius)/wheelRadius
if wheelForce - tGS <= 10:
break
else:
loadDiff = wheelForce - tGS
fDiff = min(loadDiff*transLoss, wheelForceMax)
acceleration = fDiff / mass
tCur = iterStep * timeStep
vCur = vCur + acceleration*timeStep
times.append(tCur)
velocities.append(vCur)
torques.append(wheelForce*wheelRadius)
pCar = pCar + vCur * timeStep
# all done, go to next timestep
iterStep += 1
# when a time is found, update the simulated acceleration time
simAccTime = iterStep*timeStep
if power > 2e6:
print('Reqd power > 2 MW, its not gonna happen')
break
#acceleration limited by friction
if power/v1 > wheelForceMax:
mission_pass = False
else:
mission_pass = True
return times, torques, velocities, power, mission_pass
def plot_png(xs, ys):
setdpi=600
plt.plot(xs, ys, label=f'{power/1e3:.0f} kW')
plt.xlabel('Velocity [m/s]')
plt.ylabel('Torque [Nm]')
plt.legend(loc='best')
plt.ylim(bottom=0)
plt.savefig('static/images/torque.png', dpi=setdpi)
return 'plotting done, see disk'
def output_csv(torques, velocities, power):
with open(f'static/csv/torques{power/1e3:.0f}kW.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',', \
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['velocity[m/s], torque[Nm]'])
for i, val in enumerate(torques):
writer.writerow([velocities[i], torques[i]])
return 'done printing csv'
def sim_json(Cd, frontArea, mass, grade, v0, v1, cgh, wtRearFrac, wheelbase, driveWheel,
desiredAccTime, muTire, wheelRadius, name):
#run the simulation
times, torques, velocities, power, mission_pass = accelerateVehicle(Cd, frontArea, mass, grade, v0, v1, cgh, wtRearFrac, wheelbase, driveWheel,
desiredAccTime, muTire, wheelRadius)
# make a zip of it, iterate over things in the zip and stuff them into a dict.
# the [::10] returns only each 10th value, to save the Chart.JS some effort and make
# the plot animations a bit smoother.
outslice = 20
vel = velocities[::outslice]
vel.append(velocities[-1])
tq = torques[::outslice]
tq.append(torques[-1])
time = times[::outslice]
time.append(times[-1])
#add a power struct
pwr = (np.array(vel)*np.array(tq)/wheelRadius)/1e3
pwr = pwr.tolist()
torquespeed = [{'x':i, 'y':j} for i,j in zip(vel, tq)]
timespeed = [{'x':i, 'y':j} for i,j in zip(time, vel)]
powerspeed = [{'x':i, 'y':j} for i,j in zip(vel,pwr)]
string_dict = {'Modelname': name, 'Power': power*1e-3, 'SolutionFound': mission_pass, \
'torquespeed': torquespeed, 'timespeed': timespeed, 'powerspeed': powerspeed}
return string_dict
if __name__ == "__main__":
mass = 1800.
Cd = 0.3
frontArea = 2.
grade = 0.
v0 = 0.
v1 = 100.0/3.6
cgh = 0.6
wtRearFrac = 0.56
wheelbase = 2.5
driveWheel = 'RWD'
desiredAccTime = 9.
muTire = 0.9
wheelRadius = 0.3
name = 'mainsim'
start_time = time.time()
json = sim_json(Cd, frontArea, mass, grade, v0, v1, cgh, wtRearFrac, wheelbase, driveWheel, \
desiredAccTime, muTire, wheelRadius, name)
dt = (time.time()-start_time)
print("Solution found {:.3f} kW in {:.3f} s".format(json['Power'], dt))
#print(json)