Skip to content

Commit

Permalink
Random fixes
Browse files Browse the repository at this point in the history
- Optimizations
- Bug fixes
- Cleanup
- Speed up tests
  • Loading branch information
mads256h committed Nov 18, 2024
1 parent 6f7c416 commit 700ea79
Show file tree
Hide file tree
Showing 93 changed files with 798 additions and 813 deletions.
4 changes: 2 additions & 2 deletions Assets/EditTests/CoverageCalculatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public void InitializeCalculatorAndMaps()
private static SimulationMap<Tile> GenerateCollisionMap()
{
var tiles = new SimulationMapTile<Tile>[Width, Height];
Tile.Rand = new Random(RandomSeed);
var wall = Tile.GetRandomWall();
var random = new Random(RandomSeed);
var wall = Tile.GetRandomWall(random);
for (var x = 0; x < Width; x++)
{
for (var y = 0; y < Height; y++)
Expand Down
4 changes: 2 additions & 2 deletions Assets/PlayModeTests/CommunicationTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public class CommunicationTest
var bitmap = new Tile[MapWidth, MapHeight];
var firstWallRowY = MapHeight / 2;
var lastWallRowY = firstWallRowY + wallThicknessInTiles;
Tile.Rand = new Random(RandomSeed);
var wall = Tile.GetRandomWall();
var random = new Random(RandomSeed);
var wall = Tile.GetRandomWall(random);

for (var x = 0; x < MapWidth; x++)
{
Expand Down
13 changes: 6 additions & 7 deletions Assets/PlayModeTests/ExplorationCsvDataWriterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ public void SetUp()
{
System.IO.Directory.CreateDirectory(Directory);
}

}

[TearDown]
Expand Down Expand Up @@ -60,11 +59,11 @@ private void InitSimulator()
[Test]
public void ExplorationSnapshotToCsvTest()
{
_explorationSimulation.ExplorationTracker.snapShots.Add(new ExplorationSnapShot(1, 0.1f, 0.1f, 1f));
_explorationSimulation.ExplorationTracker.snapShots.Add(new ExplorationSnapShot(2, 0.2f, 0.2f, 5f));
_explorationSimulation.ExplorationTracker.snapShots.Add(new ExplorationSnapShot(3, 0.5f, 0.3f, 10f));
_explorationSimulation.ExplorationTracker.snapShots.Add(new ExplorationSnapShot(4, 0.7f, 0.4f, 10f));
_explorationSimulation.ExplorationTracker.snapShots.Add(new ExplorationSnapShot(5, 0.9f, 0.5f, 5f));
_explorationSimulation.ExplorationTracker.SnapShots.Add(new ExplorationSnapShot(1, 0.1f, 0.1f, 1f));
_explorationSimulation.ExplorationTracker.SnapShots.Add(new ExplorationSnapShot(2, 0.2f, 0.2f, 5f));
_explorationSimulation.ExplorationTracker.SnapShots.Add(new ExplorationSnapShot(3, 0.5f, 0.3f, 10f));
_explorationSimulation.ExplorationTracker.SnapShots.Add(new ExplorationSnapShot(4, 0.7f, 0.4f, 10f));
_explorationSimulation.ExplorationTracker.SnapShots.Add(new ExplorationSnapShot(5, 0.9f, 0.5f, 5f));

_explorationSimulation.CommunicationManager.CommunicationTracker.InterconnectionSnapShot.Add(1, true);
_explorationSimulation.CommunicationManager.CommunicationTracker.InterconnectionSnapShot.Add(3, false);
Expand All @@ -87,7 +86,7 @@ public void ExplorationSnapshotToCsvTest()
var writer = new ExplorationCsvDataWriter(_explorationSimulation, filename);
writer.CreateCsvFile(Delimiter);

var lines = File.ReadAllLines(filename + ".csv");
var lines = File.ReadAllLines($"{filename}.csv");
Assert.AreEqual(expectedExplorationSnapShots.Count, lines.Length - 1); // -1 because of header
for (var i = 0; i < expectedExplorationSnapShots.Count; i++)
{
Expand Down
4 changes: 2 additions & 2 deletions Assets/PlayModeTests/MaterialCommunicationTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public class MaterialCommunicationTest
var bitmap = new Tile[MapWidth, MapHeight];
const int firstWallRowY = MapHeight / 2;
var lastWallRowY = firstWallRowY + wallThicknessInTiles;
Tile.Rand = new Random(RandomSeed);
var wall = Tile.GetRandomWall();
var random = new Random(RandomSeed);
var wall = Tile.GetRandomWall(random);

for (var x = 0; x < MapWidth; x++)
{
Expand Down
4 changes: 0 additions & 4 deletions Assets/PlayModeTests/MinotaurDoorwayTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ public IEnumerator BlankMap()
{
InitSimulator("blank", new List<Vector2Int> { new Vector2Int(0, 0) });

_maes.PressPlayButton();
_maes.SimulationManager.AttemptSetPlayState(Maes.UI.SimulationPlayState.FastAsPossible);
return AssertDoorsWhenFinished(0);
}
Expand All @@ -140,7 +139,6 @@ public IEnumerator SingleDoorway()
{
InitSimulator("doorway", new List<Vector2Int> { new Vector2Int(0, 0) });

_maes.PressPlayButton();
_maes.SimulationManager.AttemptSetPlayState(Maes.UI.SimulationPlayState.FastAsPossible);
return AssertDoorsWhenFinished(1);
}
Expand All @@ -150,7 +148,6 @@ public IEnumerator Corner()
{
InitSimulator("doorway_corner", new List<Vector2Int> { new Vector2Int(0, 0) });

_maes.PressPlayButton();
_maes.SimulationManager.AttemptSetPlayState(Maes.UI.SimulationPlayState.FastAsPossible);
return AssertDoorsWhenFinished(1);
}
Expand All @@ -160,7 +157,6 @@ public IEnumerator Hallway()
{
InitSimulator("hallway", new List<Vector2Int> { new Vector2Int(0, -24) });

_maes.PressPlayButton();
_maes.SimulationManager.AttemptSetPlayState(Maes.UI.SimulationPlayState.FastAsPossible);
return AssertDoorsWhenFinished(1);
}
Expand Down
5 changes: 3 additions & 2 deletions Assets/PlayModeTests/Robot2DControllerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
using Maes.Robot.Task;
using Maes.Simulation;
using Maes.Simulation.SimulationScenarios;
using Maes.UI;

using NUnit.Framework;

Expand Down Expand Up @@ -106,7 +107,7 @@ public IEnumerator MoveTo_IsDistanceCorrectTest(float movementDistance)
var startingPosition = transform.position;
var expectedEndingPosition = startingPosition + (controller.GetForwardDirectionVector() * movementDistance);

_maes.PressPlayButton();
_maes.SimulationManager.AttemptSetPlayState(SimulationPlayState.FastAsPossible);

// Wait until the robot has started and completed the movement task
while (_testAlgorithm.Tick < 10 || _testAlgorithm.Controller.GetStatus() != RobotStatus.Idle)
Expand Down Expand Up @@ -155,7 +156,7 @@ public IEnumerator Rotate_RotatesCorrectAmountOfDegrees(float degreesToRotate)

expectedAngle %= 360;

_maes.PressPlayButton();
_maes.SimulationManager.AttemptSetPlayState(SimulationPlayState.FastAsPossible);

// Wait until the robot has started and completed the movement task
while (_testAlgorithm.Tick < 10 || _testAlgorithm.Controller.GetStatus() != RobotStatus.Idle)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ public class ExplorationExperimentBase : MonoBehaviour
/// <param name="algorithmName"></param>
/// <param name="constraintName"></param>
/// <param name="mapSize"></param>
/// <param name="mapIterations"></param>
/// <param name="desiredSeed"></param>
/// <param name="desiredRobots"></param>
public void RunSimulation(string mapType, string algorithmName, string constraintName, string mapSize, int mapIterations, int? desiredSeed = null, int? desiredRobots = null)
{
var constraintsDict = new Dictionary<string, RobotConstraints>();
Expand Down
39 changes: 10 additions & 29 deletions Assets/Scripts/ExperimentSimulations/ExplorationTimeoutTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

using Maes.Algorithms;
using Maes.ExplorationAlgorithm.Greed;
Expand Down Expand Up @@ -139,7 +138,6 @@ public void MinosVsGreedSimulation(string constraintName, string amount)
{
var robotCount = amountOfRobots;

var regex = new Regex($@"{algorithmName}-seed-{mapConfig.RandomSeed}-mapConfig\.HeightInTiles-{mapConfig.HeightInTiles}-comms-{constraintName}-robots-{robotCount}-SpawnTogether_.*\.csv");
if (robotCount == 5 && mapConfig.RandomSeed == 585462)
{
simulator.EnqueueScenario(new MySimulationScenario(seed: 123,
Expand Down Expand Up @@ -173,33 +171,16 @@ public void MinosVsGreedSimulation(string constraintName, string amount)
spawningPosHashSet.Add(new Vector2Int(random.Next(-mapConfig.HeightInTiles / 2, mapConfig.HeightInTiles / 2), random.Next(-mapConfig.HeightInTiles / 2, mapConfig.HeightInTiles / 2)));
}

regex = new Regex($@"{algorithmName}-seed-{mapConfig.RandomSeed}-mapConfig\.HeightInTiles-{mapConfig.HeightInTiles}-comms-{constraintName}-robots-{robotCount}-SpawnApart_.*\.csv");
if (false)
{
simulator.EnqueueScenario(new MySimulationScenario(seed: 123,
mapSpawner: generator => generator.GenerateMap(mapConfig),
robotSpawner: (buildingConfig, spawner) => spawner.SpawnRobotsAtPositions(
collisionMap: buildingConfig,
seed: 123,
numberOfRobots: robotCount,
spawnPositions: spawningPosHashSet.ToList(),
createAlgorithmDelegate: algorithms[algorithmName]),
statisticsFileName: $"{algorithmName}-seed-{mapConfig.RandomSeed}-mapConfig.HeightInTiles-{mapConfig.HeightInTiles}-comms-{constraintName}-robots-{robotCount}-SpawnApart",
robotConstraints: constraintsDict[constraintName]));
}
else
{
simulator.EnqueueScenario(new MySimulationScenario(seed: 123,
mapSpawner: generator => generator.GenerateMap(mapConfig),
robotSpawner: (buildingConfig, spawner) => spawner.SpawnRobotsAtPositions(
collisionMap: buildingConfig,
seed: 123,
numberOfRobots: robotCount,
spawnPositions: spawningPosHashSet.ToList(),
createAlgorithmDelegate: algorithms[algorithmName]),
statisticsFileName: $"{algorithmName}-seed-{mapConfig.RandomSeed}-mapConfig.HeightInTiles-{mapConfig.HeightInTiles}-comms-{constraintName}-robots-{robotCount}-SpawnApart",
robotConstraints: constraintsDict[constraintName]));
}
simulator.EnqueueScenario(new MySimulationScenario(seed: 123,
mapSpawner: generator => generator.GenerateMap(mapConfig),
robotSpawner: (buildingConfig, spawner) => spawner.SpawnRobotsAtPositions(
collisionMap: buildingConfig,
seed: 123,
numberOfRobots: robotCount,
spawnPositions: spawningPosHashSet.ToList(),
createAlgorithmDelegate: algorithms[algorithmName]),
statisticsFileName: $"{algorithmName}-seed-{mapConfig.RandomSeed}-mapConfig.HeightInTiles-{mapConfig.HeightInTiles}-comms-{constraintName}-robots-{robotCount}-SpawnApart",
robotConstraints: constraintsDict[constraintName]));
}
}

Expand Down
2 changes: 1 addition & 1 deletion Assets/Scripts/ExplorationAlgorithm/CircleTestAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public void SetController(Robot2DController controller)
public void UpdateLogic()
{
// Don't collect data if dragging against the wall
if (_controller.IsCurrentlyColliding())
if (_controller.IsCurrentlyColliding)
{
_controller.StopCurrentTask();
_shouldEnd = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Text;

using Maes.Algorithms;
using Maes.Map;
using Maes.Robot;
Expand All @@ -12,15 +14,15 @@ public class FollowWaypointsAlgorithm : IExplorationAlgorithm
private Robot2DController _controller = null!;
// Set by SetController
private CoarseGrainedMap _map = null!;
private readonly Waypoint[] _waypoints = {
private static readonly Waypoint[] Waypoints = {
new(new Vector2Int(5,5)),
new(new Vector2Int(10,10)),
new(new Vector2Int(20,20)),
new(new Vector2Int(30,30))
};
private int _currentWaypointIndex;

private struct Waypoint
private readonly struct Waypoint
{
public readonly Vector2Int Destination;

Expand All @@ -32,7 +34,7 @@ public Waypoint(Vector2Int destination)

public void UpdateLogic()
{
if (_currentWaypointIndex >= _waypoints.Length)
if (_currentWaypointIndex >= Waypoints.Length)
{
_controller.StopCurrentTask();
return;
Expand All @@ -41,13 +43,13 @@ public void UpdateLogic()
if (IsDestinationReached())
{
_currentWaypointIndex++;
if (_currentWaypointIndex >= _waypoints.Length)
if (_currentWaypointIndex >= Waypoints.Length)
{
_controller.StopCurrentTask();
return;
}
}
_controller.PathAndMoveTo(_waypoints[_currentWaypointIndex].Destination);
_controller.PathAndMoveTo(Waypoints[_currentWaypointIndex].Destination);
}

public void SetController(Robot2DController controller)
Expand All @@ -58,17 +60,25 @@ public void SetController(Robot2DController controller)

public string GetDebugInfo()
{
return $"currentWaypointIndex: {_currentWaypointIndex}" +
$"\nCoarse Map Position: {_map.GetApproximatePosition()}" +
$"\nCurrent Tile: {_map.GetCurrentTile()}" +
$"\nCurrent position: {_map.GetCurrentPosition()}" +
$"\nDestination: {_waypoints[_currentWaypointIndex].Destination}" +
$"\nStatus: {_controller.GetStatus()}";
return
new StringBuilder().Append("currentWaypointIndex: ")
.Append(_currentWaypointIndex)
.Append("\nCoarse Map Position: ")
.Append(_map.GetApproximatePosition())
.Append("\nCurrent Tile: ")
.Append(_map.GetCurrentTile())
.Append("\nCurrent position: ")
.Append(_map.GetCurrentPosition())
.Append("\nDestination: ")
.Append(Waypoints[_currentWaypointIndex].Destination)
.Append("\nStatus: ")
.Append(_controller.GetStatus())
.ToString();
}

private bool IsDestinationReached()
{
return _map.GetTileCenterRelativePosition(_waypoints[_currentWaypointIndex].Destination).Distance < 0.5f;
return _map.GetTileCenterRelativePosition(Waypoints[_currentWaypointIndex].Destination).Distance < 0.5f;
}
}
}
2 changes: 1 addition & 1 deletion Assets/Scripts/ExplorationAlgorithm/Greed/Greed.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public void UpdateLogic()
}
}

if (_controller.IsCurrentlyColliding())
if (_controller.IsCurrentlyColliding)
{
if (_controller.GetStatus() != Robot.Task.RobotStatus.Idle)
{
Expand Down
16 changes: 11 additions & 5 deletions Assets/Scripts/ExplorationAlgorithm/Minotaur/EdgeDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,22 +102,28 @@ private EdgeState UpdateState()
/// <summary>
/// Gets the tiles around the robot by casting 360-<paramref name="startAngle"/> rays. These rays expand from the robot and out being stopped by the <paramref name="limiters"/>.
/// <para></para>
/// If only one ray is desired, consider <seealso cref="GetFurthestTileAroundPoint(float, int, List{SlamTileStatus}, bool, bool)"/>
/// If only one ray is desired, consider <seealso cref="GetFurthestTileAroundPoint(float, int, List{SlamTileStatus}, Vector2Int?, bool, bool)"/>
/// </summary>
/// <param name="range">The distance of the ray</param>
/// <param name="limiters">What tiles should stop the rays</param>
/// <param name="point"></param>
/// <param name="slamPrecision">Target slam tiles instead of coarse tiles</param>
/// <param name="startAngle">If set above 0 then this will create arcs instead of circles around the robot, based on <see cref="Vector2.right"/> counter-clockwise</param>
/// <returns>The unique tiles that were hit</returns>
public IEnumerable<Vector2Int> GetTilesAroundPoint(int range, List<SlamTileStatus> limiters, Vector2Int? point = null, bool slamPrecision = false, int startAngle = 0)
public HashSet<Vector2Int> GetTilesAroundPoint(int range, List<SlamTileStatus> limiters, Vector2Int? point = null, bool slamPrecision = false, int startAngle = 0)
{
IPathFindingMap map = slamPrecision ? _slamMap : _coarseMap;
var tiles = new List<Vector2Int>();
var tiles = new HashSet<Vector2Int>();
for (var angle = startAngle; angle < 360; angle++)
{
tiles.Add(GetFurthestTileAroundPoint(_coarseMap.GetApproximateGlobalDegrees() + angle, range, limiters, slamPrecision: slamPrecision));
var tile = GetFurthestTileAroundPoint(_coarseMap.GetApproximateGlobalDegrees() + angle, range, limiters, slamPrecision: slamPrecision);
if (map.IsWithinBounds(tile))
{
tiles.Add(tile);
}
}
return tiles.Distinct().Where(tile => map.IsWithinBounds(tile));

return tiles;
}

public Vector2Int GetFurthestTileAroundPoint(float angle, int range, List<SlamTileStatus> limiters, Vector2Int? point = null, bool snapToGrid = false, bool slamPrecision = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
//
// Original repository: https://github.com/Molitany/MAES

using System;
using System.Collections.Generic;

using Maes.Algorithms;
Expand Down Expand Up @@ -52,17 +53,17 @@ public IMinotaurMessage Combine(IMinotaurMessage otherMessage, MinotaurAlgorithm
public IMinotaurMessage? Process(MinotaurAlgorithm minotaur)
{
var doorwayTile = CoarseGrainedMap.FromSlamMapCoordinate(_doorway.Center);
var pathLengthToDoorway = minotaur._map.GetPath(doorwayTile, false, false);
var pathLengthToDoorway = minotaur._map.GetPath(doorwayTile, false);
if (pathLengthToDoorway != null)
{
foreach (var knownDoorway in minotaur._doorways)
{
if (pathLengthToDoorway.Contains(CoarseGrainedMap.FromSlamMapCoordinate(knownDoorway.Center)))
if (Array.IndexOf(pathLengthToDoorway, CoarseGrainedMap.FromSlamMapCoordinate(knownDoorway.Center)) != -1)
{
return null;
}
}
var bid = new Dictionary<int, int>() { { minotaur._controller.GetRobotID(), pathLengthToDoorway.Count } };
var bid = new Dictionary<int, int>() { { minotaur._controller.GetRobotID(), pathLengthToDoorway.Length } };
minotaur._doorways.Add(_doorway);
return new BiddingMessage(_requesterID, bid, _doorway);
}
Expand Down
Loading

0 comments on commit 700ea79

Please sign in to comment.