blocksim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
blocksim/vehicle.py ADDED
@@ -0,0 +1,1274 @@
1
+ """Ground vehicle dynamics: tires, wheels, a planar chassis and a driver.
2
+
3
+ Scope is the handling/ride core of a vehicle-dynamics library -- the part
4
+ that is physics rather than plumbing::
5
+
6
+ SteeringManeuver -> delta ------------------------------+
7
+ LongitudinalDriver -> accel/brake -> Wheel -> omega -> |
8
+ ^ v
9
+ +--- Fx --- FialaTire -> Fx, Fy
10
+ ^ |
11
+ vx, vy_axle, Fz v
12
+ +--- VehicleBody3DOF
13
+
14
+ WHY IT IS SPLIT THIS WAY
15
+ The wheel and the tire are a feedback pair: the tire needs the wheel
16
+ speed to know its slip, and the wheel needs the tire force to know its
17
+ torque balance. blocksim decides direct feedthrough per BLOCK, not per
18
+ port, so if the wheel's outputs declared the tire force as an input the
19
+ compiler would see a cycle and hand the pair to the algebraic solver --
20
+ every step, for a loop that does not actually exist.
21
+
22
+ ::
23
+
24
+ So the split follows the real dependency: `Wheel` integrates omega and
25
+ its output is a pure function of that state (no feedthrough), while
26
+ `FialaTire` does all the algebra, computing its own slip from the hub
27
+ kinematics. Same for the chassis: `VehicleBody3DOF` outputs only
28
+ functions of its states, so nothing downstream of it can close a loop
29
+ back through it. The diagram compiles with no algebraic loop at all.
30
+
31
+ LOAD TRANSFER
32
+ Axle normal loads depend on longitudinal acceleration, which depends on
33
+ the tire forces, which depend on the normal loads -- a genuine
34
+ algebraic loop if load transfer is instantaneous. It is not: the
35
+ suspension mediates it. `VehicleBody3DOF` therefore carries the
36
+ accelerations as first-order lagged STATES with a suspension time
37
+ constant, which is both closer to the physics and free of the loop.
38
+
39
+ SOURCES
40
+ The tire is Fiala's brush model (Fiala 1954), in the form given in the
41
+ standard references (Pacejka, *Tyre and Vehicle Dynamics*; Gillespie,
42
+ *Fundamentals of Vehicle Dynamics*). Combined slip is friction-circle
43
+ limiting of the two pure-slip forces -- see `FialaTire` for exactly
44
+ what that does and does not claim.
45
+ """
46
+
47
+ from dataclasses import dataclass
48
+ from typing import Optional
49
+
50
+ import numpy as np
51
+
52
+ from .core import Block, System
53
+
54
+ __all__ = [
55
+ "FialaTire",
56
+ "FourWheelAssembly",
57
+ "LongitudinalDriver",
58
+ "SteeringManeuver",
59
+ "VehicleAssembly",
60
+ "VehicleBody3DOF",
61
+ "VehicleBody4Wheel",
62
+ "Wheel",
63
+ "four_wheel_vehicle",
64
+ "rear_wheel_drive_vehicle",
65
+ ]
66
+
67
+ GRAVITY = 9.80665
68
+
69
+
70
+ # ==========================================================================
71
+ # tire
72
+ # ==========================================================================
73
+ def fiala_longitudinal(kappa, Fz, mu, C_kappa):
74
+ """Pure longitudinal force from Fiala's brush model.
75
+
76
+ Linear in the adhesion region, saturating to ``mu * Fz``. The two
77
+ branches meet at ``kappa_c = mu Fz / (2 C_kappa)``, where both give
78
+ exactly ``mu Fz / 2``.
79
+ """
80
+ if Fz <= 0.0:
81
+ return 0.0
82
+ limit = mu * Fz
83
+ kappa_c = limit / (2.0 * C_kappa)
84
+ if abs(kappa) <= kappa_c:
85
+ return C_kappa * kappa
86
+ return np.sign(kappa) * (limit - limit**2 / (4.0 * C_kappa * abs(kappa)))
87
+
88
+
89
+ def fiala_lateral(alpha, Fz, mu, C_alpha):
90
+ """Pure lateral force from Fiala's brush model.
91
+
92
+ Below the critical slip angle ``atan(3 mu Fz / C_alpha)`` the contact
93
+ patch is partly adhering and the cubic term applies; beyond it the
94
+ whole patch slides and the force is flat at ``mu Fz``. The small-angle
95
+ limit recovers ``Fy = -C_alpha * alpha``.
96
+ """
97
+ if Fz <= 0.0:
98
+ return 0.0
99
+ limit = mu * Fz
100
+ tan_a = np.tan(alpha)
101
+ alpha_c = np.arctan(3.0 * limit / C_alpha)
102
+ if abs(alpha) >= alpha_c:
103
+ return -np.sign(alpha) * limit
104
+ H = 1.0 - C_alpha * abs(tan_a) / (3.0 * limit)
105
+ return -np.sign(alpha) * limit * (1.0 - H**3)
106
+
107
+
108
+ class FialaTire(Block):
109
+ """A tire that computes its own slip from the hub kinematics.
110
+
111
+ Like the blockset's "Fiala Wheel", this block owns the slip
112
+ calculation as well as the force generation: give it the wheel speed,
113
+ the hub velocity and the normal load and it returns the contact-patch
114
+ forces. Keeping the algebra here -- and out of :class:`Wheel` -- is
115
+ what keeps the wheel/tire pair from looking like an algebraic loop.
116
+
117
+ Combined slip is FRICTION-CIRCLE LIMITING, not Fiala's own combined
118
+ derivation: the two pure-slip forces are computed independently and,
119
+ if their vector sum exceeds ``mu Fz``, both are scaled back onto the
120
+ circle. It is continuous, cheap, and correct at the limit and in the
121
+ linear region; it is approximate in between, where a full combined
122
+ brush model or Magic Formula would differ.
123
+
124
+ Parameters
125
+ ----------
126
+ C_kappa, C_alpha
127
+ longitudinal and cornering stiffness (N, N/rad).
128
+ mu
129
+ peak friction coefficient.
130
+ Re
131
+ effective rolling radius (m). Must match the :class:`Wheel`.
132
+ pneumatic_trail
133
+ trail at zero slip (m) for the aligning moment.
134
+ ``Mz = -t Fy`` with ``t`` falling linearly to zero at the critical
135
+ slip angle -- a standard simplification, not Fiala's Mz.
136
+ v_low
137
+ speed below which the slip denominators are regularised (m/s).
138
+ steered
139
+ when True the block takes a steer-angle input.
140
+
141
+ Inputs
142
+ ``omega`` (rad/s), ``vx`` (m/s, body frame), ``vy_axle`` (m/s,
143
+ lateral velocity of this axle), ``Fz`` (N), and ``delta`` (rad)
144
+ when ``steered``.
145
+ Outputs
146
+ ``Fx``, ``Fy`` (N, WHEEL frame), ``Mz`` (Nm), ``kappa``, ``alpha``.
147
+ """
148
+
149
+ FX, FY, MZ, KAPPA, ALPHA = 0, 1, 2, 3, 4
150
+
151
+ def __init__(
152
+ self,
153
+ C_kappa: float = 8.0e4,
154
+ C_alpha: float = 6.0e4,
155
+ mu: float = 0.9,
156
+ Re: float = 0.31,
157
+ pneumatic_trail: float = 0.03,
158
+ v_low: float = 1.0,
159
+ steered: bool = False,
160
+ Fz_nominal: Optional[float] = None,
161
+ load_sensitivity: float = 1.0,
162
+ name: Optional[str] = None,
163
+ ):
164
+ if C_kappa <= 0 or C_alpha <= 0:
165
+ raise ValueError("tire stiffnesses must be positive")
166
+ if mu <= 0:
167
+ raise ValueError("mu must be positive")
168
+ if Fz_nominal is not None and Fz_nominal <= 0:
169
+ raise ValueError("Fz_nominal must be positive")
170
+ if not 0.0 < load_sensitivity <= 1.0:
171
+ raise ValueError(
172
+ "load_sensitivity is an exponent in (0, 1]; 1 makes stiffness "
173
+ "proportional to load, which cancels lateral transfer exactly"
174
+ )
175
+ self.C_kappa = float(C_kappa)
176
+ self.C_alpha = float(C_alpha)
177
+ self.mu = float(mu)
178
+ self.Re = float(Re)
179
+ self.pneumatic_trail = float(pneumatic_trail)
180
+ self.v_low = float(v_low)
181
+ self.steered = bool(steered)
182
+ self.Fz_nominal = None if Fz_nominal is None else float(Fz_nominal)
183
+ self.load_sensitivity = float(load_sensitivity)
184
+
185
+ inputs = [("omega", "rad/s"), ("vx", "m/s"), ("vy_axle", "m/s"), ("Fz", "N")]
186
+ if self.steered:
187
+ inputs.append(("delta", "rad"))
188
+ super().__init__(
189
+ num_inputs=len(inputs),
190
+ num_outputs=5,
191
+ name=name,
192
+ inputs=inputs,
193
+ outputs=[
194
+ ("Fx", "N"),
195
+ ("Fy", "N"),
196
+ ("Mz", "N*m"),
197
+ ("kappa", None),
198
+ ("alpha", "rad"),
199
+ ],
200
+ )
201
+
202
+ def slip(self, omega, vx, vy_axle, delta=0.0):
203
+ """(kappa, alpha) for this hub state, regularised near standstill.
204
+
205
+ The hub velocity is resolved into the wheel frame first, so the
206
+ slip angle is the angle between the wheel's heading and where it
207
+ is actually going.
208
+ """
209
+ cd, sd = np.cos(delta), np.sin(delta)
210
+ vx_w = vx * cd + vy_axle * sd # longitudinal, wheel frame
211
+ vy_w = vy_axle * cd - vx * sd # lateral, wheel frame
212
+
213
+ # a vanishing denominator is the classic way these models blow up
214
+ # at standstill; clamp it rather than letting slip go to infinity
215
+ denom = max(abs(vx_w), self.v_low)
216
+ kappa = (omega * self.Re - vx_w) / denom
217
+ alpha = np.arctan2(vy_w, denom)
218
+ return kappa, alpha
219
+
220
+ def _load_factor(self, Fz):
221
+ return (max(Fz, 0.0) / self.Fz_nominal) ** self.load_sensitivity
222
+
223
+ def cornering_stiffness(self, Fz):
224
+ """Cornering stiffness at this normal load.
225
+
226
+ With `Fz_nominal` unset this is a constant -- the classic Fiala
227
+ parameterisation. Setting it scales the stiffness as
228
+ ``(Fz/Fz_nominal) ** load_sensitivity``.
229
+ """
230
+ if self.Fz_nominal is None:
231
+ return self.C_alpha
232
+ return self.C_alpha * self._load_factor(Fz)
233
+
234
+ def peak_friction(self, Fz):
235
+ """Friction coefficient at this normal load.
236
+
237
+ This is the half of load sensitivity that matters most for lateral
238
+ load transfer. With a CONSTANT mu an axle's saturated capability is
239
+ ``mu Fz_inner + mu Fz_outer = mu Fz_total``, exactly unchanged by
240
+ moving load across the axle, and its linear-region stiffness is
241
+ unchanged too -- only Fiala's intermediate cubic responds, weakly,
242
+ because the critical slip angle moves with load. Real tires lose
243
+ friction as they are loaded up, and that concavity is most of what
244
+ makes roll couple distribution a balance knob.
245
+
246
+ So when `Fz_nominal` is set, mu scales as
247
+ ``(Fz/Fz_nominal) ** (load_sensitivity - 1)``, which makes the peak
248
+ force ``mu Fz`` grow as ``Fz ** load_sensitivity`` -- the same
249
+ concave law as the stiffness, from one exponent. Real tires sit
250
+ around 0.6 to 0.9; an exponent of exactly 1 restores the degenerate
251
+ case where transfer cancels and the four-wheel body behaves like
252
+ the bicycle model.
253
+ """
254
+ if self.Fz_nominal is None:
255
+ return self.mu
256
+ if Fz <= 0.0:
257
+ return self.mu
258
+ return self.mu * self._load_factor(Fz) * self.Fz_nominal / Fz
259
+
260
+ def forces(self, kappa, alpha, Fz):
261
+ """(Fx, Fy) with friction-circle limiting of the pure-slip forces."""
262
+ if Fz <= 0.0: # wheel off the ground carries nothing
263
+ return 0.0, 0.0
264
+ mu = self.peak_friction(Fz)
265
+ Fx = fiala_longitudinal(kappa, Fz, mu, self.C_kappa)
266
+ Fy = fiala_lateral(alpha, Fz, mu, self.cornering_stiffness(Fz))
267
+
268
+ limit = mu * Fz
269
+ demand = np.hypot(Fx, Fy)
270
+ if demand > limit:
271
+ scale = limit / demand
272
+ Fx *= scale
273
+ Fy *= scale
274
+ return Fx, Fy
275
+
276
+ def aligning_moment(self, alpha, Fy, Fz):
277
+ if Fz <= 0.0:
278
+ return 0.0
279
+ alpha_c = np.arctan(
280
+ 3.0 * self.peak_friction(Fz) * Fz / self.cornering_stiffness(Fz)
281
+ )
282
+ trail = self.pneumatic_trail * max(0.0, 1.0 - abs(alpha) / alpha_c)
283
+ return -trail * Fy
284
+
285
+ def output(self, t, u):
286
+ delta = float(u[4]) if self.steered else 0.0
287
+ kappa, alpha = self.slip(float(u[0]), float(u[1]), float(u[2]), delta)
288
+ Fz = float(u[3])
289
+ Fx, Fy = self.forces(kappa, alpha, Fz)
290
+ return np.array([Fx, Fy, self.aligning_moment(alpha, Fy, Fz), kappa, alpha])
291
+
292
+
293
+ # ==========================================================================
294
+ # wheel
295
+ # ==========================================================================
296
+ class Wheel(Block):
297
+ """Wheel rotational dynamics: ``J omega' = tau_drive - tau_brake - Fx Re``.
298
+
299
+ Its output is a pure function of its state, deliberately: the tire
300
+ force it consumes never reaches its outputs, so the compiler does not
301
+ mistake the wheel/tire pair for an algebraic loop.
302
+
303
+ Brake torque always opposes rotation, through a ``tanh`` around zero
304
+ speed rather than a hard ``sign``. That regularisation is what keeps a
305
+ locked wheel from chattering; it also means this block models
306
+ approach-to-lock but not true stick-slip, for which the brake torque
307
+ would have to switch mode on a located zero crossing.
308
+
309
+ Parameters
310
+ ----------
311
+ J
312
+ rotational inertia (kg m^2).
313
+ Re
314
+ effective rolling radius (m). Must match the :class:`FialaTire`.
315
+ omega0
316
+ initial wheel speed (rad/s).
317
+ omega_eps
318
+ transition scale of the tanh around zero speed (rad/s).
319
+
320
+ Inputs
321
+ ``tau_drive`` (Nm), ``tau_brake`` (Nm, magnitude), ``Fx`` (N).
322
+ Outputs
323
+ ``omega`` (rad/s), ``v_wheel`` (m/s, ``omega * Re``).
324
+ """
325
+
326
+ OMEGA, V_WHEEL = 0, 1
327
+
328
+ def __init__(
329
+ self,
330
+ J: float = 1.2,
331
+ Re: float = 0.31,
332
+ omega0: float = 0.0,
333
+ omega_eps: float = 1.0,
334
+ name: Optional[str] = None,
335
+ ):
336
+ if J <= 0:
337
+ raise ValueError("wheel inertia must be positive")
338
+ self.J = float(J)
339
+ self.Re = float(Re)
340
+ self.omega_eps = float(omega_eps)
341
+
342
+ super().__init__(
343
+ num_inputs=3,
344
+ num_outputs=2,
345
+ num_states=1,
346
+ name=name,
347
+ inputs=[("tau_drive", "N*m"), ("tau_brake", "N*m"), ("Fx", "N")],
348
+ outputs=[("omega", "rad/s"), ("v_wheel", "m/s")],
349
+ states=[("omega", "rad/s")],
350
+ )
351
+ self.x0 = np.array([float(omega0)])
352
+
353
+ def derivative(self, t, x, u):
354
+ omega = x[0]
355
+ tau_drive, tau_brake, Fx = float(u[0]), float(u[1]), float(u[2])
356
+ opposing = abs(tau_brake) * np.tanh(omega / self.omega_eps)
357
+ return np.array([(tau_drive - opposing - Fx * self.Re) / self.J])
358
+
359
+ def output(self, t, x):
360
+ return np.array([x[0], x[0] * self.Re])
361
+
362
+
363
+ # ==========================================================================
364
+ # chassis
365
+ # ==========================================================================
366
+ class VehicleBody3DOF(Block):
367
+ """Planar (bicycle) vehicle body: longitudinal, lateral and yaw.
368
+
369
+ States are ``[vx, vy, r, psi, X, Y, ax, ay]``. The last two are the
370
+ accelerations passed through a first-order lag of time constant
371
+ `tau_load`, standing in for the suspension: that is what lets the
372
+ normal loads be reported as functions of STATE rather than of the
373
+ current tire forces, which is what would otherwise make load transfer
374
+ an algebraic loop. Everything this block outputs is a function of its
375
+ states, so no loop can close through it.
376
+
377
+ Front tire forces come in the FRONT WHEEL frame and are resolved by
378
+ the steer angle here; rear forces are already in the body frame.
379
+
380
+ Parameters
381
+ ----------
382
+ mass
383
+ vehicle mass (kg).
384
+ Izz
385
+ yaw inertia (kg m^2).
386
+ a, b
387
+ distance from CG to the front and rear axle (m).
388
+ h_cg
389
+ CG height (m), which sets the longitudinal load transfer.
390
+ Cd, frontal_area, rho
391
+ aerodynamic drag.
392
+ Crr
393
+ rolling resistance coefficient.
394
+ tau_load
395
+ suspension lag on the load transfer (s).
396
+ v_low
397
+ speed below which slip denominators are regularised (m/s).
398
+ x0
399
+ initial ``[vx, vy, r, psi, X, Y]`` (accelerations start at zero).
400
+
401
+ Inputs
402
+ ``Fxf``, ``Fyf`` (N, front wheel frame), ``Fxr``, ``Fyr`` (N, body
403
+ frame), ``delta`` (rad).
404
+ Outputs
405
+ ``vx``, ``vy``, ``r``, ``psi``, ``X``, ``Y``, ``ax``, ``ay``,
406
+ ``vy_f``, ``vy_r`` (axle lateral velocities), ``Fz_f``, ``Fz_r``.
407
+ """
408
+
409
+ VX, VY, R, PSI, X, Y, AX, AY, VY_F, VY_R, FZ_F, FZ_R = range(12)
410
+
411
+ def __init__(
412
+ self,
413
+ mass: float = 1500.0,
414
+ Izz: float = 2500.0,
415
+ a: float = 1.2,
416
+ b: float = 1.5,
417
+ h_cg: float = 0.55,
418
+ Cd: float = 0.32,
419
+ frontal_area: float = 2.2,
420
+ rho: float = 1.225,
421
+ Crr: float = 0.012,
422
+ tau_load: float = 0.05,
423
+ v_low: float = 1.0,
424
+ x0=None,
425
+ name: Optional[str] = None,
426
+ ):
427
+ if mass <= 0 or Izz <= 0:
428
+ raise ValueError("mass and yaw inertia must be positive")
429
+ if a <= 0 or b <= 0:
430
+ raise ValueError("both axle distances must be positive")
431
+ if tau_load <= 0:
432
+ raise ValueError("tau_load must be positive (it breaks the load loop)")
433
+ self.mass = float(mass)
434
+ self.Izz = float(Izz)
435
+ self.a = float(a)
436
+ self.b = float(b)
437
+ self.L = self.a + self.b
438
+ self.h_cg = float(h_cg)
439
+ self.Cd = float(Cd)
440
+ self.frontal_area = float(frontal_area)
441
+ self.rho = float(rho)
442
+ self.Crr = float(Crr)
443
+ self.tau_load = float(tau_load)
444
+ self.v_low = float(v_low)
445
+
446
+ labels = [
447
+ ("vx", "m/s"),
448
+ ("vy", "m/s"),
449
+ ("r", "rad/s"),
450
+ ("psi", "rad"),
451
+ ("X", "m"),
452
+ ("Y", "m"),
453
+ ("ax", "m/s^2"),
454
+ ("ay", "m/s^2"),
455
+ ]
456
+ super().__init__(
457
+ num_inputs=5,
458
+ num_outputs=12,
459
+ num_states=8,
460
+ name=name,
461
+ inputs=[
462
+ ("Fxf", "N"),
463
+ ("Fyf", "N"),
464
+ ("Fxr", "N"),
465
+ ("Fyr", "N"),
466
+ ("delta", "rad"),
467
+ ],
468
+ outputs=labels
469
+ + [
470
+ ("vy_f", "m/s"),
471
+ ("vy_r", "m/s"),
472
+ ("Fz_f", "N"),
473
+ ("Fz_r", "N"),
474
+ ],
475
+ states=labels,
476
+ )
477
+ self.x0 = np.zeros(8)
478
+ if x0 is not None:
479
+ initial = np.atleast_1d(np.asarray(x0, dtype=float))
480
+ if initial.size not in (6, 8):
481
+ raise ValueError("x0 must be [vx, vy, r, psi, X, Y] (or all 8 states)")
482
+ self.x0[: initial.size] = initial
483
+
484
+ # ---- static axle loads -------------------------------------------------
485
+ @property
486
+ def static_load_front(self) -> float:
487
+ return self.mass * GRAVITY * self.b / self.L
488
+
489
+ @property
490
+ def static_load_rear(self) -> float:
491
+ return self.mass * GRAVITY * self.a / self.L
492
+
493
+ def _resistance(self, vx):
494
+ """Aerodynamic drag plus rolling resistance, both opposing motion."""
495
+ drag = 0.5 * self.rho * self.Cd * self.frontal_area * vx * abs(vx)
496
+ rolling = self.Crr * self.mass * GRAVITY * np.tanh(vx / self.v_low)
497
+ return drag + rolling
498
+
499
+ def derivative(self, t, x, u):
500
+ vx, vy, r = x[0], x[1], x[2]
501
+ psi = x[3]
502
+ ax_lag, ay_lag = x[6], x[7]
503
+ Fxf, Fyf, Fxr, Fyr, delta = (float(v) for v in u[:5])
504
+
505
+ cd, sd = np.cos(delta), np.sin(delta)
506
+ # front forces arrive in the wheel frame; resolve them into the body
507
+ Fx_body = Fxf * cd - Fyf * sd + Fxr - self._resistance(vx)
508
+ Fy_body = Fxf * sd + Fyf * cd + Fyr
509
+ Mz = self.a * (Fxf * sd + Fyf * cd) - self.b * Fyr
510
+
511
+ ax = Fx_body / self.mass
512
+ ay = Fy_body / self.mass
513
+
514
+ dvx = ax + vy * r
515
+ dvy = ay - vx * r
516
+ dr = Mz / self.Izz
517
+
518
+ return np.array(
519
+ [
520
+ dvx,
521
+ dvy,
522
+ dr,
523
+ r,
524
+ vx * np.cos(psi) - vy * np.sin(psi),
525
+ vx * np.sin(psi) + vy * np.cos(psi),
526
+ (ax - ax_lag) / self.tau_load,
527
+ (ay - ay_lag) / self.tau_load,
528
+ ]
529
+ )
530
+
531
+ def output(self, t, x):
532
+ vy, r, ax_lag = x[1], x[2], x[6]
533
+ # longitudinal load transfer, through the suspension lag
534
+ transfer = self.mass * ax_lag * self.h_cg / self.L
535
+ return np.concatenate(
536
+ [
537
+ x,
538
+ [
539
+ vy + self.a * r,
540
+ vy - self.b * r,
541
+ max(0.0, self.static_load_front - transfer),
542
+ max(0.0, self.static_load_rear + transfer),
543
+ ],
544
+ ]
545
+ )
546
+
547
+ # ---- closed-form handling predictions ----------------------------------
548
+ def understeer_gradient(self, C_alpha_front, C_alpha_rear) -> float:
549
+ """Gillespie's K = W_f/C_af - W_r/C_ar, in rad per g.
550
+
551
+ Positive is understeer. This is what a slowly-increasing-steer test
552
+ measures as the slope of steer angle against lateral acceleration,
553
+ so it is the natural thing to validate a model against.
554
+ """
555
+ return (
556
+ self.static_load_front / C_alpha_front
557
+ - self.static_load_rear / C_alpha_rear
558
+ )
559
+
560
+ def steady_state_steer(self, radius, speed, C_alpha_front, C_alpha_rear) -> float:
561
+ """Steer angle to hold `radius` at `speed`: delta = L/R + K ay/g."""
562
+ K = self.understeer_gradient(C_alpha_front, C_alpha_rear)
563
+ return self.L / radius + K * speed**2 / (radius * GRAVITY)
564
+
565
+ def yaw_rate_gain(self, speed, C_alpha_front, C_alpha_rear) -> float:
566
+ """Steady-state r/delta, the classic bicycle-model handling gain."""
567
+ K = self.understeer_gradient(C_alpha_front, C_alpha_rear)
568
+ return speed / (self.L + K * speed**2 / GRAVITY)
569
+
570
+
571
+ class VehicleBody4Wheel(Block):
572
+ """Planar body with four corners, so load transfers sideways as well.
573
+
574
+ Same three degrees of freedom as :class:`VehicleBody3DOF` -- there is
575
+ still no roll DOF -- but the weight is carried at four contact patches
576
+ instead of two axles, which buys three things the bicycle model simply
577
+ cannot express:
578
+
579
+ * **Roll couple distribution.** `roll_couple_front` splits the lateral
580
+ transfer between the axles, and that is the classic handling-balance
581
+ knob: stiffen the front and the car understeers. It only works with
582
+ a LOAD-SENSITIVE tire -- see :meth:`FialaTire.cornering_stiffness`,
583
+ because with stiffness proportional to load the transfer cancels.
584
+ * **Left/right asymmetry.** Per-corner friction gives split-mu
585
+ braking, and the differing longitudinal forces make a real yaw
586
+ moment through the track, which is also how torque vectoring works.
587
+ * **Inside wheel lift.** A corner's load is clamped at zero, so hard
588
+ cornering unloads the inside wheels the way it actually does.
589
+
590
+ Roll is quasi-static: the lateral transfer follows the lagged lateral
591
+ acceleration, with no roll angle state and no roll inertia. Transient
592
+ roll and its phase lag need a fourth degree of freedom.
593
+
594
+ Front tire forces arrive in the FRONT WHEEL frame (both front wheels
595
+ take the same steer angle -- parallel steer, not Ackermann); rear
596
+ forces are already in the body frame. Tire aligning moments are not
597
+ summed into the yaw equation: they matter for steering feel, and this
598
+ block models vehicle motion.
599
+
600
+ Parameters
601
+ ----------
602
+ mass, Izz, a, b, h_cg, Cd, frontal_area, rho, Crr, tau_load, v_low, x0
603
+ As for :class:`VehicleBody3DOF`.
604
+ track_front, track_rear
605
+ wheel centre-to-centre spacing (m).
606
+ roll_couple_front
607
+ fraction of the lateral load transfer taken by the
608
+ front axle, in [0, 1]. 0.5 splits it evenly.
609
+
610
+ Inputs
611
+ ``Fx_fl``, ``Fy_fl``, ``Fx_fr``, ``Fy_fr`` (front wheel frame),
612
+ ``Fx_rl``, ``Fy_rl``, ``Fx_rr``, ``Fy_rr`` (body frame), ``delta``.
613
+ Outputs
614
+ ``vx``, ``vy``, ``r``, ``psi``, ``X``, ``Y``, ``ax``, ``ay``, then
615
+ the per-corner longitudinal speeds ``vx_fl..vx_rr``, the per-axle
616
+ lateral speeds ``vy_f``, ``vy_r``, and the corner loads
617
+ ``Fz_fl..Fz_rr``.
618
+ """
619
+
620
+ # inputs
621
+ FX_FL, FY_FL, FX_FR, FY_FR, FX_RL, FY_RL, FX_RR, FY_RR, DELTA = range(9)
622
+ # outputs
623
+ VX, VY, R, PSI, X, Y, AX, AY = range(8)
624
+ VX_FL, VX_FR, VX_RL, VX_RR = 8, 9, 10, 11
625
+ VY_F, VY_R = 12, 13
626
+ FZ_FL, FZ_FR, FZ_RL, FZ_RR = 14, 15, 16, 17
627
+
628
+ def __init__(
629
+ self,
630
+ mass: float = 1500.0,
631
+ Izz: float = 2500.0,
632
+ a: float = 1.2,
633
+ b: float = 1.5,
634
+ h_cg: float = 0.55,
635
+ track_front: float = 1.55,
636
+ track_rear: float = 1.55,
637
+ roll_couple_front: float = 0.5,
638
+ Cd: float = 0.32,
639
+ frontal_area: float = 2.2,
640
+ rho: float = 1.225,
641
+ Crr: float = 0.012,
642
+ tau_load: float = 0.05,
643
+ v_low: float = 1.0,
644
+ x0=None,
645
+ name: Optional[str] = None,
646
+ ):
647
+ if mass <= 0 or Izz <= 0:
648
+ raise ValueError("mass and yaw inertia must be positive")
649
+ if a <= 0 or b <= 0:
650
+ raise ValueError("both axle distances must be positive")
651
+ if track_front <= 0 or track_rear <= 0:
652
+ raise ValueError("both tracks must be positive")
653
+ if not 0.0 <= roll_couple_front <= 1.0:
654
+ raise ValueError("roll_couple_front is a front fraction in [0, 1]")
655
+ if tau_load <= 0:
656
+ raise ValueError("tau_load must be positive (it breaks the load loop)")
657
+
658
+ self.mass = float(mass)
659
+ self.Izz = float(Izz)
660
+ self.a = float(a)
661
+ self.b = float(b)
662
+ self.L = self.a + self.b
663
+ self.h_cg = float(h_cg)
664
+ self.track_front = float(track_front)
665
+ self.track_rear = float(track_rear)
666
+ self.roll_couple_front = float(roll_couple_front)
667
+ self.Cd = float(Cd)
668
+ self.frontal_area = float(frontal_area)
669
+ self.rho = float(rho)
670
+ self.Crr = float(Crr)
671
+ self.tau_load = float(tau_load)
672
+ self.v_low = float(v_low)
673
+
674
+ state_labels = [
675
+ ("vx", "m/s"),
676
+ ("vy", "m/s"),
677
+ ("r", "rad/s"),
678
+ ("psi", "rad"),
679
+ ("X", "m"),
680
+ ("Y", "m"),
681
+ ("ax", "m/s^2"),
682
+ ("ay", "m/s^2"),
683
+ ]
684
+ corners = ("fl", "fr", "rl", "rr")
685
+ super().__init__(
686
+ num_inputs=9,
687
+ num_outputs=18,
688
+ num_states=8,
689
+ name=name,
690
+ inputs=[(f"F{axis}_{c}", "N") for c in corners for axis in ("x", "y")]
691
+ + [("delta", "rad")],
692
+ outputs=state_labels
693
+ + [(f"vx_{c}", "m/s") for c in corners]
694
+ + [("vy_f", "m/s"), ("vy_r", "m/s")]
695
+ + [(f"Fz_{c}", "N") for c in corners],
696
+ states=state_labels,
697
+ )
698
+ self.x0 = np.zeros(8)
699
+ if x0 is not None:
700
+ initial = np.atleast_1d(np.asarray(x0, dtype=float))
701
+ if initial.size not in (6, 8):
702
+ raise ValueError("x0 must be [vx, vy, r, psi, X, Y] (or all 8 states)")
703
+ self.x0[: initial.size] = initial
704
+
705
+ # ---- static corner loads -----------------------------------------------
706
+ @property
707
+ def static_load_front(self) -> float:
708
+ """Per-WHEEL static load at the front."""
709
+ return self.mass * GRAVITY * self.b / (2.0 * self.L)
710
+
711
+ @property
712
+ def static_load_rear(self) -> float:
713
+ return self.mass * GRAVITY * self.a / (2.0 * self.L)
714
+
715
+ def _resistance(self, vx):
716
+ drag = 0.5 * self.rho * self.Cd * self.frontal_area * vx * abs(vx)
717
+ rolling = self.Crr * self.mass * GRAVITY * np.tanh(vx / self.v_low)
718
+ return drag + rolling
719
+
720
+ def corner_loads(self, ax, ay):
721
+ """The four normal loads at these (lagged) accelerations.
722
+
723
+ Positive `ax` shifts load rearward; positive `ay` is a left turn,
724
+ which rolls the car right and loads the RIGHT-hand wheels. Each
725
+ corner is clamped at zero -- an unloaded wheel cannot pull down.
726
+ """
727
+ longitudinal = self.mass * ax * self.h_cg / self.L # front -> rear
728
+ roll_moment = self.mass * ay * self.h_cg
729
+ lateral_front = self.roll_couple_front * roll_moment / self.track_front
730
+ lateral_rear = (1.0 - self.roll_couple_front) * roll_moment / self.track_rear
731
+
732
+ front = self.static_load_front - 0.5 * longitudinal
733
+ rear = self.static_load_rear + 0.5 * longitudinal
734
+ return (
735
+ max(0.0, front - lateral_front), # front left
736
+ max(0.0, front + lateral_front), # front right
737
+ max(0.0, rear - lateral_rear), # rear left
738
+ max(0.0, rear + lateral_rear), # rear right
739
+ )
740
+
741
+ def derivative(self, t, x, u):
742
+ vx, vy, r, psi = x[0], x[1], x[2], x[3]
743
+ ax_lag, ay_lag = x[6], x[7]
744
+ (Fx_fl, Fy_fl, Fx_fr, Fy_fr, Fx_rl, Fy_rl, Fx_rr, Fy_rr, delta) = (
745
+ float(v) for v in u[:9]
746
+ )
747
+
748
+ cd, sd = np.cos(delta), np.sin(delta)
749
+ # resolve each front corner out of its wheel frame individually, so
750
+ # a left/right force difference survives into the yaw equation
751
+ fl_x, fl_y = Fx_fl * cd - Fy_fl * sd, Fx_fl * sd + Fy_fl * cd
752
+ fr_x, fr_y = Fx_fr * cd - Fy_fr * sd, Fx_fr * sd + Fy_fr * cd
753
+
754
+ Fx_body = fl_x + fr_x + Fx_rl + Fx_rr - self._resistance(vx)
755
+ Fy_body = fl_y + fr_y + Fy_rl + Fy_rr
756
+
757
+ # yaw from the axle lateral forces, plus the couple that any
758
+ # left/right longitudinal imbalance makes across the track --
759
+ # split-mu braking and torque vectoring both live in that term
760
+ Mz = (
761
+ self.a * (fl_y + fr_y)
762
+ - self.b * (Fy_rl + Fy_rr)
763
+ + 0.5 * self.track_front * (fr_x - fl_x)
764
+ + 0.5 * self.track_rear * (Fx_rr - Fx_rl)
765
+ )
766
+
767
+ ax = Fx_body / self.mass
768
+ ay = Fy_body / self.mass
769
+ return np.array(
770
+ [
771
+ ax + vy * r,
772
+ ay - vx * r,
773
+ Mz / self.Izz,
774
+ r,
775
+ vx * np.cos(psi) - vy * np.sin(psi),
776
+ vx * np.sin(psi) + vy * np.cos(psi),
777
+ (ax - ax_lag) / self.tau_load,
778
+ (ay - ay_lag) / self.tau_load,
779
+ ]
780
+ )
781
+
782
+ def output(self, t, x):
783
+ vx, vy, r = x[0], x[1], x[2]
784
+ ax_lag, ay_lag = x[6], x[7]
785
+ half_f, half_r = 0.5 * self.track_front, 0.5 * self.track_rear
786
+ # v = v_cg + omega x r, with the left wheels at +track/2
787
+ return np.concatenate(
788
+ [
789
+ x,
790
+ [
791
+ vx - r * half_f, # front left
792
+ vx + r * half_f, # front right
793
+ vx - r * half_r, # rear left
794
+ vx + r * half_r, # rear right
795
+ vy + self.a * r,
796
+ vy - self.b * r,
797
+ ],
798
+ self.corner_loads(ax_lag, ay_lag),
799
+ ]
800
+ )
801
+
802
+ # ---- handling predictions, shared with the bicycle model ---------------
803
+ def understeer_gradient(self, C_alpha_front, C_alpha_rear) -> float:
804
+ """K = W_f/C_af - W_r/C_ar, with AXLE loads and AXLE stiffnesses."""
805
+ return (
806
+ 2.0 * self.static_load_front / C_alpha_front
807
+ - 2.0 * self.static_load_rear / C_alpha_rear
808
+ )
809
+
810
+ def yaw_rate_gain(self, speed, C_alpha_front, C_alpha_rear) -> float:
811
+ K = self.understeer_gradient(C_alpha_front, C_alpha_rear)
812
+ return speed / (self.L + K * speed**2 / GRAVITY)
813
+
814
+
815
+ # ==========================================================================
816
+ # driver and maneuvers
817
+ # ==========================================================================
818
+ class LongitudinalDriver(Block):
819
+ """PI speed tracker that splits its command into throttle and brake.
820
+
821
+ Outputs are normalised demands in ``[0, 1]``; scale them to torques
822
+ with a :class:`~blocksim.math.Gain`. The integrator is clamped while a
823
+ demand is saturated, so a long acceleration at full throttle does not
824
+ wind up and then overshoot.
825
+
826
+ Parameters
827
+ ----------
828
+ Kp, Ki
829
+ gains on the speed error (1 per m/s, 1 per m).
830
+ brake_ratio
831
+ brake demand per unit of negative command -- braking is
832
+ far more authoritative than the engine, so the same error should
833
+ not ask for the same effort in both directions.
834
+ deadband
835
+ speed error (m/s) inside which neither pedal is applied,
836
+ which stops the driver dithering between them at steady speed.
837
+
838
+ Inputs
839
+ ``v_ref`` (m/s), ``vx`` (m/s).
840
+ Outputs
841
+ ``throttle`` (0..1), ``brake`` (0..1).
842
+ """
843
+
844
+ THROTTLE, BRAKE = 0, 1
845
+
846
+ def __init__(
847
+ self,
848
+ Kp: float = 0.5,
849
+ Ki: float = 0.1,
850
+ brake_ratio: float = 1.0,
851
+ deadband: float = 0.0,
852
+ name: Optional[str] = None,
853
+ ):
854
+ self.Kp = float(Kp)
855
+ self.Ki = float(Ki)
856
+ self.brake_ratio = float(brake_ratio)
857
+ self.deadband = float(deadband)
858
+
859
+ super().__init__(
860
+ num_inputs=2,
861
+ num_outputs=2,
862
+ num_states=1,
863
+ name=name,
864
+ inputs=[("v_ref", "m/s"), ("vx", "m/s")],
865
+ outputs=[("throttle", None), ("brake", None)],
866
+ states=[("integral", None)],
867
+ )
868
+ self.x0 = np.zeros(1)
869
+
870
+ def _command(self, x, u):
871
+ error = float(u[0]) - float(u[1])
872
+ if abs(error) < self.deadband:
873
+ error = 0.0
874
+ return error, self.Kp * error + self.Ki * x[0]
875
+
876
+ def derivative(self, t, x, u):
877
+ error, command = self._command(x, u)
878
+ # clamp the integrator whenever the pedal it drives is on its stop
879
+ if (command > 1.0 and error > 0.0) or (command < -1.0 and error < 0.0):
880
+ return np.array([0.0])
881
+ return np.array([error])
882
+
883
+ def output(self, t, x, u):
884
+ _error, command = self._command(x, u)
885
+ throttle = float(np.clip(command, 0.0, 1.0))
886
+ brake = float(np.clip(-command * self.brake_ratio, 0.0, 1.0))
887
+ return np.array([throttle, brake])
888
+
889
+
890
+ class SteeringManeuver(Block):
891
+ """Open-loop steer-angle profiles for standard handling tests.
892
+
893
+ ``profile`` selects one of:
894
+
895
+ ``step``
896
+ Step to `amplitude` at `t_start`.
897
+ ``ramp``
898
+ Slowly increasing steer: a linear ramp of `ramp_rate` rad/s, the
899
+ test used to measure the understeer gradient.
900
+ ``double_lane_change``
901
+ One full sine period out, a dwell, then one full period back --
902
+ the open-loop approximation of the ISO 3888 course. Not the ISO
903
+ test itself, which is a cone layout driven closed-loop.
904
+ ``sine_dwell``
905
+ NHTSA FMVSS 126: a sine at `frequency`, held at the second peak
906
+ for `dwell`, then completed.
907
+ ``swept_sine``
908
+ Constant-amplitude sine sweeping from `f_start` to `f_end`, for
909
+ frequency-response identification.
910
+
911
+ Outputs
912
+ ``delta`` (rad).
913
+ """
914
+
915
+ PROFILES = ("step", "ramp", "double_lane_change", "sine_dwell", "swept_sine")
916
+
917
+ def __init__(
918
+ self,
919
+ profile: str = "step",
920
+ amplitude: float = 0.05,
921
+ t_start: float = 1.0,
922
+ frequency: float = 0.7,
923
+ dwell: float = 0.5,
924
+ gap: float = 0.5,
925
+ ramp_rate: float = 0.01,
926
+ f_start: float = 0.1,
927
+ f_end: float = 4.0,
928
+ duration: float = 10.0,
929
+ name: Optional[str] = None,
930
+ ):
931
+ if profile not in self.PROFILES:
932
+ raise ValueError(
933
+ f"unknown profile {profile!r}; choose from {', '.join(self.PROFILES)}"
934
+ )
935
+ self.profile = profile
936
+ self.amplitude = float(amplitude)
937
+ self.t_start = float(t_start)
938
+ self.frequency = float(frequency)
939
+ self.dwell = float(dwell)
940
+ self.gap = float(gap)
941
+ self.ramp_rate = float(ramp_rate)
942
+ self.f_start = float(f_start)
943
+ self.f_end = float(f_end)
944
+ self.duration = float(duration)
945
+
946
+ super().__init__(
947
+ num_inputs=0,
948
+ num_outputs=1,
949
+ name=name,
950
+ outputs=[("delta", "rad")],
951
+ )
952
+
953
+ def output(self, t):
954
+ return np.array([getattr(self, f"_{self.profile}")(t - self.t_start)])
955
+
956
+ # ---- profiles, each taking time SINCE t_start ---------------------------
957
+ def _step(self, tau):
958
+ return self.amplitude if tau >= 0.0 else 0.0
959
+
960
+ def _ramp(self, tau):
961
+ return self.ramp_rate * tau if tau > 0.0 else 0.0
962
+
963
+ def _double_lane_change(self, tau):
964
+ period = 1.0 / self.frequency
965
+ if tau < 0.0:
966
+ return 0.0
967
+ if tau < period: # out
968
+ return self.amplitude * np.sin(2.0 * np.pi * self.frequency * tau)
969
+ if tau < period + self.gap: # straighten up
970
+ return 0.0
971
+ back = tau - period - self.gap
972
+ if back < period: # and back
973
+ return -self.amplitude * np.sin(2.0 * np.pi * self.frequency * back)
974
+ return 0.0
975
+
976
+ def _sine_dwell(self, tau):
977
+ period = 1.0 / self.frequency
978
+ if tau < 0.0:
979
+ return 0.0
980
+ if tau < 0.75 * period: # up, over, and down to the second peak
981
+ return self.amplitude * np.sin(2.0 * np.pi * self.frequency * tau)
982
+ if tau < 0.75 * period + self.dwell: # held at the peak
983
+ return -self.amplitude
984
+ rest = tau - self.dwell
985
+ if rest < period:
986
+ return self.amplitude * np.sin(2.0 * np.pi * self.frequency * rest)
987
+ return 0.0
988
+
989
+ def _swept_sine(self, tau):
990
+ if tau < 0.0 or tau > self.duration:
991
+ return 0.0
992
+ rate = (self.f_end - self.f_start) / self.duration
993
+ phase = 2.0 * np.pi * (self.f_start * tau + 0.5 * rate * tau**2)
994
+ return self.amplitude * np.sin(phase)
995
+
996
+
997
+ # ==========================================================================
998
+ # reference assembly
999
+ # ==========================================================================
1000
+ @dataclass
1001
+ class VehicleAssembly:
1002
+ """The blocks of an assembled vehicle, so a caller can read or retune
1003
+ any of them after the wiring is done."""
1004
+
1005
+ system: System
1006
+ body: VehicleBody3DOF
1007
+ tire_front: FialaTire
1008
+ tire_rear: FialaTire
1009
+ wheel_front: Wheel
1010
+ wheel_rear: Wheel
1011
+ driver: LongitudinalDriver
1012
+ steering: SteeringManeuver
1013
+ speed_reference: object
1014
+
1015
+
1016
+ def rear_wheel_drive_vehicle(
1017
+ speed: float = 20.0,
1018
+ body: Optional[VehicleBody3DOF] = None,
1019
+ tire_front: Optional[FialaTire] = None,
1020
+ tire_rear: Optional[FialaTire] = None,
1021
+ wheel_front: Optional[Wheel] = None,
1022
+ wheel_rear: Optional[Wheel] = None,
1023
+ driver: Optional[LongitudinalDriver] = None,
1024
+ steering: Optional[SteeringManeuver] = None,
1025
+ drive_torque: float = 2000.0,
1026
+ brake_torque: float = 6000.0,
1027
+ brake_bias: float = 0.6,
1028
+ system: Optional[System] = None,
1029
+ ) -> VehicleAssembly:
1030
+ """Wire the five blocks into a rear-wheel-drive car, ready to run.
1031
+
1032
+ The assembly is the fiddly part -- twenty connections, and getting the
1033
+ reference frames wrong is silent -- so it lives here rather than being
1034
+ retyped per study. Every block can be passed in pre-configured; the
1035
+ defaults give a 1500 kg saloon trimmed at `speed` on a mu = 0.9 road.
1036
+
1037
+ `brake_bias` is the fraction of brake torque at the front axle, which
1038
+ is forward-biased on a real car because load transfer under braking
1039
+ puts the grip there.
1040
+ """
1041
+ if not 0.0 <= brake_bias <= 1.0:
1042
+ raise ValueError("brake_bias is a front fraction in [0, 1]")
1043
+
1044
+ from .math import Gain
1045
+ from .sources import Constant
1046
+
1047
+ sys = system if system is not None else System()
1048
+ body = body or VehicleBody3DOF(x0=[speed, 0.0, 0.0, 0.0, 0.0, 0.0], name="body")
1049
+ tire_front = tire_front or FialaTire(steered=True, name="tire_front")
1050
+ tire_rear = tire_rear or FialaTire(steered=False, name="tire_rear")
1051
+ if tire_front.steered is not True:
1052
+ raise ValueError("the front tire of a steered vehicle needs steered=True")
1053
+
1054
+ wheel_front = wheel_front or Wheel(
1055
+ Re=tire_front.Re, omega0=speed / tire_front.Re, name="wheel_front"
1056
+ )
1057
+ wheel_rear = wheel_rear or Wheel(
1058
+ Re=tire_rear.Re, omega0=speed / tire_rear.Re, name="wheel_rear"
1059
+ )
1060
+ driver = driver or LongitudinalDriver(Kp=0.5, Ki=0.2, name="driver")
1061
+ steering = steering or SteeringManeuver(
1062
+ profile="step", amplitude=0.0, name="steering"
1063
+ )
1064
+
1065
+ reference = Constant(value=speed, name="v_ref")
1066
+ throttle_gain = Gain(K=drive_torque, name="drive_torque")
1067
+ brake_front = Gain(K=brake_torque * brake_bias, name="brake_front")
1068
+ brake_rear = Gain(K=brake_torque * (1.0 - brake_bias), name="brake_rear")
1069
+ no_drive = Constant(value=0.0, name="no_front_drive")
1070
+
1071
+ for blk in (
1072
+ body,
1073
+ tire_front,
1074
+ tire_rear,
1075
+ wheel_front,
1076
+ wheel_rear,
1077
+ driver,
1078
+ steering,
1079
+ reference,
1080
+ throttle_gain,
1081
+ brake_front,
1082
+ brake_rear,
1083
+ no_drive,
1084
+ ):
1085
+ sys.add(blk)
1086
+
1087
+ # driver: speed error -> pedal demands -> torques
1088
+ sys.connect(reference, 0, driver, 0)
1089
+ sys.connect(body, VehicleBody3DOF.VX, driver, 1)
1090
+ sys.connect(driver, LongitudinalDriver.THROTTLE, throttle_gain, 0)
1091
+ sys.connect(driver, LongitudinalDriver.BRAKE, brake_front, 0)
1092
+ sys.connect(driver, LongitudinalDriver.BRAKE, brake_rear, 0)
1093
+
1094
+ # wheels: the front is braked only, the rear is driven and braked
1095
+ sys.connect(no_drive, 0, wheel_front, 0)
1096
+ sys.connect(brake_front, 0, wheel_front, 1)
1097
+ sys.connect(tire_front, FialaTire.FX, wheel_front, 2)
1098
+ sys.connect(throttle_gain, 0, wheel_rear, 0)
1099
+ sys.connect(brake_rear, 0, wheel_rear, 1)
1100
+ sys.connect(tire_rear, FialaTire.FX, wheel_rear, 2)
1101
+
1102
+ # tires: hub kinematics and normal load in, contact forces out
1103
+ sys.connect(wheel_front, Wheel.OMEGA, tire_front, 0)
1104
+ sys.connect(body, VehicleBody3DOF.VX, tire_front, 1)
1105
+ sys.connect(body, VehicleBody3DOF.VY_F, tire_front, 2)
1106
+ sys.connect(body, VehicleBody3DOF.FZ_F, tire_front, 3)
1107
+ sys.connect(steering, 0, tire_front, 4)
1108
+
1109
+ sys.connect(wheel_rear, Wheel.OMEGA, tire_rear, 0)
1110
+ sys.connect(body, VehicleBody3DOF.VX, tire_rear, 1)
1111
+ sys.connect(body, VehicleBody3DOF.VY_R, tire_rear, 2)
1112
+ sys.connect(body, VehicleBody3DOF.FZ_R, tire_rear, 3)
1113
+
1114
+ # contact forces back into the chassis (front still in the wheel frame)
1115
+ sys.connect(tire_front, FialaTire.FX, body, 0)
1116
+ sys.connect(tire_front, FialaTire.FY, body, 1)
1117
+ sys.connect(tire_rear, FialaTire.FX, body, 2)
1118
+ sys.connect(tire_rear, FialaTire.FY, body, 3)
1119
+ sys.connect(steering, 0, body, 4)
1120
+
1121
+ return VehicleAssembly(
1122
+ system=sys,
1123
+ body=body,
1124
+ tire_front=tire_front,
1125
+ tire_rear=tire_rear,
1126
+ wheel_front=wheel_front,
1127
+ wheel_rear=wheel_rear,
1128
+ driver=driver,
1129
+ steering=steering,
1130
+ speed_reference=reference,
1131
+ )
1132
+
1133
+
1134
+ @dataclass
1135
+ class FourWheelAssembly:
1136
+ """The blocks of an assembled four-corner vehicle.
1137
+
1138
+ `tires` and `wheels` are in corner order: front left, front right,
1139
+ rear left, rear right.
1140
+ """
1141
+
1142
+ system: System
1143
+ body: VehicleBody4Wheel
1144
+ tires: tuple
1145
+ wheels: tuple
1146
+ driver: LongitudinalDriver
1147
+ steering: SteeringManeuver
1148
+ speed_reference: object
1149
+
1150
+ CORNERS = ("fl", "fr", "rl", "rr")
1151
+
1152
+ def tire(self, corner: str) -> FialaTire:
1153
+ return self.tires[self.CORNERS.index(corner)]
1154
+
1155
+ def wheel(self, corner: str) -> Wheel:
1156
+ return self.wheels[self.CORNERS.index(corner)]
1157
+
1158
+
1159
+ def four_wheel_vehicle(
1160
+ speed: float = 20.0,
1161
+ body: Optional[VehicleBody4Wheel] = None,
1162
+ tires=None,
1163
+ driver: Optional[LongitudinalDriver] = None,
1164
+ steering: Optional[SteeringManeuver] = None,
1165
+ drive_torque: float = 2000.0,
1166
+ brake_torque: float = 6000.0,
1167
+ brake_bias: float = 0.6,
1168
+ system: Optional[System] = None,
1169
+ ) -> FourWheelAssembly:
1170
+ """Wire four corners onto a :class:`VehicleBody4Wheel`, ready to run.
1171
+
1172
+ `tires` is four :class:`FialaTire` blocks in corner order (front left,
1173
+ front right, rear left, rear right); the two front ones must have
1174
+ ``steered=True``. Giving them different `mu` is how you set up a
1175
+ split-mu surface.
1176
+
1177
+ Drive torque is split evenly across the rear wheels, which is what an
1178
+ open differential does; brake torque is split by `brake_bias` front to
1179
+ rear and evenly left to right.
1180
+ """
1181
+ if not 0.0 <= brake_bias <= 1.0:
1182
+ raise ValueError("brake_bias is a front fraction in [0, 1]")
1183
+
1184
+ from .math import Gain
1185
+ from .sources import Constant
1186
+
1187
+ sys = system if system is not None else System()
1188
+ body = body or VehicleBody4Wheel(x0=[speed, 0.0, 0.0, 0.0, 0.0, 0.0], name="body")
1189
+ if tires is None:
1190
+ tires = tuple(
1191
+ FialaTire(steered=corner in ("fl", "fr"), name=f"tire_{corner}")
1192
+ for corner in FourWheelAssembly.CORNERS
1193
+ )
1194
+ tires = tuple(tires)
1195
+ if len(tires) != 4:
1196
+ raise ValueError("four tires are needed, in order fl, fr, rl, rr")
1197
+ if not (tires[0].steered and tires[1].steered):
1198
+ raise ValueError("both front tires need steered=True")
1199
+ if tires[2].steered or tires[3].steered:
1200
+ raise ValueError("the rear tires of this vehicle are not steered")
1201
+
1202
+ wheels = tuple(
1203
+ Wheel(Re=tire.Re, omega0=speed / tire.Re, name=f"wheel_{corner}")
1204
+ for tire, corner in zip(tires, FourWheelAssembly.CORNERS)
1205
+ )
1206
+ driver = driver or LongitudinalDriver(Kp=0.5, Ki=0.2, name="driver")
1207
+ steering = steering or SteeringManeuver(
1208
+ profile="step", amplitude=0.0, name="steering"
1209
+ )
1210
+
1211
+ reference = Constant(value=speed, name="v_ref")
1212
+ # an open differential splits the drive torque evenly across the axle
1213
+ drive = Gain(K=0.5 * drive_torque, name="drive_torque")
1214
+ brake_f = Gain(K=0.5 * brake_torque * brake_bias, name="brake_front")
1215
+ brake_r = Gain(K=0.5 * brake_torque * (1.0 - brake_bias), name="brake_rear")
1216
+ no_drive = Constant(value=0.0, name="no_front_drive")
1217
+
1218
+ for blk in (body, driver, steering, reference, drive, brake_f, brake_r, no_drive):
1219
+ sys.add(blk)
1220
+ for blk in tires + wheels:
1221
+ sys.add(blk)
1222
+
1223
+ sys.connect(reference, 0, driver, 0)
1224
+ sys.connect(body, VehicleBody4Wheel.VX, driver, 1)
1225
+ sys.connect(driver, LongitudinalDriver.THROTTLE, drive, 0)
1226
+ sys.connect(driver, LongitudinalDriver.BRAKE, brake_f, 0)
1227
+ sys.connect(driver, LongitudinalDriver.BRAKE, brake_r, 0)
1228
+
1229
+ hub_speed = (
1230
+ VehicleBody4Wheel.VX_FL,
1231
+ VehicleBody4Wheel.VX_FR,
1232
+ VehicleBody4Wheel.VX_RL,
1233
+ VehicleBody4Wheel.VX_RR,
1234
+ )
1235
+ axle_lateral = (
1236
+ VehicleBody4Wheel.VY_F,
1237
+ VehicleBody4Wheel.VY_F,
1238
+ VehicleBody4Wheel.VY_R,
1239
+ VehicleBody4Wheel.VY_R,
1240
+ )
1241
+ corner_load = (
1242
+ VehicleBody4Wheel.FZ_FL,
1243
+ VehicleBody4Wheel.FZ_FR,
1244
+ VehicleBody4Wheel.FZ_RL,
1245
+ VehicleBody4Wheel.FZ_RR,
1246
+ )
1247
+
1248
+ for i, (tire, wheel) in enumerate(zip(tires, wheels)):
1249
+ front = i < 2
1250
+ sys.connect(no_drive if front else drive, 0, wheel, 0)
1251
+ sys.connect(brake_f if front else brake_r, 0, wheel, 1)
1252
+ sys.connect(tire, FialaTire.FX, wheel, 2)
1253
+
1254
+ sys.connect(wheel, Wheel.OMEGA, tire, 0)
1255
+ sys.connect(body, hub_speed[i], tire, 1)
1256
+ sys.connect(body, axle_lateral[i], tire, 2)
1257
+ sys.connect(body, corner_load[i], tire, 3)
1258
+ if front:
1259
+ sys.connect(steering, 0, tire, 4)
1260
+
1261
+ sys.connect(tire, FialaTire.FX, body, 2 * i)
1262
+ sys.connect(tire, FialaTire.FY, body, 2 * i + 1)
1263
+
1264
+ sys.connect(steering, 0, body, VehicleBody4Wheel.DELTA)
1265
+
1266
+ return FourWheelAssembly(
1267
+ system=sys,
1268
+ body=body,
1269
+ tires=tires,
1270
+ wheels=wheels,
1271
+ driver=driver,
1272
+ steering=steering,
1273
+ speed_reference=reference,
1274
+ )