invigplan

package
v1.177.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 27, 2026 License: BSD-3-Clause Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package invigplan contains the pure (DB- and ZPA-free) domain model and the hard/soft constraints used to plan invigilations (Aufsichten) automatically.

The package is deliberately self-contained so that it can be unit-tested without MongoDB and reused by both the optimizer and the validation code: a Problem is a static snapshot of everything the planner needs, a Plan is the mutable assignment the optimizer searches over, and every constraint is its own small function/type registered in the Registry. Adding a new rule means adding a constraint and registering it – nothing else changes.

Index

Constants

View Source
const Unassigned = -1

Unassigned marks a position that currently has no invigilator.

Variables

This section is empty.

Functions

func Optimize

func Optimize(p *Problem, reg *Registry, opts Options) (*Plan, Result)

Optimize builds a greedy hard-feasible start and improves it with simulated annealing. Every intermediate plan stays hard-feasible (moves are only applied when the registry allows them), so the result satisfies all hard constraints; the soft constraints are traded off via the cost function.

Types

type DayTimeWindow added in v1.91.0

type DayTimeWindow struct {
	Date  time.Time // calendar date the window applies to
	From  time.Time // earliest allowed start; zero = no lower bound
	Until time.Time // latest allowed end; zero = no upper bound
}

DayTimeWindow restricts the times an invigilator may invigilate on one calendar date: an assigned position must start no earlier than From (if set) and end no later than Until (if set). It is sub-slot granular and NTA-aware, since Position.End() already includes the room's (possibly NTA-extended) duration. Several windows may share a date – then the position only has to fit into one of them (see AllowsTime), e.g. 08:00–11:00 and 14:00–open to keep 11:00–14:00 free.

type Distribution

type Distribution struct {
	Kind    Kind
	ByCount map[int]int
	Max     int
	Total   int
}

Distribution summarizes how many positions of one kind each invigilator does: ByCount maps "n positions" -> "number of invigilators doing n". It lets you judge fairness at a glance (e.g. everyone 0–2 reserves is fine).

type HardConstraint

type HardConstraint interface {
	Name() string
	Check(p *Problem, plan *Plan) []Violation
	Allows(p *Problem, plan *Plan, posIdx, invigID int) bool
}

HardConstraint must always hold. Check reports all violations in a (possibly externally built) plan – used by the validation. Allows is the fast feasibility test the optimizer uses to keep every plan hard-feasible by construction: it answers "may invigID take position posIdx in this plan?".

type Invigilator

type Invigilator struct {
	ID            int
	TargetMinutes int // = InvigilatorTodos.TotalMinutes

	ExcludedDays  map[int]bool
	ExcludedSlots map[[2]int]bool

	// OwnExamSlots are slots in which this person has an own exam and therefore
	// must not take a (non-self) invigilation. For NTA exams running into the
	// following slot the builder also adds that following slot.
	OwnExamSlots map[[2]int]bool
	OwnExamDays  map[int]bool

	// OwnExams are the time windows the person is present for their own exams –
	// including multi-room exams they do *not* invigilate themselves. They count
	// toward the daily presence span (daySpanSoft) so an early own exam plus a
	// late invigilation is recognised as a long day.
	OwnExams []TimeSpan

	// TimeWindows restrict, per calendar date, the times the person may
	// invigilate (see DayTimeWindow). Empty means unrestricted.
	TimeWindows []DayTimeWindow
}

Invigilator holds everything about a person needed to decide and score assignments. All slot keys are [2]int{day, slot}.

func (*Invigilator) AllowsTime added in v1.91.0

func (in *Invigilator) AllowsTime(pos Position) bool

AllowsTime reports whether the position fits the person's time windows. Only windows on the position's calendar date are considered; if there are any, the position must fit into at least one of them (windows on the same date are OR-combined). With no window for that date (or no windows at all) the position is allowed.

func (*Invigilator) Available

func (in *Invigilator) Available(day, slot int) bool

Available reports whether the person may in principle invigilate in the slot regarding their stated availability (excluded day/slot). Time-of-day restrictions are handled by timeWindowHard, the own-exam restriction by ownExamHard.

type Kind

type Kind int

Kind classifies a position for the even-distribution soft constraints.

const (
	KindRoom    Kind = iota // a normal exam room
	KindNTA                 // a room holding a single NTA student
	KindReserve             // the per-slot reserve
)

func (Kind) String

func (k Kind) String() string

type MinuteSummary

type MinuteSummary struct {
	WithinTolerance int
	Over            int // more than tolerance above target
	Under           int // more than tolerance below target
	MaxOver         int // largest positive deviation beyond the band
	MaxUnder        int // largest negative deviation beyond the band
}

MinuteSummary reports how the assigned minutes sit relative to the targets.

type Options

