Skip to content

optimaru.meeting_scheduling

Generated from the sources of optimaru/meeting_scheduling/ and the stubs of its compiled extension. The guide explains the model and the constraints in prose.

optimaru.meeting_scheduling

Meeting scheduling — Python wrapper of the C++ solver on the optimaru engine.

Assigns meetings a starting time grain (15-minute units) and a room. The two are one decision variable per meeting, the composite encoding grain_room = time_grain_pos * room_count + room_index (-1 == unassigned). There are 5 hard + 2 medium + 5 soft constraints; the medium level is folded into the engine's soft level as soft = -(medium * MEDIUM_SCALE + raw soft), MEDIUM_SCALE == 1e6. constraint_info() lists each constraint's default level and weight (the medium pair at weight 1, in medium units); constraint_costs(schedule) gives the raw per-constraint costs::

import optimaru.meeting_scheduling as ms

schedule = ms.generate_demo_data()  # the demo instance (24 meetings)
result = ms.solve(schedule, time_limit_seconds=10.0, random_seed=42)
print(result.score.hard, result.score.soft)

solve accepts both a _core.MeetingSchedule (solved in place and returned) and the pydantic mirror models.MeetingScheduleModel (converted, solved, and returned as a new model; the one passed in is left as it was). The pydantic mirror (for serialization) is in optimaru.meeting_scheduling.models.

optimaru.meeting_scheduling.models

Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.

Mirrors _core's Person/TimeGrain/Room/Meeting/MeetingAssignment/MeetingSchedule 1:1. People/meetings/time grains/rooms are referenced by list index. Meetings and assignments are 1:1.

Score mapping (hard / medium / soft -> engine Score): score_hard is the hard level as-is, score_soft is -(medium penalty * 1e6 + soft penalty) — folded with a 1e6 offset so medium (required+preferred / preferred attendance conflicts) always dominates soft::

from optimaru.meeting_scheduling.models import MeetingScheduleModel, generate_demo_data

model = generate_demo_data()                 # the demo instance
clone = MeetingScheduleModel.model_validate_json(model.model_dump_json())
schedule = clone.to_core()                   # pydantic -> engine

PersonModel

Bases: StrictModel

An attendee. Referenced by index into the people list.

TimeGrainModel

Bases: StrictModel

A 15-minute time grain. grain_index is the unit duration/overlap is computed in (consecutive and 1-based in the demo).

RoomModel

Bases: StrictModel

A meeting room. capacity feeds the hard room_capacity_cost (and larger_room_capacity_cost).

MeetingModel

Bases: StrictModel

A meeting (fixed input). required/preferred_attendees are lists of people indices — one element is one attendance.

MeetingAssignmentModel

Bases: StrictModel

One meeting's assignment. grain_room is the composite variable time_grain_pos * room_count + room_index (None == unassigned); meeting is a meetings index.

MeetingScheduleModel

Bases: StrictModel

Mirror of the whole schedule. score is a read-only result, kept as a separate field.

to_core

to_core() -> _core.MeetingSchedule

pydantic -> engine object (the score field is ignored; the engine recomputes it).

from_core classmethod

from_core(schedule: MeetingSchedule) -> MeetingScheduleModel

engine object -> pydantic (including the current assignment and score).

MeetingScheduleRequest

Bases: SolveRequest

The meeting schedule with the settings of one solve (see SolveRequest for those).

generate_demo_data

generate_demo_data() -> MeetingScheduleModel

The demo instance (deterministic; exposes C++ ms::buildDemoData as-is): 20 people, 160 time grains (4 days x 40), 3 rooms (30/20/16 seats), 24 meetings (8/12/16 grains).

with_initial_solution

with_initial_solution(problem, solution)

Return a copy of problem whose search starts from solution.

solution is what a solve returns: a MeetingScheduleModel, or a plain dict of that shape (the JSON the API returned). Assignments are matched by id. An assignment left out becomes unassigned and the construction heuristic places it, and only it, so a complete solution starts the search exactly from it. problem is not mutated. Pinned assignments keep their value on problem, whatever solution says.

