Clean up Java style (#5990)

Also make equivalent changes in C++ where applicable.

Co-authored-by: Sriman Achanta <68172138+srimanachanta@users.noreply.github.com>
This commit is contained in:
Tyler Veness
2023-12-03 16:21:32 -08:00
committed by GitHub
parent 66172ab288
commit 2bb1409b82
113 changed files with 426 additions and 617 deletions

View File

@@ -12,7 +12,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import edu.wpi.first.math.geometry.Pose3d;
import edu.wpi.first.math.geometry.Rotation3d;
import edu.wpi.first.math.util.Units;
import java.io.IOException;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -28,7 +27,7 @@ class LoadConfigTest {
}
@Test
void test2022RapidReact() throws IOException {
void test2022RapidReact() {
AprilTagFieldLayout layout = AprilTagFields.k2022RapidReact.loadAprilTagLayoutField();
// Blue Hangar Truss - Hub

View File

@@ -98,7 +98,7 @@ public final class Main {
// parse file
JsonElement top;
try {
top = new JsonParser().parse(Files.newBufferedReader(Paths.get(configFile)));
top = JsonParser.parseReader(Files.newBufferedReader(Paths.get(configFile)));
} catch (IOException ex) {
System.err.println("could not open '" + configFile + "': " + ex);
return false;

View File

@@ -114,7 +114,7 @@ public final class CameraServer {
}
@Override
public void close() throws Exception {
public void close() {
if (m_booleanValueEntry != null) {
m_booleanValueEntry.close();
}

View File

@@ -102,7 +102,7 @@ public class VideoListener implements AutoCloseable {
listener.accept(event);
} catch (Throwable throwable) {
System.err.println(
"Unhandled exception during listener callback: " + throwable.toString());
"Unhandled exception during listener callback: " + throwable);
throwable.printStackTrace();
}
}

View File

@@ -131,8 +131,7 @@ public class DMAJNISample {
}
// + 2 Hack, but needed to not have to call into JNI
int value = readValue(data.m_valueType + 2, data.m_index);
return value;
return readValue(data.m_valueType + 2, data.m_index);
}
public void getAnalogAccumulator(int analogInputHandle, AccumulatorResult result) {

View File

@@ -574,7 +574,7 @@ public final class NetworkTable {
return m_inst.addListener(
new String[] {m_pathWithSep},
EnumSet.of(NetworkTableEvent.Kind.kPublish, NetworkTableEvent.Kind.kImmediate),
new Consumer<NetworkTableEvent>() {
new Consumer<>() {
final Set<String> m_notifiedTables = new HashSet<>();
@Override

View File

@@ -190,14 +190,14 @@ final class ProtobufEntryImpl<T> extends EntryBase implements ProtobufEntry<T> {
private TimestampedObject<T> fromRaw(TimestampedRaw raw, T defaultValue) {
if (raw.value.length == 0) {
return new TimestampedObject<T>(0, 0, defaultValue);
return new TimestampedObject<>(0, 0, defaultValue);
}
try {
synchronized (m_buf) {
return new TimestampedObject<T>(raw.timestamp, raw.serverTime, m_buf.read(raw.value));
return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.read(raw.value));
}
} catch (IOException e) {
return new TimestampedObject<T>(0, 0, defaultValue);
return new TimestampedObject<>(0, 0, defaultValue);
}
}

View File

@@ -32,7 +32,7 @@ public final class ProtobufTopic<T> extends Topic {
* @return ProtobufTopic for value class
*/
public static <T> ProtobufTopic<T> wrap(Topic topic, Protobuf<T, ?> proto) {
return new ProtobufTopic<T>(topic, proto);
return new ProtobufTopic<>(topic, proto);
}
/**
@@ -47,7 +47,7 @@ public final class ProtobufTopic<T> extends Topic {
*/
public static <T> ProtobufTopic<T> wrap(
NetworkTableInstance inst, int handle, Protobuf<T, ?> proto) {
return new ProtobufTopic<T>(inst, handle, proto);
return new ProtobufTopic<>(inst, handle, proto);
}
/**
@@ -63,7 +63,7 @@ public final class ProtobufTopic<T> extends Topic {
* @return subscriber
*/
public ProtobufSubscriber<T> subscribe(T defaultValue, PubSubOption... options) {
return new ProtobufEntryImpl<T>(
return new ProtobufEntryImpl<>(
this,
ProtobufBuffer.create(m_proto),
NetworkTablesJNI.subscribe(
@@ -87,7 +87,7 @@ public final class ProtobufTopic<T> extends Topic {
*/
public ProtobufPublisher<T> publish(PubSubOption... options) {
m_inst.addSchema(m_proto);
return new ProtobufEntryImpl<T>(
return new ProtobufEntryImpl<>(
this,
ProtobufBuffer.create(m_proto),
NetworkTablesJNI.publish(
@@ -113,7 +113,7 @@ public final class ProtobufTopic<T> extends Topic {
*/
public ProtobufPublisher<T> publishEx(String properties, PubSubOption... options) {
m_inst.addSchema(m_proto);
return new ProtobufEntryImpl<T>(
return new ProtobufEntryImpl<>(
this,
ProtobufBuffer.create(m_proto),
NetworkTablesJNI.publishEx(
@@ -144,7 +144,7 @@ public final class ProtobufTopic<T> extends Topic {
* @return entry
*/
public ProtobufEntry<T> getEntry(T defaultValue, PubSubOption... options) {
return new ProtobufEntryImpl<T>(
return new ProtobufEntryImpl<>(
this,
ProtobufBuffer.create(m_proto),
NetworkTablesJNI.getEntry(

View File

@@ -177,15 +177,14 @@ final class StructArrayEntryImpl<T> extends EntryBase implements StructArrayEntr
@SuppressWarnings("PMD.AvoidCatchingGenericException")
private TimestampedObject<T[]> fromRaw(TimestampedRaw raw, T[] defaultValue) {
if (raw.value.length == 0) {
return new TimestampedObject<T[]>(0, 0, defaultValue);
return new TimestampedObject<>(0, 0, defaultValue);
}
try {
synchronized (m_buf) {
return new TimestampedObject<T[]>(
raw.timestamp, raw.serverTime, m_buf.readArray(raw.value));
return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.readArray(raw.value));
}
} catch (RuntimeException e) {
return new TimestampedObject<T[]>(0, 0, defaultValue);
return new TimestampedObject<>(0, 0, defaultValue);
}
}

View File

@@ -32,7 +32,7 @@ public final class StructArrayTopic<T> extends Topic {
* @return StructArrayTopic for value class
*/
public static <T> StructArrayTopic<T> wrap(Topic topic, Struct<T> struct) {
return new StructArrayTopic<T>(topic, struct);
return new StructArrayTopic<>(topic, struct);
}
/**
@@ -47,7 +47,7 @@ public final class StructArrayTopic<T> extends Topic {
*/
public static <T> StructArrayTopic<T> wrap(
NetworkTableInstance inst, int handle, Struct<T> struct) {
return new StructArrayTopic<T>(inst, handle, struct);
return new StructArrayTopic<>(inst, handle, struct);
}
/**
@@ -63,7 +63,7 @@ public final class StructArrayTopic<T> extends Topic {
* @return subscriber
*/
public StructArraySubscriber<T> subscribe(T[] defaultValue, PubSubOption... options) {
return new StructArrayEntryImpl<T>(
return new StructArrayEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.subscribe(
@@ -87,7 +87,7 @@ public final class StructArrayTopic<T> extends Topic {
*/
public StructArrayPublisher<T> publish(PubSubOption... options) {
m_inst.addSchema(m_struct);
return new StructArrayEntryImpl<T>(
return new StructArrayEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.publish(
@@ -113,7 +113,7 @@ public final class StructArrayTopic<T> extends Topic {
*/
public StructArrayPublisher<T> publishEx(String properties, PubSubOption... options) {
m_inst.addSchema(m_struct);
return new StructArrayEntryImpl<T>(
return new StructArrayEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.publishEx(
@@ -144,7 +144,7 @@ public final class StructArrayTopic<T> extends Topic {
* @return entry
*/
public StructArrayEntry<T> getEntry(T[] defaultValue, PubSubOption... options) {
return new StructArrayEntryImpl<T>(
return new StructArrayEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.getEntry(

View File

@@ -188,14 +188,14 @@ final class StructEntryImpl<T> extends EntryBase implements StructEntry<T> {
@SuppressWarnings("PMD.AvoidCatchingGenericException")
private TimestampedObject<T> fromRaw(TimestampedRaw raw, T defaultValue) {
if (raw.value.length == 0) {
return new TimestampedObject<T>(0, 0, defaultValue);
return new TimestampedObject<>(0, 0, defaultValue);
}
try {
synchronized (m_buf) {
return new TimestampedObject<T>(raw.timestamp, raw.serverTime, m_buf.read(raw.value));
return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.read(raw.value));
}
} catch (RuntimeException e) {
return new TimestampedObject<T>(0, 0, defaultValue);
return new TimestampedObject<>(0, 0, defaultValue);
}
}

View File

@@ -32,7 +32,7 @@ public final class StructTopic<T> extends Topic {
* @return StructTopic for value class
*/
public static <T> StructTopic<T> wrap(Topic topic, Struct<T> struct) {
return new StructTopic<T>(topic, struct);
return new StructTopic<>(topic, struct);
}
/**
@@ -46,7 +46,7 @@ public final class StructTopic<T> extends Topic {
* @return StructTopic for value class
*/
public static <T> StructTopic<T> wrap(NetworkTableInstance inst, int handle, Struct<T> struct) {
return new StructTopic<T>(inst, handle, struct);
return new StructTopic<>(inst, handle, struct);
}
/**
@@ -62,7 +62,7 @@ public final class StructTopic<T> extends Topic {
* @return subscriber
*/
public StructSubscriber<T> subscribe(T defaultValue, PubSubOption... options) {
return new StructEntryImpl<T>(
return new StructEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.subscribe(
@@ -86,7 +86,7 @@ public final class StructTopic<T> extends Topic {
*/
public StructPublisher<T> publish(PubSubOption... options) {
m_inst.addSchema(m_struct);
return new StructEntryImpl<T>(
return new StructEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.publish(
@@ -112,7 +112,7 @@ public final class StructTopic<T> extends Topic {
*/
public StructPublisher<T> publishEx(String properties, PubSubOption... options) {
m_inst.addSchema(m_struct);
return new StructEntryImpl<T>(
return new StructEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.publishEx(
@@ -143,7 +143,7 @@ public final class StructTopic<T> extends Topic {
* @return entry
*/
public StructEntry<T> getEntry(T defaultValue, PubSubOption... options) {
return new StructEntryImpl<T>(
return new StructEntryImpl<>(
this,
StructBuffer.create(m_struct),
NetworkTablesJNI.getEntry(

View File

@@ -6,7 +6,6 @@ package edu.wpi.first.networktables;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
@@ -61,8 +60,8 @@ class NetworkTableTest {
return Stream.of(
Arguments.of(Collections.singletonList("/"), ""),
Arguments.of(Collections.singletonList("/"), "/"),
Arguments.of(Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/baz"), "/foo/bar/baz"),
Arguments.of(Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/"), "/foo/bar/"));
Arguments.of(List.of("/", "/foo", "/foo/bar", "/foo/bar/baz"), "/foo/bar/baz"),
Arguments.of(List.of("/", "/foo", "/foo/bar", "/foo/bar/"), "/foo/bar/"));
}
@ParameterizedTest

View File

@@ -4,11 +4,10 @@
package edu.wpi.first.networktables;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -31,9 +30,9 @@ class RawTest {
void testGenericByteArray() {
GenericEntry entry = m_inst.getTopic("test").getGenericEntry("raw");
entry.setRaw(new byte[] {5}, 10);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {5}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {5});
entry.setRaw(new byte[] {5, 6, 7}, 1, 2, 15);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7});
assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, -1, 2, 20));
assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, 1, -2, 20));
assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, 1, 1, 20));
@@ -43,9 +42,9 @@ class RawTest {
void testRawByteArray() {
RawEntry entry = m_inst.getRawTopic("test").getEntry("raw", new byte[] {});
entry.set(new byte[] {5}, 10);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {5}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {5});
entry.set(new byte[] {5, 6, 7}, 1, 2, 15);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7});
assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, -1, 1, 20));
assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, 1, -1, 20));
assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, 1, 1, 20));
@@ -55,15 +54,15 @@ class RawTest {
void testGenericByteBuffer() {
GenericEntry entry = m_inst.getTopic("test").getGenericEntry("raw");
entry.setRaw(ByteBuffer.wrap(new byte[] {5}), 10);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {5}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {5});
entry.setRaw(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1), 15);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7});
entry.setRaw(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1).limit(2), 16);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6});
entry.setRaw(ByteBuffer.wrap(new byte[] {8, 9, 0}), 1, 2, 20);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {9, 0}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {9, 0});
entry.setRaw(ByteBuffer.wrap(new byte[] {1, 2, 3}).position(2), 0, 2, 25);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {1, 2}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {1, 2});
assertThrows(
IndexOutOfBoundsException.class,
() -> entry.setRaw(ByteBuffer.wrap(new byte[] {5}), -1, 1, 30));
@@ -79,15 +78,15 @@ class RawTest {
void testRawByteBuffer() {
RawEntry entry = m_inst.getRawTopic("test").getEntry("raw", new byte[] {});
entry.set(ByteBuffer.wrap(new byte[] {5}), 10);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {5}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {5});
entry.set(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1), 15);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7});
entry.set(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1).limit(2), 16);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {6});
entry.set(ByteBuffer.wrap(new byte[] {8, 9, 0}), 1, 2, 20);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {9, 0}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {9, 0});
entry.set(ByteBuffer.wrap(new byte[] {1, 2, 3}).position(2), 0, 2, 25);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {1, 2}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {1, 2});
assertThrows(
IndexOutOfBoundsException.class,
() -> entry.set(ByteBuffer.wrap(new byte[] {5}), -1, 1, 30));
@@ -105,13 +104,13 @@ class RawTest {
ByteBuffer bb = ByteBuffer.allocateDirect(3);
bb.put(new byte[] {5, 6, 7});
entry.setRaw(bb.position(1), 15);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7});
entry.setRaw(bb.limit(2), 16);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6});
bb.clear();
bb.put(new byte[] {8, 9, 0});
entry.setRaw(bb, 1, 2, 20);
assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {9, 0}));
assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {9, 0});
assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, -1, 1, 25));
assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, 1, -1, 25));
assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, 2, 2, 25));
@@ -123,13 +122,13 @@ class RawTest {
ByteBuffer bb = ByteBuffer.allocateDirect(3);
bb.put(new byte[] {5, 6, 7});
entry.set(bb.position(1), 15);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7});
entry.set(bb.limit(2), 16);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {6});
bb.clear();
bb.put(new byte[] {8, 9, 0});
entry.set(bb, 1, 2, 20);
assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {9, 0}));
assertArrayEquals(entry.get(new byte[] {}), new byte[] {9, 0});
assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, -1, 1, 25));
assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, 1, -1, 25));
assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, 2, 2, 25));

View File

@@ -683,9 +683,7 @@ public final class CommandScheduler implements Sendable, AutoCloseable {
null);
builder.addIntegerArrayProperty(
"Cancel",
() -> {
return new long[] {};
},
() -> new long[] {},
toCancel -> {
Map<Long, Command> ids = new LinkedHashMap<>();
for (Command command : m_scheduledCommands) {

View File

@@ -153,7 +153,7 @@ class ParallelRaceGroupTest extends CommandTestBase
scheduler.run();
command2Holder.setFinished(true);
// at this point the sequential group should be done
assertDoesNotThrow(() -> scheduler.run());
assertDoesNotThrow(scheduler::run);
assertFalse(scheduler.isScheduled(group2));
}
}

View File

@@ -288,7 +288,7 @@ class SchedulingRecursionTest extends CommandTestBase {
scheduler.schedule(cCancelsD);
scheduler.schedule(dCancelsAll);
assertDoesNotThrow(() -> scheduler.run());
assertDoesNotThrow(scheduler::run);
assertEquals(4, counter.get());
assertFalse(scheduler.isScheduled(aCancelsB));
assertFalse(scheduler.isScheduled(bCancelsC));

View File

@@ -4,6 +4,7 @@
#include "frc/I2C.h"
#include <algorithm>
#include <utility>
#include <hal/FRCUsageReporting.h>
@@ -96,7 +97,7 @@ bool I2C::VerifySensor(int registerAddress, int count,
uint8_t deviceData[4];
for (int i = 0, curRegisterAddress = registerAddress; i < count;
i += 4, curRegisterAddress += 4) {
int toRead = count - i < 4 ? count - i : 4;
int toRead = std::min(count - i, 4);
// Read the chunk of data. Return false if the sensor does not respond.
if (Read(curRegisterAddress, toRead, deviceData)) {
return false;

View File

@@ -23,15 +23,15 @@ using namespace frc;
/** Converts volts to PSI per the REV Analog Pressure Sensor datasheet. */
units::pounds_per_square_inch_t VoltsToPSI(units::volt_t sensorVoltage,
units::volt_t supplyVoltage) {
auto pressure = 250 * (sensorVoltage.value() / supplyVoltage.value()) - 25;
return units::pounds_per_square_inch_t{pressure};
return units::pounds_per_square_inch_t{
250 * (sensorVoltage.value() / supplyVoltage.value()) - 25};
}
/** Converts PSI to volts per the REV Analog Pressure Sensor datasheet. */
units::volt_t PSIToVolts(units::pounds_per_square_inch_t pressure,
units::volt_t supplyVoltage) {
auto voltage = supplyVoltage.value() * (0.004 * pressure.value() + 0.1);
return units::volt_t{voltage};
return units::volt_t{supplyVoltage.value() *
(0.004 * pressure.value() + 0.1)};
}
wpi::mutex PneumaticHub::m_handleLock;

View File

@@ -92,26 +92,22 @@ Pose2d DifferentialDrivetrainSim::GetPose() const {
}
units::ampere_t DifferentialDrivetrainSim::GetLeftCurrentDraw() const {
auto loadIleft =
m_motor.Current(
units::radians_per_second_t{m_x(State::kLeftVelocity) *
m_currentGearing / m_wheelRadius.value()},
units::volt_t{m_u(0)}) *
wpi::sgn(m_u(0));
return loadIleft;
return m_motor.Current(units::radians_per_second_t{m_x(State::kLeftVelocity) *
m_currentGearing /
m_wheelRadius.value()},
units::volt_t{m_u(0)}) *
wpi::sgn(m_u(0));
}
units::ampere_t DifferentialDrivetrainSim::GetRightCurrentDraw() const {
auto loadIRight =
m_motor.Current(
units::radians_per_second_t{m_x(State::kRightVelocity) *
m_currentGearing / m_wheelRadius.value()},
units::volt_t{m_u(1)}) *
wpi::sgn(m_u(1));
return loadIRight;
return m_motor.Current(
units::radians_per_second_t{m_x(State::kRightVelocity) *
m_currentGearing /
m_wheelRadius.value()},
units::volt_t{m_u(1)}) *
wpi::sgn(m_u(1));
}
units::ampere_t DifferentialDrivetrainSim::GetCurrentDraw() const {
return GetLeftCurrentDraw() + GetRightCurrentDraw();
}

View File

@@ -7,6 +7,7 @@
#include <memory>
#include <hal/Types.h>
#include <units/pressure.h>
#include <wpi/DenseMap.h>
#include <wpi/mutex.h>

View File

@@ -108,9 +108,9 @@ public class ADIS16448_IMU implements AutoCloseable, Sendable {
_32s(10),
_64s(11);
private int value;
private final int value;
private CalibrationTime(int value) {
CalibrationTime(int value) {
this.value = value;
}
}
@@ -130,9 +130,9 @@ public class ADIS16448_IMU implements AutoCloseable, Sendable {
private IMUAxis m_yaw_axis;
/* Offset data storage */
private double m_offset_data_gyro_rate_x[];
private double m_offset_data_gyro_rate_y[];
private double m_offset_data_gyro_rate_z[];
private double[] m_offset_data_gyro_rate_x;
private double[] m_offset_data_gyro_rate_y;
private double[] m_offset_data_gyro_rate_z;
/* Instant raw output variables */
private double m_gyro_rate_x = 0.0;
@@ -199,7 +199,7 @@ public class ADIS16448_IMU implements AutoCloseable, Sendable {
private SimDouble m_simAccelZ;
/* CRC-16 Look-Up Table */
int adiscrc[] =
int[] adiscrc =
new int[] {
0x0000, 0x17CE, 0x0FDF, 0x1811, 0x1FBE, 0x0870, 0x1061, 0x07AF,
0x1F3F, 0x08F1, 0x10E0, 0x072E, 0x0081, 0x174F, 0x0F5E, 0x1890,
@@ -358,7 +358,7 @@ public class ADIS16448_IMU implements AutoCloseable, Sendable {
/** */
private static int toShort(int... buf) {
return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF) << 0));
return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF)));
}
/** */
@@ -481,7 +481,7 @@ public class ADIS16448_IMU implements AutoCloseable, Sendable {
}
public int configDecRate(int m_decRate) {
int writeValue = m_decRate;
int writeValue;
int readbackValue;
if (!switchToStandardSPI()) {
DriverStation.reportError("Failed to configure/reconfigure standard SPI.", false);

View File

@@ -193,9 +193,9 @@ public class ADIS16470_IMU implements AutoCloseable, Sendable {
_32s(10),
_64s(11);
private int value;
private final int value;
private CalibrationTime(int value) {
CalibrationTime(int value) {
this.value = value;
}
}
@@ -396,7 +396,7 @@ public class ADIS16470_IMU implements AutoCloseable, Sendable {
* @return
*/
private static int toShort(int... buf) {
return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF) << 0));
return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF)));
}
/**
@@ -593,7 +593,6 @@ public class ADIS16470_IMU implements AutoCloseable, Sendable {
if (!switchToAutoSPI()) {
DriverStation.reportError("Failed to configure/reconfigure auto SPI.", false);
}
;
}
/**

View File

@@ -239,6 +239,7 @@ public final class DriverStation {
for (int i = 0; i < count; i++) {
if (axes.m_axes[i] != m_prevAxes.m_axes[i]) {
needToLog = true;
break;
}
}
}
@@ -255,6 +256,7 @@ public final class DriverStation {
for (int i = 0; i < count; i++) {
if (povs.m_povs[i] != m_prevPOVs.m_povs[i]) {
needToLog = true;
break;
}
}
}

View File

@@ -369,7 +369,7 @@ public class I2C implements AutoCloseable {
byte[] deviceData = new byte[4];
for (int i = 0; i < count; i += 4) {
int toRead = count - i < 4 ? count - i : 4;
int toRead = Math.min(count - i, 4);
// Read the chunk of data. Return false if the sensor does not
// respond.
dataToSend[0] = (byte) (registerAddress + i);

View File

@@ -66,7 +66,7 @@ public abstract class MotorSafety {
synchronized (m_listMutex) {
m_instanceList.add(this);
if (m_safetyThread == null) {
m_safetyThread = new Thread(() -> threadMain(), "MotorSafety Thread");
m_safetyThread = new Thread(MotorSafety::threadMain, "MotorSafety Thread");
m_safetyThread.setDaemon(true);
m_safetyThread.start();
}

View File

@@ -113,7 +113,7 @@ public class Notifier implements AutoCloseable {
updateAlarm();
} else {
// Need to update the alarm to cause it to wait again
updateAlarm((long) -1);
updateAlarm(-1);
}
} finally {
m_processLock.unlock();
@@ -134,7 +134,7 @@ public class Notifier implements AutoCloseable {
error = cause;
}
DriverStation.reportError(
"Unhandled exception in Notifier thread: " + error.toString(), error.getStackTrace());
"Unhandled exception in Notifier thread: " + error, error.getStackTrace());
DriverStation.reportError(
"The Runnable for this Notifier (or methods called by it) should have handled "
+ "the exception above.\n"

View File

@@ -59,8 +59,7 @@ public class PneumaticHub implements PneumaticsBase {
output.write(("currentVersion=" + fwVersion).getBytes(StandardCharsets.UTF_8));
}
} catch (IOException ex) {
DriverStation.reportError(
"Could not write " + fileName + ": " + ex.toString(), ex.getStackTrace());
DriverStation.reportError("Could not write " + fileName + ": " + ex, ex.getStackTrace());
}
}
@@ -115,14 +114,12 @@ public class PneumaticHub implements PneumaticsBase {
/** Converts volts to PSI per the REV Analog Pressure Sensor datasheet. */
private static double voltsToPsi(double sensorVoltage, double supplyVoltage) {
double pressure = 250 * (sensorVoltage / supplyVoltage) - 25;
return pressure;
return 250 * (sensorVoltage / supplyVoltage) - 25;
}
/** Converts PSI to volts per the REV Analog Pressure Sensor datasheet. */
private static double psiToVolts(double pressure, double supplyVoltage) {
double voltage = supplyVoltage * (0.004 * pressure + 0.1);
return voltage;
return supplyVoltage * (0.004 * pressure + 0.1);
}
private final DataStore m_dataStore;

View File

@@ -6,5 +6,5 @@ package edu.wpi.first.wpilibj;
public enum PneumaticsModuleType {
CTREPCM,
REVPH;
REVPH
}

View File

@@ -101,9 +101,7 @@ public class PowerDistribution implements Sendable, AutoCloseable {
* @return The current of the channel in Amperes
*/
public double getCurrent(int channel) {
double current = PowerDistributionJNI.getChannelCurrent(m_handle, channel);
return current;
return PowerDistributionJNI.getChannelCurrent(m_handle, channel);
}
/**

View File

@@ -321,8 +321,7 @@ public abstract class RobotBase implements AutoCloseable {
robotName = elements[0].getClassName();
}
DriverStation.reportError(
"Unhandled exception instantiating robot " + robotName + " " + throwable.toString(),
elements);
"Unhandled exception instantiating robot " + robotName + " " + throwable, elements);
DriverStation.reportError(
"The robot program quit unexpectedly."
+ " This is usually due to a code error.\n"
@@ -353,8 +352,7 @@ public abstract class RobotBase implements AutoCloseable {
output.write(WPILibVersion.Version.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException ex) {
DriverStation.reportError(
"Could not write FRC_Lib_Version.ini: " + ex.toString(), ex.getStackTrace());
DriverStation.reportError("Could not write FRC_Lib_Version.ini: " + ex, ex.getStackTrace());
}
}
@@ -366,8 +364,7 @@ public abstract class RobotBase implements AutoCloseable {
if (cause != null) {
throwable = cause;
}
DriverStation.reportError(
"Unhandled exception: " + throwable.toString(), throwable.getStackTrace());
DriverStation.reportError("Unhandled exception: " + throwable, throwable.getStackTrace());
errorOnExit = true;
} finally {
m_runMutex.lock();

View File

@@ -33,7 +33,7 @@ public final class RobotController {
* @return FPGA Revision number.
*/
public static long getFPGARevision() {
return (long) HALUtil.getFPGARevision();
return HALUtil.getFPGARevision();
}
/**

View File

@@ -59,12 +59,12 @@ public final class SensorUtil {
*/
public static void checkDigitalChannel(final int channel) {
if (!DIOJNI.checkDIOChannel(channel)) {
StringBuilder buf = new StringBuilder();
buf.append("Requested DIO channel is out of range. Minimum: 0, Maximum: ")
.append(kDigitalChannels)
.append(", Requested: ")
.append(channel);
throw new IllegalArgumentException(buf.toString());
String buf =
"Requested DIO channel is out of range. Minimum: 0, Maximum: "
+ kDigitalChannels
+ ", Requested: "
+ channel;
throw new IllegalArgumentException(buf);
}
}
@@ -76,12 +76,12 @@ public final class SensorUtil {
*/
public static void checkRelayChannel(final int channel) {
if (!RelayJNI.checkRelayChannel(channel)) {
StringBuilder buf = new StringBuilder();
buf.append("Requested relay channel is out of range. Minimum: 0, Maximum: ")
.append(kRelayChannels)
.append(", Requested: ")
.append(channel);
throw new IllegalArgumentException(buf.toString());
String buf =
"Requested relay channel is out of range. Minimum: 0, Maximum: "
+ kRelayChannels
+ ", Requested: "
+ channel;
throw new IllegalArgumentException(buf);
}
}
@@ -93,12 +93,12 @@ public final class SensorUtil {
*/
public static void checkPWMChannel(final int channel) {
if (!PWMJNI.checkPWMChannel(channel)) {
StringBuilder buf = new StringBuilder();
buf.append("Requested PWM channel is out of range. Minimum: 0, Maximum: ")
.append(kPwmChannels)
.append(", Requested: ")
.append(channel);
throw new IllegalArgumentException(buf.toString());
String buf =
"Requested PWM channel is out of range. Minimum: 0, Maximum: "
+ kPwmChannels
+ ", Requested: "
+ channel;
throw new IllegalArgumentException(buf);
}
}
@@ -110,12 +110,12 @@ public final class SensorUtil {
*/
public static void checkAnalogInputChannel(final int channel) {
if (!AnalogJNI.checkAnalogInputChannel(channel)) {
StringBuilder buf = new StringBuilder();
buf.append("Requested analog input channel is out of range. Minimum: 0, Maximum: ")
.append(kAnalogInputChannels)
.append(", Requested: ")
.append(channel);
throw new IllegalArgumentException(buf.toString());
String buf =
"Requested analog input channel is out of range. Minimum: 0, Maximum: "
+ kAnalogInputChannels
+ ", Requested: "
+ channel;
throw new IllegalArgumentException(buf);
}
}
@@ -127,12 +127,12 @@ public final class SensorUtil {
*/
public static void checkAnalogOutputChannel(final int channel) {
if (!AnalogJNI.checkAnalogOutputChannel(channel)) {
StringBuilder buf = new StringBuilder();
buf.append("Requested analog output channel is out of range. Minimum: 0, Maximum: ")
.append(kAnalogOutputChannels)
.append(", Requested: ")
.append(channel);
throw new IllegalArgumentException(buf.toString());
String buf =
"Requested analog output channel is out of range. Minimum: 0, Maximum: "
+ kAnalogOutputChannels
+ ", Requested: "
+ channel;
throw new IllegalArgumentException(buf);
}
}

View File

@@ -216,7 +216,7 @@ public class SerialPort implements AutoCloseable {
*/
public String readString(int count) {
byte[] out = read(count);
return new String(out, 0, out.length, StandardCharsets.US_ASCII);
return new String(out, StandardCharsets.US_ASCII);
}
/**

View File

@@ -75,9 +75,7 @@ public class Tracer {
StringBuilder sb = new StringBuilder();
m_lastEpochsPrintTime = now;
m_epochs.forEach(
(key, value) -> {
sb.append(String.format("\t%s: %.6fs\n", key, value / 1.0e6));
});
(key, value) -> sb.append(String.format("\t%s: %.6fs\n", key, value / 1.0e6)));
if (sb.length() > 0) {
output.accept(sb.toString());
}

View File

@@ -209,7 +209,7 @@ public class Watchdog implements Closeable, Comparable<Watchdog> {
}
private static void updateAlarm() {
if (m_watchdogs.size() == 0) {
if (m_watchdogs.isEmpty()) {
NotifierJNI.cancelNotifierAlarm(m_notifier);
} else {
NotifierJNI.updateNotifierAlarm(
@@ -233,7 +233,7 @@ public class Watchdog implements Closeable, Comparable<Watchdog> {
m_queueMutex.lock();
try {
if (m_watchdogs.size() == 0) {
if (m_watchdogs.isEmpty()) {
continue;
}

View File

@@ -50,7 +50,7 @@ public final class LiveWindow {
private static Runnable disabledListener;
static {
SendableRegistry.setLiveWindowBuilderFactory(() -> new SendableBuilderImpl());
SendableRegistry.setLiveWindowBuilderFactory(SendableBuilderImpl::new);
enabledPub.set(false);
}
@@ -105,10 +105,7 @@ public final class LiveWindow {
} else {
System.out.println("stopping live window mode.");
SendableRegistry.foreachLiveWindow(
dataHandle,
cbdata -> {
((SendableBuilderImpl) cbdata.builder).stopLiveWindowMode();
});
dataHandle, cbdata -> ((SendableBuilderImpl) cbdata.builder).stopLiveWindowMode());
if (disabledListener != null) {
disabledListener.run();
}

View File

@@ -17,7 +17,8 @@ import edu.wpi.first.wpilibj.PWM;
* 884 controllers also but if users experience issues such as asymmetric behavior around the
* deadband or inability to saturate the controller in either direction, calibration is recommended.
* The calibration procedure can be found in the Victor 884 User Manual available from VEX Robotics:
* http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf
* <a
* href="http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf">http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf</a>
*
* <ul>
* <li>2.027ms = full "forward"

View File

@@ -236,12 +236,9 @@ public class DifferentialDrivetrainSim {
* @return the drivetrain's left side current draw, in amps
*/
public double getLeftCurrentDrawAmps() {
var loadIleft =
m_motor.getCurrent(
getState(State.kLeftVelocity) * m_currentGearing / m_wheelRadiusMeters,
m_u.get(0, 0))
* Math.signum(m_u.get(0, 0));
return loadIleft;
return m_motor.getCurrent(
getState(State.kLeftVelocity) * m_currentGearing / m_wheelRadiusMeters, m_u.get(0, 0))
* Math.signum(m_u.get(0, 0));
}
/**
@@ -250,13 +247,9 @@ public class DifferentialDrivetrainSim {
* @return the drivetrain's right side current draw, in amps
*/
public double getRightCurrentDrawAmps() {
var loadIright =
m_motor.getCurrent(
getState(State.kRightVelocity) * m_currentGearing / m_wheelRadiusMeters,
m_u.get(1, 0))
* Math.signum(m_u.get(1, 0));
return loadIright;
return m_motor.getCurrent(
getState(State.kRightVelocity) * m_currentGearing / m_wheelRadiusMeters, m_u.get(1, 0))
* Math.signum(m_u.get(1, 0));
}
/**

View File

@@ -135,7 +135,7 @@ public class GenericHIDSim {
*/
public boolean getOutput(int outputNumber) {
long outputs = getOutputs();
return (outputs & (1 << (outputNumber - 1))) != 0;
return (outputs & (1L << (outputNumber - 1))) != 0;
}
/**

View File

@@ -10,6 +10,7 @@ import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.trajectory.Trajectory;
import edu.wpi.first.networktables.DoubleArrayEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Game field object on a Field2d. */
@@ -70,9 +71,7 @@ public class FieldObject2d implements AutoCloseable {
*/
public synchronized void setPoses(List<Pose2d> poses) {
m_poses.clear();
for (Pose2d pose : poses) {
m_poses.add(pose);
}
m_poses.addAll(poses);
updateEntry();
}
@@ -83,9 +82,7 @@ public class FieldObject2d implements AutoCloseable {
*/
public synchronized void setPoses(Pose2d... poses) {
m_poses.clear();
for (Pose2d pose : poses) {
m_poses.add(pose);
}
Collections.addAll(m_poses, poses);
updateEntry();
}
@@ -109,7 +106,7 @@ public class FieldObject2d implements AutoCloseable {
*/
public synchronized List<Pose2d> getPoses() {
updateFromEntry();
return new ArrayList<Pose2d>(m_poses);
return new ArrayList<>(m_poses);
}
void updateEntry() {
@@ -143,7 +140,7 @@ public class FieldObject2d implements AutoCloseable {
return;
}
double[] arr = m_entry.get((double[]) null);
double[] arr = m_entry.get(null);
if (arr != null) {
if ((arr.length % 3) != 0) {
return;

View File

@@ -31,9 +31,9 @@ class ListenerExecutor implements Executor {
/** Runs all posted tasks. Called periodically from main thread. */
public void runListenerTasks() {
// Locally copy tasks from internal list; minimizes blocking time
Collection<Runnable> tasks = new ArrayList<>();
Collection<Runnable> tasks;
synchronized (m_lock) {
tasks.addAll(m_tasks);
tasks = new ArrayList<>(m_tasks);
m_tasks.clear();
}

View File

@@ -144,11 +144,7 @@ class TimedRobotTest {
void disabledModeTest() {
MockRobot robot = new MockRobot();
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
DriverStationSim.setEnabled(false);
@@ -231,11 +227,7 @@ class TimedRobotTest {
void autonomousModeTest() {
MockRobot robot = new MockRobot();
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
DriverStationSim.setEnabled(true);
@@ -320,11 +312,7 @@ class TimedRobotTest {
void teleopModeTest() {
MockRobot robot = new MockRobot();
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
DriverStationSim.setEnabled(true);
@@ -411,11 +399,7 @@ class TimedRobotTest {
MockRobot robot = new MockRobot();
robot.enableLiveWindowInTest(isLW);
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
DriverStationSim.setEnabled(true);
@@ -531,11 +515,7 @@ class TimedRobotTest {
void modeChangeTest() {
MockRobot robot = new MockRobot();
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
// Start in disabled
@@ -655,17 +635,9 @@ class TimedRobotTest {
MockRobot robot = new MockRobot();
final AtomicInteger callbackCount = new AtomicInteger(0);
robot.addPeriodic(
() -> {
callbackCount.addAndGet(1);
},
kPeriod / 2.0);
robot.addPeriodic(() -> callbackCount.addAndGet(1), kPeriod / 2.0);
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
DriverStationSim.setEnabled(false);
@@ -704,12 +676,7 @@ class TimedRobotTest {
MockRobot robot = new MockRobot();
final AtomicInteger callbackCount = new AtomicInteger(0);
robot.addPeriodic(
() -> {
callbackCount.addAndGet(1);
},
kPeriod / 2.0,
kPeriod / 4.0);
robot.addPeriodic(() -> callbackCount.addAndGet(1), kPeriod / 2.0, kPeriod / 4.0);
// Expirations in this test (ms)
//
@@ -720,11 +687,7 @@ class TimedRobotTest {
// p | 0.75p
// 2p | 1.25p
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
DriverStationSim.setEnabled(false);

View File

@@ -54,22 +54,10 @@ class TimesliceRobotTest {
// | RobotPeriodic() | 0 | 2 |
// | Callback 1 | 2 | 0.5 |
// | Callback 2 | 2.5 | 1 |
robot.schedule(
() -> {
callbackCount1.addAndGet(1);
},
0.0005);
robot.schedule(
() -> {
callbackCount2.addAndGet(1);
},
0.001);
robot.schedule(() -> callbackCount1.addAndGet(1), 0.0005);
robot.schedule(() -> callbackCount2.addAndGet(1), 0.001);
Thread robotThread =
new Thread(
() -> {
robot.startCompetition();
});
Thread robotThread = new Thread(robot::startCompetition);
robotThread.start();
DriverStationSim.setEnabled(false);

View File

@@ -33,12 +33,7 @@ class WatchdogTest {
void enableDisableTest() {
final AtomicInteger watchdogCounter = new AtomicInteger(0);
try (Watchdog watchdog =
new Watchdog(
0.4,
() -> {
watchdogCounter.addAndGet(1);
})) {
try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) {
// Run 1
watchdog.enable();
SimHooks.stepTiming(0.2);
@@ -71,12 +66,7 @@ class WatchdogTest {
void resetTest() {
final AtomicInteger watchdogCounter = new AtomicInteger(0);
try (Watchdog watchdog =
new Watchdog(
0.4,
() -> {
watchdogCounter.addAndGet(1);
})) {
try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) {
watchdog.enable();
SimHooks.stepTiming(0.2);
watchdog.reset();
@@ -92,12 +82,7 @@ class WatchdogTest {
void setTimeoutTest() {
final AtomicInteger watchdogCounter = new AtomicInteger(0);
try (Watchdog watchdog =
new Watchdog(
1.0,
() -> {
watchdogCounter.addAndGet(1);
})) {
try (Watchdog watchdog = new Watchdog(1.0, () -> watchdogCounter.addAndGet(1))) {
watchdog.enable();
SimHooks.stepTiming(0.2);
watchdog.setTimeout(0.2);
@@ -137,12 +122,7 @@ class WatchdogTest {
void epochsTest() {
final AtomicInteger watchdogCounter = new AtomicInteger(0);
try (Watchdog watchdog =
new Watchdog(
0.4,
() -> {
watchdogCounter.addAndGet(1);
})) {
try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) {
// Run 1
watchdog.enable();
watchdog.addEpoch("Epoch 1");
@@ -173,18 +153,8 @@ class WatchdogTest {
final AtomicInteger watchdogCounter1 = new AtomicInteger(0);
final AtomicInteger watchdogCounter2 = new AtomicInteger(0);
try (Watchdog watchdog1 =
new Watchdog(
0.2,
() -> {
watchdogCounter1.addAndGet(1);
});
Watchdog watchdog2 =
new Watchdog(
0.6,
() -> {
watchdogCounter2.addAndGet(1);
})) {
try (Watchdog watchdog1 = new Watchdog(0.2, () -> watchdogCounter1.addAndGet(1));
Watchdog watchdog2 = new Watchdog(0.6, () -> watchdogCounter2.addAndGet(1))) {
watchdog2.enable();
SimHooks.stepTiming(0.25);
assertEquals(0, watchdogCounter1.get(), "Watchdog triggered early");

View File

@@ -136,7 +136,7 @@ class ShuffleboardInstanceTest {
try (StringSubscriber subscriber =
m_ntInstance
.getStringTopic("/Shuffleboard/.metadata/Selected")
.subscribe("", PubSubOption.keepDuplicates(true)); ) {
.subscribe("", PubSubOption.keepDuplicates(true))) {
listener =
m_ntInstance.addListener(
subscriber,

View File

@@ -79,7 +79,7 @@ class AddressableLEDSimTest {
BufferCallback callback = new BufferCallback();
try (AddressableLED led = new AddressableLED(0);
CallbackStore cb = sim.registerDataCallback(callback); ) {
CallbackStore cb = sim.registerDataCallback(callback)) {
assertFalse(sim.getRunning());
assertEquals(1, sim.getLength()); // Defaults to 1 led

View File

@@ -63,7 +63,7 @@ class DCMotorSimTest {
try (var motor = new PWMVictorSPX(0);
var encoder = new Encoder(0, 1);
var controller = new PIDController(0.04, 0.0, 0.001); ) {
var controller = new PIDController(0.04, 0.0, 0.001)) {
var encoderSim = new EncoderSim(encoder);
encoderSim.resetData();

View File

@@ -25,7 +25,7 @@ class DigitalPWMSimTest {
BooleanCallback initializeCallback = new BooleanCallback();
DoubleCallback dutyCycleCallback = new DoubleCallback();
try (CallbackStore initCb = sim.registerInitializedCallback(initializeCallback, false);
CallbackStore dutyCycleCb = sim.registerDutyCycleCallback(dutyCycleCallback, false); ) {
CallbackStore dutyCycleCb = sim.registerDutyCycleCallback(dutyCycleCallback, false)) {
final double kTestDutyCycle = 0.191;
output.enablePWM(kTestDutyCycle);

View File

@@ -58,7 +58,7 @@ class RelaySimTest {
try (CallbackStore fwdCb = sim.registerInitializedForwardCallback(forwardCallback, false);
CallbackStore revCb = sim.registerInitializedReverseCallback(reverseCallback, false);
Relay relay = new Relay(0, Relay.Direction.kForward); ) {
Relay relay = new Relay(0, Relay.Direction.kForward)) {
assertTrue(sim.getInitializedForward());
assertFalse(sim.getInitializedReverse());
@@ -84,7 +84,7 @@ class RelaySimTest {
try (CallbackStore fwdCb = sim.registerInitializedForwardCallback(forwardCallback, false);
CallbackStore revCb = sim.registerInitializedReverseCallback(reverseCallback, false);
Relay relay = new Relay(0, Relay.Direction.kReverse); ) {
Relay relay = new Relay(0, Relay.Direction.kReverse)) {
assertFalse(sim.getInitializedForward());
assertTrue(sim.getInitializedReverse());

View File

@@ -41,18 +41,10 @@ class SimDeviceSimTest {
SimDevice dev1 = SimDevice.create("testDC1")) {
try (CallbackStore callback1 =
SimDeviceSim.registerDeviceCreatedCallback(
"testDC",
(name, handle) -> {
callback1Counter.addAndGet(1);
},
false);
"testDC", (name, handle) -> callback1Counter.addAndGet(1), false);
CallbackStore callback2 =
SimDeviceSim.registerDeviceCreatedCallback(
"testDC",
(name, handle) -> {
callback2Counter.addAndGet(1);
},
true)) {
"testDC", (name, handle) -> callback2Counter.addAndGet(1), true)) {
assertEquals(0, callback1Counter.get(), "Callback 1 called early");
assertEquals(
1,
@@ -82,11 +74,7 @@ class SimDeviceSimTest {
SimDevice dev1 = SimDevice.create("testDF1");
try (CallbackStore callback =
SimDeviceSim.registerDeviceFreedCallback(
"testDF",
(name, handle) -> {
counter.addAndGet(1);
},
false)) {
"testDF", (name, handle) -> counter.addAndGet(1), false)) {
assertEquals(0, counter.get(), "Callback called early");
dev1.close();
assertEquals(1, counter.get(), "Callback called either more than once or not at all");
@@ -108,16 +96,10 @@ class SimDeviceSimTest {
SimDeviceSim sim = new SimDeviceSim("testVM1");
try (CallbackStore callback1 =
sim.registerValueCreatedCallback(
(name, handle, readonly, value) -> {
callback1Counter.addAndGet(1);
},
false);
(name, handle, readonly, value) -> callback1Counter.addAndGet(1), false);
CallbackStore callback2 =
sim.registerValueCreatedCallback(
(name, handle, readonly, value) -> {
callback2Counter.addAndGet(1);
},
true)) {
(name, handle, readonly, value) -> callback2Counter.addAndGet(1), true)) {
assertEquals(0, callback1Counter.get(), "Callback 1 called early");
assertEquals(
1,
@@ -148,18 +130,10 @@ class SimDeviceSimTest {
SimValue simVal = sim.getValue("v1");
try (CallbackStore callback1 =
sim.registerValueChangedCallback(
simVal,
(name, handle, readonly, value) -> {
callback1Counter.addAndGet(1);
},
false);
simVal, (name, handle, readonly, value) -> callback1Counter.addAndGet(1), false);
CallbackStore callback2 =
sim.registerValueChangedCallback(
simVal,
(name, handle, readonly, value) -> {
callback2Counter.addAndGet(1);
},
true)) {
simVal, (name, handle, readonly, value) -> callback2Counter.addAndGet(1), true)) {
assertEquals(0, callback1Counter.get(), "Callback 1 called early");
assertEquals(
1,

View File

@@ -75,7 +75,7 @@ class SendableChooserTest {
chooser.addOption(String.valueOf(i), i);
}
AtomicInteger currentVal = new AtomicInteger();
chooser.onChange(val -> currentVal.set(val));
chooser.onChange(currentVal::set);
SmartDashboard.putData("changeListenerChooser", chooser);
SmartDashboard.updateValues();

View File

@@ -22,8 +22,8 @@ public class ReplaceMeTrapezoidProfileCommand extends TrapezoidProfileCommand {
// Use current trajectory state here
},
// Goal state
() -> new TrapezoidProfile.State(),
TrapezoidProfile.State::new,
// Current state
() -> new TrapezoidProfile.State());
TrapezoidProfile.State::new);
}
}

View File

@@ -32,7 +32,7 @@ import org.opencv.imgproc.Imgproc;
public class Robot extends TimedRobot {
@Override
public void robotInit() {
var visionThread = new Thread(() -> apriltagVisionThreadProc());
var visionThread = new Thread(this::apriltagVisionThreadProc);
visionThread.setDaemon(true);
visionThread.start();
}

View File

@@ -78,7 +78,7 @@ public class RobotContainer {
// End at desired position in meters; implicitly starts at 0
() -> new TrapezoidProfile.State(3, 0),
// Current position
() -> new TrapezoidProfile.State(),
TrapezoidProfile.State::new,
// Require the drive
m_robotDrive)
.beforeStarting(m_robotDrive::resetEncoders)

View File

@@ -29,7 +29,7 @@ public class DriveDistanceProfiled extends TrapezoidProfileCommand {
// End at desired position in meters; implicitly starts at 0
() -> new TrapezoidProfile.State(meters, 0),
// Current position
() -> new TrapezoidProfile.State(),
TrapezoidProfile.State::new,
// Require the drive
drive);
// Reset drive encoders since we're starting at 0

View File

@@ -50,16 +50,12 @@ public class Pneumatics extends SubsystemBase {
*/
public Command disableCompressorCommand() {
return startEnd(
() -> {
// Disable closed-loop mode on the compressor.
m_compressor.disable();
},
() -> {
// Enable closed-loop mode based on the digital pressure switch connected to the
// PCM/PH.
// The switch is open when the pressure is over ~120 PSI.
m_compressor.enableDigital();
})
// Disable closed-loop mode on the compressor.
m_compressor::disable,
// Enable closed-loop mode based on the digital pressure switch connected to the
// PCM/PH.
// The switch is open when the pressure is over ~120 PSI.
m_compressor::enableDigital)
.withName("Compressor Disabled");
}
}

View File

@@ -53,33 +53,17 @@ public class Robot extends TimedRobot {
tab.add("Compressor", m_compressor);
// Also publish some raw data
tab.addDouble(
"PH Pressure [PSI]",
() -> {
// Get the pressure (in PSI) from the analog sensor connected to the PH.
// This function is supported only on the PH!
// On a PCM, this function will return 0.
return m_compressor.getPressure();
});
tab.addDouble(
"Compressor Current",
() -> {
// Get compressor current draw.
return m_compressor.getCurrent();
});
tab.addBoolean(
"Compressor Active",
() -> {
// Get whether the compressor is active.
return m_compressor.isEnabled();
});
tab.addBoolean(
"Pressure Switch",
() -> {
// Get the digital pressure switch connected to the PCM/PH.
// The switch is open when the pressure is over ~120 PSI.
return m_compressor.getPressureSwitchValue();
});
// Get the pressure (in PSI) from the analog sensor connected to the PH.
// This function is supported only on the PH!
// On a PCM, this function will return 0.
tab.addDouble("PH Pressure [PSI]", m_compressor::getPressure);
// Get compressor current draw.
tab.addDouble("Compressor Current", m_compressor::getCurrent);
// Get whether the compressor is active.
tab.addBoolean("Compressor Active", m_compressor::isEnabled);
// Get the digital pressure switch connected to the PCM/PH.
// The switch is open when the pressure is over ~120 PSI.
tab.addBoolean("Pressure Switch", m_compressor::getPressureSwitchValue);
}
@SuppressWarnings("PMD.UnconditionalIfStatement")

View File

@@ -44,7 +44,7 @@ public class Intake implements AutoCloseable {
}
@Override
public void close() throws Exception {
public void close() {
m_piston.close();
m_motor.close();
}

View File

@@ -4,11 +4,11 @@
package edu.wpi.first.wpilibj;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.concurrent.atomic.AtomicBoolean;

View File

@@ -7,8 +7,8 @@ package edu.wpi.first.wpilibj;
import static org.junit.Assert.assertEquals;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -38,7 +38,7 @@ public class BuiltInAccelerometerTest extends AbstractComsSetup {
/** Test with all valid ranges to make sure unpacking is always done correctly. */
@Parameters
public static Collection<BuiltInAccelerometer.Range[]> generateData() {
return Arrays.asList(
return List.of(
new BuiltInAccelerometer.Range[][] {
{BuiltInAccelerometer.Range.k2G},
{BuiltInAccelerometer.Range.k4G},

View File

@@ -14,8 +14,8 @@ import edu.wpi.first.math.filter.LinearFilter;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
@@ -56,7 +56,7 @@ public class MotorEncoderTest extends AbstractComsSetup {
@Parameters(name = "{index}: {0}")
public static Collection<MotorEncoderFixture<?>[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(
return List.of(
new MotorEncoderFixture<?>[][] {
{TestBench.getTalonPair()}, {TestBench.getVictorPair()}, {TestBench.getJaguarPair()}
});

View File

@@ -10,8 +10,8 @@ import static org.junit.Assert.assertTrue;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.Before;
@@ -44,7 +44,7 @@ public class MotorInvertingTest extends AbstractComsSetup {
@Parameters(name = "{index}: {0}")
public static Collection<MotorEncoderFixture<?>[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(
return List.of(
new MotorEncoderFixture<?>[][] {
{TestBench.getTalonPair()}, {TestBench.getVictorPair()}, {TestBench.getJaguarPair()}
});

View File

@@ -4,17 +4,17 @@
package edu.wpi.first.wpilibj;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import edu.wpi.first.hal.can.CANMessageNotFoundException;
import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
@@ -65,7 +65,7 @@ public class PDPTest extends AbstractComsSetup {
@Parameters(name = "{index}: {0}, Expected Stopped Current Draw: {1}")
public static Collection<Object[]> generateData() {
// logger.fine("Loading the MotorList");
return Arrays.asList(new Object[][] {{TestBench.getTalonPair(), 0.0}});
return List.of(new Object[][] {{TestBench.getTalonPair(), 0.0}});
}
@After

View File

@@ -16,8 +16,8 @@ import edu.wpi.first.wpilibj.smartdashboard.SendableBuilderImpl;
import edu.wpi.first.wpilibj.test.AbstractComsSetup;
import edu.wpi.first.wpilibj.test.TestBench;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
@@ -72,13 +72,13 @@ public class PIDTest extends AbstractComsSetup {
@Parameters
public static Collection<Object[]> generateData() {
// logger.fine("Loading the MotorList");
Collection<Object[]> data = new ArrayList<Object[]>();
Collection<Object[]> data = new ArrayList<>();
double kp = 0.001;
double ki = 0.0005;
double kd = 0.0;
for (int i = 0; i < 1; i++) {
data.addAll(
Arrays.asList(
List.of(
new Object[][] {
{kp, ki, kd, TestBench.getTalonPair()},
{kp, ki, kd, TestBench.getVictorPair()},

View File

@@ -31,7 +31,7 @@ public abstract class AbstractComsSetup {
// We have no way to stop the MockDS, so its thread is daemon.
private static MockDS ds;
/**
/*
* This sets up the network communications library to enable the driver station. After starting
* network coms, it will loop until the driver station returns that the robot is enabled, to
* ensure that tests will be able to run on the hardware.

View File

@@ -34,15 +34,11 @@ public abstract class AbstractTestSuite {
*/
protected List<Class<?>> getAnnotatedTestClasses() {
SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class);
List<Class<?>> classes = new ArrayList<>();
if (annotation == null) {
throw new RuntimeException(
String.format("class '%s' must have a SuiteClasses annotation", getClass().getName()));
}
for (Class<?> c : annotation.value()) {
classes.add(c);
}
return classes;
return List.of(annotation.value());
}
private boolean areAnySuperClassesOfTypeAbstractTestSuite(Class<?> check) {

View File

@@ -24,9 +24,8 @@ public class AntJunitLauncher {
*/
public static void main(String... args) {
if (args.length == 0) {
String path =
String pathToReports =
String.format("%s/%s", System.getProperty("user.dir"), "/testResults/AntReports");
String pathToReports = path;
Project project = new Project();
try {

View File

@@ -20,7 +20,6 @@ import edu.wpi.first.wpilibj.motorcontrol.Talon;
import edu.wpi.first.wpilibj.motorcontrol.Victor;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
@@ -59,7 +58,7 @@ public final class TestBench {
* The single constructor for the TestBench. This method is private in order to prevent multiple
* TestBench objects from being allocated.
*/
protected TestBench() {}
private TestBench() {}
/**
* Constructs a new set of objects representing a connected set of Talon controlled Motors and an
@@ -68,7 +67,7 @@ public final class TestBench {
* @return a freshly allocated Talon, Encoder pair
*/
public static MotorEncoderFixture<Talon> getTalonPair() {
return new MotorEncoderFixture<Talon>() {
return new MotorEncoderFixture<>() {
@Override
protected Talon giveMotorController() {
return new Talon(kTalonChannel);
@@ -98,7 +97,7 @@ public final class TestBench {
* @return a freshly allocated Victor, Encoder pair
*/
public static MotorEncoderFixture<Victor> getVictorPair() {
return new MotorEncoderFixture<Victor>() {
return new MotorEncoderFixture<>() {
@Override
protected Victor giveMotorController() {
return new Victor(kVictorChannel);
@@ -128,7 +127,7 @@ public final class TestBench {
* @return a freshly allocated Jaguar, Encoder pair
*/
public static MotorEncoderFixture<Jaguar> getJaguarPair() {
return new MotorEncoderFixture<Jaguar>() {
return new MotorEncoderFixture<>() {
@Override
protected Jaguar giveMotorController() {
return new Jaguar(kJaguarChannel);
@@ -190,9 +189,9 @@ public final class TestBench {
/** Gets two lists of possible DIO pairs for the two pairs. */
private static List<List<Integer[]>> getDIOCrossConnect() {
List<List<Integer[]>> pairs = new ArrayList<List<Integer[]>>();
List<List<Integer[]>> pairs = new ArrayList<>();
List<Integer[]> setA =
Arrays.asList(
List.of(
new Integer[][] {
{DIOCrossConnectA1, DIOCrossConnectA2},
{DIOCrossConnectA2, DIOCrossConnectA1}
@@ -200,7 +199,7 @@ public final class TestBench {
pairs.add(setA);
List<Integer[]> setB =
Arrays.asList(
List.of(
new Integer[][] {
{DIOCrossConnectB1, DIOCrossConnectB2},
{DIOCrossConnectB2, DIOCrossConnectB1}
@@ -252,7 +251,7 @@ public final class TestBench {
* @return pairs of DIOCrossConnectFixtures
*/
public static Collection<Integer[]> getDIOCrossConnectCollection() {
Collection<Integer[]> pairs = new ArrayList<Integer[]>();
Collection<Integer[]> pairs = new ArrayList<>();
for (Collection<Integer[]> collection : getDIOCrossConnect()) {
pairs.addAll(collection);
}
@@ -267,7 +266,7 @@ public final class TestBench {
*/
private static Collection<Integer[]> getPairArray(
List<Integer[]> listA, List<Integer[]> listB, boolean flip) {
Collection<Integer[]> encoderPortPairs = new ArrayList<Integer[]>();
Collection<Integer[]> encoderPortPairs = new ArrayList<>();
for (Integer[] portPairsA : listA) {
Integer[] inputs = new Integer[5];
inputs[0] = portPairsA[0]; // InputA
@@ -279,7 +278,7 @@ public final class TestBench {
inputs[4] = flip ? 0 : 1; // The flip bit
}
ArrayList<Integer[]> construtorInput = new ArrayList<Integer[]>();
ArrayList<Integer[]> construtorInput = new ArrayList<>();
construtorInput.add(inputs);
inputs = inputs.clone();
@@ -300,7 +299,7 @@ public final class TestBench {
* @return A collection of different input pairs to use for the encoder
*/
public static Collection<Integer[]> getEncoderDIOCrossConnectCollection() {
Collection<Integer[]> encoderPortPairs = new ArrayList<Integer[]>();
Collection<Integer[]> encoderPortPairs = new ArrayList<>();
assert getDIOCrossConnect().size() == 2;
encoderPortPairs.addAll(
getPairArray(getDIOCrossConnect().get(0), getDIOCrossConnect().get(1), false));

View File

@@ -8,7 +8,6 @@ import edu.wpi.first.wpilibj.WpiLibJTestSuite;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.logging.LogManager;
@@ -77,40 +76,36 @@ public class TestSuite extends AbstractTestSuite {
/** Displays a help message for the user when they use the --help flag at runtime. */
protected static void displayHelp() {
StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n");
helpMessage.append(
"\t"
String helpMessage =
"Test Parameters help: \n"
+ "\t"
+ QUICK_TEST_FLAG
+ " will cause the quick test to be run. Ignores other flags except for "
+ METHOD_REPEAT_FILTER
+ "\n");
helpMessage.append(
"\t"
+ "\n"
+ "\t"
+ CLASS_NAME_FILTER
+ " will use the supplied regex text to search for suite/test class names "
+ "matching the regex and run them.\n");
helpMessage.append(
"\t"
+ "matching the regex and run them.\n"
+ "\t"
+ METHOD_NAME_FILTER
+ " will use the supplied regex text to search for test methods (excluding methods "
+ "with the @Ignore annotation) and run only those methods. Can be paired with "
+ METHOD_REPEAT_FILTER
+ " to "
+ "repeat the selected tests multiple times.\n");
helpMessage.append(
"\t"
+ "repeat the selected tests multiple times.\n"
+ "\t"
+ METHOD_REPEAT_FILTER
+ " will repeat the tests selected with either "
+ QUICK_TEST_FLAG
+ " or "
+ CLASS_NAME_FILTER
+ " and run them the given number of times.\n");
helpMessage.append(
"[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This "
+ " and run them the given number of times.\n"
+ "[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This "
+ "documentation can be found at "
+ "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n");
helpMessage.append("\n");
helpMessage.append("\n");
+ "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n"
+ "\n"
+ "\n";
TestBench.out().println(helpMessage);
}
@@ -123,7 +118,7 @@ public class TestSuite extends AbstractTestSuite {
StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n");
invalidMessage.append("Params received: ");
for (String a : args) {
invalidMessage.append(a + " ");
invalidMessage.append(a).append(" ");
}
invalidMessage.append("\n");
invalidMessage.append(
@@ -145,9 +140,9 @@ public class TestSuite extends AbstractTestSuite {
for (Class<?> c : classes) {
if (c.getPackage().equals(packagE)) {
packagE = c.getPackage();
loadedTestsMessage.append(packagE.getName() + "\n");
loadedTestsMessage.append(packagE.getName()).append("\n");
}
loadedTestsMessage.append("\t" + c.getSimpleName() + "\n");
loadedTestsMessage.append("\t").append(c.getSimpleName()).append("\n");
}
TestBench.out().println(loadedTestsMessage);
}
@@ -193,7 +188,7 @@ public class TestSuite extends AbstractTestSuite {
}
}
ArrayList<String> argsParsed = new ArrayList<String>(Arrays.asList(args));
ArrayList<String> argsParsed = new ArrayList<>(List.of(args));
if (argsParsed.contains(HELP_FLAG)) {
// If the user inputs the help flag then return the help message and exit
// without running any tests
@@ -257,7 +252,7 @@ public class TestSuite extends AbstractTestSuite {
// If a specific method has been requested
if (methodFilter) {
List<ClassMethodPair> pairs = (new TestSuite()).getMethodMatching(methodRegex);
if (pairs.size() == 0) {
if (pairs.isEmpty()) {
displayInvalidUsage(
"None of the arguments passed to the method name filter matched.", args);
return null;
@@ -292,7 +287,7 @@ public class TestSuite extends AbstractTestSuite {
// If a specific class has been requested
if (classFilter) {
List<Class<?>> testClasses = (new TestSuite()).getSuiteOrTestMatchingRegex(classRegex);
if (testClasses.size() == 0) {
if (testClasses.isEmpty()) {
displayInvalidUsage("None of the arguments passed to the filter matched.", args);
return null;
}

View File

@@ -288,7 +288,7 @@ public class Matrix<R extends Num, C extends Num> {
* @return The resultant matrix.
*/
public Matrix<R, C> div(int value) {
return new Matrix<>(this.m_storage.divide((double) value));
return new Matrix<>(this.m_storage.divide(value));
}
/**
@@ -488,7 +488,7 @@ public class Matrix<R extends Num, C extends Num> {
* @return The element by element power of "this" and b.
*/
public final Matrix<R, C> elementPower(int b) {
return new Matrix<>(this.m_storage.elementPower((double) b));
return new Matrix<>(this.m_storage.elementPower(b));
}
/**
@@ -545,7 +545,7 @@ public class Matrix<R extends Num, C extends Num> {
*/
public final <R2 extends Num, C2 extends Num> Matrix<R2, C2> block(
int height, int width, int startingRow, int startingCol) {
return new Matrix<R2, C2>(
return new Matrix<>(
this.m_storage.extractMatrix(
startingRow, startingRow + height, startingCol, startingCol + width));
}
@@ -607,8 +607,7 @@ public class Matrix<R extends Num, C extends Num> {
return new Matrix<>(new SimpleMatrix(temp.getNumRows(), temp.getNumCols()));
}
throw new RuntimeException(
"Cholesky decomposition failed! Input matrix:\n" + m_storage.toString());
throw new RuntimeException("Cholesky decomposition failed! Input matrix:\n" + m_storage);
}
return new Matrix<>(SimpleMatrix.wrap(chol.getT(null)));

View File

@@ -16,9 +16,8 @@ import java.util.function.Function;
* Constructs a control-affine plant inversion model-based feedforward from given model dynamics.
*
* <p>If given the vector valued function as f(x, u) where x is the state vector and u is the input
* vector, the B matrix(continuous input matrix) is calculated through a {@link
* edu.wpi.first.math.system.NumericalJacobian}. In this case f has to be control-affine (of the
* form f(x) + Bu).
* vector, the B matrix(continuous input matrix) is calculated through a {@link NumericalJacobian}.
* In this case f has to be control-affine (of the form f(x) + Bu).
*
* <p>The feedforward is calculated as <strong> u_ff = B<sup>+</sup> (rDot - f(x))</strong>, where
* <strong> B<sup>+</sup> </strong> is the pseudoinverse of B.
@@ -26,8 +25,8 @@ import java.util.function.Function;
* <p>This feedforward does not account for a dynamic B matrix, B is either determined or supplied
* when the feedforward is created and remains constant.
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf.
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>.
*/
public class ControlAffinePlantInversionFeedforward<States extends Num, Inputs extends Num> {
/** The current reference state. */

View File

@@ -17,8 +17,8 @@ import org.ejml.simple.SimpleMatrix;
* system and makes it behave like some other system. This can be used to make a drivetrain more
* controllable during teleop driving by making it behave like a slower or more benign drivetrain.
*
* <p>For more on the underlying math, read appendix B.3 in
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf.
* <p>For more on the underlying math, read appendix B.3 in <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>.
*/
public class ImplicitModelFollower<States extends Num, Inputs extends Num, Outputs extends Num> {
// Computed controller output

View File

@@ -65,8 +65,8 @@ public class LTVDifferentialDriveController {
/**
* Constructs a linear time-varying differential drive controller.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning</a>
* for how to select the tolerances.
*
* @param plant The differential drive velocity plant.

View File

@@ -80,8 +80,8 @@ public class LTVUnicycleController {
/**
* Constructs a linear time-varying unicycle controller.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning</a>
* for how to select the tolerances.
*
* @param qelems The maximum desired error tolerance for each state.
@@ -95,8 +95,8 @@ public class LTVUnicycleController {
/**
* Constructs a linear time-varying unicycle controller.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning</a>
* for how to select the tolerances.
*
* @param qelems The maximum desired error tolerance for each state.

View File

@@ -17,8 +17,8 @@ import org.ejml.simple.SimpleMatrix;
* <p>The feedforward is calculated as <strong> u_ff = B<sup>+</sup> (r_k+1 - A r_k) </strong>,
* where <strong> B<sup>+</sup> </strong> is the pseudoinverse of B.
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf.
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>.
*/
public class LinearPlantInversionFeedforward<
States extends Num, Inputs extends Num, Outputs extends Num> {

View File

@@ -19,8 +19,8 @@ import org.ejml.simple.SimpleMatrix;
* Contains the controller coefficients and logic for a linear-quadratic regulator (LQR). LQRs use
* the control law u = K(r - x).
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf.
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>.
*/
public class LinearQuadraticRegulator<States extends Num, Inputs extends Num, Outputs extends Num> {
/** The current reference state. */
@@ -35,8 +35,8 @@ public class LinearQuadraticRegulator<States extends Num, Inputs extends Num, Ou
/**
* Constructs a controller with the given coefficients and plant. Rho is defaulted to 1.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning</a>
* for how to select the tolerances.
*
* @param plant The plant being controlled.
@@ -61,8 +61,8 @@ public class LinearQuadraticRegulator<States extends Num, Inputs extends Num, Ou
/**
* Constructs a controller with the given coefficients and plant.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning</a>
* for how to select the tolerances.
*
* @param A Continuous system matrix of the plant being controlled.
@@ -107,14 +107,12 @@ public class LinearQuadraticRegulator<States extends Num, Inputs extends Num, Ou
var discB = discABPair.getSecond();
if (!StateSpaceUtil.isStabilizable(discA, discB)) {
var builder = new StringBuilder("The system passed to the LQR is uncontrollable!\n\nA =\n");
builder
.append(discA.getStorage().toString())
.append("\nB =\n")
.append(discB.getStorage().toString())
.append('\n');
var msg = builder.toString();
var msg =
"The system passed to the LQR is uncontrollable!\n\nA =\n"
+ discA.getStorage().toString()
+ "\nB =\n"
+ discB.getStorage().toString()
+ '\n';
MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace());
throw new IllegalArgumentException(msg);
}
@@ -258,8 +256,9 @@ public class LinearQuadraticRegulator<States extends Num, Inputs extends Num, Ou
* are time-delayed too long, the LQR may be unstable. However, if we know the amount of delay, we
* can compute the control based on where the system will be after the time delay.
*
* <p>See https://file.tavsys.net/control/controls-engineering-in-frc.pdf appendix C.4 for a
* derivation.
* <p>See <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>
* appendix C.4 for a derivation.
*
* @param plant The plant being controlled.
* @param dtSeconds Discretization timestep in seconds.

View File

@@ -30,9 +30,9 @@ import java.util.function.BiFunction;
* error covariance by linearizing the models around the state estimate, then applying the linear
* Kalman filter equations.
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control
* theory".
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>
* chapter 9 "Stochastic control theory".
*/
public class ExtendedKalmanFilter<States extends Num, Inputs extends Num, Outputs extends Num>
implements KalmanTypeFilter<States, Inputs, Outputs> {
@@ -59,8 +59,8 @@ public class ExtendedKalmanFilter<States extends Num, Inputs extends Num, Output
/**
* Constructs an extended Kalman filter.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices</a>
* for how to select the standard deviations.
*
* @param states a Nat representing the number of states.
@@ -97,8 +97,8 @@ public class ExtendedKalmanFilter<States extends Num, Inputs extends Num, Output
/**
* Constructs an extended Kalman filter.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices</a>
* for how to select the standard deviations.
*
* @param states a Nat representing the number of states.

View File

@@ -25,9 +25,9 @@ import edu.wpi.first.math.system.LinearSystem;
* amount of the difference between the actual measurements and the measurements predicted by the
* model.
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control
* theory".
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>
* chapter 9 "Stochastic control theory".
*/
public class KalmanFilter<States extends Num, Inputs extends Num, Outputs extends Num>
implements KalmanTypeFilter<States, Inputs, Outputs> {
@@ -45,8 +45,8 @@ public class KalmanFilter<States extends Num, Inputs extends Num, Outputs extend
/**
* Constructs a Kalman filter with the given plant.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices</a>
* for how to select the standard deviations.
*
* @param states A Nat representing the states of the system.
@@ -82,15 +82,12 @@ public class KalmanFilter<States extends Num, Inputs extends Num, Outputs extend
var C = plant.getC();
if (!StateSpaceUtil.isDetectable(discA, C)) {
var builder =
new StringBuilder("The system passed to the Kalman filter is unobservable!\n\nA =\n");
builder
.append(discA.getStorage().toString())
.append("\nC =\n")
.append(C.getStorage().toString())
.append('\n');
var msg = builder.toString();
var msg =
"The system passed to the Kalman filter is unobservable!\n\nA =\n"
+ discA.getStorage().toString()
+ "\nC =\n"
+ C.getStorage().toString()
+ '\n';
MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace());
throw new IllegalArgumentException(msg);
}

View File

@@ -28,9 +28,9 @@ import edu.wpi.first.math.system.LinearSystem;
* <p>This class assumes predict() and correct() are called in pairs, so the Kalman gain converges
* to a steady-state value. If they aren't, use {@link KalmanFilter} instead.
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control
* theory".
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>
* chapter 9 "Stochastic control theory".
*/
public class SteadyStateKalmanFilter<States extends Num, Inputs extends Num, Outputs extends Num> {
private final Nat<States> m_states;
@@ -46,8 +46,8 @@ public class SteadyStateKalmanFilter<States extends Num, Inputs extends Num, Out
/**
* Constructs a steady-state Kalman filter with the given plant.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices</a>
* for how to select the standard deviations.
*
* @param states A Nat representing the states of the system.
@@ -81,15 +81,12 @@ public class SteadyStateKalmanFilter<States extends Num, Inputs extends Num, Out
var C = plant.getC();
if (!StateSpaceUtil.isDetectable(discA, C)) {
var builder =
new StringBuilder("The system passed to the Kalman filter is unobservable!\n\nA =\n");
builder
.append(discA.getStorage().toString())
.append("\nC =\n")
.append(C.getStorage().toString())
.append('\n');
var msg = builder.toString();
var msg =
"The system passed to the Kalman filter is unobservable!\n\nA =\n"
+ discA.getStorage().toString()
+ "\nC =\n"
+ C.getStorage().toString()
+ '\n';
MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace());
throw new IllegalArgumentException(msg);
}

View File

@@ -31,12 +31,13 @@ import org.ejml.simple.SimpleMatrix;
* <p>An unscented Kalman filter uses nonlinear state and measurement models. It propagates the
* error covariance using sigma points chosen to approximate the true probability distribution.
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control
* theory".
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>
* chapter 9 "Stochastic control theory".
*
* <p>This class implements a square-root-form unscented Kalman filter (SR-UKF). For more
* information about the SR-UKF, see https://www.researchgate.net/publication/3908304.
* information about the SR-UKF, see <a
* href="https://www.researchgate.net/publication/3908304">https://www.researchgate.net/publication/3908304</a>.
*/
public class UnscentedKalmanFilter<States extends Num, Inputs extends Num, Outputs extends Num>
implements KalmanTypeFilter<States, Inputs, Outputs> {
@@ -64,8 +65,8 @@ public class UnscentedKalmanFilter<States extends Num, Inputs extends Num, Outpu
/**
* Constructs an Unscented Kalman Filter.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices</a>
* for how to select the standard deviations.
*
* @param states A Nat representing the number of states.
@@ -104,8 +105,8 @@ public class UnscentedKalmanFilter<States extends Num, Inputs extends Num, Outpu
* custom functions for arithmetic can be useful if you have angles in the state or measurements,
* because they allow you to correctly account for the modular nature of angle arithmetic.
*
* <p>See
* https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices
* <p>See <a
* href="https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices">https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices</a>
* for how to select the standard deviations.
*
* @param states A Nat representing the number of states.
@@ -206,7 +207,7 @@ public class UnscentedKalmanFilter<States extends Num, Inputs extends Num, Outpu
var qrStorage = Sbar.transpose().getStorage();
if (!qr.decompose(qrStorage.getDDRM())) {
throw new RuntimeException("QR decomposition failed! Input matrix:\n" + qrStorage.toString());
throw new RuntimeException("QR decomposition failed! Input matrix:\n" + qrStorage);
}
Matrix<C, C> newS = new Matrix<>(new SimpleMatrix(qr.getR(null, true)));

View File

@@ -35,9 +35,13 @@ import org.ejml.simple.SimpleMatrix;
* PID controller out of this class!
*
* <p>For more on filters, we highly recommend the following articles:<br>
* https://en.wikipedia.org/wiki/Linear_filter<br>
* https://en.wikipedia.org/wiki/Iir_filter<br>
* https://en.wikipedia.org/wiki/Fir_filter<br>
* <a
* href="https://en.wikipedia.org/wiki/Linear_filter">https://en.wikipedia.org/wiki/Linear_filter</a>
* <br>
* <a href="https://en.wikipedia.org/wiki/Iir_filter">https://en.wikipedia.org/wiki/Iir_filter</a>
* <br>
* <a href="https://en.wikipedia.org/wiki/Fir_filter">https://en.wikipedia.org/wiki/Fir_filter</a>
* <br>
*
* <p>Note 1: calculate() should be called by the user on a known, regular period. You can use a
* Notifier for this or do it "inline" with code in a periodic function.

View File

@@ -117,19 +117,15 @@ public class Rotation3d implements Interpolatable<Rotation3d> {
// Require that the rotation matrix is special orthogonal. This is true if
// the matrix is orthogonal (RRᵀ = I) and normalized (determinant is 1).
if (R.times(R.transpose()).minus(Matrix.eye(Nat.N3())).normF() > 1e-9) {
var builder = new StringBuilder("Rotation matrix isn't orthogonal\n\nR =\n");
builder.append(R.getStorage().toString()).append('\n');
var msg = builder.toString();
var msg = "Rotation matrix isn't orthogonal\n\nR =\n" + R.getStorage().toString() + '\n';
MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace());
throw new IllegalArgumentException(msg);
}
if (Math.abs(R.det() - 1.0) > 1e-9) {
var builder =
new StringBuilder("Rotation matrix is orthogonal but not special orthogonal\n\nR =\n");
builder.append(R.getStorage().toString()).append('\n');
var msg = builder.toString();
var msg =
"Rotation matrix is orthogonal but not special orthogonal\n\nR =\n"
+ R.getStorage().toString()
+ '\n';
MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace());
throw new IllegalArgumentException(msg);
}
@@ -191,7 +187,6 @@ public class Rotation3d implements Interpolatable<Rotation3d> {
// If the dot product is 1, the two vectors point in the same direction so
// there's no rotation. The default initialization of m_q will work.
m_q = new Quaternion();
return;
} else if (dotNorm < -1.0 + 1E-9) {
// If the dot product is -1, the two vectors point in opposite directions
// so a 180 degree rotation is required. Any orthogonal vector can be used

View File

@@ -87,7 +87,7 @@ public class TravelingSalesman {
* array.
*/
private <Poses extends Num> Vector<Poses> neighbor(Vector<Poses> state) {
var proposedState = new Vector<Poses>(state);
var proposedState = new Vector<>(state);
int rangeStart = (int) (Math.random() * (state.getNumRows() - 1));
int rangeEnd = (int) (Math.random() * (state.getNumRows() - 1));

View File

@@ -25,8 +25,8 @@ import org.ejml.simple.SimpleMatrix;
* of the controller (U is an output because that's what goes to the motors and Y is an input
* because that's what comes back from the sensors).
*
* <p>For more on the underlying math, read
* https://file.tavsys.net/control/controls-engineering-in-frc.pdf.
* <p>For more on the underlying math, read <a
* href="https://file.tavsys.net/control/controls-engineering-in-frc.pdf">https://file.tavsys.net/control/controls-engineering-in-frc.pdf</a>.
*/
public class LinearSystemLoop<States extends Num, Inputs extends Num, Outputs extends Num> {
private final LinearQuadraticRegulator<States, Inputs, Outputs> m_controller;

View File

@@ -38,7 +38,7 @@ public interface TrajectoryConstraint {
/** Represents a minimum and maximum acceleration. */
class MinMax {
public double minAccelerationMetersPerSecondSq = -Double.MAX_VALUE;
public double maxAccelerationMetersPerSecondSq = +Double.MAX_VALUE;
public double maxAccelerationMetersPerSecondSq = Double.MAX_VALUE;
/**
* Constructs a MinMax.

View File

@@ -42,8 +42,7 @@ class DARETest extends UtilityClassTest<DARE> {
.times((B.transpose().times(X).times(B).plus(R)).inv())
.times(B.transpose().times(X).times(A)))
.plus(Q);
assertMatrixEqual(
new Matrix<States, States>(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y);
assertMatrixEqual(new Matrix<>(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y);
}
<States extends Num, Inputs extends Num> void assertDARESolution(
@@ -63,8 +62,7 @@ class DARETest extends UtilityClassTest<DARE> {
.times((B.transpose().times(X).times(B).plus(R)).inv())
.times(B.transpose().times(X).times(A).plus(N.transpose())))
.plus(Q);
assertMatrixEqual(
new Matrix<States, States>(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y);
assertMatrixEqual(new Matrix<>(new SimpleMatrix(Y.getNumRows(), Y.getNumCols())), Y);
}
@Test

View File

@@ -18,8 +18,7 @@ class ControlAffinePlantInversionFeedforwardTest {
@Test
void testCalculate() {
ControlAffinePlantInversionFeedforward<N2, N1> feedforward =
new ControlAffinePlantInversionFeedforward<N2, N1>(
Nat.N2(), Nat.N1(), this::getDynamics, 0.02);
new ControlAffinePlantInversionFeedforward<>(Nat.N2(), Nat.N1(), this::getDynamics, 0.02);
assertEquals(
48.0, feedforward.calculate(VecBuilder.fill(2, 2), VecBuilder.fill(3, 3)).get(0, 0), 1e-6);
@@ -28,8 +27,7 @@ class ControlAffinePlantInversionFeedforwardTest {
@Test
void testCalculateState() {
ControlAffinePlantInversionFeedforward<N2, N1> feedforward =
new ControlAffinePlantInversionFeedforward<N2, N1>(
Nat.N2(), Nat.N1(), this::getDynamics, 0.02);
new ControlAffinePlantInversionFeedforward<>(Nat.N2(), Nat.N1(), this::getDynamics, 0.02);
assertEquals(
48.0, feedforward.calculate(VecBuilder.fill(2, 2), VecBuilder.fill(3, 3)).get(0, 0), 1e-6);

View File

@@ -21,7 +21,7 @@ class ImplicitModelFollowerTest {
var plant = LinearSystemId.identifyDrivetrainSystem(1.0, 1.0, 1.0, 1.0);
var imf = new ImplicitModelFollower<N2, N2, N2>(plant, plant);
var imf = new ImplicitModelFollower<>(plant, plant);
Matrix<N2, N1> x = VecBuilder.fill(0.0, 0.0);
Matrix<N2, N1> xImf = VecBuilder.fill(0.0, 0.0);
@@ -66,7 +66,7 @@ class ImplicitModelFollowerTest {
// Linear acceleration is slower, but angular acceleration is the same
var plantRef = LinearSystemId.identifyDrivetrainSystem(1.0, 2.0, 1.0, 1.0);
var imf = new ImplicitModelFollower<N2, N2, N2>(plant, plantRef);
var imf = new ImplicitModelFollower<>(plant, plantRef);
Matrix<N2, N1> x = VecBuilder.fill(0.0, 0.0);
Matrix<N2, N1> xImf = VecBuilder.fill(0.0, 0.0);

View File

@@ -21,7 +21,7 @@ class LinearPlantInversionFeedforwardTest {
Matrix<N2, N1> B = VecBuilder.fill(0, 1);
LinearPlantInversionFeedforward<N2, N1, N1> feedforward =
new LinearPlantInversionFeedforward<N2, N1, N1>(A, B, 0.02);
new LinearPlantInversionFeedforward<>(A, B, 0.02);
assertEquals(
47.502599,

View File

@@ -5,6 +5,7 @@
package edu.wpi.first.math.estimator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.geometry.Pose2d;
@@ -254,7 +255,7 @@ class DifferentialDrivePoseEstimatorTest {
"Estimator converged to one vision measurement: "
+ estimator.getEstimatedPosition().toString()
+ " -> "
+ measurement.toString();
+ measurement;
var dx = Math.abs(measurement.getX() - estimator.getEstimatedPosition().getX());
var dy = Math.abs(measurement.getY() - estimator.getEstimatedPosition().getY());
@@ -263,7 +264,7 @@ class DifferentialDrivePoseEstimatorTest {
measurement.getRotation().getDegrees()
- estimator.getEstimatedPosition().getRotation().getDegrees());
assertEquals(dx > 0.08 || dy > 0.08 || dtheta > 0.08, true, errorLog);
assertTrue(dx > 0.08 || dy > 0.08 || dtheta > 0.08, errorLog);
}
}

View File

@@ -22,7 +22,6 @@ import edu.wpi.first.math.system.NumericalJacobian;
import edu.wpi.first.math.system.plant.DCMotor;
import edu.wpi.first.math.trajectory.TrajectoryConfig;
import edu.wpi.first.math.trajectory.TrajectoryGenerator;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
@@ -114,7 +113,7 @@ class ExtendedKalmanFilterTest {
dtSeconds);
List<Pose2d> waypoints =
Arrays.asList(
List.of(
new Pose2d(2.75, 22.521, new Rotation2d()),
new Pose2d(24.73, 19.68, Rotation2d.fromDegrees(5.846)));
var trajectory =

View File

@@ -5,6 +5,7 @@
package edu.wpi.first.math.estimator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.geometry.Pose2d;
@@ -267,7 +268,7 @@ class MecanumDrivePoseEstimatorTest {
"Estimator converged to one vision measurement: "
+ estimator.getEstimatedPosition().toString()
+ " -> "
+ measurement.toString();
+ measurement;
var dx = Math.abs(measurement.getX() - estimator.getEstimatedPosition().getX());
var dy = Math.abs(measurement.getY() - estimator.getEstimatedPosition().getY());
@@ -276,7 +277,7 @@ class MecanumDrivePoseEstimatorTest {
measurement.getRotation().getDegrees()
- estimator.getEstimatedPosition().getRotation().getDegrees());
assertEquals(dx > 0.08 || dy > 0.08 || dtheta > 0.08, true, errorLog);
assertTrue(dx > 0.08 || dy > 0.08 || dtheta > 0.08, errorLog);
}
}

View File

@@ -5,6 +5,7 @@
package edu.wpi.first.math.estimator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.geometry.Pose2d;
@@ -288,7 +289,7 @@ class SwerveDrivePoseEstimatorTest {
"Estimator converged to one vision measurement: "
+ estimator.getEstimatedPosition().toString()
+ " -> "
+ measurement.toString();
+ measurement;
var dx = Math.abs(measurement.getX() - estimator.getEstimatedPosition().getX());
var dy = Math.abs(measurement.getY() - estimator.getEstimatedPosition().getY());
@@ -297,7 +298,7 @@ class SwerveDrivePoseEstimatorTest {
measurement.getRotation().getDegrees()
- estimator.getEstimatedPosition().getRotation().getDegrees());
assertEquals(dx > 0.08 || dy > 0.08 || dtheta > 0.08, true, errorLog);
assertTrue(dx > 0.08 || dy > 0.08 || dtheta > 0.08, errorLog);
}
}

View File

@@ -26,7 +26,6 @@ import edu.wpi.first.math.system.plant.DCMotor;
import edu.wpi.first.math.system.plant.LinearSystemId;
import edu.wpi.first.math.trajectory.TrajectoryConfig;
import edu.wpi.first.math.trajectory.TrajectoryGenerator;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
@@ -137,7 +136,7 @@ class UnscentedKalmanFilterTest {
dtSeconds);
List<Pose2d> waypoints =
Arrays.asList(
List.of(
new Pose2d(2.75, 22.521, new Rotation2d()),
new Pose2d(24.73, 19.68, Rotation2d.fromDegrees(5.846)));
var trajectory =

View File

@@ -129,9 +129,9 @@ class LinearFilterTest {
1,
3,
// f(x) = sin(x)
(double x) -> Math.sin(x),
Math::sin,
// df/dx = cos(x)
(double x) -> Math.cos(x),
Math::cos,
h,
-20.0,
20.0);
@@ -140,7 +140,7 @@ class LinearFilterTest {
1,
3,
// f(x) = ln(x)
(double x) -> Math.log(x),
Math::log,
// df/dx = 1/x
(double x) -> 1.0 / x,
h,
@@ -162,7 +162,7 @@ class LinearFilterTest {
2,
5,
// f(x) = sin(x)
(double x) -> Math.sin(x),
Math::sin,
// d²f/dx² = -sin(x)
(double x) -> -Math.sin(x),
h,
@@ -173,7 +173,7 @@ class LinearFilterTest {
2,
5,
// f(x) = ln(x)
(double x) -> Math.log(x),
Math::log,
// d²f/dx² = -1/x²
(double x) -> -1.0 / (x * x),
h,
@@ -201,9 +201,9 @@ class LinearFilterTest {
1,
2,
// f(x) = sin(x)
(double x) -> Math.sin(x),
Math::sin,
// df/dx = cos(x)
(double x) -> Math.cos(x),
Math::cos,
h,
-20.0,
20.0);
@@ -212,7 +212,7 @@ class LinearFilterTest {
1,
2,
// f(x) = ln(x)
(double x) -> Math.log(x),
Math::log,
// df/dx = 1/x
(double x) -> 1.0 / x,
h,
@@ -234,7 +234,7 @@ class LinearFilterTest {
2,
4,
// f(x) = sin(x)
(double x) -> Math.sin(x),
Math::sin,
// d²f/dx² = -sin(x)
(double x) -> -Math.sin(x),
h,
@@ -245,7 +245,7 @@ class LinearFilterTest {
2,
4,
// f(x) = ln(x)
(double x) -> Math.log(x),
Math::log,
// d²f/dx² = -1/x²
(double x) -> -1.0 / (x * x),
h,

View File

@@ -11,7 +11,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.util.Units;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class Pose3dTest {
@@ -194,7 +194,7 @@ class Pose3dTest {
@Test
void testComplexTwists() {
var initial_poses =
Arrays.asList(
List.of(
new Pose3d(
new Translation3d(0.698303, -0.959096, 0.271076),
new Rotation3d(new Quaternion(0.86403, -0.076866, 0.147234, 0.475254))),
@@ -212,7 +212,7 @@ class Pose3dTest {
new Rotation3d(new Quaternion(0.807886, 0.029298, 0.257788, 0.529157))));
var final_poses =
Arrays.asList(
List.of(
new Pose3d(
new Translation3d(-0.230448, -0.511957, 0.198406),
new Rotation3d(new Quaternion(0.753984, 0.347016, 0.409105, 0.379106))),
@@ -267,7 +267,7 @@ class Pose3dTest {
@Test
void testTwistNaN() {
var initial_poses =
Arrays.asList(
List.of(
new Pose3d(
new Translation3d(6.32, 4.12, 0.00),
new Rotation3d(
@@ -277,7 +277,7 @@ class Pose3dTest {
new Rotation3d(
new Quaternion(0.9999999999999793, 0.0, 0.0, 2.0352360299846772E-7))));
var final_poses =
Arrays.asList(
List.of(
new Pose3d(
new Translation3d(6.33, 4.15, 0.00),
new Rotation3d(

View File

@@ -21,7 +21,7 @@ class SimulatedAnnealingTest {
new SimulatedAnnealing<Double>(
2.0,
x -> MathUtil.clamp(x + (Math.random() - 0.5) * stepSize, -3, 3),
x -> function.applyAsDouble(x));
function::applyAsDouble);
double solution = simulatedAnnealing.solve(-1.0, 5000);
@@ -38,7 +38,7 @@ class SimulatedAnnealingTest {
new SimulatedAnnealing<Double>(
2.0,
x -> MathUtil.clamp(x + (Math.random() - 0.5) * stepSize, 0, 7),
x -> function.applyAsDouble(x));
function::applyAsDouble);
double solution = simulatedAnnealing.solve(-1.0, 5000);

View File

@@ -14,7 +14,6 @@ import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.spline.SplineParameterizer.MalformedSplineException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
@@ -151,7 +150,7 @@ class CubicHermiteSplineTest {
() ->
run(
new Pose2d(10, 10, Rotation2d.fromDegrees(90)),
Arrays.asList(new Translation2d(10, 10.5)),
List.of(new Translation2d(10, 10.5)),
new Pose2d(10, 11, Rotation2d.fromDegrees(-90))));
}
}

View File

@@ -34,12 +34,7 @@ class NumericalIntegrationTest {
void testZeroRKDP() {
var y1 =
NumericalIntegration.rkdp(
(x, u) -> {
return VecBuilder.fill(0);
},
VecBuilder.fill(0),
VecBuilder.fill(0),
0.1);
(x, u) -> VecBuilder.fill(0), VecBuilder.fill(0), VecBuilder.fill(0), 0.1);
assertEquals(0.0, y1.get(0, 0), 1e-3);
}

Some files were not shown because too many files have changed in this diff Show More