type Options struct {
	Iterations int
	StartTemp  float64
	EndTemp    float64
	Seed       int64

	// StopOnBalance allows the search to end early once the balance is reached
	// and everything is filled, but only after StagnationLimit iterations without
	// any further improvement of the best plan – so the remaining soft goals
	// (distribution, days, span) still get optimized once the balance holds.
	StopOnBalance   bool
	StagnationLimit int

	// OnProgress, if set, is called every ProgressEvery iterations with a
	// snapshot of the current best plan. It is throttled on purpose: calling it
	// per iteration would dominate the runtime with terminal I/O.
	OnProgress    func(Progress)
	ProgressEvery int
}

Options controls the simulated-annealing optimizer.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns sensible defaults. The temperatures are scaled to the typical lower-tier soft-constraint delta of a single move; the dominant beyond-tolerance penalty is large enough to be treated as near-hard.

type Plan

type Plan struct {
	Assign []int
	// contains filtered or unexported fields
}

Plan is the mutable assignment the optimizer searches over. Assign maps a position index to an invigilator id (or Unassigned); byInvig is the inverse index, kept in sync by Set/Clear.

func Greedy

func Greedy(p *Problem, reg *Registry, rng *rand.Rand) *Plan

Greedy fills the open positions, most-constrained first, always choosing the allowed invigilator currently furthest below their target minutes. Positions that no invigilator may take are left open.

func NewPlan

func NewPlan(prob *Problem) *Plan

NewPlan returns an empty plan with all fixed positions already applied.

func (*Plan) Clear

func (pl *Plan) Clear(posIdx int)

Clear unassigns a position. Fixed positions are left untouched.

func (*Plan) Clone

func (pl *Plan) Clone() *Plan

Clone returns a deep copy of the plan sharing the same Problem.

func (*Plan) CountKind

func (pl *Plan) CountKind(invigID int, kind Kind) int

CountKind returns how many positions of the given kind are assigned to the invigilator.

func (*Plan) Days

func (pl *Plan) Days(invigID int) []int

Days returns the distinct day numbers the invigilator is assigned to.

func (*Plan) DoingMinutes

func (pl *Plan) DoingMinutes(invigID int) int

DoingMinutes returns the minutes assigned to an invigilator that count toward the contingent (self-invigilations contribute 0).

func (*Plan) HasInSlot

func (pl *Plan) HasInSlot(invigID, day, slot, exceptPos int) bool

HasInSlot reports whether the invigilator already has a position in (day,slot), ignoring the position exceptPos (use -1 to ignore none).

func (*Plan) IsFixed

func (pl *Plan) IsFixed(posIdx int) bool

IsFixed reports whether a position is locked (pre-planned or self).

func (*Plan) Positions

func (pl *Plan) Positions(invigID int) []int

Positions returns the sorted position indices assigned to an invigilator.

func (*Plan) Set

func (pl *Plan) Set(posIdx, invigID int)

Set assigns a position to an invigilator. Fixed positions cannot be changed.

func (*Plan) Unfilled

func (pl *Plan) Unfilled() []int

Unfilled returns the indices of positions that still have no invigilator.

type Position

type Position struct {
	Day, Slot int
	Room      string // "" for the reserve
	IsReserve bool
	IsNTA     bool
	IsSelf    bool // self-invigilation (examiner supervising their own exam)

	// Minutes counts toward the invigilator's minute contingent. It is 0 for
	// self-invigilations, the exam duration for a normal room and (per the
	// existing model) 60 for a reserve.
	Minutes int

	// Block is the real time the position occupies, used for the time-gap and
	// the daily-span constraints. For a reserve or self-invigilation this is the
	// longest exam duration in the slot, otherwise the exam duration.
	Block int

	Start time.Time
}

Position is one invigilation that has to be filled: a room in a slot, or the reserve of a slot. Self-invigilations are modelled as positions too, but are always part of Problem.Fixed and therefore never moved by the optimizer.

func (Position) End

func (p Position) End() time.Time

End returns the time the position is over (Start + Block).

func (Position) Kind

func (p Position) Kind() Kind

Kind classifies the position for distribution balancing.

func (Position) SlotKey

func (p Position) SlotKey() [2]int

SlotKey identifies the (day, slot) a position lives in.

type Problem

type Problem struct {
	Positions    []Position
	Invigilators []Invigilator

	// Fixed maps a position index to the invigilator it is locked to (pre-planned
	// invigilations and self-invigilations). Fixed positions are never moved.
	Fixed map[int]int

	TimelagMin   int     // minimum minutes between two invigilations (rooms.timelag)
	ToleranceMin int     // allowed deviation from TargetMinutes (default 60)
	MaxSpanHours float64 // max hours from first start to last end per day (default 8)
	Weights      Weights
	// contains filtered or unexported fields
}

Problem is the immutable snapshot the planner works on.

func (*Problem) BalanceSatisfied

func (p *Problem) BalanceSatisfied(plan *Plan) bool

BalanceSatisfied reports whether every invigilator is within the tolerance of their target minutes. This is the optimizer's primary stopping criterion.

func (*Problem) DistributionOf

func (p *Problem) DistributionOf(plan *Plan, kind Kind) Distribution

DistributionOf computes the per-invigilator count distribution of one kind.

