Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 116 additions & 8 deletions Docs/2_Architecture/2.8_Simulation.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

## Simulation is the process of running our robot code on a computer other than the robot to test it without being limited by physical hardware

### Overview

Generally speaking, simulation depends on sending the inputs we would like to test to a model of a system (mechanism) and analyzing the simulated results.
There are several ways to do this, depending on what you’re simulating.
This could be something small, like simulated readings of an encoder, or something more complex, like a physics simulation of an arm.
Simulation is important for a couple of reasons—we can test something without risking breaking an actual physical part, as well as being able to concurrently develop code as those physical components are being built (which is often the case during the build season).

### Sim GUI

We have a number of tools at our disposal for simulation.
One is WPILib’s built in desktop simulation.
One is WPILib’s built-in desktop simulation.
This handles the process of sending inputs (from joysticks, widgets in the sim dashboard, etc) and running robot code on a computer.
This is the backbone of our simulation.

Expand All @@ -33,7 +37,6 @@ A state-space model is a set of matrix equations that describe how a system chan
---
</details>


Like other simulated systems, the mechanism’s state is updated periodically with simulated inputs.
For example, we can simulate the change in position of an elevator when a certain voltage is applied to its motor using this mathematical model.

Expand All @@ -45,37 +48,142 @@ We tend to use one or two of these per robot for major mechanisms.
If you want to learn more about this sort of modeling, look at the [control theory for FRC book](https://file.tavsys.net/control/controls-engineering-in-frc.pdf).
Note that the topics covered by this book are largely far more advanced than high schoolers have the math background for, and it is not required reading.

### AdvantageScope

Running a model is useful, but even more useful is being able to visualize the output of the model.
There are several dashboards you can use to do this, but we mainly use AdvantageScope.
[AdvantageScope](https://github.com/Mechanical-Advantage/AdvantageScope) is a tool developed by Team 6328 to visualize data from live robots, simulated robots, and robot logs.
It provides a variety of formats to visualize data from line graphs to 3d field models to tables and more.
It provides a variety of formats to visualize data.
These applications include things like line graphs, 2d field modeling, 3d robot modeling, tables, timeline plots, custom widgets, and more.

<img src="../../Assets/AdvantageScopeScreenshot.png" alt="Screenshot of Advantagescope" width="600"/>

This way we can run autonomous routines, drive around in sim, test mechanisms, and even run 3d calculations like localizing with AprilTags, all without requiring the robot.
Another major feature of AdvantageScope is the ability to log telemetry and replay runs.
This is helpful for collecting data, replaying matches, and comparing sim with the real results.

It is closely integrated with AdvantageKit, a logging framework also from Team 6328, but does not require it.

You can find the docs [here.](https://docs.advantagescope.org/)

### 3d Modeling
3d modeling in AdvantageScope requires us to import and configure any 3d CAD robot models and field components we want to use.
Our team prefers this approach because it's helpful to visualise and test the full robot and all its components.
In the simulator, both 2D and 3D geometry types are supported, such as, Pose2d, Pose3d, Translation2d, and Translation3d.

<img src="https://docs.advantagescope.org/assets/images/3d-field-1-5a9b65221b7a7b12c2c0ed8d5eb5b76e.png" alt="Screenshot of Advantagescope 3d field" width="400"/>

More details about the 3d field can be found [here](https://docs.advantagescope.org/tab-reference/3d-field), and more info about importing custom assets is [here.](https://docs.advantagescope.org/more-features/custom-assets)
In order to implement these custom CAD models, they have to be [converted into the gITF format.](https://docs.advantagescope.org/more-features/gltf-convert)

### 2d Mechanism Modeling
Mechanism2d is an object which provides simple 2D visualization of mechanisms.
Setting up the mechanism 2d involves:
- creating a new Mechanism2d object
- defining a root node where the mechanism is anchored (this can be a pivot point or robot base) using MechanismRoot2d.
- Finally we append existing nodes or ligaments with MechanismLigament2d to add more components.
For instance, with Mechanism2d, we can create a shoulder mechanism and add the wrist to it as a ligament.
You can define linkages, arms, elevators, etc and update their state in code.
This can be displayed in the sim GUI, and is also compatible with AdvantageScope's 2D & 3D visualization tools.

Example code:
```Java
// Mechanisms
private final LoggedMechanism2d elevatorMech2d =
new LoggedMechanism2d(3.0, 4.0); //width, height
private final LoggedMechanismRoot2d
elevatorRoot = elevatorMech2d.getRoot("Elevator", 21.5, 0.0); //name, x, y
private final LoggedMechanismLigament2d carriageLigament =
new LoggedMechanismLigament2d("Carriage", 0, ELEVATOR_ANGLE.getDegrees()); //name, length, angle
// Append carriage ligament to be based on elevator root
elevatorRoot.append(carriageLigament);
```

<img src="https://docs.wpilib.org/en/stable/_images/advantagescope-mechanism.png" alt="Screenshot of Advantagescope with mech 2d" width="400"/>

More details:
- [WPILib Mech2d docs](https://docs.wpilib.org/en/stable/docs/software/dashboards/glass/mech2d-widget.html)
- [WPILib API Reference](https://github.wpilib.org/allwpilib/docs/release/java/edu/wpi/first/wpilibj/smartdashboard/Mechanism2d.html)

### WPILib Sim Classes
WPILib provides sim classes such as ElevatorSim and SingledJointedArmSim.
These require parameters such as gear ratios, mass, and motor types so the simulation knows how to behave.
Once we set up the simulation we can use it to test our code against a virtual mechanism.

Go [here](https://github.wpilib.org/allwpilib/docs/release/java/edu/wpi/first/wpilibj/simulation/package-summary.html) to check out the specific WPILib sim classes and methods.

Take a look at this quick example:
```Java
new ElevatorSim(
DCMotor.getKrakenX60Foc(1), //gear box: type of motor and number of motors
ElevatorSubsystem.GEAR_RATIO, //gearing: gear ratio
Units.lbsToKilograms(7.0 + (3.25 / 2)), //carriage mass: mass of elevator carriage
ElevatorSubsystem.DRUM_RADIUS_METERS, // drumRadiusMeters: radius of the drum the elevator spool is wrapped around
0.0, // minHeightMeters: the minimum height
ElevatorSubsystem.MAX_EXTENSION_METERS, // maxHeightMeters: the maximum height
true, // simumateGravity: should gravity be simulated?
0.0); //measurementStdDevs: standard deviation of measurements
```

### MapleSim
Our team also integrates MapleSim into the robot code.
MapleSim supports more complex physics simulations.
MapleSim allows us to simulate more complex interactions between the robot and other things on the field (field elements, game pieces, other robots, etc).
This lets us test and tune the robot behavior in a more realistic way.
We mostly use this for a more accurate swerve simulation.

Example code:
```Java
//simulate drive motor with MapleSim
simulation.useDriveMotorController(
new MaplePhoenixUtil.TalonFXMotorControllerSim(driveTalon, true));
//simulate steer motor with MapleSim and remote CANcoder
simulation.useSteerMotorController(
new MaplePhoenixUtil.TalonFXMotorControllerWithRemoteCancoderSim(
turnTalon,
swerveConstants.getTurnMotorInverted(),
cancoder,
false,
Angle.ofBaseUnits(moduleConstants.cancoderOffset().getRadians(), Radian)));
```

The MapleSim docs are [here.](https://shenzhen-robotics-alliance.github.io/maple-sim/)

### Sim vs Real
The final major tool is being able to swap between simulated inputs and outputs (IO) and real IO easily and correctly.
We will cover what this looks like with AdvantageKit [here](AdvantageKit.md), but at a high level, this means that we have both a sim and real version of each mechanism in our code.
We will cover what this looks like with AdvantageKit [here](https://github.com/HighlanderRobotics/Highlanders-Training/blob/c79d758fda0429e41651b35bf9bfec68248e90c5/Docs/2_Architecture/2.6_AdvantageKit.md#L4), but at a high level, this means that we have both a sim and real version of each mechanism in our code.
This is so we can easily test our code in sim and have minimal work to move it to real hardware.

---

The real IO layer controls the actual motors, sensors, and hardware on the robot.
The sim IO replaces those with the simulated versions that approximate how the robot component should behave.
The overall code structure is the same; however, the specific implementation differs.
To elaborate, in the real code, this means dealing with initializing, configuring, and driving hardware like Talons or CANcoders, while sim code uses simulation classes, like ElevatorSim, to mimic their behavior.

As you look through the code, you'll notice that real has hardware based commands, whereas sim uses methods from the sim classes.

if you want to take a closer look at what the specific code looks like, follow along with [this tutorial](https://github.com/HighlanderRobotics/Highlanders-Training/blob/c79d758fda0429e41651b35bf9bfec68248e90c5/Docs/2_Architecture/2.9_KitbotExampleWalkthroughSim.md#L4) for adding sim capabilities to the kitbot.

---

### Resources

- Read through the [WPILib docs intro to simulation](https://docs.wpilib.org/en/stable/docs/software/wpilib-tools/robot-simulation/introduction.html).
- Optional additional reading on [state space modeling](https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html)
- [WPILib simulations](https://github.wpilib.org/allwpilib/docs/release/java/edu/wpi/first/wpilibj/simulation/package-summary.html)

### Examples

- The [kitbot example code](../../Examples/KitbotDemoSim)

- The [kitbot example code](../../Examples/KitbotDemoSim)
### Exercises

- Download and install [AdvantageScope](https://github.com/Mechanical-Advantage/AdvantageScope).
- Follow [this tutorial](KitbotExampleWalkthroughSim.md) to convert your kitbot code to AdvantageKit and simulation.
- Follow [this tutorial](https://github.com/HighlanderRobotics/Highlanders-Training/blob/c79d758fda0429e41651b35bf9bfec68248e90c5/Docs/2_Architecture/2.9_KitbotExampleWalkthroughSim.md#L4) to convert your kitbot code to AdvantageKit and simulation.

### Notes

- Structuring a codebase to be simulateable is not an easy task.
- Structuring a codebase to be simulatable is not an easy task.
It is important to be familiar with the tools we have and stick to a clean structure to make it easy to simulate our code.
- Code that has been tested in sim does not necessarily work on the robot.
Be sure to stay safe and prepare for unexpected behavior when testing, especially for the first time.