grain_room is the composite time_grain_pos * room_count + room_index (the position in time_grains, not grain_index), so it is only valid for the same time grains and rooms in the same order: ValueError if solution lists different ones.

Raises ValueError naming the assignment for an unknown or repeated id and for a grain_room outside 0..grain_room_count - 1 (None is unassigned; the engine does not range-check).

parameter_uses

parameter_uses(model: MeetingScheduleModel) -> list[ParameterUse]

The parameters model sets away from their defaults that act only through a cost.

solve refuses a selection that holds none of a parameter's costs (optimaru._constraint.require_costs); the table is "Parameters and their costs" in docs/use-cases/README.md.

solve_request

solve_request(request: MeetingScheduleRequest, *, constraints=None) -> MeetingScheduleModel

Solve a pydantic request and return the solved problem model.

This is solve(request.model_input, ...) with the request's settings as the keywords of the same names (see SolveRequest), and constraints the selection solve takes. The request is not changed.

optimaru.meeting_scheduling.constraints

Constraint assembly specs — an API for picking the cost function declaratively.

The default path (ms.solve(schedule)) enables all twelve constraints at the provider weights. This module is the alternative path next to it: pick constraints, change weights, change levels, shape the cost, and pass the list to solve(schedule, constraints=...).

A constraint list reads one way: one class call per constraint::

import optimaru.meeting_scheduling as ms
from optimaru.meeting_scheduling.constraints import (
    MeetingOverlapCost, RoomConflictCost, get_constraints,
)

ms.solve(schedule, constraints=get_constraints())           # the defaults as-is
ms.solve(schedule, constraints=[                             # picked
    RoomConflictCost(), MeetingOverlapCost(weight=100),
])

Only listed constraints are scored — leave one out and its term disappears from the score. (The module also carries ready-made default instances: room_conflict_cost is RoomConflictCost(), and so on.)

Every spec takes five knobs:

  • weight linear multiplier on the constraint cost, in units of its level. None = the C++ component default (ms.constraint_info() lists them).
  • level None = the default level, otherwise a Level or its name (Level.MEDIUM or "medium"). Any flippable constraint may take any of the three levels. The two attendance conflicts that are not both-required (required_and_preferred_attendance_conflict_cost, preferred_attendance_conflict_cost) are medium: folded into the engine's soft level as medium * 1e6 (MEDIUM_SCALE). On another level, level="hard" charges one hard unit per person-grain, level="soft" one soft unit per person-grain, and a weight is in units of the level in effect.
  • exponent sign-preserving power shaping: weight * sign(c) * |c| ** exponent, per (grain, room) cell for the five per-meeting constraints and on the total for the seven pair constraints. 2.0 = squared, so concentrated violations grow much costlier.
  • offset (keyword) shifts that shaping, at the same granularity; 0.0 = none.
  • clip (keyword) True (the default) counts only what lies beyond the offset, sign(c) * max(0, |c| - offset) ** exponent; False shapes c - offset as it is, so every cell (or total) below the offset — an empty cell (cost 0) included — lowers the penalty. With an offset it is refused on hard (OvertimeCost and the other hard constraints by default), because hard 0 must mean no violation; medium folds into soft here, so it is allowed there.

The same constraint may be picked several times; each pick is scored on its own with its own knobs and the picks add up. The overlap plus its square beyond eight grains::

ms.solve(schedule, constraints=[
    *get_constraints(),
    MeetingOverlapCost(weight=1, exponent=2, offset=8),
])

ms.constraint_costs(schedule, picks) keys the second pick "meeting_overlap_cost#2".

Attendance conflicts split into three terms: hard when both are required, medium when only one is required or both are preferred — levels separate impossible schedules from merely regrettable ones.

Names (name) are the C++ component names in snake_case (RoomConflictCost -> room_conflict_cost). The core derives them mechanically, so there is no hand-maintained alias table — check them with ms.list_constraints(). Module-level instance names use the same snake_case, so they match the strings list_constraints() prints.

Constraint dataclass

Spec selecting one constraint: weight / level / shaping.

Subclasses set the ClassVars: name (the snake_case registry name the core reports in list_constraints(); required), label_en / label_ko (a short title) and description_en / description_ko (one or two sentences on what one unit of raw cost means). An intermediate base that should not need a name passes abstract=True::

class _RouteLimit(Constraint, abstract=True): ...

offset and clip are keyword-only, so the positional order stays weight, level, exponent followed by a subclass's domain parameters. A name must not contain #, which constraint_costs() keys repeated picks with ("<name>#<k>").

params

params() -> dict[str, Any]

The domain parameters: every dataclass field but the five knobs.

Level

Bases: StrEnum

The score level a constraint is charged on. Hard dominates medium, medium dominates soft.

Score

Bases: NamedTuple

Engine-level (hard, soft) from score(). Penalties, so <= 0 without rewards.

A domain with a medium level folds it the way its C++ Score adapter does (into soft, or below hard), so this compares directly with the engine.

OvertimeCost dataclass

Bases: Constraint

Meetings ending past the end of the calendar. Default: hard, weight 1.

The case where no TimeGrain exists at the last grain index. The raw cost is that index, not the overrun, so running further over costs more.

RoomCapacityCost dataclass

Bases: Constraint

Seats missing in the assigned room for the attendees. Default: hard, weight 1.

DayCrossingCost dataclass

Bases: Constraint

Meetings whose last grain falls on a different day than the first. Default: hard, weight 1.

Counted per TimeGrain at the last index on another day. Running off the calendar entirely gives 0 — overtime_cost values that.

MeetingEndTimeCost dataclass

Bases: Constraint

Each meeting's own last grain index. Default: soft, weight 1.

Pulls the whole schedule toward the front of the calendar.

LargerRoomCapacityCost dataclass

Bases: Constraint

For every room strictly larger than the assigned one, the capacity difference. Default: soft, weight 1.

Fills big rooms first and leaves small rooms for meetings that only fit there. Per-room totals are precomputed by ScoreCalculator::prepare. Not a capacity overflow (that is room_capacity_cost).

RoomConflictCost dataclass

Bases: Constraint

Grains in which two meetings use the same room at the same time. Default: hard, weight 1.

RequiredAttendanceConflictCost dataclass

Bases: Constraint

Overlapping grains of a person required in both meetings. Default: hard, weight 1.

Someone who must be in two meetings at once makes the schedule impossible, so it is hard. A meeting listing the same person as required twice folds in here too.

RequiredAndPreferredAttendanceConflictCost dataclass

Bases: Constraint

Overlapping grains of a person required in one and preferred in the other. Default: medium, weight 1.

Both directions count — which is why an edge carries separate forward/backward weights and the component adds them. The weight is in medium units; the domain folds the medium level into the engine soft level as medium * 1e6.

PreferredAttendanceConflictCost dataclass

Bases: Constraint

Overlapping grains of a person preferred in both. Default: medium, weight 1.

Regrettable rather than impossible, so it sits at medium: below the hard constraints and above every soft convenience term. The weight is in medium units; the domain folds the medium level into the engine soft level as medium * 1e6.

ConsecutiveMeetingsCost dataclass

Bases: Constraint

Two meetings back to back without a single grain between. Default: soft, weight 100.

The most expensive soft term of the provider — a day packed with gapless meetings is what attendees actually complain about. Any two adjacent meetings count, whatever their rooms and attendees.

MeetingOverlapCost dataclass

Bases: Constraint

Grains in which any two meetings run at once. Default: soft, weight 10.

Regardless of room or attendees. Spreads the calendar so meetings someone might want to attend both of do not overlap.

RoomChangeCost dataclass

Bases: Constraint

Shared attendees whose next meeting starts within two grains in a different room. Default: soft, weight 1.

Unlike the three conflict constraints, this is not about overlap — it fires precisely when meetings do not overlap much (people have to pack up and walk).

get_constraints

get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]

Return the cost function. Without arguments, all twelve default constraints.

When constraints is given, that list is used as-is — only the listed constraints are scored::

get_constraints([RoomConflictCost(), MeetingOverlapCost(weight=100)])

