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
- func Optimize(p *Problem, reg *Registry, opts Options) (*Plan, Result)
- type DayTimeWindow
- type Distribution
- type HardConstraint
- type Invigilator
- type Kind
- type MinuteSummary
- type Options
- type Plan
- func (pl *Plan) Clear(posIdx int)
- func (pl *Plan) Clone() *Plan
- func (pl *Plan) CountKind(invigID int, kind Kind) int
- func (pl *Plan) Days(invigID int) []int
- func (pl *Plan) DoingMinutes(invigID int) int
- func (pl *Plan) HasInSlot(invigID, day, slot, exceptPos int) bool
- func (pl *Plan) IsFixed(posIdx int) bool
- func (pl *Plan) Positions(invigID int) []int
- func (pl *Plan) Set(posIdx, invigID int)
- func (pl *Plan) Unfilled() []int
- type Position
- type Problem
- type Progress
- type Registry
- type Result
- type SoftConstraint
- type Stats
- type TimeSpan
- type Violation
- type Weights
Constants ¶
const Unassigned = -1
Unassigned marks a position that currently has no invigilator.
Variables ¶
This section is empty.
Functions ¶
func Optimize ¶
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 ¶
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 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 ¶
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 (*Plan) CountKind ¶
CountKind returns how many positions of the given kind are assigned to the invigilator.
func (*Plan) DoingMinutes ¶
DoingMinutes returns the minutes assigned to an invigilator that count toward the contingent (self-invigilations contribute 0).
func (*Plan) HasInSlot ¶
HasInSlot reports whether the invigilator already has a position in (day,slot), ignoring the position exceptPos (use -1 to ignore none).
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.
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 ¶
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.
type Progress ¶ added in v1.84.2
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 ¶
Allows reports whether assigning posIdx to invigID violates no hard constraint. A fixed position can only keep its locked invigilator.
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 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
// NegativeBalanceFactor multiplies the centering penalty when a person is
// *under* their target (doing too little); >1 prefers slightly over to
// slightly under, especially for low-workload invigilators.
NegativeBalanceFactor 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 gentle 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.
func DefaultWeights ¶
func DefaultWeights() Weights
DefaultWeights returns sensible starting weights; they are meant to be overridable from config (invigilation.optimizer.weights.*).