Zametek.Maths.Graphs.Compilers 4.2.0

dotnet add package Zametek.Maths.Graphs.Compilers --version 4.2.0
                    
NuGet\Install-Package Zametek.Maths.Graphs.Compilers -Version 4.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Zametek.Maths.Graphs.Compilers" Version="4.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Zametek.Maths.Graphs.Compilers" Version="4.2.0" />
                    
Directory.Packages.props
<PackageReference Include="Zametek.Maths.Graphs.Compilers" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Zametek.Maths.Graphs.Compilers --version 4.2.0
                    
#r "nuget: Zametek.Maths.Graphs.Compilers, 4.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Zametek.Maths.Graphs.Compilers@4.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Zametek.Maths.Graphs.Compilers&version=4.2.0
                    
Install as a Cake Addin
#tool nuget:?package=Zametek.Maths.Graphs.Compilers&version=4.2.0
                    
Install as a Cake Tool

Zametek.Maths.Graphs

NuGet Version Zametek.Maths.Graphs.Primitives

NuGet Version Zametek.Maths.Graphs.Compilers

A headless library for building and compiling vertex (Activity-on-Vertex) and arrow (Activity-on-Arrow) directed graphs for project scheduling. It provides dynamic dependency resolution, transitive reduction, edge redirection, critical path calculation, activity priority calculation, and mapped/unmapped resource scheduling.

  • Zametek.Maths.Graphs.Primitives - the domain model: activities, events, edges, nodes, graphs, resources, resource schedules and work streams, plus their interfaces and enums.
  • Zametek.Maths.Graphs.Compilers - the builders, compilers and engines that turn a set of dependent activities into a compiled schedule.

Background: critical path analysis

This library is an implementation of the Critical Path Method (CPM), the classic technique for scheduling a set of project activities. Given a list of activities, each with a duration and a set of dependencies (the activities that must finish before it can start), CPM works out:

  • the earliest and latest each activity can start and finish without delaying the project, and
  • the critical path - the longest chain of dependent activities, which determines the shortest possible project duration.

The calculation is two passes over the dependency graph:

  • a forward pass computes, for every activity, the earliest start (ES) and earliest finish (EF = ES + duration). An activity cannot start until all its dependencies have finished, so its ES is the maximum EF of its dependencies.
  • a backward pass computes the latest start (LS) and latest finish (LF) that still allow the project to finish on time.

From these come three measures of float, or slack:

  • total slack - how long an activity can slip without delaying the project.
  • free slack - how long it can slip without delaying any of its successors.
  • interfering slack - the part of total slack whose use would eat into a successor's float (total slack minus free slack).

An activity with zero total slack is on the critical path: any delay to it delays the whole project. The closely related PERT technique builds on the same network model. The library exposes all three slack values plus an IsCritical flag on each activity (see Slack: total, free and interfering).

On top of the basic method the library also performs transitive reduction (removing redundant dependencies), cycle detection (via Tarjan's strongly connected components algorithm), and resource-constrained scheduling (see Scheduling with resources).

Quick start

Install the compilers package (it pulls in the primitives):

dotnet add package Zametek.Maths.Graphs.Compilers

The fastest path is the Activity-on-Vertex compiler. Add activities (each with an id, a duration and optional dependency ids), then Compile(...):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Zametek.Maths.Graphs;

// Type parameters: <activity-id, resource-id, work-stream-id, activity-type>.
var compiler = new VertexGraphCompiler<int, int, int, IDependentActivity<int, int, int>>();

//                                                   id  duration
compiler.AddActivity(new DependentActivity<int, int, int>(1, 6));
compiler.AddActivity(new DependentActivity<int, int, int>(2, 7));
//                                                   id  duration  dependencies
compiler.AddActivity(new DependentActivity<int, int, int>(3, 8, new[] { 1, 2 }));
compiler.AddActivity(new DependentActivity<int, int, int>(4, 4, new[] { 3 }));

// No resources supplied => infinite resources (pure critical-path schedule).
// Every Compile form takes a CancellationToken; pass a real one to make long
// compiles cancellable, or CancellationToken.None to opt out.
IGraphCompilation<int, int, int, IDependentActivity<int, int, int>> compilation = compiler.Compile(CancellationToken.None);

if (compilation.CompilationErrors.Any())
{
    foreach (IGraphCompilationError error in compilation.CompilationErrors)
    {
        Console.WriteLine($"{error.ErrorCode}: {error.ErrorMessage}");
    }
    return;
}

foreach (IDependentActivity<int, int, int> activity in compilation.DependentActivities.OrderBy(x => x.Id))
{
    bool isCritical = activity.TotalSlack == 0;
    Console.WriteLine(
        $"Activity {activity.Id}: " +
        $"ES={activity.EarliestStartTime}, EF={activity.EarliestFinishTime}, " +
        $"LS={activity.LatestStartTime}, LF={activity.LatestFinishTime}, " +
        $"slack={activity.TotalSlack}{(isCritical ? "  <- critical path" : string.Empty)}");
}

Console.WriteLine($"Project runs from {compiler.StartTime} to {compiler.FinishTime}.");

Running it prints the following (no resources were supplied, so this is the pure critical-path schedule):

Activity 1: ES=0, EF=6, LS=1, LF=7, slack=1
Activity 2: ES=0, EF=7, LS=0, LF=7, slack=0  <- critical path
Activity 3: ES=7, EF=15, LS=7, LF=15, slack=0  <- critical path
Activity 4: ES=15, EF=19, LS=15, LF=19, slack=0  <- critical path
Project runs from 0 to 19.

Activities 2, 3 and 4 form the critical path (2 -> 3 -> 4), so the project takes 19 time units. Activity 1 carries one unit of total slack: it could start as late as time 1 (its LS) without pushing out the finish.

There is also an ArrowGraphCompiler, but it is meant for rendering an Activity-on-Arrow diagram, not for analysis - always analyse with the vertex compiler. See Choosing a compiler below.

Activity-on-Vertex vs Activity-on-Arrow

The same project network can be drawn two ways, and the library supports both. They are duals of one another - the activities and the connectors swap roles:

Activity-on-Vertex (AoV) Activity-on-Arrow (AoA)
Also known as precedence diagram / activity-on-node arrow diagram / PERT chart
Activities are nodes edges (arrows)
Connectors are edges (the dependencies) nodes (events / milestones)
Extra structure none dummy edges inserted to preserve dependencies
Compiler VertexGraphCompiler ArrowGraphCompiler
ToGraph() returns Graph<T, IEvent<T>, TDependentActivity> Graph<T, TDependentActivity, IEvent<T>>

In an AoV graph each activity is a node and an arrow from A to B simply means "B depends on A". It maps directly onto your input, needs no extra elements, and is what the critical-path engine actually runs on.

An AoA graph is the traditional hand-drawn network: activities are arrows between numbered event-nodes. Because not every dependency pattern can be expressed that way, zero-duration dummy edges have to be inserted automatically. This makes AoA larger and more expensive to build, and primarily useful as a diagram.

The domain types (in Zametek.Maths.Graphs.Primitives) are:

  • IActivity<…> / Activity<…> - a unit of work: its Duration, the computed EarliestStartTime / LatestStartTime / EarliestFinishTime / LatestFinishTime, and FreeSlack / TotalSlack.
  • IDependentActivity<…> / DependentActivity<…> - an activity that also carries Dependencies (and PlanningDependencies). This is what you feed the compilers.
  • IEvent<…> / Event<…> - a start/end marker on the graph; created and managed for you.
  • IResource<…> / Resource<…> - something that performs activities.
  • IWorkStream<…> / WorkStream<…> - a phase or grouping of work.
  • Graph<…>, Node<…>, Edge<…> - the raw graph structure, available via ToGraph().

Choosing a compiler: analyse with Vertex, render with Arrow

Use VertexGraphCompiler for all analysis. Use ArrowGraphCompiler only when you need to render an Activity-on-Arrow diagram. This is a firm recommendation, for two reasons:

  1. Performance. Vertex graphs map straight onto your activities with no extra elements, so they compile much faster. Arrow graphs need dummy-edge orchestration and a larger structure.

  2. API surface. The two compilers are deliberately not symmetric:

    VertexGraphCompiler ArrowGraphCompiler
    Compile(...) returns IGraphCompilation<…> (activities, resource schedules, work streams, errors) void
    Compile(ct) yes yes
    Compile(resources, ct) / Compile(resources, workStreams, ct) yes no
    Resource scheduling and work streams yes no
    Limit validation and compilation errors yes no
    Critical-path times yes yes
    ToGraph() yes yes

The arrow compiler's Compile(ct) only sanity-checks the graph, applies transitive reduction and runs the critical-path calculation so the network can be laid out. It returns nothing and performs no resource scheduling - its sole purpose is to prepare a structure for ToGraph().

The intended workflow is therefore: do the real scheduling with the vertex compiler; then, if you want to display an AoA network diagram, feed the same activities into an arrow compiler purely to build the renderable graph:

// Render-only: build an Activity-on-Arrow diagram from the same activities.
var arrow = new ArrowGraphCompiler<int, int, int, IDependentActivity<int, int, int>>();
arrow.AddActivity(new DependentActivity<int, int, int>(1, 6));
arrow.AddActivity(new DependentActivity<int, int, int>(2, 7));
arrow.AddActivity(new DependentActivity<int, int, int>(3, 8, new[] { 1, 2 }));
arrow.AddActivity(new DependentActivity<int, int, int>(4, 4, new[] { 3 }));

arrow.Compile(cancellationToken);   // lays out the network; returns void, schedules nothing
Graph<int, IDependentActivity<int, int, int>, IEvent<int>> diagram = arrow.ToGraph();
// Hand `diagram` (nodes = events, edges = activities + dummy edges) to your renderer.

Using the compilers

Constructing

Each compiler has a parameterless constructor wired with the default engines:

var aov = new VertexGraphCompiler<int, int, int, IDependentActivity<int, int, int>>();
var aoa = new ArrowGraphCompiler<int, int, int, IDependentActivity<int, int, int>>();

The four type parameters are <T, TResourceId, TWorkStreamId, TDependentActivity>:

  • T - the activity id type. Must be a struct; int and Guid are supported out of the box for id generation.
  • TResourceId, TWorkStreamId - the id types for resources and work streams.
  • TDependentActivity - the activity contract, usually IDependentActivity<T, TResourceId, TWorkStreamId>.

Defining activities

DependentActivity has several constructors; the common ones take an id, a duration and (optionally) a set of dependency ids:

new DependentActivity<int, int, int>(1, 6);                       // no dependencies
new DependentActivity<int, int, int>(3, 8, new[] { 1, 2 });       // depends on 1 and 2

You can also mutate an activity's Dependencies set before adding it. AddActivity reads the activity's Dependencies (unioned with PlanningDependencies) to wire the graph, and returns false if the id already exists:

var activity = new DependentActivity<int, int, int>(5, 3);
activity.Dependencies.Add(4);
compiler.AddActivity(activity);

Call GetNextActivityId() to obtain an unused id.

Compiling

Compile(...) runs the full pipeline - dependency resolution, the critical-path forward/backward passes, resource scheduling and back-filling - and returns an IGraphCompilation. Every form requires a CancellationToken as its last argument (pass CancellationToken.None to opt out of cancellation):

IGraphCompilation<int, int, int, IDependentActivity<int, int, int>> result = compiler.Compile(CancellationToken.None);

Always check result.CompilationErrors first (for example circular dependencies or unsatisfiable constraints). If it is empty, the schedule is valid. The result exposes:

  • DependentActivities - the compiled activities, each populated with start/finish times and slack.
  • ResourceSchedules - the per-resource timelines (see below).
  • WorkStreams - the work streams actually used.
  • CompilationErrors - any problems found.

After a compile the compiler also exposes StartTime, FinishTime and CyclomaticComplexity.

Reading the critical path

Each compiled activity carries its CPM results. The IsCritical flag (true when TotalSlack <= 0) identifies the critical path:

IEnumerable<IDependentActivity<int, int, int>> criticalPath = result.DependentActivities
    .Where(a => a.IsCritical)
    .OrderBy(a => a.EarliestStartTime);

Slack: total, free and interfering

Each activity exposes three read-only slack values plus an IsCritical flag:

Property Meaning Definition in the model
TotalSlack How long the activity can slip without delaying the whole project. LatestFinishTime - EarliestFinishTime
FreeSlack How long it can slip without delaying any successor (without consuming anyone else's float). computed during the critical-path pass
InterferingSlack The portion of total slack that would delay a successor if used - the difference between the two. TotalSlack - FreeSlack
IsCritical Whether the activity is on the critical path. TotalSlack <= 0

Free slack is always less than or equal to total slack, and interfering slack is whatever is left over. An activity with positive total slack but zero free slack can still move - but only by eating into its successors' float, so it "interferes" with them. A critical activity has zero total slack; a negative total slack means the schedule is over-constrained (a deadline cannot be met), which also shows up as a post-compilation error (see Compilation errors).

Scheduling with resources

Critical-path analysis on its own assumes unlimited resources - every activity is free to start the moment its dependencies allow. Real projects have finite people and equipment, so activities that could run in parallel often have to be queued because they compete for the same resource. Reconciling the dependency schedule with limited capacity is resource-constrained scheduling, or resource levelling.

Activities and resources combine like this: each IResource is offered the activities (honouring their dependencies and a priority order), and the compiler allocates each activity to a resource, re-running the critical-path passes around the allocation so the reported start/finish times reflect resource contention as well as dependencies. The result is a set of per-resource timelines (IResourceSchedule) alongside the updated activity times.

Pass a list of IResource to Compile to schedule onto finite resources. With no resources (or an empty list) the compiler assumes infinite resources and produces the pure critical-path schedule shown in the quick start.

var resources = new List<IResource<int, int>>
{
    new Resource<int, int>(
        id: 10, name: "Alice",
        isExplicitTarget: false, isInactive: false,
        interActivityAllocationType: InterActivityAllocationType.Indirect,
        unitCost: 1.0, unitBilling: 1.0, allocationOrder: 0,
        interActivityPhases: Array.Empty<int>()),
};

IGraphCompilation<int, int, int, IDependentActivity<int, int, int>> result = compiler.Compile(resources, CancellationToken.None);

foreach (IResourceSchedule<int, int, int> schedule in result.ResourceSchedules)
{
    string ids = string.Join(", ", schedule.ScheduledActivities.Select(a => a.Id));
    Console.WriteLine($"Resource {schedule.Resource.Id}: [{ids}] ({schedule.StartTime}..{schedule.FinishTime})");
}

A third overload, Compile(resources, workStreams, cancellationToken), additionally reports which IWorkStreams were used.

With no resources, the schedules are lanes. A compile with no resources still returns ResourceSchedules, so that a chart can show how many activities run at the same time. Each schedule is a lane: it has no resource (Resource is null), and each activity that takes time is on one lane, at its earliest start time. No lane has two activities at once. The lanes change nothing in the plan. The times, the slack, the critical activities and the finish are those of the critical path alone, and ResourceDependencies stays empty. AllocatedToResources holds the number of the lane of the activity (1 for the first lane), as it did before.

Up to 4.1.1, the compile made each lane a synthetic resource: an activity depended on the activity before it on its lane. Two activities with no connection then had a dependency, and the first one lost slack, or was shown as critical. With a maximum LFT or a minimum free slack, an activity could also start later, and the plan could finish later than its critical path.

Targeting resources and explicit targets

By default the scheduler may place any activity on any (non-explicit) resource. You can constrain this from both sides.

From the activity side, set TargetResources to the ids of the resources allowed to perform it, and TargetResourceOperator to say how they combine:

  • LogicalOperator.AND - the activity needs all of its target resources; if any are missing from the supplied list it cannot be scheduled.
  • LogicalOperator.OR - any one of the target resources will do.
  • LogicalOperator.ACTIVE_AND - like AND, but evaluated only over the resources actually present in the supplied list.

From the resource side, set IsExplicitTarget = true to make a resource opt-in only: it picks up an activity only if that activity names it in TargetResources. Explicit-target resources are skipped during ordinary priority allocation, so they are never pulled onto general work.

Two modelling problems can result, and both are reported as compilation errors rather than thrown:

  • if every supplied resource is an explicit target but some non-dummy activity targets none of them, that activity could never be scheduled - reported as P0040;
  • if an activity is obliged (via AND / ACTIVE_AND) to use explicit-target resources that are not in the supplied list, that is reported as P0060.

After compilation, each activity's AllocatedToResources lists the resources it was actually placed on.

Inter-activity allocation types

A resource's InterActivityAllocationType controls how its time - and therefore its cost, billing and effort - is spread across the schedule between the activities it performs:

  • Direct - the resource is allocated, and charged, only while actively performing scheduled activities; idle gaps between its activities are not counted. Use this for resources you pay per task.
  • Indirect - the resource is allocated continuously across the span of its involvement, filling the gaps between its activities as well. Use this for overhead, supervision or equipment committed to the project for the duration regardless of moment-to-moment work. An indirect resource that performs no direct activities at all still receives a schedule covering its phases.
  • None - no inter-activity spreading; only the scheduled activities themselves are allocated. Used internally for synthetic resources.

The resulting IResourceSchedule exposes these decisions as per-time-unit streams - ActivityAllocation, CostAllocation, BillingAllocation and EffortAllocation - alongside StartTime and FinishTime. Activities flagged HasNoCost, HasNoBilling or HasNoEffort are excluded from the corresponding stream.

Allocation order

When more than one resource could take an activity, the scheduler offers work to resources in ascending AllocationOrder (the resources are sorted by it to build the priority list). Lower numbers are preferred, so AllocationOrder lets you express "fill resource A before resource B". Dependencies and target-resource constraints are always honoured within that order.

An activity gives way to one that has no other resource. At each moment, the scheduler goes through the activities that are ready, in the order of the priority list (least total slack first), and each takes the first free resource in the allocation order that it can use. An activity with LogicalOperator.OR can use any one of its targets, and an activity with no targets can use any one resource that is not an explicit target. Thus, such an activity can take the one resource that a later activity in the list needs, while another resource that it could use stays free. The scheduler then moves it to the free resource, and the other activity starts at the same moment. A move can need a chain of moves (A leaves R1 for R2, and B leaves R2 for R3). The scheduler makes the fewest moves, and it tries the resources in the allocation order.

For example, R1 has allocation order 0 and R2 has allocation order 1. Activity 2 can use R1 or R2, activity 3 can use only R1, and both are ready at time 1, with 2 first in the priority list. Activity 2 takes R1, and so 3 has no resource. Activity 2 then moves to R2, and 3 starts on R1 at time 1. Up to 4.1.1, activity 3 waited for R1 while R2 did nothing.

The rule has limits, and they are deliberate:

  • It acts only when a resource is free and an activity that could start now waits. With no such activity, each activity is on the first free resource in the allocation order, as before.
  • Only an activity that started at that same moment moves. The scheduler does not look ahead, and it does not move an activity that started earlier. An activity that takes R1 today can still hold up an activity that becomes ready tomorrow and can use only R1.
  • An activity that needs all of its targets (AND, ACTIVE_AND) does not move. But it can be the one that waits: each activity on one of its targets then moves to a resource that it does not need.
  • No activity starts later at that moment than it did without the rule. But a different choice of resource changes what follows, and so a plan can also finish later than before. In 5,000 random plans with 2 to 4 resources, 901 got another schedule: 605 finished earlier and 46 finished later.

Work-stream phases

Work streams (IWorkStream) group activities into phases of a project; an activity declares the phases it belongs to via TargetWorkStreams. A resource declares the phases it is associated with via InterActivityPhases (a set of work-stream ids). This matters mostly for indirect resources, where the phases tie an overhead resource to the parts of the project it spans. When you call Compile(resources, workStreams, cancellationToken), the result's WorkStreams is exactly the set of phases actually used - the intersection of the work streams referenced by activities and those referenced by the scheduled resources.

Editing and other operations

  • RemoveActivity(id) - remove an activity and detach it from its dependents.
  • SetActivityDependencies(id, dependencies, planningDependencies) - replace an activity's dependencies.
  • TransitiveReduction() - strip redundant dependencies, keeping only the minimal edge set.
  • ToGraph() - export the current Graph<…> structure (nodes, edges and events).
  • Reset() - clear all activities and start over.

Each compiler guards its state with an internal lock, so individual operations are thread-safe.

Simulating a schedule

ScheduleSimulator runs a Monte Carlo simulation of a plan. A plan gives each activity one duration. A real activity has a range: an optimistic duration (O), a most likely duration (ML) and a pessimistic duration (P). Each iteration of the simulation draws a duration for every activity that has a range. It then schedules the whole plan again, onto its resources, as a compile does. The result tells you how the finish time of the plan varies, and which activities and paths decide it.

// The activities are those that a compile takes, and each has the duration that the plan
// schedules: the expected duration (O + 4 ML + P) / 6, rounded to the nearest whole unit
// with halves up. DurationEstimate gives the expected duration, and checks 0 <= O <= ML <= P.
var estimates = new Dictionary<int, DurationEstimate>
{
    [1] = new DurationEstimate(2, 4, 6),
    [2] = new DurationEstimate(4, 5, 12),
};
var simulator = new ScheduleSimulator<int, int, int>(activities, resources, workStreams, estimates);

if (simulator.CompilationErrors.Count > 0)
{
    // The plan cannot be scheduled, and the simulator reports why.
}

SimulationResult<int> result = simulator.Run(
    new SimulationSettings { Iterations = 10_000, Seed = 42, Distribution = DurationDistribution.BetaPert },
    progress: null,
    CancellationToken.None);

An activity that has no entry in estimates keeps its duration in every iteration.

Engines of your own. ScheduleSimulator<T, TResourceId, TWorkStreamId> schedules the plan with the standard engines. If you compile with engines of your own, use ScheduleSimulator<T, TResourceId, TWorkStreamId, TActivity> and give it a factory: an IVertexGraphFactory<T, TResourceId, TWorkStreamId, TActivity>, which makes the builders and the compiler of the first check of the plan. The simulation then schedules the plan in the same way as your compile does. VertexGraphFactory is the standard factory. Give it an engines bundle that holds the engines that you want to change, and it uses the standard engines for the rest.

var simulator = new ScheduleSimulator<int, int, int, MyActivity>(
    activities, resources, workStreams, estimates,
    new VertexGraphFactory<int, int, int, MyActivity>(
        new VertexGraphBuilderEngines<int, int, int, MyActivity>
        {
            ResourceSchedulingEngine = new MyScheduler(),
        }));
  • CreateCompiler() gives a compiler with a builder of its own. The simulation calls it once, when it makes the simulator, for the first check of the plan, and never for an iteration. The compile of the first check gives CompilationErrors and PlannedFinishTime. If your compiler is a class of your own (it derives from VertexGraphCompiler), return it from this method.
  • CreateBuilder() gives a new, empty builder each time. The simulation calls it once for each task that runs iterations, and it can call it from any thread.
  • VertexGraphFactory gives the same engines to every builder that it makes, as CloneObject does for a clone. The engines must hold no state, or be safe for use by many threads. All the standard engines are. An engine that holds state needs a factory of your own, one that makes new engines in CreateBuilder: implement IVertexGraphFactory. The ID generator factory of the bundle (EdgeIdGeneratorFactory) is one of these engines. A generator of IDs holds the count of one graph, and so each builder asks that factory for a generator of its own.
  • The constructor throws an ArgumentNullException for a factory that is null, and an InvalidOperationException for a factory that gives a null compiler. A run fails with an AggregateException that holds an InvalidOperationException for a factory that gives a null builder, or a builder that already holds activities.
  • CloneObject of an activity must give an object of the type TActivity. The constructor throws an ArgumentException when it does not.
  • An iteration calls the same methods of the builder as a compile does: the critical-path calculation, the resource scheduler and the other engines. It does not call VertexGraphCompiler.Compile. Only the first check of the plan does that, with the compiler from the factory. Thus, the engines decide how a simulation schedules a plan, and anything that a compiler adds to them is not a part of the iterations.

What the result holds. The result is raw, and it holds no statistics: you make the mean, the percentiles, the histogram and the criticality index from it. For each iteration it holds the finish time (FinishTimes), the activities that were critical (IsCritical(iteration, activityIndex), one bit for each) and the critical paths (CriticalPathIndexes(iteration), as indexes into CriticalPaths). An iteration that failed has the finish time SimulationResult.FailedFinishTime. The resource scheduler could not place every activity, the schedule ran past GraphLimits.MaximumTimeValue, or an activity could not finish by its maximum latest finish time. FailureReason(iteration) tells which (SimulationIterationFailure), and MaximumLatestFinishTimeMissCount(activityIndex) counts the iterations in which an activity missed its maximum. A compile with the durations of such an iteration reports an error, and so the statistics leave the iteration out. But the iterations that miss a maximum are the late ones, and so the statistics of the others are too early. Report the number of failed iterations with the statistics. Both the critical activities and the paths can be left out (RecordCriticalActivities, RecordCriticalPaths) to save memory.

The distributions. DurationDistribution has five members, and every one stays within the range from O to P.

Member What it is
BetaPert (the default) The beta of the reference PERT tools: its mean is the PERT mean and its variance is the PERT variance, ((P - O) / 6) squared. It matches the expected duration and the standard deviation that DurationEstimate gives.
ModifiedBetaPert The usual modified PERT beta: its mode is ML, and ModifiedBetaShape (4 by default) sets how tightly it is drawn around the mode.
Triangular A triangle with its minimum at O, its mode at ML and its maximum at P.
Normal A normal distribution with the PERT mean and the PERT standard deviation, held to the range from O to P.
Uniform A uniform distribution from O to P.

A draw is rounded to the nearest whole time unit, with halves up, because the scheduler works in whole units. A draw of 0 for an activity that takes time stays 0: the activity is then as short as a milestone in that iteration.

Repeatable results. The same plan and the same settings give the same result. The iterations are split into chunks of 64, each with a generator of its own, and its seed comes from Seed and the number of the chunk. A result therefore does not depend on MaxDegreeOfParallelism, nor on the order in which the threads finish, and a run of fewer iterations is the start of a longer run with the same seed. The generator is xoshiro256** and the draws use only the operations that IEEE 754 fixes to the bit (the logarithm and the exponential are written out in the library), so the Rust port gives the same result, bit for bit, for the same plan and settings. SimulationBaseline.txt in the tests pins this, and both test suites check it.

Critical paths. A critical path is a chain of critical activities, each of which starts at the moment that the one before it finishes, from the start of the plan to its finish. The link between two steps is CriticalPathLink.Dependency (the plan says so) or CriticalPathLink.Resource (the activities share a resource, and the resource is busy with the one before). An activity of zero duration (a milestone) is passed through and does not appear on the path, and so two chains that differ only by a milestone are one path. A resource link between two activities that the plan also ties, directly or through milestones, is a link of the plan. Thus, it makes no second path. Whole days make ties common, and so an iteration can have several critical paths. The result gives all of them, up to MaximumCriticalPathsPerIteration (32 by default), and IsCriticalPathListComplete(iteration) says when the list was cut short. How to share the weight of an iteration among its tied paths is for the caller to decide.

Cost. An iteration costs about as much as a compile, and the cost grows with the square of the number of activities. On the sample plan of the application (46 activities and 15 resources), one iteration takes about 0.8 ms; on a layered plan of 1,000 activities it takes about 100 ms. The simulator reports its progress to an IProgress<int>, and it stops between iterations when its token is cancelled. Behind the simulator, one internal class (SimulationIterationRunner) does the scheduling of an iteration, and the tests hold it to a full compile of the same plan with the same durations, so that a faster scheduler can replace it later.

A plan with no resources. With no resources, an iteration is the critical-path calculation alone, as a compile is: the finish times and the critical activities are those of the plan. ScheduleOntoSyntheticResources has no effect any more. Up to 4.1.1, a compile with no resources scheduled the plan onto synthetic resources, which could make more activities critical, and the setting made a simulation do the same.

The Rust port has the same types and the same behaviour (ScheduleSimulator, SimulationSettings, SimulationResult and the others), and the same iterations for the same seed. The Rust ScheduleSimulator::new uses the standard engines, and ScheduleSimulator::with_factory takes a factory in the same way as the constructor above: a value that implements the trait IVertexGraphFactory, such as VertexGraphFactory::with_engines(engines). The trait requires Send + Sync, which is the Rust form of "safe for use by many threads".

Limits

Compilation applies sanity limits to its inputs, exposed as public constants on GraphLimits so you can validate user input at the point of entry rather than waiting for a compile:

Constant Value Applies to
GraphLimits.MinimumTimeValue 0 every declared time value - negative times are never meaningful
GraphLimits.MaximumTimeValue 100_000 Duration, MinimumEarliestStartTime, MaximumLatestFinishTime, MinimumFreeSlack, and the compiled schedule's finish time. At one time unit per day this is roughly 270 years
GraphLimits.MaximumActivityCount 2_000 activities in the graph
GraphLimits.MaximumResourceCount 1_000 resources supplied to Compile (after inactive ones are filtered out)
GraphLimits.MaximumWorkStreamCount 100 work streams supplied to Compile
GraphLimits.MaximumSimulationIterations 1_000_000 iterations in one simulation (SimulationSettings.Iterations), enforced by the setter rather than by a compilation error

These are sanity bounds, not algorithmic ceilings: they exist so that absurd or corrupted input fails with a clear error instead of consuming unbounded time and memory. Declared values and counts are checked before compilation and reported as P0080. The computed schedule length is checked separately, after scheduling, and reported as C0020 - per-value limits cannot bound it on their own, because individually legal durations still sum.

Two of the limits are enforced earlier still, by the types that carry the value rather than by the compiler: the SimulationSettings.Iterations setter and the DurationEstimate constructor both throw ArgumentOutOfRangeException on an out-of-range value, so those fail at the point of assignment and never reach a P0080.

Both checks belong to VertexGraphCompiler. ArrowGraphCompiler.Compile returns void and so has nothing to report an error through: it validates none of these limits and will accept a graph of any size. That costs nothing in the intended workflow, where the arrow compiler only renders activities the vertex compiler has already compiled - but an arrow-only compile is unbounded, so validate against these constants yourself if you drive one directly. See Choosing a compiler.

The time limit is what keeps memory predictable. Each resource schedule retains five per-time-unit allocation streams, so what a compilation holds grows as (horizon x resources), independently of activity count. Those streams are stored packed one bit per flag rather than one byte, which keeps the worst case permitted by these limits - a 100,000-unit horizon across 1,000 resources - at about 60 MB rather than 476 MB.

A note on scale: the activity limit bounds what is accepted, not what is comfortable, though the two are much closer together than they used to be. Measured on a layered graph across 20 resources, a full compile takes about 30 ms at 250 activities, 110 ms at 1,000 and 360 ms at the 2,000 limit - so anything the limit accepts now compiles comfortably inside an interactive edit-recompile cycle. Cost still grows faster than linearly, and the priority-list calculation is still the largest single part of it at roughly two thirds. The figures come from CompileScalingTests, and the performance notes carry the full breakdown.

Compilation errors

VertexGraphCompiler.Compile(...) does not throw for modelling problems - it collects them in IGraphCompilation.CompilationErrors so you can surface several at once. (It still throws ArgumentNullException for a null resources / workStreams argument, and InvalidOperationException for internal failures such as an impossible back-fill.) Each entry is an IGraphCompilationError with a GraphCompilationErrorCode and a human-readable ErrorMessage. Always check the list before trusting the schedule:

IGraphCompilation<int, int, int, IDependentActivity<int, int, int>> result = compiler.Compile(CancellationToken.None);
if (result.CompilationErrors.Any())
{
    foreach (IGraphCompilationError error in result.CompilationErrors)
    {
        Console.WriteLine($"{error.ErrorCode}: {error.ErrorMessage}");
    }
}

The codes (P = pre-compilation, C = post-compilation):

Code Raised when
P0010 Invalid dependencies - an activity depends on an id that no activity in the graph has.
P0020 Circular dependencies - the dependencies form a cycle (found with Tarjan's algorithm).
P0030 Invalid pre-compilation constraints - an activity's requested constraints are self-contradictory, e.g. MinimumEarliestStartTime + Duration > MaximumLatestFinishTime, or both MinimumFreeSlack and MaximumLatestFinishTime are set.
P0040 All resources explicit, activity untargeted - every supplied resource is an explicit target, but a non-dummy activity targets none of them, so it could never be scheduled.
P0050 Unable to remove unnecessary edges - the graph could not be cleaned up / reduced during pre-compilation.
P0060 Explicit target resources unavailable - an activity must use specific explicit-target resources that are not in the supplied list.
P0070 Internally inconsistent input collections - an activity's or resource's set reports contents that its own lookups cannot find, the classic symptom of unsynchronized concurrent modification while the compilation inputs were being prepared. Scheduling such data could never make progress, so it is rejected up front.
P0080 Outside supported limits - a declared time value (duration or time constraint) is negative or larger than GraphLimits.MaximumTimeValue, or there are more activities, resources or work streams than the corresponding limit allows. See Limits.
C0010 Invalid post-compilation constraints - after scheduling, the computed times violate an activity's constraints (e.g. LatestFinishTime > MaximumLatestFinishTime, EarliestStartTime < MinimumEarliestStartTime, FreeSlack < MinimumFreeSlack, or times that came out negative or out of order).
C0020 Resource scheduling could not produce a usable schedule - either the scheduler proved that one or more activities can never be scheduled onto the supplied resources (so it stopped and reported them instead of looping forever), or the computed schedule ran past GraphLimits.MaximumTimeValue. The latter is the case the per-value limits cannot catch, because individually legal durations still sum. Through Compile(...) the other static causes are caught earlier (P0040, P0060, P0070, P0080), so the stall form is the last line of defence - e.g. inputs corrupted mid-compile, or a scheduling engine driven directly without the pre-compilation checks.

For example, a graph where activity 1 depends on 2 and activity 2 depends on 1 produces:

P0020: Circular activity dependencies:
2 -> 1

a dependency on a non-existent activity 99 produces:

P0010: Invalid activity dependencies:
99 is invalid but referenced by: 1

and an activity that cannot fit inside its own time window (MinimumEarliestStartTime 10 + Duration 5 against MaximumLatestFinishTime 12) produces:

P0030: Invalid activity constraints:
1 -> (MinimumEarliestStartTime + Duration) must be greater than MaximumLatestFinishTime

The ErrorMessage text lists the specific activities involved, so it can be shown directly to a user.

Error message reference

Every ErrorMessage opens with a fixed header line for its code, followed by one line per offending activity (all offenders for a code are gathered into that one message so they can be shown together):

Code ErrorMessage header Per-activity detail line
P0010 Invalid activity dependencies: <dependencyId> is invalid but referenced by: <id>, <id>, ...
P0020 Circular activity dependencies: <id> -> <id> -> ... (one line per cycle)
P0030 Invalid activity constraints: <id> -> <reason> (reasons below)
P0040 All resources are explicit targets, but not all activities have targeted resources (header only)
P0050 Unable to remove unnecessary edges (header only)
P0060 Unavailable resources for activities: <id> -> <resourceId>, <resourceId>, ...
P0070 Internally inconsistent input collections (possible concurrent modification of compilation inputs): Activity <id> -> <collection> or Resource <id> -> InterActivityPhases
P0080 Values or counts outside the supported limits: Activity <id> -> <value> is <actual>, which is outside the supported range of <min> to <max>, or The number of <activities\|resources\|work streams> is <actual>, which exceeds the maximum supported count of <max>
C0010 Invalid activity constraints: <id> -> <reason> (reasons below)
C0020 Resource scheduling could not make progress with the following activities: (stall) or The computed schedule finish time (<actual>) exceeds the maximum supported time value (<max>) (horizon) <id> -> <reason> (reasons below; stall form only)

P0030 and C0010 share the same header - they are the same constraint checks run at different times (P before scheduling, C after), so the ErrorCode is what tells them apart.

P0030 (pre-compilation) reports, per activity, whichever applies first:

  • Cannot set MinimumFreeSlack and MaximumLatestFinishTime at the same time
  • (MinimumEarliestStartTime + Duration) must be greater than MaximumLatestFinishTime

C0010 (post-compilation) reports, per activity, any of these once the scheduled times are known:

  • EarliestStartTime cannot be less than zero
  • EarliestFinishTime cannot be less than zero
  • LatestStartTime cannot be less than zero
  • LatestFinishTime cannot be less than zero
  • LatestStartTime cannot be less than EarliestStartTime
  • LatestFinishTime cannot be less than EarliestFinishTime
  • EarliestStartTime cannot be less than MinimumEarliestStartTime
  • LatestFinishTime cannot be more than MaximumLatestFinishTime
  • FreeSlack cannot be less than MinimumFreeSlack

P0070 (pre-compilation) names each offending set on its owner - TargetResources, TargetWorkStreams, AllocatedToResources, Dependencies, PlanningDependencies, ResourceDependencies or Successors on an activity; InterActivityPhases on a resource.

C0020 (during scheduling) reports, per stuck activity, the most precise reason the scheduler could determine:

  • requires all of its target resources, but the following are not available: <resourceId>, <resourceId>, ...
  • none of its target resources are available: <resourceId>, <resourceId>, ...
  • its target resource set is internally inconsistent - lookups disagree with its contents (possible concurrent modification of compilation inputs)
  • has no target resources, but every supplied resource is an explicit target
  • cannot be scheduled within the maximum supported time value (<max>)
  • waiting on dependencies that can never complete: <id>, <id>, ...
  • could not be assigned to any resource

Where this is used

These packages are the scheduling engine behind Zametek.ProjectPlan - a free, open-source, cross-platform desktop alternative to Microsoft Project. Its wiki is a good application-level tour of how activities, resources, work streams, Gantt charts and arrow-graph diagrams come together for end users, and shows the "analyse as vertex, render as arrow" split in practice.

Extensibility

Every engine the builders rely on sits behind a public interface and can be supplied through the builders' (and compilers') engine-injecting constructors:

  • IIdGeneratorFactory<T> - makes the ID generator (IIdGenerator<T>: NextIdGenerator, PreviousIdGenerator) of each builder. StandardIdGeneratorFactory is the default, and PreviousIdGeneratorFactory and NextIdGeneratorFactory make the two generators. A generator holds the count of one graph, and so a builder asks the factory for a generator of its own when it is made (see below). The factory itself holds no state.
  • IEventGenerator<T> - event creation (EventGenerator, RemovableEventGenerator).
  • IActivityGenerator<…> - dummy activity creation (DummyActivityGenerator).
  • IArrowCriticalPathEngine<…> / IVertexCriticalPathEngine<…> - critical path calculation.
  • IArrowStronglyConnectedComponentsFinder<…> / IVertexStronglyConnectedComponentsFinder<…> - cycle detection.
  • IResourceSchedulingEngine<…> - resource scheduling and its surrounding pipeline.
  • IArrowTransitiveReducer<…> / IVertexTransitiveReducer<…> - transitive reduction, and IDummyEdgeOrchestrator<…> - the dummy-edge operations (ArrowTransitiveReducer, VertexTransitiveReducer, DummyEdgeOrchestrator). Like every other engine these are stateless: the builder passes them the graph state - and, per call, the collaborators each needs (the arrow reducer takes the SCC finder and the orchestrator; the orchestrator takes the ID/activity generators and the SCC finder) - so they are injected directly, with no factory seam.

Rather than the telescoping constructors, engines can also be supplied through an engines bundle - ArrowGraphBuilderEngines<…> / VertexGraphBuilderEngines<…> - where every property defaults to the standard implementation and only the customised ones need setting. The bundle constructors are the stable injection surface: new engines are added as new bundle properties without breaking the signature.

var builder = new VertexGraphBuilder<int, int, int, IDependentActivity<int, int, int>>(
    new VertexGraphBuilderEngines<int, int, int, IDependentActivity<int, int, int>>
    {
        CriticalPathEngine = new MyInstrumentedCpmEngine(),   // everything else defaults
    });
var compiler = new VertexGraphCompiler<int, int, int, IDependentActivity<int, int, int>>(builder);

A builder is not an engine: it holds the state of one graph, and so it cannot be shared. Code that needs many builders, or a compiler that agrees with its builders, takes a factory: IVertexGraphFactory<…> / IArrowGraphFactory<…>, with the methods CreateBuilder() and CreateCompiler(). VertexGraphFactory<…> / ArrowGraphFactory<…> are the standard ones, and they take the same engines bundle as the builders do.

IVertexGraphFactory<int, int, int, IDependentActivity<int, int, int>> factory =
    new VertexGraphFactory<int, int, int, IDependentActivity<int, int, int>>(
        new VertexGraphBuilderEngines<int, int, int, IDependentActivity<int, int, int>>
        {
            CriticalPathEngine = new MyInstrumentedCpmEngine(),   // everything else defaults
        });

var builder = factory.CreateBuilder();      // a new, empty builder
var compiler = factory.CreateCompiler();    // a compiler, with a builder of its own

A standard factory gives the same engines to all its builders, as CloneObject() does for a clone, and so the engines must hold no state (all the standard engines hold none). The ID generator factories of the bundle are among them: each builder that the factory makes asks them for ID generators of its own. The default constructors of VertexGraphCompiler and ArrowGraphCompiler make their builder with these factories. ScheduleSimulator takes a vertex factory.

IDs of your own. A builder makes IDs for the elements that you do not name: the events of a vertex graph, and the dummy activities and the events (nodes) of an arrow graph. An IIdGenerator<T> gives them, and a builder takes an IIdGeneratorFactory<T> that makes the generator, in place of the generator. The factory is asked in three cases: for a new builder, which holds no IDs, for a builder that loads a graph, and for the clone of a builder (CloneObject()). The last two give the IDs that the graph holds, and the generator must not give any of them. Thus, you do not work out where a generator starts, and a clone has a generator of the same kind as its original.

// IDs in steps of 10, over the highest ID that the graph holds.
class StepIdGenerator : IIdGenerator<int>
{
    private int m_Value;
    public StepIdGenerator(int start) => m_Value = start;
    public int Generate() => m_Value += 10;
}

class StepIdGeneratorFactory : IIdGeneratorFactory<int>
{
    public IIdGenerator<int> Create(IEnumerable<int> usedIds) => new StepIdGenerator(usedIds.DefaultIfEmpty(0).Max());
}

var builder = new VertexGraphBuilder<int, int, int, IDependentActivity<int, int, int>>(new StepIdGeneratorFactory());

The standard factories do this for the two kinds of ID that the library knows. StandardIdGeneratorFactory<T> is the default of the bundles: for int it makes descending IDs (PreviousIdGeneratorFactory: negative, and so clear of the positive IDs of the activities, and it starts under the lowest ID that the graph holds), and for Guid, which has no previous value, it makes new GUIDs (NextIdGeneratorFactory). PreviousIdGeneratorFactory<T>(initial) and NextIdGeneratorFactory<T>(initial) start from initial, or from the lowest or highest ID of the graph if that is further on.

The critical-path engines and SCC finders read graph state through the read-only IArrowGraphState<…> / IVertexGraphState<…> contracts. The transitive reducers and the dummy-edge orchestrator restructure the graph, so they take the concrete ArrowGraphState<…> / VertexGraphState<…> directly: the state type is public, but its structural-mutation API is internal, so an external engine can read the state yet only the library's own engines can restructure it. Injected engines are preserved through CloneObject().

Breaking changes

4.2.0

Two changes to the result of a compile, in .NET and in Rust. The release does not change the API of 4.1.1. But it changes the schedule of some plans that compiled without errors, and the times of a plan that is compiled with no resources.

  • An activity gives way to one that has no other resource. The scheduler goes through the ready activities in the order of the priority list, and each takes the first free resource in the allocation order that it can use. An activity that can use any one of several resources (LogicalOperator.OR, or no targets) could take the one resource that a later activity in the list needed, while another resource that it could use stayed free. The later activity then waited, and the free resource did nothing. Now the activities that started at that moment move to free resources, so that the activity that waits can start. Nothing changes at a moment when no resource is free, or when no activity waits that could start. In 5,000 random plans with 2 to 4 resources, 901 got another schedule: 605 finished earlier and 46 finished later. See Allocation order.
  • A compile with no resources gives the critical path of the plan alone. Up to 4.1.1, such a compile made each lane of its schedule a synthetic resource, and an activity depended on the activity before it on its lane. Two activities with no connection then had a dependency: the first one lost slack, and it could be shown as critical. With a maximum LFT or a minimum free slack, an activity could also start later, and the plan could finish later than its critical path. Now the times, the slack, the critical activities and the finish are those of the plan, and ResourceDependencies stays empty. The compile still returns the lanes in ResourceSchedules, each activity at its earliest start time, with no two activities at once on a lane. AllocatedToResources holds the number of the lane, as before. A compile with resources is not affected: it still makes the resource dependencies and calculates the critical path with them. See Scheduling with resources.
  • SimulationSettings.ScheduleOntoSyntheticResources has no effect. With no resources, an iteration of a simulation is the critical-path calculation alone, as a compile is. The setting stays, so that the API does not change. In Rust, the field schedule_onto_synthetic_resources stays in the same way.
  • IResourceSchedulingEngine.ReplaceWithSyntheticResources is no longer called by the compile. It stays in the interface. An engine of your own that rebuilds the schedules of a compile with no resources (RebuildAlignedResourceSchedules with infiniteResources) must give lanes that have no two activities at once: no dependency does that for it any more.

4.1.1

A fix, in .NET and in Rust. The release does not change the API of 4.1.0. A compile that did not throw before gives the same result as before, and a simulation gives the same iterations.

  • An activity that must finish by time 0 no longer crashes the compile. A maximum LFT that an activity cannot meet pulls the activity back, also to before time 0. When no activity finished after time 0, the schedule finished at time 0, and its allocation streams had no slots. The compile then threw ArgumentOutOfRangeException, and the Rust port panicked. Now the streams of such a schedule are empty, and the compile reports C0010, as it did when the schedule finished after time 0. The first check of a simulator is a compile, and so the simulator of such a plan now reports C0010 and does not throw.

4.1.0

Two fixes and an addition, in .NET and in Rust. The release only adds to the API of 4.0.1. A plan that compiled without errors gives the same schedule as before. A simulation of a plan without a maximum LFT gives the same iterations as before.

  • The allocation streams cover the whole schedule. In the first pass of the scheduler, the streams ran to the last finish on the resources. In the second pass, they ran to the latest LFT. A milestone in a phase after the last activity of the phase that takes time made the first pass throw ArgumentOutOfRangeException. A maximum LFT that a milestone cannot meet made the second pass throw InvalidOperationException. The streams now also run to the latest EFT. The first plan compiles, and the phase of the indirect resource runs to the milestone. The second plan gives C0010, as a maximum LFT that an activity with a duration cannot meet already did.
  • A simulation iteration that cannot meet a maximum LFT fails. Such an iteration gave the maximum as its finish time, and so the statistics were too early. A minimum EST and a maximum LFT can hold an activity to a window. A draw longer than the window made the whole simulation throw. Such an iteration now fails, as a compile with its durations gives an error (C0010 or P0030). The failed iterations are the late ones, and so the statistics of the other iterations are too early. Report the number of failed iterations with the statistics.
  • New: why an iteration failed. SimulationIterationFailure tells why: ResourceSchedulingStall, MaximumTimeValueExceeded or InvalidConstraints (None for an iteration that did not fail). SimulationResult has HasFailureReasons, FailureReason(iteration) and MaximumLatestFinishTimeMissCount(activityIndex), and a constructor that takes them. A simulation always records them, and the constructor of 4.0.1 stays. The Rust port has the same enum, and SimulationResult::with_failure_reasons, has_failure_reasons, failure_reason and maximum_latest_finish_time_miss_count.

4.0.1

A fix to the critical paths of a simulation, in .NET and in Rust. No type of 4.0.0 changes, and a simulation gives the same finish times and the same critical activities as before.

  • A resource link beside a chain of the plan through milestones is a link of the plan. Sometimes one resource does two activities in turn, and the plan also ties them through one or more milestones. Then 4.0.0 gave two critical paths with the same activities: one with a CriticalPathLink.Resource step, and one with a CriticalPathLink.Dependency step. A caller that shares the weight of an iteration among its tied paths split it between the two. Each such step doubled the paths, and so the paths could fill MaximumCriticalPathsPerIteration: in the sample plan of the application, one chain of activities was 16 paths. The library already made a resource link beside a direct dependency a link of the plan. It now does the same through milestones. The step is a Dependency, and the two chains are one path.

4.0.0

Breaking changes in two places, in the .NET API and in the Rust API: a builder takes an ID generator factory in place of an ID generator, and the simulator that takes the engines of the caller takes a factory object in place of a delegate. Code that does neither is not affected. The compilers with their parameterless constructors are the same, and so is ScheduleSimulator<T, TResourceId, TWorkStreamId> (the standard engines). The release also adds the factories themselves.

  • A builder takes an IIdGeneratorFactory<T> in place of an IIdGenerator<T>. In 3.x a builder took its ID generators (one for a vertex builder, two for an arrow builder) as constructor parameters, or as the EdgeIdGenerator and NodeIdGenerator properties of an engines bundle. A generator holds the count of one graph, and so a builder could not make another one. CloneObject() made a PreviousIdGenerator that started under the lowest ID of the graph, and so a clone lost the generator that you gave. A graph with Guid IDs, which have no previous value, could not be cloned at all, and the methods that clone inside (CalculateCriticalPathPriorityList and CalculateResourceSchedulesByPriorityList) failed with it. Now the builder asks the factory for a generator of its own when it is made, and its clone asks the same factory again. The constructors of VertexGraphBuilder and ArrowGraphBuilder that took generators take factories in the same places, and the bundle properties are now EdgeIdGeneratorFactory and NodeIdGeneratorFactory. To move to 4.0.0, change new NextIdGenerator<int>(n) to new NextIdGeneratorFactory<int>(n), new PreviousIdGenerator<int>(n) to new PreviousIdGeneratorFactory<int>(n), and EdgeIdGenerator = … to EdgeIdGeneratorFactory = …. A generator class of your own stays as it is: add a factory that makes it. See Extensibility.
  • What else changes with it. A builder that loads a graph starts its generators clear of the IDs of the graph (in 3.x the generator that the caller gave started where the caller said). The clone of a builder has a generator of the same kind as its original, and its first ID follows the lowest or the highest ID of the graph without a gap (in 3.x it skipped one number). Guid IDs work for the builders, the compilers and the simulator on the standard engines, because the default ID generator factory, StandardIdGeneratorFactory<T>, makes new GUIDs for them. For int, the IDs that a new builder makes are the same as before.
  • ScheduleSimulator<T, TResourceId, TWorkStreamId, TActivity> takes an IVertexGraphFactory<…>. In 3.3.0 the last parameter of the constructor was a Func<VertexGraphBuilder<…>>, a delegate that made the builders. It is now factory, an IVertexGraphFactory<T, TResourceId, TWorkStreamId, TActivity> with two methods: CreateBuilder(), which the simulation calls for each task that runs iterations, and CreateCompiler(), which it calls once, for the first check of the plan. The first check is a compile by the compiler that the factory gives, and CompilationErrors and PlannedFinishTime come from that compile. The constructor of 3.3.0, with the delegate, is gone. To move to 4.0.0, give a new VertexGraphFactory<T, TResourceId, TWorkStreamId, TActivity>(engines), where the engines bundle holds the engines of your old builder, or implement the interface. See Simulating a schedule.
  • New: IVertexGraphFactory<…>, VertexGraphFactory<…>, IArrowGraphFactory<…> and ArrowGraphFactory<…>. A factory makes the builders and the compilers of one flavour of graph. The standard factories take the same engines bundle as the builders, give the same engines to all the builders that they make (engines hold no state), and each builder that they make asks the ID generator factories of the bundle for ID generators of its own. The default constructors of VertexGraphCompiler and ArrowGraphCompiler now make their builder with a factory, and the convenience constructors of the builders take their standard engines from the engines bundle. They behave as before. See Extensibility.
  • New: IIdGeneratorFactory<T>, StandardIdGeneratorFactory<T>, PreviousIdGeneratorFactory<T> and NextIdGeneratorFactory<T>. See above and Extensibility.
  • The Rust port has the same factories, and its engine traits and its Key require Send + Sync. The Rust builders take an IIdGeneratorFactory (PreviousIdGeneratorFactory or NextIdGeneratorFactory) in place of an IIdGenerator: VertexGraphBuilder::new and from_graph, and the arrow builder in the same way, take factories, and the bundles have the fields edge_id_generator_factory and node_id_generator_factory (an Arc<dyn IIdGeneratorFactory<K>>). ScheduleSimulator::with_factory takes an IVertexGraphFactory, and ScheduleSimulator::new is the same as before. A standard factory shares one engine between all its builders, and the builders run on many threads, and so the engine traits (IEventGenerator, IVertexCriticalPathEngine, IResourceSchedulingEngine, IIdGeneratorFactory and the others) now have Send + Sync as supertraits. Key has them too, because the standard ID generator factories hold a key. An engine of your own that is not safe for many threads must be made so. In both languages, a builder that already holds activities makes the run fail.

3.3.0

Additive, with one change to the dependencies: no type of 3.2.0 changes. The release adds a Monte Carlo simulation of a schedule. See Simulating a schedule.

  • ScheduleSimulator<T, TResourceId, TWorkStreamId, TActivity> (in Zametek.Maths.Graphs.Compilers) runs the simulation with the builder that a factory of the caller gives it, and so with the engines of the caller. ScheduleSimulator<T, TResourceId, TWorkStreamId> is the same with the standard engines. Each iteration draws a duration for every activity that has estimates, schedules the plan again onto its resources, and records the finish time, the critical activities and the critical paths.
  • DurationEstimate, DurationDistribution, SimulationSettings, SimulationResult<T>, CriticalPath<T>, CriticalPathStep<T> and CriticalPathLink (in Zametek.Maths.Graphs.Primitives) are the input and the result. DurationEstimate holds the three estimates (0 ⇐ O ⇐ ML ⇐ P) and works out the PERT expected duration and standard deviation.
  • GraphLimits.MaximumSimulationIterations is 1,000,000.
  • Zametek.Maths.Graphs.Compilers no longer depends on Zametek.Utility. The package used it for one list shuffle, which is now part of the package. Thus, the package no longer brings Zametek.Utility, Newtonsoft.Json, System.Reflection.TypeExtensions and System.ValueTuple into your project. If your code uses one of them through this package, add a reference of your own.
  • The same result in .NET and in Rust. For the same plan and settings, both ports give the same finish times, critical activities and critical paths. The logarithm, the exponential, the generator (xoshiro256**) and every sampler are written out in both, and a shared baseline file is checked by both test suites.

3.2.0

A release driven by one production hang and the investigation it started. The hang is fixed and guarded; compiling a graph at the activity limit went from about 6.9 seconds to about 0.4; every recursive traversal in the library is now iterative; and the library will now tell you when it cannot schedule something rather than looping forever. The full account, with measurements, is in the performance notes and TODO.

Cancellation is now mandatory on every entry point whose cost grows with the size of the graph, on both flavours. The token is not decorative: it is checked once per activity placed in the priority-list calculation, which is the loop that dominates, as well as between pipeline phases and on every resource-scheduling tick. Pass CancellationToken.None to opt out.

  • VertexGraphCompiler.Compile() is replaced by Compile(cancellationToken), and likewise for the resources and resources, workStreams forms.
  • ArrowGraphCompiler.Compile() is replaced by Compile(cancellationToken).
  • ArrowGraphBuilder.CalculateCriticalPath() is replaced by CalculateCriticalPath(cancellationToken); both builders' CalculateCriticalPathPriorityList() by CalculateCriticalPathPriorityList(cancellationToken); and both builders' CalculateResourceSchedulesByPriorityList(resources) by the form taking a token.
  • IResourceSchedulingEngine.CalculateResourceSchedules(…) gains the token, so any custom scheduling engine must be updated.

What the token cannot do is worth knowing. The engine seams (IArrowCriticalPathEngine, IArrowTransitiveReducer, IDummyEdgeOrchestrator, IVertexCriticalPathEngine) deliberately carry no token, so a cancellation arriving during one of those calls is observed when it returns rather than immediately. That bounds the delay to a single engine call; on a graph that was never transitively reduced, the dummy-edge redirection inside a critical-path calculation is the longest such call.

The other breaking changes:

  • IVertexCriticalPathEngine gains BeginIncrementalCriticalPath. Any external implementation of that interface must add it. Returning null is a valid implementation and makes the priority-list calculation recalculate in full after every duration change, exactly as it did before - so the cheapest way to restore an existing engine is a one-line => null.
  • VertexGraphBuilder.AddPreCompilationErrors gains a workStreams parameter, because the work-stream count is one of the limits now validated and the method had no way to see it.
  • GraphCompilationErrorCode gains P0070, P0080 and C0020, and its members now carry explicit numeric values. The values are pinned deliberately - consumers serialise them into saved project files - so they are appended at the next unused number rather than in code order: C0010 = 6, P0070 = 7, C0020 = 8, P0080 = 9. Existing codes keep the values they already had. A switch over the enum that was previously exhaustive no longer is.
  • The ResourceSchedule allocation streams are stored bit-packed. The public surface is unchanged - they were already IEnumerable<bool> on both the interface and the constructor - but the concrete type behind them is now PackedBoolList rather than List<bool>, so a consumer casting to List<bool> will break. Measured at the published limits, 1,000 resources across a 100,000-unit horizon retains 60 MB rather than 476 MB.

New, additive:

  • GraphLimits publishes the accepted ranges (time values 0 to 100,000; 2,000 activities; 1,000 resources; 100 work streams) so input can be validated before compiling. Violations are reported as P0080, and a computed schedule running past the horizon as C0020 - the case per-value limits cannot catch, because individually legal durations still sum. See Limits.
  • Stall detection. The scheduler proves when one or more activities can never be scheduled onto the supplied resources and reports C0020 with a diagnosis naming them, instead of looping forever. Driving a scheduling engine directly surfaces the same thing as ResourceSchedulingStallException. P0070 rejects structurally corrupted input up front - a set whose lookups disagree with its own contents, the signature of unsynchronized concurrent modification.
  • IVertexIncrementalCriticalPath<T>, the incremental recalculation behind the priority-list speedup, available to callers that change one duration at a time.
  • ResourceScheduleBuilder.FirstActivityStartTime, alongside the existing LastActivityFinishTime.

Behaviour-preserving, and the reason the numbers moved:

  • The critical-path engines walk nodes and events in dependency order instead of sweeping the remaining set repeatedly, taking a pass from O(depth x E) to O(V + E) in both flavours.
  • The priority-list calculation recalculates once and thereafter propagates only what a duration change actually moves.
  • Every recursive traversal is now iterative, removing stack-overflow risk on deep chains - two of them were confirmed to kill the process, not merely thought to be at risk.
  • Transitive reduction computes ancestors as compact bitsets rather than a dictionary of hash sets.
  • Two defects in the arrow dummy-edge path: a walk that enumerated every start-to-node path rather than visiting each edge once (60 seconds and 158 GB on a 150-activity graph, now 2 ms and 1 MB), and a redirection that copied an edge set purely to ask whether it was empty.

Every one of these is guarded by a committed golden baseline over a 56-graph corpus, checked byte-for-byte from both the C# and Rust suites.

3.1.0

This release also contains behaviour-preserving performance and robustness work - iterative deep-graph traversals (no more stack-overflow risk on very deep dependency chains), compact bitset ancestors for transitive reduction, linear arrow-graph construction and reduced allocation churn in the CPM and scheduling passes - recorded in the performance notes. The breaking changes are:

  • The transitive reducers and the dummy-edge orchestrator are now stateless: they take the graph state (and any collaborators) as method parameters instead of capturing it at construction. As a result the IArrowTransitiveReducerFactory / IVertexTransitiveReducerFactory / IDummyEdgeOrchestratorFactory interfaces and their default implementations are removed; the single ITransitiveReducer<T> is split into IVertexTransitiveReducer<…> / IArrowTransitiveReducer<…>; the engines bundles expose TransitiveReducer / DummyEdgeOrchestrator engine properties in place of the former …Factory properties; and VertexGraphState<…> / ArrowGraphState<…> are now public (their structural-mutation API stays internal) so the injected engines can take them directly.
  • The builders' WhenTesting property is renamed to ShuffleProcessingOrder, which is what it actually does: when true, the critical-path passes process remaining edges in a random order on each iteration (results are identical either way; tests use it to prove order-independence).
  • ArrowGraphBuilder.ToGraph() and VertexGraphBuilder.ToGraph() now throw InvalidOperationException when the graph cannot be cleaned up, instead of silently returning null.
  • Both packages now compile with nullable reference types enabled and the public API is annotated. Notable contract changes for consumers with nullable enabled: IActivity.Name/Notes, IResource.Name and IScheduledActivity.Name are string?; IResourceSchedule.Resource is nullable (unmapped/synthetic schedules carry no resource); IVertexTransitiveReducer/IArrowTransitiveReducer.GetAncestorNodesLookup(…) and the builders' GetAncestorNodesLookup() are declared nullable (they return null for unsatisfied or circular dependencies, as before).
  • DummyActivityGenerator<…>.Generate now throws InvalidOperationException if the created dummy activity is not assignable to TActivity, instead of returning null.

3.0.0

  • ICanBeRemoved now declares SetAsReadOnly() and SetAsRemovable(). Previously these mutators lived only on IActivity<…> and the concrete Event / Activity types, leaving IEvent<T> asymmetric. Any external type implementing IEvent<T> - or ICanBeRemoved directly - must now provide both methods. This makes events symmetric with activities and allows RemovableEventGenerator<T> to decorate any IEventGenerator<T> (defaulting to EventGenerator<T>) instead of constructing events directly.
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Zametek.Maths.Graphs.Compilers:

Repository Stars
countincognito/Zametek.ProjectPlan
A simple, Open Source, and cross-platform desktop alternative to Microsoft Project for designing and creating project plans.
Version Downloads Last Updated
4.2.0 120 11/20/2026
4.1.1 106 11/14/2026
4.1.0 167 11/11/2026
4.0.1 153 11/5/2026
4.0.0 151 10/23/2026
3.3.0 132 10/17/2026
3.2.0 448 8/19/2026
3.1.0 290 7/21/2026
3.0.2 209 7/7/2026
3.0.1 160 6/30/2026
3.0.0 166 6/24/2026
2.4.8 695 8/24/2025
2.4.7 248 8/12/2025
2.4.6 139 8/1/2025
2.4.5 167 7/18/2025
2.4.4 240 7/6/2025
2.4.1 190 6/28/2025
2.4.0 193 6/20/2025
Loading failed