func (*Problem) Invigilator

func (p *Problem) Invigilator(id int) *Invigilator

Invigilator returns the invigilator with the given id, or nil.

func (*Problem) MinuteSummary

func (p *Problem) MinuteSummary(plan *Plan) MinuteSummary

MinuteSummary computes the minute-balance summary of a plan.

func (*Problem) Prepare

func (p *Problem) Prepare()

Prepare builds the internal indices. It must be called once before the Problem is used by a Plan or the constraints.

func (*Problem) Stats

func (p *Problem) Stats() Stats

Stats computes a summary of the problem. The minute sums let you sanity-check feasibility: SumTargetMinutes should be close to SumPositionMinutes.

type Progress added in v1.84.2

type Progress struct {
	Iteration int
	Total     int
	BestCost  float64
	Balance   bool
	Unfilled  int
}

Progress is a throttled snapshot of the optimizer state for UI feedback.

type Registry

type Registry struct {
	Hard []HardConstraint
	Soft []SoftConstraint
}

Registry bundles the active constraints. Add a new rule by appending it here (see DefaultRegistry). Both the optimizer and the validation use a Registry.

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry returns the constraints in their intended order.

func (*Registry) Allows

func (r *Registry) Allows(p *Problem, plan *Plan, posIdx, invigID int) bool

Allows reports whether assigning posIdx to invigID violates no hard constraint. A fixed position can only keep its locked invigilator.

func (*Registry) Cost

func (r *Registry) Cost(p *Problem, plan *Plan) (total float64, byConstraint map[string]float64, violations []Violation)

Cost is the optimizer's objective: the summed (weighted) soft penalty. The per-constraint penalties and violations are returned for reporting.

func (*Registry) HardViolations

func (r *Registry) HardViolations(p *Problem, plan *Plan) []Violation

HardViolations returns all hard-constraint violations of the current plan.

type Result

type Result struct {
	Cost             float64
	CostByConstraint map[string]float64
	Violations       []Violation
	BalanceSatisfied bool
	Unfilled         int
	Iterations       int
	StoppedEarly     bool
}

Result reports what the optimizer achieved.

type SoftConstraint

type SoftConstraint interface {
	Name() string
	Cost(p *Problem, plan *Plan) (penalty float64, violations []Violation)
}

SoftConstraint should hold. Cost returns the total (weighted) penalty of the plan together with the individual violations for reporting.

type Stats

type Stats struct {
	Positions          int
	Rooms              int
	NTARooms           int
	Reserves           int
	SelfPositions      int
	FixedPositions     int
	Invigilators       int
	SumPositionMinutes int // minutes that have to be covered (self counts 0)
	SumTargetMinutes   int // sum of all invigilators' target minutes
}

Stats summarizes a Problem for inspection before the optimizer runs.

type TimeSpan

type TimeSpan struct {
	Day   int
	Start time.Time
	End   time.Time
}

TimeSpan is a presence interval on a given day.

type Violation

type Violation struct {
	Constraint    string
	Message       string
	InvigilatorID int // 0 for a global / position-level violation
	Day, Slot     int
	Penalty       float64
}

Violation describes a single broken constraint. For hard constraints the mere presence of a violation means the plan is infeasible; for soft constraints Penalty carries the (already weighted) cost contribution.

type Weights

type Weights struct {
	MinuteBalance   float64 // centering inside the band, scaled by relative deviation
	BeyondTolerance float64 // linear, per minute outside the band (dominant)
	Coverage        float64
	MaxDays         float64
	PreferExamDays  float64
	Distribution    float64
	DaySpan         float64

	// OverTargetFactor multiplies the centering penalty when a person is *over*
	// their target (doing more than they have to – "noch offen" negative); >1
	// prefers leaving someone slightly under their target to pushing them over,
	// especially for low-workload invigilators.
	OverTargetFactor float64
}

Weights scales the soft-constraint penalties. They are tiered so that "minimum total cost" matches the intended priority order:

Coverage  ≫  BeyondTolerance  ≫  { Distribution, MaxDays, DaySpan, PreferExamDays }

Coverage (filling every position) is near-mandatory. BeyondTolerance makes the primary objective – everyone within ±tolerance of their target minutes – dominate all remaining soft goals: it is applied linearly per minute outside the tolerance, with a weight large enough that a single person outside the band outranks the entire budget of the lower-tier constraints. MinuteBalance is the centering *inside* the band; it is scaled by the *relative* deviation (deviation / target) so that people who only have to do little are pulled closer to their target than people with a large workload. It is weighted *above* the distribution/days/span constraints, so getting the low-workload people close to zero takes priority over an even reserve/NTA distribution.

Tier order: Coverage ≫ BeyondTolerance ≫ MinuteBalance ≫ {Distribution, MaxDays, DaySpan, PreferExamDays}.

func DefaultWeights

func DefaultWeights() Weights

DefaultWeights returns sensible starting weights; they are meant to be overridable from config (invigilation.optimizer.weights.*).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL