Enhance AI and simulation components with presence management and routing capabilities
- Introduced the `HSchool.Ai` project, responsible for routing, day plans, and presence management. - Updated the `HSchool.Simulation` project to integrate with the new AI functionalities, improving decision-making and presence tracking. - Added `travelMinutes` to room and territory definitions, ensuring accurate movement calculations within the simulation. - Enhanced the `School` class to manage presence and implement empty-time skipping functionality. - Updated documentation to reflect the new AI features and their impact on school simulation. - Added tests for presence management and routing to ensure robust functionality and reliability.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
using HSchool.Content;
|
||||
|
||||
namespace HSchool.Ai.Tests;
|
||||
|
||||
internal static class PackDocuments
|
||||
{
|
||||
public static IReadOnlyList<ContentDocument> FromDirectory(string packId, string packRoot)
|
||||
{
|
||||
var documents = new List<ContentDocument>();
|
||||
foreach (var path in Directory.EnumerateFiles(packRoot, "*.*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (!path.EndsWith(".jsonc", StringComparison.OrdinalIgnoreCase)
|
||||
&& !path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var relative = Path.GetRelativePath(packRoot, path).Replace('\\', '/');
|
||||
documents.Add(new ContentDocument(packId, relative, File.ReadAllText(path)));
|
||||
}
|
||||
|
||||
return documents;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class Fixtures
|
||||
{
|
||||
public static (DefCatalog Catalog, MapLayout Map) Vanilla()
|
||||
{
|
||||
var root = Path.Combine(AppContext.BaseDirectory, "vanilla");
|
||||
var documents = PackDocuments.FromDirectory(CatalogLoader.CorePackId, root);
|
||||
var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents);
|
||||
var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents);
|
||||
Assert.NotNull(map);
|
||||
return (catalog, map);
|
||||
}
|
||||
|
||||
public static string RepoRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "h-school.sln")))
|
||||
{
|
||||
dir = dir.Parent;
|
||||
}
|
||||
|
||||
if (dir is null)
|
||||
{
|
||||
throw new InvalidOperationException("Could not find h-school.sln from the test output directory.");
|
||||
}
|
||||
|
||||
return dir.FullName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<RootNamespace>HSchool.Ai.Tests</RootNamespace>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<OutputType>Exe</OutputType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\HSchool.Ai\HSchool.Ai.csproj" />
|
||||
<ProjectReference Include="..\..\src\HSchool.Content\HSchool.Content.csproj" />
|
||||
<ProjectReference Include="..\..\src\HSchool.People\HSchool.People.csproj" />
|
||||
<ProjectReference Include="..\..\src\HSchool.Schedule\HSchool.Schedule.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\..\src\HSchool.Server\mods\core\**\*">
|
||||
<Link>vanilla\%(RecursiveDir)%(Filename)%(Extension)</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,156 @@
|
||||
using HSchool.Content;
|
||||
using HSchool.People;
|
||||
using HSchool.Schedule;
|
||||
|
||||
namespace HSchool.Ai.Tests;
|
||||
|
||||
public class WalkingTests
|
||||
{
|
||||
private static readonly DateTime TuesdayLesson = new(2012, 4, 3, 8, 45, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime Sunday = new(2012, 4, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime SpringBreak = new(2012, 3, 31, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
[Fact]
|
||||
public void PathFrom201ToFirstFloorRestroom_GoesThroughStairsAndCorridors()
|
||||
{
|
||||
var (catalog, map) = Fixtures.Vanilla();
|
||||
var walks = WalkGraph.Build(catalog, map);
|
||||
|
||||
var hops = walks.Path("classroom-201", "restroom-1");
|
||||
|
||||
Assert.Equal(["corridor-2", "stairs-2", "stairs-1", "corridor-1", "restroom-1"], hops);
|
||||
Assert.DoesNotContain("yard", hops);
|
||||
Assert.Equal(6.5f, walks.Minutes("classroom-201", "restroom-1"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PresenceStepper_TakesTheSameMinutesAsTheGraph()
|
||||
{
|
||||
var (catalog, map) = Fixtures.Vanilla();
|
||||
var walks = WalkGraph.Build(catalog, map);
|
||||
var hops = walks.Path("classroom-201", "restroom-1");
|
||||
var cost = walks.Minutes("classroom-201", "restroom-1");
|
||||
var presence = new Presence("classroom-201", 0f, "restroom-1", HeadingHome: false, [.. hops]);
|
||||
|
||||
var walked = PresenceStepper.Advance(presence, walks, cost);
|
||||
|
||||
Assert.Equal("restroom-1", walked.NodeId);
|
||||
Assert.Empty(walked.Path);
|
||||
Assert.Equal(0f, walked.RemainingMinutes);
|
||||
|
||||
var stepwise = presence;
|
||||
var elapsed = 0f;
|
||||
const float step = 0.25f;
|
||||
while (stepwise.NodeId != "restroom-1" || stepwise.Path.Length > 0 || stepwise.RemainingMinutes > 0)
|
||||
{
|
||||
stepwise = PresenceStepper.Advance(stepwise, walks, step);
|
||||
elapsed += step;
|
||||
Assert.True(elapsed <= cost + step);
|
||||
}
|
||||
|
||||
Assert.Equal(cost, elapsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GymAfterClassroom101_CostsSixMinutesAgainstATenMinuteBreak()
|
||||
{
|
||||
var (catalog, map) = Fixtures.Vanilla();
|
||||
var walks = WalkGraph.Build(catalog, map);
|
||||
var hops = walks.Path("classroom-101", "gym-hall");
|
||||
|
||||
Assert.Equal(["corridor-1", "porch", "yard", "gym-hall"], hops);
|
||||
Assert.Equal(6f, walks.Minutes("classroom-101", "gym-hall"));
|
||||
Assert.Equal(10, catalog.DayFrame!.BreakMinutes);
|
||||
Assert.True(walks.Minutes("classroom-101", "gym-hall") < catalog.DayFrame.BreakMinutes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComesToday_IsFalseOnSundayAndHolidays()
|
||||
{
|
||||
var (catalog, map) = Fixtures.Vanilla();
|
||||
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Slavic", TuesdayLesson);
|
||||
var pupil = roster.People.First(person => person.IsStudent);
|
||||
var schoolClass = roster.Classes.First(row => row.Id == pupil.ClassId);
|
||||
var table = new Timetable(
|
||||
[new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 1, Period: 1)],
|
||||
[]);
|
||||
|
||||
Assert.True(Duty.ComesToday(pupil, table, catalog, TuesdayLesson, weekDays: 5));
|
||||
Assert.False(Duty.ComesToday(pupil, table, catalog, Sunday, weekDays: 5));
|
||||
Assert.False(Duty.ComesToday(pupil, table, catalog, SpringBreak, weekDays: 5));
|
||||
Assert.False(Duty.ComesToday(
|
||||
roster.People.First(person => person.IsParent && !person.IsStaff && !person.IsStudent),
|
||||
table,
|
||||
catalog,
|
||||
TuesdayLesson,
|
||||
weekDays: 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClassWithoutLessons_StaysAway_TeacherWithAnotherClassComes()
|
||||
{
|
||||
var (catalog, map) = Fixtures.Vanilla();
|
||||
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Slavic", TuesdayLesson);
|
||||
var idle = roster.Classes[0];
|
||||
var busy = roster.Classes[1];
|
||||
var idlePupil = roster.People.First(person => person.Id == idle.PupilIds[0]);
|
||||
var busyPupil = roster.People.First(person => person.Id == busy.PupilIds[0]);
|
||||
var teacher = roster.People.First(person => person.IsParent && !person.IsStudent && !person.IsStaff) with
|
||||
{
|
||||
IsStaff = true,
|
||||
Position = Staffing.TeacherPosition,
|
||||
};
|
||||
var table = new Timetable(
|
||||
[new LessonPlacement(busy.Id, "Mathematics", teacher.Id, busy.RoomId, Day: 1, Period: 1)],
|
||||
[]);
|
||||
|
||||
Assert.False(Duty.ComesToday(idlePupil, table, catalog, TuesdayLesson, weekDays: 5));
|
||||
Assert.True(Duty.ComesToday(busyPupil, table, catalog, TuesdayLesson, weekDays: 5));
|
||||
Assert.True(Duty.ComesToday(teacher, table, catalog, TuesdayLesson, weekDays: 5));
|
||||
Assert.Null(Duty.RoomAt(idlePupil, idle, table, catalog, TuesdayLesson, weekDays: 5));
|
||||
Assert.Equal(busy.RoomId, Duty.RoomAt(busyPupil, busy, table, catalog, TuesdayLesson, weekDays: 5));
|
||||
Assert.Equal(busy.RoomId, Duty.RoomAt(teacher, null, table, catalog, TuesdayLesson, weekDays: 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SameSeedAndMap_YieldTheSameDayPlan()
|
||||
{
|
||||
var (catalog, map) = Fixtures.Vanilla();
|
||||
var walks = WalkGraph.Build(catalog, map);
|
||||
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 9, "Slavic", TuesdayLesson);
|
||||
var pupil = roster.People.First(person => person.IsStudent);
|
||||
var schoolClass = roster.Classes.First(row => row.Id == pupil.ClassId);
|
||||
var table = new Timetable(
|
||||
[new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 1, Period: 1)],
|
||||
[]);
|
||||
|
||||
var first = DayPlans.Build(catalog, walks, pupil, schoolClass, table, TuesdayLesson, weekDays: 5, schoolSeed: 9);
|
||||
var second = DayPlans.Build(catalog, walks, pupil, schoolClass, table, TuesdayLesson, weekDays: 5, schoolSeed: 9);
|
||||
|
||||
Assert.Equal(first, second);
|
||||
Assert.True(first.Comes);
|
||||
Assert.Equal(schoolClass.RoomId, first.FirstRoom);
|
||||
Assert.True(first.AppearAt < DateTime.SpecifyKind(TuesdayLesson.Date.Add(new TimeSpan(8, 30, 0)), DateTimeKind.Utc));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Assembly_DoesNotReferenceArchAspNetOrSockets()
|
||||
{
|
||||
var names = typeof(WalkGraph).Assembly.GetReferencedAssemblies().Select(assembly => assembly.Name!);
|
||||
Assert.DoesNotContain(names, name => name.StartsWith("Arch", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.DoesNotContain(names, name => name.Contains("AspNet", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.DoesNotContain(names, name => name.Contains("Sockets", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sources_DoNotUseWallClock()
|
||||
{
|
||||
var root = Path.Combine(Fixtures.RepoRoot(), "src", "HSchool.Ai");
|
||||
foreach (var path in Directory.EnumerateFiles(root, "*.cs"))
|
||||
{
|
||||
var text = File.ReadAllText(path);
|
||||
Assert.DoesNotContain("DateTime.Now", text, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("DateTime.UtcNow", text, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,52 @@ public class CalendarTests
|
||||
Assert.Equal(DaySlot.BreakAfter(2), slot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextWorkMorning_FromSaturdayLandsOnMondaySix()
|
||||
{
|
||||
var catalog = LoadVanilla();
|
||||
var next = SchoolDay.NextWorkMorning(catalog, new DateTime(2012, 4, 7, 10, 0, 0, DateTimeKind.Utc), weekDays: 5);
|
||||
|
||||
Assert.Equal(new DateTime(2012, 4, 9, 6, 0, 0, DateTimeKind.Utc), next);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextWorkMorning_FromTuesdayNightLandsOnThatMorning()
|
||||
{
|
||||
var catalog = LoadVanilla();
|
||||
var next = SchoolDay.NextWorkMorning(catalog, new DateTime(2012, 4, 3, 3, 0, 0, DateTimeKind.Utc), weekDays: 5);
|
||||
|
||||
Assert.Equal(new DateTime(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc), next);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextWorkMorning_FromTuesdayEveningLandsOnWednesday()
|
||||
{
|
||||
var catalog = LoadVanilla();
|
||||
var next = SchoolDay.NextWorkMorning(catalog, new DateTime(2012, 4, 3, 22, 0, 0, DateTimeKind.Utc), weekDays: 5);
|
||||
|
||||
Assert.Equal(new DateTime(2012, 4, 4, 6, 0, 0, DateTimeKind.Utc), next);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InWorkWindow_SevenOnAWorkday_IsAlreadyOpen()
|
||||
{
|
||||
var catalog = LoadVanilla();
|
||||
var seven = new DateTime(2012, 4, 3, 7, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
Assert.True(SchoolDay.IsWorkday(catalog, seven, weekDays: 5));
|
||||
Assert.True(SchoolDay.InWorkWindow(catalog, seven, weekDays: 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InWorkWindow_DoesNotNeedTeachers()
|
||||
{
|
||||
var catalog = LoadVanilla();
|
||||
var morning = new DateTime(2012, 4, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
Assert.True(SchoolDay.InWorkWindow(catalog, morning, weekDays: 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Subject_UnknownRoom_FailsTheCatalog()
|
||||
{
|
||||
|
||||
@@ -106,7 +106,7 @@ public class CatalogLoaderTests
|
||||
CatalogLoader.CorePackId,
|
||||
"rooms",
|
||||
"office",
|
||||
"""{ "defName": "Office", "slots": [{ "key": "chair", "thing": "Chair" }], "positions": ["Principal"] }"""),
|
||||
"""{ "defName": "Office", "slots": [{ "key": "chair", "thing": "Chair" }], "positions": ["Principal"], "travelMinutes": 1 }"""),
|
||||
]));
|
||||
|
||||
Assert.Contains("Chair", ex.Message);
|
||||
@@ -126,4 +126,28 @@ public class CatalogLoaderTests
|
||||
Assert.Equal("Мебель", catalog.Label("ru", catalog.Things["Chair"]));
|
||||
Assert.Equal("Chair", catalog.Label("en", catalog.Things["Chair"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConcreteRoomWithoutTravelMinutes_FailsTheCatalog()
|
||||
{
|
||||
var ex = Assert.Throws<ContentLoadException>(() => _loader.Load(
|
||||
[CatalogLoader.CorePackId],
|
||||
[
|
||||
PackDocuments.Def(CatalogLoader.CorePackId, "rooms", "office", """{ "defName": "Office" }"""),
|
||||
]));
|
||||
|
||||
Assert.Contains("travelMinutes", ex.Message, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConcreteTerritoryWithoutTravelMinutes_FailsTheCatalog()
|
||||
{
|
||||
var ex = Assert.Throws<ContentLoadException>(() => _loader.Load(
|
||||
[CatalogLoader.CorePackId],
|
||||
[
|
||||
PackDocuments.Def(CatalogLoader.CorePackId, "territories", "yard", """{ "defName": "Yard" }"""),
|
||||
]));
|
||||
|
||||
Assert.Contains("travelMinutes", ex.Message, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ public class InheritanceTests
|
||||
var ex = Assert.Throws<ContentLoadException>(() => _loader.Load(
|
||||
[CatalogLoader.CorePackId],
|
||||
[
|
||||
PackDocuments.Def(CatalogLoader.CorePackId, "rooms", "office", """{ "defName": "Office" }"""),
|
||||
PackDocuments.Def(CatalogLoader.CorePackId, "rooms", "office", """{ "defName": "Office", "travelMinutes": 1 }"""),
|
||||
PackDocuments.Def(CatalogLoader.CorePackId, "things", "chair", """{ "defName": "Chair", "parent": "Office" }"""),
|
||||
]));
|
||||
|
||||
|
||||
@@ -125,14 +125,14 @@ public class MapValidationTests
|
||||
CatalogLoader.CorePackId,
|
||||
"territories",
|
||||
"yard",
|
||||
abstractYard ? """{ "defName": "Yard", "abstract": true }""" : """{ "defName": "Yard" }"""),
|
||||
abstractYard ? """{ "defName": "Yard", "abstract": true }""" : """{ "defName": "Yard", "travelMinutes": 1 }"""),
|
||||
PackDocuments.Def(CatalogLoader.CorePackId, "buildings", "main", """{ "defName": "Main" }"""),
|
||||
PackDocuments.Def(CatalogLoader.CorePackId, "floors", "floor", """{ "defName": "Floor" }"""),
|
||||
PackDocuments.Def(
|
||||
CatalogLoader.CorePackId,
|
||||
"rooms",
|
||||
"office",
|
||||
"""{ "defName": "Office", "slots": [{ "key": "seat", "thing": "Chair" }], "positions": ["Principal"] }"""),
|
||||
"""{ "defName": "Office", "slots": [{ "key": "seat", "thing": "Chair" }], "positions": ["Principal"], "travelMinutes": 1 }"""),
|
||||
];
|
||||
|
||||
private static MapLayout MiniMap(
|
||||
|
||||
@@ -62,7 +62,7 @@ public class MapViewTests
|
||||
new ContentDocument(
|
||||
CatalogLoader.CorePackId,
|
||||
"defs/territories/yard.jsonc",
|
||||
"""{ "defName": "Yard" }"""),
|
||||
"""{ "defName": "Yard", "travelMinutes": 1 }"""),
|
||||
new ContentDocument(
|
||||
CatalogLoader.CorePackId,
|
||||
"localizations/ru.jsonc",
|
||||
|
||||
@@ -74,7 +74,8 @@ public class PatchTests
|
||||
{
|
||||
"defName": "Office",
|
||||
"slots": [ { "key": "seat", "thing": "Chair" } ],
|
||||
"works": ["TeachLesson", "WalkSchool"]
|
||||
"works": ["TeachLesson", "WalkSchool"],
|
||||
"travelMinutes": 1
|
||||
}
|
||||
"""),
|
||||
PackDocuments.Patch(
|
||||
|
||||
@@ -57,6 +57,13 @@ public class VanillaCoreTests
|
||||
Assert.DoesNotContain(map.Rooms, room => room.Label is "1A" or "1B" or "2A" or "2B");
|
||||
Assert.Equal(16, map.Rooms.Single(room => room.Id == "classroom-101").Seats);
|
||||
Assert.Empty(map.Rooms.Single(room => room.Id == "classroom-101").Slots);
|
||||
Assert.Equal(0.5f, catalog.Rooms["Classroom"].TravelMinutes);
|
||||
Assert.Equal(1.5f, catalog.Rooms["Corridor"].TravelMinutes);
|
||||
Assert.Equal(1.5f, catalog.Rooms["Stairwell"].TravelMinutes);
|
||||
Assert.Equal(1f, catalog.Rooms["EntranceHall"].TravelMinutes);
|
||||
Assert.Equal(3f, catalog.Territories["SchoolYard"].TravelMinutes);
|
||||
Assert.Equal(4, catalog.Traits["Diligent"].CommuteMinutes);
|
||||
Assert.Equal(-4, catalog.Traits["Lazy"].CommuteMinutes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -120,6 +120,19 @@ public class GameClockTests
|
||||
Assert.Equal(DateTimeKind.Utc, clock.Time.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JumpTo_MovesTheCalendarWithoutTicking()
|
||||
{
|
||||
var clock = new GameClock(Start) { IsRunning = false };
|
||||
var target = new DateTime(2012, 4, 9, 6, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
clock.JumpTo(target);
|
||||
|
||||
Assert.Equal(target, clock.Time);
|
||||
Assert.Equal(DateTimeKind.Utc, clock.Time.Kind);
|
||||
Assert.False(clock.IsRunning);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StartDateOutsideTheSupportedRange_Throws()
|
||||
{
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
<ProjectReference Include="..\..\src\HSchool.Simulation\HSchool.Simulation.csproj" />
|
||||
<ProjectReference Include="..\..\src\HSchool.Content\HSchool.Content.csproj" />
|
||||
<ProjectReference Include="..\..\src\HSchool.People\HSchool.People.csproj" />
|
||||
<ProjectReference Include="..\..\src\HSchool.Schedule\HSchool.Schedule.csproj" />
|
||||
<ProjectReference Include="..\..\src\HSchool.Ai\HSchool.Ai.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
using HSchool.Ai;
|
||||
using HSchool.Content;
|
||||
using HSchool.People;
|
||||
using HSchool.Schedule;
|
||||
|
||||
namespace HSchool.Simulation.Tests;
|
||||
|
||||
public class PresenceTests
|
||||
{
|
||||
private static readonly DateTime TuesdayMorning = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly float Cap = 100_000f;
|
||||
|
||||
[Fact]
|
||||
public void SundayAndHoliday_LeaveTheCampusEmpty()
|
||||
{
|
||||
var (catalog, map) = Vanilla();
|
||||
var sunday = new DateTime(2012, 4, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
using var onSunday = Open(catalog, map, sunday, seed: 1);
|
||||
onSunday.Tick(0.2d, 5d);
|
||||
Assert.True(onSunday.IsCampusEmpty());
|
||||
Assert.All(onSunday.CapturePresence(), row => Assert.Null(row.NodeId));
|
||||
|
||||
var holiday = new DateTime(2012, 6, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
using var onHoliday = Open(catalog, map, holiday, seed: 1);
|
||||
onHoliday.Tick(0.2d, 5d);
|
||||
Assert.True(onHoliday.IsCampusEmpty());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClassWithoutLessons_StaysAway_TeacherWithAnotherClassComes()
|
||||
{
|
||||
var (catalog, map) = Vanilla();
|
||||
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Slavic", TuesdayMorning);
|
||||
var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Slavic", TuesdayMorning);
|
||||
var idle = roster.Classes[0];
|
||||
var busy = roster.Classes[1];
|
||||
var hired = Staffing.Hire(catalog, map, roster, pool, pool.Applicants[0].Person.Id, Staffing.TeacherPosition, Cap);
|
||||
Assert.Equal(StaffingError.None, hired.Error);
|
||||
|
||||
using var school = School.Create(1, "Два класса", TuesdayMorning, catalog, map);
|
||||
school.InstallPeople(hired.Roster, seed: 1, "Slavic", hired.Pool);
|
||||
school.SetTimetable(new Timetable(
|
||||
[new LessonPlacement(busy.Id, "Mathematics", hired.Roster.People.First(person => person.IsStaff).Id, busy.RoomId, Day: 1, Period: 1)],
|
||||
[]));
|
||||
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
|
||||
|
||||
AdvanceTo(school, new DateTime(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc));
|
||||
|
||||
var teacherId = school.Roster!.People.First(person => person.IsStaff).Id;
|
||||
var idlePupil = idle.PupilIds[0];
|
||||
var byId = school.CapturePresence().ToDictionary(row => row.PersonId, StringComparer.Ordinal);
|
||||
Assert.Null(byId[idlePupil].NodeId);
|
||||
Assert.NotNull(byId[teacherId].NodeId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstLesson_PutsThePupilInTheirHomeroom()
|
||||
{
|
||||
var (school, homeroom, pupilId) = StaffedFirstFloorClass();
|
||||
using (school)
|
||||
{
|
||||
AdvanceTo(school, new DateTime(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc));
|
||||
|
||||
var row = school.CapturePresence().Single(item => item.PersonId == pupilId);
|
||||
Assert.Equal(homeroom, row.NodeId);
|
||||
Assert.Empty(row.Path);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PhysicalEducationAfterAClassroomLesson_ReachesTheGymOnTheBreak()
|
||||
{
|
||||
var (catalog, map) = Vanilla();
|
||||
var walks = WalkGraph.Build(catalog, map);
|
||||
Assert.Equal(6f, walks.Minutes("classroom-101", "gym-hall"));
|
||||
Assert.True(walks.Minutes("classroom-101", "gym-hall") < catalog.DayFrame!.BreakMinutes);
|
||||
|
||||
var (school, _, pupilId) = StaffedFirstFloorClass();
|
||||
using (school)
|
||||
{
|
||||
AdvanceTo(school, new DateTime(2012, 4, 3, 9, 25, 0, DateTimeKind.Utc));
|
||||
var row = school.CapturePresence().Single(item => item.PersonId == pupilId);
|
||||
Assert.Equal("gym-hall", row.NodeId);
|
||||
Assert.Empty(row.Path);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SameSeedAndMap_YieldTheSamePlaces()
|
||||
{
|
||||
var (catalog, map) = Vanilla();
|
||||
using var a = OpenStaffed(catalog, map, seed: 9);
|
||||
using var b = OpenStaffed(catalog, map, seed: 9);
|
||||
var until = new DateTime(2012, 4, 3, 9, 20, 0, DateTimeKind.Utc);
|
||||
AdvanceTo(a, until);
|
||||
AdvanceTo(b, until);
|
||||
|
||||
Assert.Equal(Fingerprint(a.CapturePresence()), Fingerprint(b.CapturePresence()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SaveAndLoadMidBreak_DoesNotTeleport()
|
||||
{
|
||||
var (catalog, map) = Vanilla();
|
||||
using var live = OpenStaffed(catalog, map, seed: 4);
|
||||
AdvanceTo(live, new DateTime(2012, 4, 3, 9, 18, 0, DateTimeKind.Utc));
|
||||
var snapshot = live.CapturePresence();
|
||||
Assert.Contains(snapshot, row => row.NodeId is not null && (row.Path.Count > 0 || row.RemainingMinutes > 0));
|
||||
|
||||
using var loaded = School.Load(2, "Сейв", live.Clock.Time, running: true, speedIndex: 0, catalog, map);
|
||||
loaded.InstallPeople(live.Roster!, seed: 4, "Slavic", live.Applicants);
|
||||
loaded.SetTimetable(live.Timetable!);
|
||||
loaded.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
|
||||
loaded.RestorePresence(snapshot);
|
||||
|
||||
Assert.Equal(Fingerprint(snapshot), Fingerprint(loaded.CapturePresence()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SkipEmpty_FromSaturdayLandsOnMondaySix()
|
||||
{
|
||||
using var school = OpenEmpty(new DateTime(2012, 4, 7, 10, 0, 0, DateTimeKind.Utc));
|
||||
var result = school.TrySkipEmpty();
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(new DateTime(2012, 4, 9, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SkipEmpty_FromTuesdayNightLandsOnThatMorning()
|
||||
{
|
||||
using var school = OpenEmpty(new DateTime(2012, 4, 3, 3, 0, 0, DateTimeKind.Utc));
|
||||
var result = school.TrySkipEmpty();
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(new DateTime(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SkipEmpty_FromTuesdayEveningLandsOnWednesday()
|
||||
{
|
||||
using var school = OpenEmpty(new DateTime(2012, 4, 3, 22, 0, 0, DateTimeKind.Utc));
|
||||
var result = school.TrySkipEmpty();
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(new DateTime(2012, 4, 4, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SkipEmpty_InTheWorkWindow_IsRejectedEvenWhenEmpty()
|
||||
{
|
||||
using var school = OpenEmpty(new DateTime(2012, 4, 3, 7, 0, 0, DateTimeKind.Utc));
|
||||
Assert.True(school.IsCampusEmpty());
|
||||
|
||||
var result = school.TrySkipEmpty();
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal(SkipEmptyError.InWorkWindow, result.Error);
|
||||
Assert.Equal(new DateTime(2012, 4, 3, 7, 0, 0, DateTimeKind.Utc), school.Clock.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SkipEmpty_SchoolWithoutTeachers_StillHasAWorkDay()
|
||||
{
|
||||
using var school = OpenEmpty(new DateTime(2012, 4, 3, 10, 0, 0, DateTimeKind.Utc));
|
||||
Assert.Equal(0, school.Roster!.People.Count(person => person.IsStaff));
|
||||
|
||||
var result = school.TrySkipEmpty();
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal(SkipEmptyError.InWorkWindow, result.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SkipEmpty_OverSummer_RunsFirstSeptemberIntake()
|
||||
{
|
||||
var start = new DateTime(2012, 6, 1, 22, 0, 0, DateTimeKind.Utc);
|
||||
using var school = OpenEmpty(start);
|
||||
var before = school.Roster!;
|
||||
var oldest = before.Classes.Max(row => row.Year);
|
||||
var graduated = before.Classes
|
||||
.Where(row => row.Year == oldest)
|
||||
.SelectMany(row => row.PupilIds)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var result = school.TrySkipEmpty();
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.True(result.PeopleChanged);
|
||||
Assert.Equal(new DateTime(2012, 9, 3, 6, 0, 0, DateTimeKind.Utc), school.Clock.Time);
|
||||
Assert.Contains(school.Roster!.Classes, row => row.Year == 1);
|
||||
Assert.DoesNotContain(school.Roster.People, person => graduated.Contains(person.Id));
|
||||
Assert.Equal(before.People.Count(person => person.IsStudent), school.Roster.People.Count(person => person.IsStudent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SkipEmpty_Week_MatchesALivedWeek()
|
||||
{
|
||||
var start = new DateTime(2012, 4, 6, 22, 0, 0, DateTimeKind.Utc);
|
||||
var until = new DateTime(2012, 4, 9, 6, 0, 0, DateTimeKind.Utc);
|
||||
using var skipped = OpenEmpty(start);
|
||||
using var lived = OpenEmpty(start);
|
||||
|
||||
Assert.True(skipped.TrySkipEmpty().Succeeded);
|
||||
while (lived.Clock.Time < until)
|
||||
{
|
||||
lived.Tick(0.2d, 5d);
|
||||
}
|
||||
|
||||
Assert.Equal(until, skipped.Clock.Time);
|
||||
Assert.Equal(until, lived.Clock.Time);
|
||||
Assert.Equal(skipped.Applicants!.Week, lived.Applicants!.Week);
|
||||
Assert.Equal(
|
||||
skipped.Applicants.Applicants.Select(row => row.Person.Id),
|
||||
lived.Applicants.Applicants.Select(row => row.Person.Id));
|
||||
Assert.Equal(
|
||||
skipped.Roster!.People.Select(person => person.Id).Order(StringComparer.Ordinal),
|
||||
lived.Roster!.People.Select(person => person.Id).Order(StringComparer.Ordinal));
|
||||
Assert.True(skipped.IsCampusEmpty());
|
||||
Assert.True(lived.IsCampusEmpty());
|
||||
Assert.Equal(Fingerprint(skipped.CapturePresence()), Fingerprint(lived.CapturePresence()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Simulation_DoesNotReferenceSockets()
|
||||
{
|
||||
var names = typeof(School).Assembly.GetReferencedAssemblies().Select(assembly => assembly.Name!);
|
||||
Assert.DoesNotContain(names, name => name.Contains("Sockets", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.DoesNotContain(names, name => name.Contains("AspNet", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private static (School School, string Homeroom, string PupilId) StaffedFirstFloorClass()
|
||||
{
|
||||
var (catalog, map) = Vanilla();
|
||||
var school = OpenStaffed(catalog, map, seed: 1);
|
||||
var homeroomClass = school.Roster!.Classes.First(row =>
|
||||
row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104");
|
||||
var pupil = homeroomClass.PupilIds
|
||||
.Select(id => school.Roster.People.First(person => person.Id == id))
|
||||
.First(person => !person.Traits.Contains("Lazy"));
|
||||
return (school, homeroomClass.RoomId, pupil.Id);
|
||||
}
|
||||
|
||||
private static School OpenStaffed(DefCatalog catalog, MapLayout map, int seed)
|
||||
{
|
||||
var roster = RosterGenerator.Generate(catalog, map, seed, "Slavic", TuesdayMorning);
|
||||
var pool = ApplicantPool.Create(catalog, roster, seed, "Slavic", TuesdayMorning);
|
||||
var schoolClass = roster.Classes.First(row =>
|
||||
row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104");
|
||||
var school = School.Create(seed, "Присутствие", TuesdayMorning, catalog, map);
|
||||
school.InstallPeople(roster, seed, "Slavic", pool);
|
||||
school.SetTimetable(new Timetable(
|
||||
[
|
||||
new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 1, Period: 1),
|
||||
new LessonPlacement(schoolClass.Id, "PhysicalEducation", "t2", "gym-hall", Day: 1, Period: 2),
|
||||
],
|
||||
[]));
|
||||
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
|
||||
return school;
|
||||
}
|
||||
|
||||
private static School Open(DefCatalog catalog, MapLayout map, DateTime start, int seed)
|
||||
{
|
||||
var roster = RosterGenerator.Generate(catalog, map, seed, "Slavic", start);
|
||||
var pool = ApplicantPool.Create(catalog, roster, seed, "Slavic", start);
|
||||
var schoolClass = roster.Classes[0];
|
||||
var school = School.Create(seed, "Присутствие", start, catalog, map);
|
||||
school.InstallPeople(roster, seed, "Slavic", pool);
|
||||
school.SetTimetable(new Timetable(
|
||||
[new LessonPlacement(schoolClass.Id, "Mathematics", "t1", schoolClass.RoomId, Day: 0, Period: 1)],
|
||||
[]));
|
||||
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
|
||||
return school;
|
||||
}
|
||||
|
||||
private static School OpenEmpty(DateTime start)
|
||||
{
|
||||
var (catalog, map) = Vanilla();
|
||||
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Slavic", start);
|
||||
var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Slavic", start);
|
||||
var school = School.Create(1, "Пустая", start, catalog, map);
|
||||
school.InstallPeople(roster, seed: 1, "Slavic", pool);
|
||||
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
|
||||
return school;
|
||||
}
|
||||
|
||||
private static void AdvanceTo(School school, DateTime until)
|
||||
{
|
||||
while (school.Clock.Time < until)
|
||||
{
|
||||
school.Tick(0.2d, 5d);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Fingerprint(IReadOnlyList<PresenceSnapshot> rows) =>
|
||||
string.Join(
|
||||
"|",
|
||||
rows.OrderBy(row => row.PersonId, StringComparer.Ordinal)
|
||||
.Select(row =>
|
||||
$"{row.PersonId}:{row.NodeId ?? "-"}:{row.RemainingMinutes:0.###}:{row.DestinationId ?? "-"}:{(row.HeadingHome ? "1" : "0")}:{string.Join(",", row.Path)}"));
|
||||
|
||||
private static (DefCatalog Catalog, MapLayout Map) Vanilla()
|
||||
{
|
||||
var root = Path.Combine(AppContext.BaseDirectory, "vanilla");
|
||||
var documents = new List<ContentDocument>();
|
||||
foreach (var path in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (!path.EndsWith(".jsonc", StringComparison.OrdinalIgnoreCase)
|
||||
&& !path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var relative = Path.GetRelativePath(root, path).Replace('\\', '/');
|
||||
documents.Add(new ContentDocument(CatalogLoader.CorePackId, relative, File.ReadAllText(path)));
|
||||
}
|
||||
|
||||
var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents);
|
||||
var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents);
|
||||
Assert.NotNull(map);
|
||||
return (catalog, map);
|
||||
}
|
||||
}
|
||||
@@ -50,10 +50,10 @@ public class SchoolTests
|
||||
{
|
||||
new ContentDocument("core", "defs/actions/sit.jsonc", """{ "defName": "Sit" }"""),
|
||||
new ContentDocument("core", "defs/things/chair.jsonc", """{ "defName": "Chair", "actions": ["Sit"] }"""),
|
||||
new ContentDocument("core", "defs/territories/yard.jsonc", """{ "defName": "Yard" }"""),
|
||||
new ContentDocument("core", "defs/territories/yard.jsonc", """{ "defName": "Yard", "travelMinutes": 1 }"""),
|
||||
new ContentDocument("core", "defs/buildings/main.jsonc", """{ "defName": "Main" }"""),
|
||||
new ContentDocument("core", "defs/floors/floor.jsonc", """{ "defName": "Floor" }"""),
|
||||
new ContentDocument("core", "defs/rooms/office.jsonc", """{ "defName": "Office" }"""),
|
||||
new ContentDocument("core", "defs/rooms/office.jsonc", """{ "defName": "Office", "travelMinutes": 1 }"""),
|
||||
};
|
||||
var catalog = loader.Load(["core"], documents);
|
||||
var map = new MapLayout
|
||||
|
||||
Reference in New Issue
Block a user