Same contract as the C++ applyConstraints: an empty list is an error (pass None for the defaults); a constraint named several times is scored once per pick, each with its own knobs.

score

score(costs: dict, constraints: list[Constraint] | None = None) -> Score

Apply specs to raw constraint costs and produce a score — pure Python.

costs is what ms.constraint_costs(schedule) returns: per constraint, the raw cost of each unit (before weight, exponent, offset and level rounding). Fetch it once and rescore with different weights without re-solving::

raw = ms.constraint_costs(schedule)
score(raw)                     # default set
score(raw, [RoomConflictCost(), MeetingOverlapCost(weight=100)])
score(raw, [MeetingOverlapCost(), MeetingOverlapCost(exponent=2, offset=8)])

No solver and no search are involved. The arithmetic matches the engine — each unit contributes weight * shape(cost, exponent, offset, clip) and hard contributions are rounded per unit before summing (the same order as the engine's applyRaw; rounding the total afterwards gives different values). A second pick of a constraint reads the same raw costs with its own knobs.

When constraints is given, only those constraints are scored — the same semantics as get_constraints. Unknown names raise ValueError.

The returned value is the engine-level (hard, soft) — the same as schedule.score: the medium level (the two non-required attendance conflicts) is folded into soft as medium * 1e6, the medium_fold every entry of costs carries.

optimaru.meeting_scheduling._core

Type stubs for optimaru.meeting_scheduling._core — the meeting-scheduling C++ solver.

The compiled module wraps the C++ domain in optimaru/meeting_scheduling/cpp, which imports the generic engine in core/optimaru.

Constraints (hard / medium / soft levels) and the score mapping (registry names; default weights per raw unit): hard 1. room_conflict_cost -1 per overlapping grain of two meetings in one room hard 2. overtime_cost -lastTimeGrainIndex when no TimeGrain exists at the last grain index hard 3. required_attendance_conflict_cost -1 per overlapping grain of pairs sharing a required attendee hard 4. room_capacity_cost -(shortfall) when needed seats (required+preferred) exceed the room capacity hard 5. day_crossing_cost -1 when start and end days differ med 6. required_and_preferred_attendance_conflict_cost -1 medium per overlapping grain of (required, preferred) pairs med 7. preferred_attendance_conflict_cost -1 medium per overlap of pairs sharing a preferred attendee soft 8. meeting_end_time_cost -lastTimeGrainIndex (per meeting) soft 9. consecutive_meetings_cost -100 per adjacent meeting pair soft 10. meeting_overlap_cost -10 per overlapping grain of distinct meetings soft 11. larger_room_capacity_cost -(capacity difference) per larger room soft 12. room_change_cost -1 when an attendee's consecutive (gap <= 2 grains) meetings change room

The engine score is Score(hard int, soft float), so medium is folded into soft: soft = -(medium penalty * MEDIUM_SCALE + raw soft penalty) (MEDIUM_SCALE == 1e6; medium always dominates soft).

A meeting's starting time grain and room are one decision variable, the composite encoding grain_room = time_grain_pos * room_count + room_index (-1 == unassigned). A meeting occupies duration_in_grains consecutive grain indices from its start grain, and every overlap constraint is computed over that whole span.

Score

Two-level score (hard, soft). hard is the integer violation sum (0 == feasible); soft is the folded medium/soft objective. Lexicographic comparison (hard first).

is_feasible

is_feasible() -> bool

True when hard >= 0: no hard constraint is violated.

Person

An attendee (fixed input). Referenced by index into the people list.

TimeGrain

A 15-minute time grain (fixed input). grain_index is the unit of duration/overlap, and (day_of_year, starting_minute_of_day) is the calendar position.

Room

A meeting room, fixed input (capacity is used by room_capacity_cost / larger_room_capacity_cost).

Meeting

A meeting (fixed input). required/preferred_attendees are lists of people indices — one element is one attendance.

required_capacity

required_capacity() -> int

Required + preferred attendee count.

MeetingAssignment

The (start grain, room) assignment of one meeting. grain_room is the composite decision variable (-1 == unassigned); meeting is a meetings index, and meetings and assignments must be 1:1.

grain_room instance-attribute

grain_room: int

time_grain_pos * room_count + room_index; -1 == unassigned.

pinned instance-attribute

pinned: bool

If True, grain_room is fixed (it counts in the score but never moves).

MeetingSchedule

The schedule: people + time_grains/rooms (value ranges) + meetings + meeting_assignments (entities). solve changes the assignments' grain_room and score in place.

Note: list attributes such as meeting_assignments return copies, so use set_assignment to change assignments. After changing the structure (meetings/grains/rooms), build a new MeetingSchedule (derived tables are prepared once, at the first scoring).

grain_room_of

grain_room_of(time_grain_pos: int, room_index: int) -> int

Composite value encoding: time_grain_pos * room_count + room_index.

assignment

assignment() -> list[int]

Current grain_room per assignment (-1 == unassigned).

set_assignment

set_assignment(assignment: Sequence[int]) -> None

Bulk-write every grain_room (length must equal the number of assignments).

SolverConfig

Engine settings (default: 30 s budget, late acceptance + ALNS).

late_acceptance_size instance-attribute

late_acceptance_size: int

0 = automatic: clamp(128 * assignments, 3200, 6400).

ruin_recreate_as_move_weight instance-attribute

ruin_recreate_as_move_weight: float

Per-step probability of also drawing destroy-repair as an ordinary move judged by the acceptor (0 disables; default 2e-4, tuned by the quality bench).

ruin_recreate_as_move_max_ruin instance-attribute

ruin_recreate_as_move_max_ruin: int

Upper bound on assignments ruined by one as-move destroy-repair (default 12).

day_fit_value_probability instance-attribute

day_fit_value_probability: float

Probability that a change move draws only start grains that keep the meeting within one day (0 disables).

best_score_limit instance-attribute

best_score_limit: tuple[int, float]

Stop early once bestScore >= (hard, soft); (0, -inf) stops at the first feasible.

Solver

solve

solve(schedule: MeetingSchedule) -> None

Solves in place: writes the assignments' grain_room and schedule.score. Pinned assignments are kept.

solve_with_constraints

solve_with_constraints(schedule: MeetingSchedule, constraints: Iterable[Any] | None = ...) -> None

Score the same solve with a caller-chosen constraint set (see optimaru.meeting_scheduling.constraints). The given list replaces the default set; None keeps the default set. A name may be picked several times: each pick is its own instance with its own knobs, and the instances add up.

ConstraintInfo

Bases: NamedTuple

One constraint-catalog row, read off the C++ default assembly.

calculate_score

calculate_score(schedule: MeetingSchedule) -> Score

Full recalculation (also stored in schedule.score).

generate_demo_data

generate_demo_data() -> MeetingSchedule

The demo instance (deterministic): 20 people, 160 time grains, 3 rooms, 24 meetings.

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case: the five per-meeting constraints, then the seven pair constraints). The same names optimaru.meeting_scheduling.constraints uses.

constraint_costs

constraint_costs(schedule: MeetingSchedule, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]

Per-constraint, per-unit raw costs — before weight/exponent/offset/level rounding. A unit is a (time grain, room) cell; a pair (global) constraint reports one cost. optimaru.meeting_scheduling.constraints.score() takes these and produces a score: {key: {"costs": [...], "weight": float, "exponent": float, "offset": float, "clip": bool, "global": bool, "level": "hard" | "medium" | "soft", "reward": bool, "level_flippable": bool, "name": str, "label": str, "default_weight": float, "default_level": str, "medium_fold": {"kind": "into_soft", "unit": 1e6}}}. The medium fold belongs to the domain, so EVERY entry carries it. None = the default constraints; a pick list (as for solve) scores exactly those picks, each entry carrying its pick's knobs, the k-th pick of a name keyed "#" from the second on.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: the default level and weight of each constraint (required_and_preferred_attendance_conflict_cost and preferred_attendance_conflict_cost are medium at weight 1 in medium units; consecutive_meetings_cost soft at 100, meeting_overlap_cost soft at 10; every other constraint at weight 1). All flippable, none a reward, all enabled by default.