nextroute

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2024 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package nextroute is a package

Index

Constants

View Source
const (
	// AtEachStop indicates that the constraint should be checked at each stop.
	// A constraint that is registered to be checked at each stop will be
	// checked as soon as all values for the expressions a stop are known. The
	// stops later in a vehicle will not been updated yet.
	AtEachStop CheckedAt = 0
	// AtEachVehicle indicates that the constraint should be checked at each
	// vehicle. A constraint that is registered to be checked at each vehicle
	// will be checked as soon as all values for the expressions of the stops
	// of a vehicle are known. The stops of other vehicles will not been
	// updated yet.
	AtEachVehicle = 1
	// AtEachSolution indicates that the constraint should be checked at each
	// solution. A constraint that is registered to be checked at each solution
	// will be checked as soon as all values for the expressions of the stops
	// of all vehicles are known, which is by definition all the stops.
	AtEachSolution = 2
	// Never indicates that the constraint should never be checked. A constraint
	// that is registered to be checked never relies completely on its estimate
	// of allowed moves to be correct. Also, not checking a constraint can
	// result in solutions that are not valid when un-planning stops.
	Never = 3
)
View Source
const (
	// Constant is a constant cost function.
	Constant Cost = 0
	// LinearVehicle is a linear cost function with respect to the number of
	// vehicles.
	LinearVehicle = 1
	// LinearStop is a linear cost function with respect to the number of stops.
	LinearStop = 2
	// QuadraticVehicle is a quadratic cost function with respect to the number
	// of vehicles.
	QuadraticVehicle = 3
	// QuadraticStop is a quadratic cost function with respect to the number of
	// stops.
	QuadraticStop = 4
	// ExponentialVehicle is an exponential cost function with respect to the
	// number of vehicles.
	ExponentialVehicle = 5
	// ExponentialStop is an exponential cost function with respect to the
	// number of stops.
	ExponentialStop = 6
	// CrazyExpensive is a function that is so expensive that it should never
	// be used.
	CrazyExpensive = 7
)

Variables

CheckViolations is a list of all possible values for CheckedAt.

Functions

func Format added in v0.23.8

func Format(
	ctx context.Context,
	options any,
	progressioner Progressioner,
	toSolutionOutputFn func(Solution) any,
	solutions ...Solution,
) schema.Output

Format formats a solution in basic format using the map function toSolutionOutputFn to map a solution to a user specific format.

func NewModelExpressionIndex

func NewModelExpressionIndex() int

NewModelExpressionIndex returns the next unique expression index. This function can be used to create a unique index for a custom expression.

Types

type Arc added in v0.23.1

type Arc interface {
	// Origin returns the origin node ([ModelStop]) of the arc.
	Origin() ModelStop
	// Destination returns the destination node ([ModelStop]) of the arc.
	Destination() ModelStop
}

Arc is a directed connection between two nodes (ModelStops) that specifies that the origin stop must be planned before the destination stop on a vehicle's route.

type Arcs added in v0.23.1

type Arcs []Arc

Arcs is a collection of [Arc]s.

type AttributesConstraint

type AttributesConstraint interface {
	ModelConstraint

	// SetStopAttributes sets the attributes for the given stop. The attributes
	// are specified as a list of strings. The attributes are not interpreted
	// in any way. They are only used to determine compatibility between stops
	// and vehicle types.
	SetStopAttributes(
		stop ModelStop,
		stopAttributes []string,
	)
	// SetVehicleTypeAttributes sets the attributes for the given vehicle type.
	// The attributes are specified as a list of strings. The attributes are not
	// interpreted in any way. They are only used to determine compatibility
	// between stops and vehicle types.
	SetVehicleTypeAttributes(
		vehicle ModelVehicleType,
		vehicleAttributes []string,
	)
	// StopAttributes returns the attributes for the given stop. The attributes
	// are specified as a list of strings.
	StopAttributes(stop ModelStop) []string

	// VehicleTypeAttributes returns the attributes for the given vehicle type.
	// The attributes are specified as a list of strings.
	VehicleTypeAttributes(vehicle ModelVehicleType) []string
}

AttributesConstraint is a constraint that limits the vehicles a plan unit can be added to. The Attribute constraint configures compatibility attributes for stops and vehicles separately. This is done by specifying a list of attributes for stops and vehicles, respectively. Stops that have configured attributes are only compatible with vehicles that match at least one of them. Stops that do not have any specified attributes are compatible with any vehicle. Vehicles that do not have any specified attributes are only compatible with stops without attributes.

func NewAttributesConstraint

func NewAttributesConstraint() (AttributesConstraint, error)

NewAttributesConstraint creates a new attributes constraint. The constraint needs to be added to the model to be taken into account.

type BinaryExpression

type BinaryExpression interface {
	ModelExpression
	// Left returns the left expression.
	Left() ModelExpression
	// Right returns the right expression.
	Right() ModelExpression
}

BinaryExpression is an expression that takes two expressions as input and returns a value.

func NewAddExpression

func NewAddExpression(
	left ModelExpression,
	right ModelExpression,
) BinaryExpression

NewAddExpression returns a new BinaryExpression that adds the values of the two expressions.

func NewMaximumExpression

func NewMaximumExpression(
	left ModelExpression,
	right ModelExpression,
) BinaryExpression

NewMaximumExpression returns a new BinaryExpression that returns the maximum of the values of the two expressions.

func NewMinimumExpression

func NewMinimumExpression(
	left ModelExpression,
	right ModelExpression,
) BinaryExpression

NewMinimumExpression returns a new BinaryExpression that returns the minimum of the values of the two expressions.

func NewMultiplyExpression

func NewMultiplyExpression(
	left ModelExpression,
	right ModelExpression,
) BinaryExpression

NewMultiplyExpression returns a new BinaryExpression that multiplies the values of the two expressions.

func NewOperatorExpression

func NewOperatorExpression(
	left ModelExpression,
	right ModelExpression,
	operator BinaryFunction,
) BinaryExpression

NewOperatorExpression returns a new BinaryExpression that uses the given operator function.

type BinaryFunction

type BinaryFunction func(float64, float64) float64

BinaryFunction is a function that takes two float64 values and returns a float64 value.

type CheckedAt

type CheckedAt int64

CheckedAt is the type indicating when to check a constraint when a move it's consequences are being propagated.

func (CheckedAt) String

func (checkViolation CheckedAt) String() string

String returns a string representation of the CheckedAt value.

type Cluster added in v0.23.1

type Cluster interface {
	ConstraintStopDataUpdater
	ModelConstraint
	ModelObjective

	// IncludeFirst returns whether the first stop of the vehicle is included in the
	// centroid calculation. The centroid is used to determine the distance
	// between a new stop and the cluster.
	IncludeFirst() bool
	// IncludeLast returns whether the last stop of the vehicle is included in
	// the centroid calculation. The centroid is used to determine the distance
	// between a new stop and the cluster.
	IncludeLast() bool

	// SetIncludeFirst sets whether the first stop of the vehicle is included in
	// the centroid calculation. The centroid is used to determine the distance
	// between a new stop and the cluster.
	SetIncludeFirst(includeFirst bool)
	// SetIncludeLast sets whether the last stop of the vehicle is included in
	// the centroid calculation. The centroid is used to determine the distance
	// between a new stop and the cluster.
	SetIncludeLast(includeLast bool)
}

Cluster is both a constraint and an objective that limits/prefers the vehicles a plan cluster will be added to. If used as a constraint a plan cluster can only be added to a vehicles whose centroid is closer to the plan cluster than the centroid of any other vehicle. In case of using it as an objective, those vehicles will be preferred.

func NewCluster added in v0.23.1

func NewCluster() (Cluster, error)

NewCluster creates a new cluster component. It needs to be added as a constraint or as an objective to the model to be taken into account. By default, the first and last stop of a vehicle are not included in the centroid calculation.

type Complexity

type Complexity interface {
	// EstimationCost returns the cost of the Estimation function.
	EstimationCost() Cost
}

Complexity is the interface for constraints that have a complexity.

type ComposedPerVehicleTypeExpression

type ComposedPerVehicleTypeExpression interface {
	ModelExpression

	// DefaultExpression returns the default expression that is used if no
	// expression is defined for a specific vehicle type.
	DefaultExpression() ModelExpression

	// Get returns the expression that is defined for the given vehicle type. If
	// no expression is defined for the given vehicle type, the default
	// expression is returned.
	Get(vehicleType ModelVehicleType) ModelExpression
	// Set sets the expression for the given vehicle type.
	Set(vehicleType ModelVehicleType, expression ModelExpression)
}

ComposedPerVehicleTypeExpression is an expression that uses an expression for each vehicle type.

func NewComposedPerVehicleTypeExpression

func NewComposedPerVehicleTypeExpression(
	defaultExpression ModelExpression,
) ComposedPerVehicleTypeExpression

NewComposedPerVehicleTypeExpression returns a new ComposedPerVehicleTypeExpression which is a composed expression that uses an expression for each vehicle type.

type ConstantExpression

type ConstantExpression interface {
	ModelExpression

	// SetValue sets the value of the expression.
	SetValue(value float64)
}

ConstantExpression is an expression that always returns the same value.

func NewConstantExpression

func NewConstantExpression(
	name string,
	value float64,
) ConstantExpression

NewConstantExpression returns an expression that always returns the same value.

type ConstraintDataUpdater

type ConstraintDataUpdater interface {
	// UpdateConstraintData is deprecated.
	UpdateConstraintData(s SolutionStop) (Copier, error)
}

ConstraintDataUpdater is a deprecated interface. Please use ConstraintStopDataUpdater instead.

type ConstraintReporter

type ConstraintReporter interface {
	// ReportConstraint returns the data that should be reported for the given
	// solution stop.
	ReportConstraint(SolutionStop) map[string]any
}

ConstraintReporter is the interface that can be used by a constraint if it wants to report data about the constraint for a solution stop. This data is used in the basic formatter.

type ConstraintSolutionDataUpdater added in v0.24.2

type ConstraintSolutionDataUpdater interface {
	// UpdateConstraintSolutionData is called when a solution has been modified.
	// The solution has all it's expression values set and this function
	// can use them to update the constraint data for the solution. The data
	// returned can be used by the estimate function and can be retrieved by the
	// Solution.ConstraintData function.
	UpdateConstraintSolutionData(s Solution) (Copier, error)
}

ConstraintSolutionDataUpdater is the interface than can be used by a constraint if it wants to store data with each solution.

type ConstraintStopDataUpdater added in v0.24.2

type ConstraintStopDataUpdater interface {
	// UpdateConstraintStopData is called when a stop is added to a solution.
	// The solutionStop has all it's expression values set and this function
	// can use them to update the constraint data for the stop. The data
	// returned can be used by the estimate function and can be retrieved by the
	// SolutionStop.ConstraintData function.
	UpdateConstraintStopData(s SolutionStop) (Copier, error)
}

ConstraintStopDataUpdater is the interface than can be used by a constraint if it wants to store data with each stop in a solution.

type ConstraintTemporal added in v0.24.1

type ConstraintTemporal interface {
	// IsTemporal returns true if the constraint is temporal.
	IsTemporal() bool
}

ConstraintTemporal is the interface that is implemented by constraints that are temporal. This interface is used to determine if the constraint is using temporal expressions, specifically travel durations. Temporal constraints require special handling when adding initial stops to a new solution because of the triangular inequality.

type Copier

type Copier interface {
	// Copy returns a copy of the object.
	Copy() Copier
}

Copier is the interface that all objects that can be copied must implement.

type Cost

type Cost uint64

Cost is type to indicate the cost of a function.

func (Cost) String

func (cost Cost) String() string

String returns the name of the cost.

type DefaultExpression

type DefaultExpression interface {
	ModelExpression
	// DefaultValue returns the default value of the expression.
	DefaultValue() float64
}

DefaultExpression is an expression that has a default value if no other values are defined.

type DirectedAcyclicGraph added in v0.23.1

type DirectedAcyclicGraph interface {
	// Arcs returns all [Arcs] in the graph.
	Arcs() Arcs

	// IndependentDirectedAcyclicGraphs returns all the independent
	// [DirectedAcyclicGraph]s in the graph. An independent
	// [DirectedAcyclicGraph] is a [DirectedAcyclicGraph] that does not share
	// any [ModelStop]s with any other [DirectedAcyclicGraph]s.
	IndependentDirectedAcyclicGraphs() ([]DirectedAcyclicGraph, error)

	// IsAllowed returns true if the sequence of stops is allowed by the DAG,
	// otherwise returns false.
	IsAllowed(stops ModelStops) (bool, error)

	// ModelStops returns all [ModelStops] in the graph.
	ModelStops() ModelStops
	// AddArc adds a new [Arc] in the graph if it was not already added. The new
	// [Arc] should not cause a cycle.
	AddArc(origin, destination ModelStop) error
	// OutboundArcs returns all [Arcs] that have the given [ModelStop] as their
	// origin.
	OutboundArcs(stop ModelStop) Arcs
}

DirectedAcyclicGraph is a set of nodes (of type ModelStop) connected by arcs that does not contain cycles. It restricts the sequence in which the stops can be planned on the vehicle. An arc (u -> v) indicates that the stop u must be planned before the stop v on the vehicle's route.

func NewDirectedAcyclicGraph added in v0.23.1

func NewDirectedAcyclicGraph() DirectedAcyclicGraph

NewDirectedAcyclicGraph creates a new DirectedAcyclicGraph.

type DistanceExpression

type DistanceExpression interface {
	ModelExpression
	// Distance returns the distance for the given vehicle type, start and
	// end stop.
	Distance(ModelVehicleType, ModelStop, ModelStop) common.Distance
}

DistanceExpression is an expression that returns a distance.

func NewDistanceExpression

func NewDistanceExpression(
	name string,
	modelExpression ModelExpression,
	unit common.DistanceUnit,
) DistanceExpression

NewDistanceExpression turns a model expression into a distance expression. The parameter unit is the unit of the model expression.

func NewHaversineExpression

func NewHaversineExpression() DistanceExpression

NewHaversineExpression returns a new DistanceExpression that calculates the distance between two stops using the Haversine formula.

type DurationExpression

type DurationExpression interface {
	ModelExpression
	// Duration returns the duration for the given vehicle type, start and
	// end stop.
	Duration(ModelVehicleType, ModelStop, ModelStop) time.Duration
}

DurationExpression is an expression that returns a duration.

func NewConstantDurationExpression

func NewConstantDurationExpression(
	name string,
	duration time.Duration,
) DurationExpression

NewConstantDurationExpression creates a new constant duration expression.

func NewDurationExpression

func NewDurationExpression(
	name string,
	expression ModelExpression,
	unit common.DurationUnit,
) DurationExpression

NewDurationExpression creates a new duration expression.

func NewScaledDurationExpression added in v0.24.1

func NewScaledDurationExpression(
	expression DurationExpression,
	scale float64,
) DurationExpression

NewScaledDurationExpression creates a new scaled duration expression.

type EarlinessObjective added in v0.23.1

type EarlinessObjective interface {
	ModelObjective

	// TargetTime returns the target time expression which defines target time
	// that is compared to either arrival, start or end at the stop - depending
	// on the given TemporalReference.
	TargetTime() StopTimeExpression

	// Earliness returns the earliness of a stop. The earliness is the
	// difference between target time and the actual arrival, start or stop of a
	// stop. Depending on the TemporalReference.
	Earliness(stop SolutionStop) float64

	// TemporalReference represents the arrival, start or stop.
	TemporalReference() TemporalReference
}

EarlinessObjective is a construct that can be added to the model as an objective. It uses to the difference of Arrival, Start or End to the target time to penalize.

func NewEarlinessObjective added in v0.23.1

func NewEarlinessObjective(
	targetTime StopTimeExpression,
	earlinessFactor StopExpression,
	temporalReference TemporalReference,
) (EarlinessObjective, error)

NewEarlinessObjective creates a construct that can be added to the model as an objective. The target time of a stop is the time the vehicle should either arrive, start or end. The latter is defined by temporal reference. The earliness factor is used to apply a penalty factor per stop to the deviating seconds.

type ExpressionObjective

type ExpressionObjective interface {
	ModelObjective

	// Expression returns the expression that is used to calculate the
	// objective.
	Expression() ModelExpression
}

ExpressionObjective is an objective that uses an expression to calculate an objective.

func NewExpressionObjective

func NewExpressionObjective(e ModelExpression) ExpressionObjective

NewExpressionObjective returns a new ExpressionObjective inteface.

type FormatOptions added in v0.23.8

type FormatOptions struct {
	Disable struct {
		Progression bool `json:"progression" usage:"disable the progression series"`
	} `json:"disable"`
}

FormatOptions are the options that influence the format of the output.

type FromStopExpression

type FromStopExpression interface {
	DefaultExpression

	// SetValue sets the value of the expression for the given from stop.
	SetValue(
		stop ModelStop,
		value float64,
	)
}

FromStopExpression is an expression that has a value for each from stop.

func NewFromStopExpression

func NewFromStopExpression(
	name string,
	defaultValue float64,
) FromStopExpression

NewFromStopExpression returns an expression whose value is based on the from stop in Value method. Expression values are calculated by calling the expression's Value method which takes a vehicle type, a from stop and a to stop as arguments.

type FromToExpression

type FromToExpression interface {
	DefaultExpression

	// SetValue sets the value of the expression for the given
	// from and to stops.
	SetValue(
		from ModelStop,
		to ModelStop,
		value float64,
	)
}

FromToExpression is an expression that has a value for each combination of from and to stop.

func NewFromToExpression

func NewFromToExpression(
	name string,
	defaultValue float64,
) FromToExpression

NewFromToExpression returns an expression whose value is based on the from and to stops in Value method. Expression values are calculated by calling the expression's Value method which takes a vehicle type, a from stop and a to stop as arguments.

type Identifier added in v0.26.0

type Identifier interface {
	// ID returns the identifier of the object.
	ID() string
	// SetID sets the identifier of the object.
	SetID(string)
}

Identifier is an interface that can be used for identifying objects.

type ImmutableSolutionPlanUnitCollection added in v0.23.1

type ImmutableSolutionPlanUnitCollection interface {
	// Iterator returns a channel that can be used to iterate over the solution
	// plan units in the collection.
	// If you break out of the for loop before the channel is closed,
	// the goroutine launched by the Iterator() method will be blocked forever,
	// waiting to send the next element on the channel. This can lead to a
	// goroutine leak and potentially exhaust the system resources. Therefore,
	// it is recommended to always use the following pattern:
	//    iter := collection.Iterator()
	//    for {
	//        element, ok := <-iter
	//        if !ok {
	//            break
	//        }
	//        // do something with element, potentially break out of the loop
	//    }
	//    close(iter)
	Iterator(quit <-chan struct{}) <-chan SolutionPlanUnit
	// RandomDraw returns a random sample of n different solution plan units.
	RandomDraw(n int) SolutionPlanUnits
	// RandomElement returns a random solution plan unit.
	RandomElement() SolutionPlanUnit
	// Size return the number of solution plan units in the collection.
	Size() int
	// SolutionPlanUnit returns the solution plan units in the collection
	// which correspond to the given model plan unit. If no such solution
	// plan unit is found, nil is returned.
	SolutionPlanUnit(modelPlanUnit ModelPlanUnit) SolutionPlanUnit
	// SolutionPlanUnits returns the solution plan units in the collection.
	// The returned slice is a defensive copy of the internal slice, so
	// modifying it will not affect the collection.
	SolutionPlanUnits() SolutionPlanUnits
}

ImmutableSolutionPlanUnitCollection is a collection of solution plan units.

type IntParameterOptions

type IntParameterOptions struct {
	StartValue               int  `json:"start_value"  usage:"start value"`
	DeltaAfterIterations     int  `json:"delta_after_iterations"  usage:"delta after each iterations"`
	Delta                    int  `json:"delta"  usage:"delta"`
	MinValue                 int  `json:"min_value"  usage:"min value of parameter"`
	MaxValue                 int  `json:"max_value"  usage:"max value of parameter"`
	SnapBackAfterImprovement bool `json:"snap_back_after_improvement"  usage:"snap back to start value after improvement of best solution"`
	Zigzag                   bool `json:"zigzag"  usage:"zigzag between min and max value lik a jig saw"`
}

IntParameterOptions are the options for an integer parameter.

type InterestedInBetterSolution added in v1.3.0

type InterestedInBetterSolution interface {
	OnBetterSolution(SolveInformation)
}

InterestedInBetterSolution is an interface that can be implemented by solve-operators that are interested in being notified when a better solution is found. The solver will call the OnBetterSolution method when a better best-solution is found.

type InterestedInStartSolve added in v1.3.0

type InterestedInStartSolve interface {
	OnStartSolve(SolveInformation)
}

InterestedInStartSolve is an interface that can be implemented by solve-operators that are interested in being notified when the solver starts solving. The solver will call the OnStartSolve method when the solver starts solving.

type LatestArrival added in v0.23.1

type LatestArrival interface {
	ConstraintReporter
	ModelConstraint
	ModelObjective

	// Latest returns the latest arrival expression which defines the latest
	// arrival of a stop.
	Latest() StopTimeExpression

	// Lateness returns the lateness of a stop. The lateness is the difference
	// between the actual arrival and its target arrival time.
	Lateness(stop SolutionStop) float64

	// SetFactor adds a factor with which a deviating stop is multiplied. This
	// is only taken into account if the construct is used as an objective.
	SetFactor(factor float64, stop ModelStop)

	// Factor returns the multiplication factor for the given stop expression.
	Factor(stop ModelStop) float64
}

LatestArrival is a construct that can be added to the model as a constraint or as an objective. The latest arrival of a stop is the latest time a stop can arrive at the location of the stop.

func NewLatestArrival added in v0.23.1

func NewLatestArrival(
	latest StopTimeExpression,
) (LatestArrival, error)

NewLatestArrival creates a construct that can be added to the model as a constraint or as an objective. The latest start of a stop is the latest time a stop can arrive at the location of the stop.

type LatestEnd

type LatestEnd interface {
	ConstraintReporter
	ModelConstraint
	ModelObjective

	// Latest returns the latest end time expression which defines the latest
	// end of a stop.
	Latest() StopTimeExpression

	// Lateness returns the lateness of a stop. The lateness is the difference
	// between the actual end and its target end time.
	Lateness(stop SolutionStop) float64

	// SetFactor adds a factor with which a deviating stop is multiplied. This
	// is only taken into account if the construct is used as an objective.
	SetFactor(factor float64, stop ModelStop)

	// Factor returns the multiplication factor for the given stop expression.
	Factor(stop ModelStop) float64
}

LatestEnd is a construct that can be added to the model as a constraint or as an objective. The latest end of a stop is the latest time a stop can end at the location of the stop.

func NewLatestEnd

func NewLatestEnd(
	latestEnd StopTimeExpression,
) (LatestEnd, error)

NewLatestEnd creates a new latest end construct. The latest end of a stop is the latest time a stop can end at the location of the stop. The LatestEnd can be added to the model as a constraint or as an objective.

type LatestStart

type LatestStart interface {
	ConstraintReporter
	ModelConstraint
	ModelObjective

	// Latest returns the latest start expression which defines the latest
	// start of a stop.
	Latest() StopTimeExpression

	// Lateness returns the lateness of a stop. The lateness is the difference
	// between the actual start and its target start time.
	Lateness(stop SolutionStop) float64

	// SetFactor adds a factor with which a deviating stop is multiplied. This
	// is only taken into account if the construct is used as an objective.
	SetFactor(factor float64, stop ModelStop)

	// Factor returns the multiplication factor for the given stop expression.
	Factor(stop ModelStop) float64
}

LatestStart is a construct that can be added to the model as a constraint or as an objective. The latest start of a stop is the latest time a stop can start at the location of the stop.

func NewLatestStart

func NewLatestStart(
	latest StopTimeExpression,
) (LatestStart, error)

NewLatestStart creates a construct that can be added to the model as a constraint or as an objective. The latest start of a stop is the latest time a stop can start at the location of the stop.

type Locker

type Locker interface {
	// Lock locks the constraint on locking a model.
	Lock(model Model) error
}

Locker is an interface for locking a constraint. This interface is called when the model is locked. The constraint can use this to initialize data structures that are used to check the constraint.

type Maximum added in v1.3.0

type Maximum interface {
	ModelConstraint
	ModelObjective

	// Expression returns the expression which is used to calculate the
	// cumulative value of each stop which is required to stay below the
	// maximum value and above zero.
	Expression() ModelExpression

	// Maximum returns the maximum expression which defines the maximum
	// cumulative value that can be assigned to a vehicle type.
	Maximum() VehicleTypeExpression

	// PenaltyOffset returns the penalty offset. Penalty offset is used to
	// offset the penalty. The penalty offset is added to the penalty if there
	// is at least one violation.
	PenaltyOffset() float64

	// SetPenaltyOffset sets the penalty offset. Penalty offset is used to
	// offset the penalty. The penalty offset is added to the penalty if there
	// is at least one violation. The default penalty offset is 0.0 and it can
	// be changed by this method and must be positive.
	SetPenaltyOffset(penaltyOffset float64) error
}

Maximum can be used as a constraint or an objective that limits the maximum cumulative value can be assigned to a vehicle type. The maximum cumulative value is defined by the expression and the maximum value is defined by the maximum expression.

func NewMaximum added in v1.3.0

func NewMaximum(
	expression ModelExpression,
	maximum VehicleTypeExpression,
) (Maximum, error)

NewMaximum creates a new maximum constraint/objective. If you add it as a constraint, it will behave it as a constraint. If you add it as an objective, it will behave as an objective.

type MaximumDurationConstraint

type MaximumDurationConstraint interface {
	ModelConstraint

	// Maximum returns the maximum expression which defines the maximum
	// duration of a vehicle type.
	Maximum() VehicleTypeDurationExpression
}

MaximumDurationConstraint is a constraint that limits the duration of a vehicle.

func NewMaximumDurationConstraint

func NewMaximumDurationConstraint(
	maximum VehicleTypeDurationExpression,
) (MaximumDurationConstraint, error)

NewMaximumDurationConstraint creates a new maximum constraint. The constraint needs to be added to the model to be taken into account.

type MaximumStopsConstraint

type MaximumStopsConstraint interface {
	ModelConstraint

	// MaximumStops returns the maximum stops expression which defines the
	// maximum number of stops a vehicle type can have.
	MaximumStops() VehicleTypeExpression
}

MaximumStopsConstraint is a constraint that limits the maximum number of stops a vehicle type can have. The maximum number of stops is defined by the maximum stops expression. The first stop of a vehicle is not counted as a stop and the last stop of a vehicle is not counted as a stop.

func NewMaximumStopsConstraint

func NewMaximumStopsConstraint(
	maximumStops VehicleTypeExpression,
) (MaximumStopsConstraint, error)

NewMaximumStopsConstraint creates a new maximum stops constraint. The constraint needs to be added to the model to be taken into account.

type MaximumTravelDurationConstraint

type MaximumTravelDurationConstraint interface {
	ModelConstraint

	// Maximum returns the maximum expression which defines the maximum
	// travel duration of a vehicle type.
	Maximum() VehicleTypeDurationExpression
}

MaximumTravelDurationConstraint is a constraint that limits the total travel duration of a vehicle.

func NewMaximumTravelDurationConstraint

func NewMaximumTravelDurationConstraint(
	maximum VehicleTypeDurationExpression,
) (MaximumTravelDurationConstraint, error)

NewMaximumTravelDurationConstraint creates a new maximum travel duration constraint. The constraint needs to be added to the model to be taken into account.

type MaximumWaitStopConstraint added in v0.23.8

type MaximumWaitStopConstraint interface {
	ModelConstraint

	// Maximum returns the maximum expression which defines the maximum time a
	// vehicle can wait at a stop. Returns nil if not set.
	Maximum() StopDurationExpression
}

MaximumWaitStopConstraint is a constraint that limits the time a vehicle can wait between two stops. Wait is defined as the time between arriving at a location of a stop and starting (to work), [SolutionStop.StartValue()] - [SolutionStop.ArrivalValue()].

func NewMaximumWaitStopConstraint added in v0.23.8

func NewMaximumWaitStopConstraint() (MaximumWaitStopConstraint, error)

NewMaximumWaitStopConstraint returns a new MaximumWaitStopConstraint. The maximum wait constraint limits the time a vehicle can wait between two stops. Wait is defined as the time between arriving at a location of a stop and starting (to work), [SolutionStop.StartValue()] - [SolutionStop.ArrivalValue()].

type MaximumWaitVehicleConstraint added in v0.23.8

type MaximumWaitVehicleConstraint interface {
	ModelConstraint

	// Maximum returns the maximum expression which defines the maximum
	// accumulated time a vehicle can wait on a route. Returns nil if not set.
	Maximum() VehicleTypeDurationExpression
}

MaximumWaitVehicleConstraint is a constraint that limits the accumulated time a vehicle can wait at stops on its route. Wait is defined as the time between arriving at a the location of stop and starting (to work), [SolutionStop.StartValue()] - [SolutionStop.ArrivalValue()].

func NewMaximumWaitVehicleConstraint added in v0.23.8

func NewMaximumWaitVehicleConstraint() (MaximumWaitVehicleConstraint, error)

NewMaximumWaitVehicleConstraint returns a new MaximumWaitVehicleConstraint. The maximum wait constraint limits the accumulated time a vehicle can wait at stops on its route. Wait is defined as the time between arriving at a location of a stop and starting (to work), [SolutionStop.StartValue()] - [SolutionStop.ArrivalValue()].

type MixItem added in v0.32.0

type MixItem struct {
	// Name is the name of the mix item.
	Name string `json:"name"`
	// Quantity is the number units of the mix items are inserted or removed from a
	// vehicle.
	Quantity int `json:"quantity"`
}

MixItem is an item that is used to specify the type of mix. The type defines the type of each item. The count is the number units of the item are inserted or removed from a vehicle.

type Model

type Model interface {
	ModelData
	SolutionObserved

	// AddConstraint adds a constraint to the model. The constraint is
	// checked at the specified violation.
	AddConstraint(constraint ModelConstraint) error

	// Constraints returns all constraints of the model.
	Constraints() ModelConstraints

	// ConstraintsCheckedAt returns all constraints of the model that
	// are checked at the specified time of having calculated the new
	// information for the changed solution.
	ConstraintsCheckedAt(violation CheckedAt) ModelConstraints

	// DistanceUnit returns the unit of distance used in the model. The
	// unit is used to convert distances to values and vice versa. This is
	// also used for reporting.
	DistanceUnit() common.DistanceUnit

	// DurationUnit returns the unit of duration used in the model. The
	// unit is used to convert durations to values and vice versa. This is
	// also used for reporting.
	DurationUnit() time.Duration

	// DurationToValue converts the specified duration to a value as it used
	// internally in the model.
	DurationToValue(duration time.Duration) float64

	// Epoch returns the epoch of the model. The epoch is used to convert
	// time.Time to float64 and vice versa. All float64 values are relative
	// to the epoch.
	Epoch() time.Time

	// Expressions returns all expressions of the model for which a solution
	// has to calculate values. The expressions are sorted by their index. The
	// constraints register their expressions with the model.
	Expressions() ModelExpressions

	// IsLocked returns true if the model is locked. The model is
	// locked after a solution has been created using the model.
	IsLocked() bool

	// NewPlanSequence creates a new plan sequence. A plan sequence is a plan
	// unit. A plan unit is a collection of stops which are always planned and
	// unplanned as a single unit. In this case they have to be planned as a
	// sequence on the same vehicle in the order of the stops provided as an
	// argument.
	NewPlanSequence(stops ModelStops) (ModelPlanStopsUnit, error)
	// NewPlanSingleStop creates a new plan unit. A plan single stop
	// is a plan unit of a single stop. A plan unit is a collection of
	// stops which are always planned and unplanned as a single unit.
	NewPlanSingleStop(stop ModelStop) (ModelPlanStopsUnit, error)
	// NewPlanMultipleStops creates a new plan of multiple [ModelStops]. A plan
	// of multiple stops is a [ModelPlanUnit] of more than one stop. A plan
	// unit is a collection of stops which are always planned and unplanned
	// as a single entity. When planned, they are always assigned to the same
	// vehicle. The function takes in a sequence represented by a
	// [DirectedAcyclicGraph] (DAG) which restricts the order in which the
	// stops can be planned on the vehicle. Using an empty DAG means that the
	// stops can be planned in any order, and they will always be assigned to
	// the same vehicle. Consider the stops [s1, s2, s3] and the sequence [s1
	// -> s2, s1 -> s3]. This means that we are restricting that the stop s1
	// must come before s2 and s3. However, we are not specifying the order of
	// s2 and s3. This means that we can plan s2 before s3 or s3 before s2.
	NewPlanMultipleStops(
		stops ModelStops,
		sequence DirectedAcyclicGraph,
	) (ModelPlanStopsUnit, error)

	// NewPlanAllPlanUnits creates a new plan units unit. A plan all plan
	// units unit is a collection of plan units which are always planned and
	// unplanned as a single unit. The sameVehicle argument specifies if the
	// plan units have to be planned on the same vehicle or not. If sameVehicle
	// is true, the plan units have to be planned on the same vehicle.
	// The plan units can only be part of one plan units unit.
	NewPlanAllPlanUnits(
		sameVehicle bool,
		planUnits ...ModelPlanUnit,
	) (ModelPlanUnitsUnit, error)

	// NewPlanOneOfPlanUnits creates a new plan units unit. A plan one of plan
	// units unit is a collection of plan units from which exactly one has to
	// be planned.
	NewPlanOneOfPlanUnits(planUnits ...ModelPlanUnit) (ModelPlanUnitsUnit, error)

	// NewStop creates a new stop. The stop is used to create plan units or can
	// be used to create a first or last stop of a vehicle.
	NewStop(location common.Location) (ModelStop, error)

	// NewVehicle creates a new vehicle. The vehicle is used to create
	// solutions. Every vehicle has a first and last stop - even if the vehicle
	// is empty.
	NewVehicle(
		vehicleType ModelVehicleType,
		start time.Time,
		first ModelStop,
		last ModelStop,
	) (ModelVehicle, error)
	// NewVehicleType creates a new vehicle type. The vehicle type is used to
	// create vehicles. The travelDuration defines the travel duration going
	// from one stop to another if the stops are planned on a vehicle of the
	// constructed type. The duration defines the duration of a stop that gets
	// planned on a vehicle of the constructed type.
	NewVehicleType(
		travelDuration TimeDependentDurationExpression,
		duration DurationExpression,
	) (ModelVehicleType, error)

	// NumberOfStops returns the number of stops in the model.
	NumberOfStops() int

	// Objective returns the objective of the model.
	Objective() ModelObjectiveSum

	// PlanUnits returns all plan units of the model. A plan unit
	// is a collection of stops which are always planned and unplanned as a
	// single unit.
	PlanUnits() ModelPlanUnits

	// PlanStopsUnits returns all plan units of the model that plan stops.
	PlanStopsUnits() ModelPlanStopsUnits

	// SequenceSampleSize returns the number of samples to take from all
	// possible permutations of the stops in a PlanUnit.
	SequenceSampleSize() int

	// SetSequenceSampleSize sets the number of samples to take from all
	// possible permutations of the stops in a PlanUnit.
	SetSequenceSampleSize(sequenceSampleSize int)

	// Random returns a random number generator.
	Random() *rand.Rand

	// SetRandom sets the random number generator of the model.
	SetRandom(random *rand.Rand)

	// Stops returns all stops of the model.
	Stops() ModelStops

	// Stop returns the stop with the specified index.
	Stop(index int) (ModelStop, error)

	// TimeFormat returns the time format used for reporting.
	TimeFormat() string

	// TimeToValue converts the specified time to a value as used
	// internally in the model.
	TimeToValue(time time.Time) float64

	// ValueToTime converts the specified value to a time.Time as used
	// by the user. It is assuming value represents time since
	// the [Model.Epoch()] in the unit [Model.DurationUnit()].
	ValueToTime(value float64) time.Time
	// Vehicles returns all vehicles of the model.
	Vehicles() ModelVehicles
	// VehicleTypes returns all vehicle types of the model.
	VehicleTypes() ModelVehicleTypes

	// Vehicle returns the vehicle with the specified index.
	Vehicle(index int) ModelVehicle

	// MaxTime returns the maximum end time (upper bound) for any stop. This
	// function uses the [Model.Epoch()] as a starting point and adds a large
	// number to provide a large enough upper bound.
	MaxTime() time.Time

	// MaxDuration returns the maximum duration (upper bound) for any stop.
	MaxDuration() time.Duration
}

Model defines routing problem.

func NewModel

func NewModel() (Model, error)

NewModel creates a new empty vehicle routing model. Please use [BuildModel] if you want a model which already has all features added to it.

type ModelConstraint

type ModelConstraint interface {
	// EstimateIsViolated estimates if the given solution, when changed by the
	// given move will be violated or not. The move is not allowed to be nil.
	// It should be a pure function, i.e. not change any state of the
	// constraint. The stopPositionsHint can be used to speed up the estimation
	// of the constraint violation.
	EstimateIsViolated(SolutionMoveStops) (isViolated bool, stopPositionsHint StopPositionsHint)
}

ModelConstraint is the interface that all constraints must implement. Constraints are used to estimate if a move is allowed and can be used to check if a solution is valid after a move is executed or plan units have been unplanned.

type ModelConstraints

type ModelConstraints []ModelConstraint

ModelConstraints is a slice of ModelConstraint.

type ModelData

type ModelData interface {
	// Data returns the data.
	Data() any
	// SetData sets the data.
	SetData(any)
}

ModelData is a data interface available on several model constructs. It allows to attach arbitrary data to a model construct.

type ModelExpression

type ModelExpression interface {
	// Index returns the unique index of the expression.
	Index() int

	// Name returns the name of the expression.
	Name() string

	// Value returns the value of the expression for the given vehicle type,
	// from stop and to stop.
	Value(ModelVehicleType, ModelStop, ModelStop) float64

	// HasNegativeValues returns true if the expression contains negative
	// values.
	HasNegativeValues() bool
	// HasPositiveValues returns true if the expression contains positive
	// values.
	HasPositiveValues() bool

	// SetName sets the name of the expression.
	SetName(string)
}

ModelExpression is an expression that can be used in a model to define values for constraints and objectives. The expression is evaluated for each stop in the solution by invoking the Value() method. The value of the expression is then used in the constraints and objective.

func NewMeasureByIndexExpression

func NewMeasureByIndexExpression(m measure.ByIndex) ModelExpression

NewMeasureByIndexExpression returns a new MeasureByIndexExpression. A MeasureByIndexExpression is a ModelExpression that uses a measure.ByIndex to calculate the cost between two stops. The index of the measure have to be the same as the index of the stops in the model.

func NewMeasureByPointExpression

func NewMeasureByPointExpression(m measure.ByPoint) ModelExpression

NewMeasureByPointExpression returns a new MeasureByPointExpression. A MeasureByPointExpression is a ModelExpression that uses a measure.ByPoint to calculate the cost between two stops.

type ModelExpressions

type ModelExpressions []ModelExpression

ModelExpressions is a slice of ModelExpression.

type ModelObjective

type ModelObjective interface {
	// EstimateDeltaValue returns the estimated change in the score if the given
	// move were executed on the given solution.
	EstimateDeltaValue(move SolutionMoveStops) float64

	// Value returns the value of the objective for the given solution.
	Value(solution Solution) float64
}

ModelObjective is an objective function that can be used to optimize a solution.

type ModelObjectiveSum

type ModelObjectiveSum interface {
	ModelObjective

	// NewTerm adds an objective to the sum. The objective is multiplied by the
	// factor.
	NewTerm(factor float64, objective ModelObjective) (ModelObjectiveTerm, error)

	// ObjectiveTerms returns the model objectives that are part of the sum.
	Terms() ModelObjectiveTerms
}

ModelObjectiveSum is a sum of model objectives.

type ModelObjectiveTerm added in v0.23.2

type ModelObjectiveTerm interface {
	Factor() float64
	Objective() ModelObjective
}

ModelObjectiveTerm is a term in a model objective sum.

type ModelObjectiveTerms added in v0.23.2

type ModelObjectiveTerms []ModelObjectiveTerm

ModelObjectiveTerms is a slice of model objective terms.

type ModelObjectives

type ModelObjectives []ModelObjective

ModelObjectives is a slice of model objectives.

type ModelPlanStopsUnit added in v0.29.0

type ModelPlanStopsUnit interface {
	ModelPlanUnit

	// Centroid returns the centroid of the unit. The centroid is the
	// average location of all stops in the unit.
	Centroid() (common.Location, error)

	// DirectedAcyclicGraph returns the [DirectedAcyclicGraph] of the plan
	// unit.
	DirectedAcyclicGraph() DirectedAcyclicGraph

	// NumberOfStops returns the number of stops in the invoking unit.
	NumberOfStops() int

	// Stops returns the stops in the invoking unit.
	Stops() ModelStops
}

ModelPlanStopsUnit is a set of stops. It is a set of stops that are required to be planned together on the same vehicle. For example, a unit can be a pickup and a delivery stop that are required to be planned together on the same vehicle.

type ModelPlanStopsUnits added in v0.29.0

type ModelPlanStopsUnits []ModelPlanStopsUnit

ModelPlanStopsUnits is a slice of model plan stops units .

type ModelPlanUnit added in v0.23.1

type ModelPlanUnit interface {
	ModelData

	// Index returns the index of the invoking unit.
	Index() int

	// IsFixed returns true if the PlanUnit is fixed.
	IsFixed() bool

	// PlanUnitsUnit returns the [ModelPlanUnitsUnit] associated with the unit
	// with a bool indicating if it actually has one. A plan unit is associated
	// with at most one plan units unit. Can be nil if the unit is not part of a
	// plan units unit in which case the second return argument will be false.
	PlanUnitsUnit() (ModelPlanUnitsUnit, bool)
}

ModelPlanUnit is a plan unit. It is a unit defining what should be planned . For example, a unit can be a pickup and a delivery stop that are required to be planned together on the same vehicle.

type ModelPlanUnits added in v0.23.1

type ModelPlanUnits []ModelPlanUnit

ModelPlanUnits is a slice of plan units .

type ModelPlanUnitsUnit added in v0.29.0

type ModelPlanUnitsUnit interface {
	ModelPlanUnit

	// PlanUnits returns the plan units in the invoking unit.
	PlanUnits() ModelPlanUnits

	// PlanOneOf returns true if the plan unit only has to plan exactly one of
	// the associated plan units. If PlanOneOf returns true, then PlanAll will
	// return false and vice versa.
	PlanOneOf() bool

	// PlanAll returns true if the plan unit has to plan all the associated
	// plan units. If PlanAll returns true, then PlanOneOf will return false
	// and vice versa.
	PlanAll() bool

	// SameVehicle returns true if all the plan units in this unit have to be
	// planned on the same vehicle. If this unit is a conjunction, then
	// this will return true if all the plan units in this unit have to be
	// planned on the same vehicle. If this unit is a disjunction, then
	// this has no semantic meaning.
	SameVehicle() bool
}

ModelPlanUnitsUnit is a set of plan units. A plan unit is a set of stops that must be visited together.

type ModelPlanUnitsUnits added in v0.29.0

type ModelPlanUnitsUnits []ModelPlanUnitsUnit

ModelPlanUnitsUnits is a slice of model plan units units .

type ModelStatistics

type ModelStatistics interface {
	// FirstLocations returns the number of unique locations that are first
	// locations of a vehicle.
	FirstLocations() int

	// LastLocations returns the number of unique locations that are last
	// locations of a vehicle.
	LastLocations() int
	// Locations returns the number of unique locations excluding first and last
	// locations of a vehicle.
	Locations() int

	// PlanUnits returns the number of plan units.
	PlanUnits() int

	// Report returns a report of the statistics.
	Report() string

	// Stops returns the number of stops.
	Stops() int

	// VehicleTypes returns the number of vehicle types.
	VehicleTypes() int
	// Vehicles returns the number of vehicles.
	Vehicles() int
}

ModelStatistics provides statistics for a model.

func NewModelStatistics

func NewModelStatistics(model Model) ModelStatistics

NewModelStatistics creates a new ModelStatistics instance.

type ModelStop

type ModelStop interface {
	ModelData

	// ClosestStops returns a slice containing the closest stops to the
	// invoking stop. The slice is sorted by increasing distance to the
	// location. The slice first stop is the stop itself. The distance used
	// is the common.Haversine distance between the stops. All the stops
	// in the model are used in the slice. Slice with similar distance are
	// sorted by their index (increasing).
	ClosestStops() ModelStops

	// HasPlanStopsUnit returns true if the stop belongs to a plan unit. For example,
	// start and end stops of a vehicle do not belong to a plan unit.
	HasPlanStopsUnit() bool

	// ID returns the identifier of the stop.
	ID() string

	// Index returns the unique index of the stop.
	Index() int

	// IsFirstOrLast returns true if the stop is the first or last stop of one
	// or more vehicles. A stop which is the first or last stop of one or more
	// vehicles is not allowed to be part of a plan unit. A stop which is the
	// first or last stop of one or more vehicles is by definition fixed.
	IsFirstOrLast() bool

	// IsFixed returns true if fixed.
	IsFixed() bool

	// Location returns the location of the stop.
	Location() common.Location

	// Model returns the model of the stop.
	Model() Model

	// EarliestStart returns the earliest start time of the stop.
	EarliestStart() (t time.Time)

	// Windows returns the time windows of the stop.
	Windows() [][2]time.Time

	// PlanStopsUnit returns the [ModelPlanStopsUnit] associated with the stop.
	// A stop is associated with at most one plan unit. Can be nil if the stop
	// is not part of a stops plan unit.
	PlanStopsUnit() ModelPlanStopsUnit

	// MeasureIndex returns the measure index of the invoking stop . This index
	// is not necessarily unique.
	// This index is used by the model expression constructed by the factory
	// NewMeasureByIndexExpression to calculate the value of the measure
	// expression. By default, the measure index is the same as the index of
	// the stop.
	MeasureIndex() int

	// SetEarliestStart sets the earliest start time of the stop.
	SetEarliestStart(t time.Time) error

	// SetMeasureIndex sets the reference index of the stop, by default the
	// measure index is the same as the index of the stop.
	// This index is used by the model expression constructed by the factory
	// NewMeasureByIndexExpression to calculate the value of the measure
	// expression.
	SetMeasureIndex(int)

	// SetWindows sets the time windows of the stop.
	SetWindows(windows [][2]time.Time) error

	// ToEarliestStartValue returns the earliest start time if the vehicle
	// arrives at the stop at the given arrival time in seconds since
	// [Model.Epoch].
	ToEarliestStartValue(arrival float64) float64

	// SetID sets the identifier of the stop. This identifier is not used by
	// nextroute, and therefore it does not have to be unique for nextroute
	// internally. However, to make this ID useful for debugging and reporting
	// it should be made unique.
	SetID(string)
}

ModelStop is a stop to be assigned to a vehicle.

type ModelStops

type ModelStops []ModelStop

ModelStops is a slice of stops.

type ModelStopsDistanceQueries added in v1.0.4

type ModelStopsDistanceQueries interface {
	// ModelStops returns the original set of stops that the distance queries
	// were created from.
	ModelStops() ModelStops
	// NearestStops returns the n nearest stops to the given stop, the stop must
	// be present in the original set of stops.
	NearestStops(stop ModelStop, n int) (ModelStops, error)
	// WithinDistanceStops returns the stops within the given distance of the
	// given stop, the stop must be present in the original set of stops.
	WithinDistanceStops(
		stop ModelStop,
		distance common.Distance,
	) (ModelStops, error)
}

ModelStopsDistanceQueries is an interface to query distances between stops.

func NewModelStopsDistanceQueries added in v1.0.4

func NewModelStopsDistanceQueries(stops ModelStops) (ModelStopsDistanceQueries, error)

NewModelStopsDistanceQueries returns a new ModelStopsDistanceQueries. The ModelStopsDistanceQueries can be used to query distances between stops. The stops must be a set of stops with valid locations.

type ModelVehicle

type ModelVehicle interface {
	ModelData

	// AddStop adds a stop to the vehicle. The stop is added to the end of the
	// vehicle, before the last stop. If fixed is true stop will be fixed and
	// can not be unplanned.
	AddStop(stop ModelStop, fixed bool) error

	// First returns the first stop of the vehicle.
	First() ModelStop

	// ID returns the identifier of the vehicle.
	ID() string
	// Index returns the index of the vehicle.
	Index() int

	// Last returns the last stop of the vehicle.
	Last() ModelStop

	// Model returns the model of the vehicle.
	Model() Model

	// SetID sets the identifier of the vehicle. This identifier is not used by
	// nextroute, and therefore it does not have to be unique for nextroute
	// internally. However, to make this ID useful for debugging and reporting it
	// should be made unique.
	SetID(string)
	// Start returns the start time of the vehicle.
	Start() time.Time
	// Stops returns the stops of the vehicle that are provided as a start
	// assignment. The first and last stop of the vehicle are not included in
	// the returned slice.
	Stops() ModelStops

	// VehicleType returns the vehicle type of the vehicle.
	VehicleType() ModelVehicleType
}

ModelVehicle is a vehicle in the model. A vehicle is a sequence of stops.

type ModelVehicleType

type ModelVehicleType interface {
	ModelData

	// TemporalValues calculates the temporal values if the vehicle
	// would depart at departure going from stop to stop. If from or to is
	// invalid, the returned travelDuration will be 0.
	TemporalValues(
		departure float64,
		from ModelStop,
		to ModelStop,
	) (travelDuration, arrival, start, end float64)

	// Index returns the index of the vehicle type.
	Index() int

	// Model returns the model of the vehicle type.
	Model() Model

	// ID returns the identifier of the vehicle.
	ID() string

	// DurationExpression returns the process duration expression of the
	// vehicle type. Is set in the factory method of the vehicle type
	// Model.NewVehicleType.
	DurationExpression() DurationExpression
	// SetDurationExpression modifies the process duration expression of
	// the vehicle type.
	SetDurationExpression(expression DurationExpression) error

	// SetID sets the identifier of the stop. This identifier is not used by
	// nextroute and therefore it does not have to be unique for nextroute
	// internally. However to make this ID useful for debugging and reporting it
	// should be made unique.
	SetID(string)

	// TravelDurationExpression returns the duration expression of the
	// vehicle type. Is set in the factory method of the vehicle type
	// Model.NewVehicleType.
	TravelDurationExpression() TimeDependentDurationExpression
	// SetTravelDurationExpression modifies the duration expression of the
	// vehicle type.
	SetTravelDurationExpression(expression TimeDependentDurationExpression) error

	// Vehicles returns the vehicles of this vehicle type.
	Vehicles() ModelVehicles
}

ModelVehicleType is a vehicle type. A vehicle type is a definition of a vehicle. It contains the process duration and travel duration expressions that are used to calculate the travel and process duration of a stop assignment to a vehicle of this type.

type ModelVehicleTypes

type ModelVehicleTypes []ModelVehicleType

ModelVehicleTypes is a slice of vehicle types.

type ModelVehicles

type ModelVehicles []ModelVehicle

ModelVehicles is a slice of ModelVehicle.

type Move

type Move = SolutionMoveStops

Move is a type alias for SolutionMoveStops. It is used to make the custom constraints and observers backward compatible.

type NoMixConstraint added in v0.32.0

type NoMixConstraint interface {
	Identifier
	ModelConstraint

	// Insert returns the mix items that are associated with a stop that
	// inserts items into a vehicle.
	Insert() map[ModelStop]MixItem
	// Remove returns the mix items that are associated with a stop that
	// removes items from a vehicle.
	Remove() map[ModelStop]MixItem
	// Value returns the value of the constraint for a stop. The value is
	// the amount of items on the vehicle at the moment of the stop. If
	// the stop is unplanned, the value has no semantic meaning.
	Value(solutionStop SolutionStop) MixItem
}

NoMixConstraint limits the order in which stops are assigned to a vehicle based upon the items the stops insert or remove from a vehicle.

func NewNoMixConstraint added in v0.32.0

func NewNoMixConstraint(
	deltas map[ModelStop]MixItem,
) (NoMixConstraint, error)

NewNoMixConstraint creates a new no-mix constraint. The constraint needs to be added to the model to be taken into account. The deltas map contains the information defining how many items a stop inserts or removes from a vehicle. If the count is positive it inserts items to the vehicle, if the count is negative it removes items from the vehicle. A stop can be present once in deltas. The constraint makes sure that at no point in time there are items on the vehicle of more than one type. The sum of the counts of all the deltas of the stops of each plan unit must be zero. The items of all the stops of a plan unit must be the same type if they have a delta.

type ObjectiveDataUpdater

type ObjectiveDataUpdater interface {
	// UpdateObjectiveData is deprecated.
	UpdateObjectiveData(s SolutionStop) (Copier, error)
}

ObjectiveDataUpdater is is a deprecated interface. Please use ObjectiveStopDataUpdater instead.

type ObjectiveSolutionDataUpdater added in v0.24.2

type ObjectiveSolutionDataUpdater interface {
	// UpdateObjectiveSolutionData is called when a solution has been modified.
	// The solution has all it's expression values set and this function
	// can use them to update the objective data for the solution. The data
	// returned can be used by the estimate function and can be retrieved by the
	// Solution.ObjectiveData function.
	UpdateObjectiveSolutionData(s Solution) (Copier, error)
}

ObjectiveSolutionDataUpdater is the interface than can be used by an objective if it wants to store data with each solution.

type ObjectiveStopDataUpdater added in v0.24.2

type ObjectiveStopDataUpdater interface {
	// UpdateObjectiveStopData is called when a stop is added to a solution.
	// The solutionStop has all it's expression values set and this function
	// can use them to update the objective data for the stop. The data
	// returned can be used by the estimate function and can be retrieved by the
	// SolutionStop.ObjectiveData function.
	UpdateObjectiveStopData(s SolutionStop) (Copier, error)
}

ObjectiveStopDataUpdater is the interface than can be used by an objective if it wants to store data with each stop in a solution.

type ParallelSolveInformation added in v1.3.0

type ParallelSolveInformation interface {
	// Cycle returns the current cycle. A cycle is a set of parallel runs.
	// In each cycle multiple runs are executed in parallel. Cycle identifies
	// how often a new solver has been created and started with the best
	// solution of the previous runs.
	Cycle() int

	// Random returns the random number generator from the solution.
	Random() *rand.Rand
	// Run returns the current run. A run is a single solve run. In each cycle
	// multiple runs are executed in parallel. Run identifies a run.
	Run() int
}

ParallelSolveInformation holds the information about the current parallel solve run.

type ParallelSolveOptions

type ParallelSolveOptions struct {
	Iterations           int           `` /* 149-byte string literal not displayed */
	Duration             time.Duration `json:"duration" usage:"maximum duration of the solver" default:"30s"`
	ParallelRuns         int           `json:"parallel_runs" usage:"maximum number of parallel runs, -1 results in using all available resources" default:"-1"`
	StartSolutions       int           `` /* 175-byte string literal not displayed */
	RunDeterministically bool          `json:"run_deterministically"  usage:"run the parallel solver deterministically"`
}

ParallelSolveOptions holds the options for the parallel solver.

type ParallelSolver

type ParallelSolver interface {
	Progressioner

	// Model returns the model of the solver.
	Model() Model

	// SetSolverFactory sets the factory for creating new solver.
	SetSolverFactory(SolverFactory)
	// SetSolveOptionsFactory sets the factory for creating new solve options.
	SetSolveOptionsFactory(SolveOptionsFactory)
	// Solve starts the solving process using the given options. It returns the
	// solutions as a channel.
	Solve(context.Context, ParallelSolveOptions, ...Solution) (SolutionChannel, error)
	// SolveEvents returns the solve-events used by the solver.
	SolveEvents() SolveEvents
}

ParallelSolver is the interface for parallel solver. The parallel solver will run multiple solver in parallel and return the best solution. The parallel solver will stop when the maximum duration is reached.

func NewParallelSolver

func NewParallelSolver(
	model Model,
) (ParallelSolver, error)

NewParallelSolver creates a new parallel solver for the given work solutions.

func NewSkeletonParallelSolver added in v1.3.0

func NewSkeletonParallelSolver(model Model) (ParallelSolver, error)

NewSkeletonParallelSolver creates a new parallel solver for nextroute.

type PerformanceObserver

type PerformanceObserver interface {
	SolutionObserver

	// Duration returns the duration since the creation of the
	// PerformanceObserver.
	Duration() time.Duration

	// Report creates a report of the performance of the model, and it's
	// subsequent use.
	Report() string
}

PerformanceObserver is an interface that is used to observe the performance of the model, and it's subsequent use.

func NewPerformanceObserver

func NewPerformanceObserver(model Model) PerformanceObserver

NewPerformanceObserver creates a new PerformanceObserver. The performance observer is used to observe the performance of the model, and it's subsequent use. The created PerformanceObserver is not connected to the model, and therefore will not observe anything. To connect the PerformanceObserver to the model, use the AddSolutionObserver() method on the Model.

type ProgressionEntry added in v1.3.0

type ProgressionEntry alns.ProgressionEntry

ProgressionEntry in alns for backwards compatibility.

type Progressioner added in v1.3.0

type Progressioner alns.Progressioner

Progressioner in alns for backwards compatibility.

type RegisteredModelExpressions

type RegisteredModelExpressions interface {
	// ModelExpressions registers the expressions that are registered with the
	// model.
	ModelExpressions() ModelExpressions
}

RegisteredModelExpressions is the interface that exposes the expressions that should be registered with the model.

type Solution

type Solution interface {
	// BestMove returns the best move for the given solution plan unit. The
	// best move is the move that has the lowest score. If there are no moves
	// available for the given solution plan unit, a move is returned which
	// is not executable, SolutionMoveStops.IsExecutable.
	BestMove(context.Context, SolutionPlanUnit) SolutionMove

	// ConstraintData returns the data of the constraint for the solution. The
	// constraint data of a solution is set by the
	// ConstraintSolutionDataUpdater.UpdateConstraintSolutionData method of the
	// constraint.
	ConstraintData(constraint ModelConstraint) any
	// Copy returns a deep copy of the solution.
	Copy() Solution

	// FixedPlanUnits returns the solution plan units that are fixed.
	// Fixed plan units are plan units that are not allowed to be planned or
	// unplanned. The union of fixed, planned and unplanned plan units
	// is the set of all plan units in the model.
	FixedPlanUnits() ImmutableSolutionPlanUnitCollection

	// Model returns the model of the solution.
	Model() Model

	// ObjectiveData returns the value of the objective for the solution. The
	// objective value of a solution is set by the
	// ObjectiveSolutionDataUpdater.UpdateObjectiveSolutionData method of the
	// objective. If the objective is not set on the solution, nil is returned.
	ObjectiveData(objective ModelObjective) any
	// ObjectiveValue returns the objective value for the objective in the
	// solution. Also returns 0.0 if the objective is not part of the solution.
	ObjectiveValue(objective ModelObjective) float64

	// PlannedPlanUnits returns the solution plan units that are planned as
	// a collection of solution plan units.
	PlannedPlanUnits() ImmutableSolutionPlanUnitCollection

	// Random returns the random number generator of the solution.
	Random() *rand.Rand

	// Score returns the score of the solution.
	Score() float64
	// SolutionPlanStopsUnit returns the [SolutionPlanStopsUnit] for the given
	// model plan unit.
	SolutionPlanStopsUnit(planUnit ModelPlanStopsUnit) SolutionPlanStopsUnit
	// SolutionPlanUnit returns the [SolutionPlanUnit] for the given
	// model plan unit.
	SolutionPlanUnit(planUnit ModelPlanUnit) SolutionPlanUnit
	// SolutionStop returns the solution stop for the given model stop.
	SolutionStop(stop ModelStop) SolutionStop
	// SolutionVehicle returns the solution vehicle for the given model vehicle.
	SolutionVehicle(vehicle ModelVehicle) SolutionVehicle

	// UnPlannedPlanUnits returns the solution plan units that are not
	// planned.
	UnPlannedPlanUnits() ImmutableSolutionPlanUnitCollection

	// Vehicles returns the vehicles of the solution.
	Vehicles() SolutionVehicles
}

Solution is a solution to a model.

func NewClusterSolution added in v1.0.4

func NewClusterSolution(
	ctx context.Context,
	m Model,
	maximumClusters int,
) (Solution, error)

NewClusterSolution creates a new solution. The solution is created from the given model using a cluster construction heuristic. The number of clusters is maximized to the number of empty vehicles in the solution and the maximumClusters parameter.

func NewRandomSolution

func NewRandomSolution(
	ctx context.Context,
	m Model,
) (Solution, error)

NewRandomSolution creates a new solution. The solution is created from the given model. The solution starts with an empty solution and will assign a random plan unit to a random vehicle. The remaining plan units are added to the solution in a random order at the best possible position.

func NewSolution

func NewSolution(
	m Model,
) (Solution, error)

NewSolution creates a new solution. The solution is created from the given model. The solution starts with all plan units unplanned. Once a solution has been created the model can no longer be changed, it becomes immutable.

func NewSweepSolution

func NewSweepSolution(
	ctx context.Context,
	m Model,
) (Solution, error)

NewSweepSolution creates a new solution. The solution is created from the given model using a sweep construction heuristic.

type SolutionChannel added in v1.3.0

type SolutionChannel <-chan Solution

SolutionChannel is a channel of solutions.

func (SolutionChannel) All added in v1.3.0

func (solutions SolutionChannel) All() []Solution

All returns all solutions in the channel.

func (SolutionChannel) Last added in v1.3.0

func (solutions SolutionChannel) Last() Solution

Last returns the last solution in the channel.

type SolutionMove added in v0.29.0

type SolutionMove interface {
	// Execute executes the move. Returns true if the move was executed
	// successfully, false if the move was not executed successfully. A
	// move is not successful if it did not result in a change in the
	// solution without violating any hard constraints. A move can be
	// marked executable even if it is not successful in executing.
	Execute(context.Context) (bool, error)

	// IsExecutable returns true if the move is executable, false if the
	// move is not executable. A move is executable if the estimates believe
	// the move will result in a change in the solution without violating
	// any hard constraints.
	IsExecutable() bool

	// IsImprovement returns true if the move is executable and the move
	// has a value less than zero, false if the move is not executable or
	// the move has a value of zero or greater than zero.
	IsImprovement() bool

	// PlanUnit returns the [SolutionPlanUnit] that is affected by the move.
	PlanUnit() SolutionPlanUnit

	// TakeBest returns the best move between the given move and the
	// current move. The best move is the move with the lowest score. If
	// the scores are equal, a random uniform distribution is used to
	// determine the move to use.
	TakeBest(that SolutionMove) SolutionMove

	// Value returns the score of the move. The score is the difference
	// between the score of the solution before the move and the score of
	// the solution after the move. The score is based on the estimates and
	// the actual score of the solution after the move should be retrieved
	// using Solution.Score after the move has been executed.
	Value() float64

	// ValueSeen returns the number of times the value of this move has been
	// seen by the estimates. A tie-breaker is a mechanism used to resolve
	// situations where multiple moves have the same value. In cases where the
	// same value is seen multiple times, a tie-breaker is applied to ensure
	// that each option has an equal chance of being selected.
	ValueSeen() int

	// IncrementValueSeen increments the number of times the value of this move
	// has been seen by the estimates and returns the move. A tie-breaker is a
	// mechanism used to resolve situations where multiple moves have the same
	// value. In cases where the same value is seen multiple times, a
	// tie-breaker is applied to ensure that each option has an equal chance of
	// being selected.
	IncrementValueSeen(inc int) SolutionMove
}

SolutionMove is a move in a solution.

func NewNotExecutableMove

func NewNotExecutableMove() SolutionMove

NewNotExecutableMove returns a new empty move. An empty move is a move that does not change the solution, and it is marked as not executable.

type SolutionMoveStops added in v0.29.0

type SolutionMoveStops interface {
	SolutionMove
	// Previous returns previous stop of the first to be planned
	// stop if it would be planned. Previous is the same stop as the
	// previous stop of the first stop position.
	Previous() SolutionStop

	// Next returns the next stop of the last to be planned
	// stop if it would be planned. Next is the same stop as the
	// next stop of the last stop position.
	Next() SolutionStop

	// PlanStopsUnit returns the [SolutionPlanStopsUnit] that is affected by the move.
	PlanStopsUnit() SolutionPlanStopsUnit

	// StopPositions returns the [StopPositions] that define the move and
	// how it will change the solution.
	StopPositions() StopPositions

	// StopPositionAt returns the stop position at the given index. The index
	// is the index is based on the positions in the move. Get the length of
	// the stop positions from [StopPositionsLength].
	StopPositionAt(index int) StopPosition

	// StopPositionsLength returns the length of the stop positions.
	StopPositionsLength() int

	// Vehicle returns the vehicle, if known, that is affected by the move. If
	// not known, nil is returned.
	Vehicle() SolutionVehicle

	// Solution returns the solution that is affected by the move.
	Solution() Solution
}

SolutionMoveStops is a move in a solution. A move is a change in the solution that can be executed. A move can be executed which may or may not result in a change in the solution. A move can be asked if it is executable, it is not executable if it is incomplete or if it is not executable because the move is not allowed. A move can be asked if it is an improvement, it is an improvement if it is executable and the move has a value less than zero. A move describes the change in the solution. The change in the solution is described by the stop positions. The stop positions describe for each stop in the associated units where in the existing solution the stop is supposed to be placed. The stop positions are ordered by the order of the stops in the unit. The first stop in the unit is the first stop in the stop positions. The last stop in the unit is the last stop in the stop positions.

type SolutionMoves added in v0.29.0

type SolutionMoves []SolutionMove

SolutionMoves is a slice of SolutionMove.

type SolutionObserved

type SolutionObserved interface {
	SolutionObserver
	SolutionUnPlanObserver

	// AddSolutionObserver adds the given solution observer to the solution
	// observed.
	AddSolutionObserver(observer SolutionObserver)

	// AddSolutionUnPlanObserver adds the given solution un-plan observer to the
	// solution observed.
	AddSolutionUnPlanObserver(observer SolutionUnPlanObserver)

	// RemoveSolutionObserver remove the given solution observer from the
	// solution observed.
	RemoveSolutionObserver(observer SolutionObserver)

	// RemoveSolutionUnPlanObserver remove the given solution un-plan observer
	// from the solution observed.
	RemoveSolutionUnPlanObserver(observer SolutionUnPlanObserver)

	// SolutionObservers returns the solution observers.
	SolutionObservers() SolutionObservers

	// SolutionUnPlanObservers returns the solution un-plan observers.
	SolutionUnPlanObservers() SolutionUnPlanObservers
}

SolutionObserved is an interface that can be implemented to observe the solution manipulation process.

type SolutionObserver

type SolutionObserver interface {
	// OnNewSolution is called when a new solution is going to be created.
	OnNewSolution(model Model)
	// OnNewSolutionCreated is called when a new solution has been created.
	OnNewSolutionCreated(solution Solution)

	// OnCopySolution is called when a solution is going to be copied.
	OnCopySolution(solution Solution)
	// OnCopiedSolution is called when a solution has been copied.
	OnCopiedSolution(solution Solution)

	// OnCheckConstraint is called when a constraint is going to be checked.
	OnCheckConstraint(
		constraint ModelConstraint,
		violation CheckedAt,
	)

	// OnSolutionConstraintChecked is called when a constraint has been checked.
	OnSolutionConstraintChecked(
		constraint ModelConstraint,
		feasible bool,
	)

	// OnStopConstraintChecked is called when a stop constraint has been checked.
	OnStopConstraintChecked(
		stop SolutionStop,
		constraint ModelConstraint,
		feasible bool,
	)

	// OnVehicleConstraintChecked is called when a vehicle constraint has been checked.
	OnVehicleConstraintChecked(
		vehicle SolutionVehicle,
		constraint ModelConstraint,
		feasible bool,
	)

	// OnEstimateIsViolated is called when the delta constraint is going to be
	// estimated if it will be violated
	OnEstimateIsViolated(
		constraint ModelConstraint,
	)
	// OnEstimatedIsViolated is called when the delta constraint score
	// has been estimated.
	OnEstimatedIsViolated(
		move SolutionMove,
		constraint ModelConstraint,
		isViolated bool,
		planPositionsHint StopPositionsHint,
	)
	// OnEstimateDeltaObjectiveScore is called when the delta objective score is
	// going to be estimated.
	OnEstimateDeltaObjectiveScore()
	// OnEstimatedDeltaObjectiveScore is called when the delta objective score
	// has been estimated.
	OnEstimatedDeltaObjectiveScore(
		estimate float64,
	)
	// OnBestMove is called when the solution is asked for it's best move.
	OnBestMove(solution Solution)
	// OnBestMoveFound is called when the solution has found it's best move.
	OnBestMoveFound(move SolutionMove)

	// OnPlan is called when a move is going to be planned.
	OnPlan(move SolutionMove)
	// OnPlanFailed is called when a move has failed to be planned.
	OnPlanFailed(move SolutionMove, constraint ModelConstraint)
	// OnPlanSucceeded is called when a move has succeeded to be planned.
	OnPlanSucceeded(move SolutionMove)
}

SolutionObserver is an interface that can be implemented to observe the solution manipulation process.

type SolutionObservers

type SolutionObservers []SolutionObserver

SolutionObservers is a slice of SolutionObserver.

type SolutionPlanStopsUnit added in v0.29.0

type SolutionPlanStopsUnit interface {
	SolutionPlanUnit
	// ModelPlanStopsUnit returns the [ModelPlanStopsUnit] this unit is
	// based upon.
	ModelPlanStopsUnit() ModelPlanStopsUnit

	// SolutionStop returns the solution stop for the given model stop.
	// Will panic if the stop is not part of the unit.
	SolutionStop(stop ModelStop) SolutionStop
	// SolutionStops returns the solution stops in this unit.
	SolutionStops() SolutionStops
	// StopPositions returns the stop positions of the invoking plan unit.
	// The stop positions are the positions of the stops in the solution.
	// If the unit is unplanned, the stop positions will be empty.
	StopPositions() StopPositions
}

SolutionPlanStopsUnit is a set of stops that are planned to be visited by a vehicle.

type SolutionPlanStopsUnits added in v0.29.0

type SolutionPlanStopsUnits []SolutionPlanStopsUnit

SolutionPlanStopsUnits is a slice of SolutionPlanStopsUnit.

type SolutionPlanUnit added in v0.23.1

type SolutionPlanUnit interface {
	// IsFixed returns true if any of stops are fixed.
	IsFixed() bool

	// IsPlanned returns true if all the stops are planned.
	IsPlanned() bool

	// ModelPlanUnit returns the model plan unit associated with the
	// solution plan unit.
	ModelPlanUnit() ModelPlanUnit

	// PlannedPlanStopsUnits returns the plan stops units associated with the
	// invoking plan unit which are planned.
	PlannedPlanStopsUnits() SolutionPlanStopsUnits

	// Solution returns the solution this unit is part of.
	Solution() Solution

	// UnPlan un-plans the unit by removing the underlying solution stops
	// from the solution. Returns true if the unit was unplanned
	// successfully, false if the unit was not unplanned successfully. A
	// unit is not successful if it did not result in a change in the
	// solution without violating any hard constraints.
	UnPlan() (bool, error)
}

SolutionPlanUnit is a set of stops that are planned to be visited by a vehicle.

type SolutionPlanUnitCollection added in v0.23.1

type SolutionPlanUnitCollection interface {
	ImmutableSolutionPlanUnitCollection
	// Add adds a [SolutionPlanUnit] to the collection.
	Add(solutionPlanUnit SolutionPlanUnit)
	// Remove removes a [SolutionPlanUnit] from the collection.
	Remove(solutionPlanUnit SolutionPlanUnit)
}

SolutionPlanUnitCollection is a collection of solution plan units.

func NewSolutionPlanUnitCollection added in v0.23.1

func NewSolutionPlanUnitCollection(
	source *rand.Rand,
	planUnits SolutionPlanUnits,
) SolutionPlanUnitCollection

NewSolutionPlanUnitCollection creates a new SolutionPlanUnitCollection. A SolutionPlanUnitCollection is a collection of solution plan units. It can be used to randomly draw a sample of solution plan unit and remove solution plan unit from the collection.

type SolutionPlanUnits added in v0.23.1

type SolutionPlanUnits []SolutionPlanUnit

SolutionPlanUnits is a slice of SolutionPlanUnit.

type SolutionPlanUnitsUnit added in v0.29.0

type SolutionPlanUnitsUnit interface {
	SolutionPlanUnit
	// ModelPlanUnitsUnit returns the [ModelPlanUnitsUnit] this unit is
	// based upon.
	ModelPlanUnitsUnit() ModelPlanUnitsUnit

	// SolutionPlanUnit returns the solution plan unit for the given model
	// plan unit. Will panic if the unit is not part of the unit.
	SolutionPlanUnit(planUnit ModelPlanUnit) SolutionPlanUnit
	// SolutionPlanUnits returns the solution units in this unit.
	SolutionPlanUnits() SolutionPlanUnits
}

SolutionPlanUnitsUnit is a set of solution plan units.

type SolutionPlanUnitsUnits added in v0.29.0

type SolutionPlanUnitsUnits []SolutionPlanUnitsUnit

SolutionPlanUnitsUnits is a slice of SolutionPlanUnitsUnit.

type SolutionStop

type SolutionStop interface {
	// Arrival returns the arrival time of the stop. If the stop is unplanned,
	// the arrival time has no semantic meaning.
	Arrival() time.Time
	// ArrivalValue returns the arrival time of the stop as a float64. If the
	// stop is unplanned, the arrival time has no semantic meaning.
	ArrivalValue() float64

	// ConstraintData returns the value of the constraint for the stop. The
	// constraint value of a stop is set by the ConstraintStopDataUpdater.
	// UpdateConstrainStopData method of the constraint. If the constraint is
	// not set on the stop, nil is returned. If the stop is unplanned, the
	// constraint value has no semantic meaning.
	ConstraintData(constraint ModelConstraint) any
	// CumulativeTravelDurationValue returns the cumulative travel duration of
	// the stop as a float64. The cumulative travel duration is the sum of the
	// travel durations of all stops that are visited before the stop. If the
	// stop is unplanned, the cumulative travel duration has no semantic
	// meaning. The returned value is the number of Model.DurationUnit units.
	CumulativeTravelDurationValue() float64
	// CumulativeTravelDuration returns the cumulative value of the expression
	// for the stop as a time.Duration. The cumulative travel duration is the
	// sum of the travel durations of all stops that are visited before the
	// stop and the stop itself. If the stop is unplanned, the cumulative
	// travel duration has no semantic meaning.
	CumulativeTravelDuration() time.Duration
	// CumulativeValue returns the cumulative value of the expression for the
	// stop as a float64. The cumulative value is the sum of the values of the
	// expression for all stops that are visited before the stop and the stop
	// itself. If the stop is unplanned, the cumulative value has no semantic
	// meaning.
	CumulativeValue(expression ModelExpression) float64

	// End returns the end time of the stop. If the stop is unplanned, the end
	// time has no semantic meaning.
	End() time.Time
	// EndValue returns the end time of the stop as a float64. If the stop is
	// unplanned, the end time has no semantic meaning. The returned value is
	// the number of Model.DurationUnit units since Model.Epoch.
	EndValue() float64

	// Index returns the index of the stop in the Solution.
	Index() int
	// IsFixed returns true if the stop is fixed. A fixed stop is a stop that
	// that can not transition form being planned to unplanned or vice versa.
	IsFixed() bool
	// IsFirst returns true if the stop is the first stop of a vehicle.
	IsFirst() bool
	// IsLast returns true if the stop is the last stop of a vehicle.
	IsLast() bool
	// IsPlanned returns true if the stop is planned. A planned stop is a stop
	// that is visited by a vehicle. An unplanned stop is a stop that is not
	// visited by a vehicle.
	IsPlanned() bool

	// ModelStop returns the ModelStop that is the basis of the SolutionStop.
	ModelStop() ModelStop
	// ModelStopIndex is the index of the ModelStop in the Model.
	ModelStopIndex() int

	// Next returns the next stop the vehicle will visit after the stop. If
	// the stop is the last stop of a vehicle, the solution stop itself is
	// returned. If the stop is unplanned, the next stop has no semantic
	// meaning and the stop itself is returned.
	Next() SolutionStop
	// NextIndex returns the index of the next solution stop the vehicle will
	// visit after the stop. If the stop is the last stop of a vehicle,
	// the index of the stop itself is returned. If the stop is unplanned,
	// the next stop has no semantic meaning and the index of the stop itself
	// is returned.
	NextIndex() int

	// ObjectiveData returns the value of the objective for the stop. The
	// objective value of a stop is set by the
	// ObjectiveStopDataUpdater.UpdateObjectiveStopData method of the objective.
	// If the objective is not set on the stop, nil is returned. If the stop is
	// unplanned, the objective value has no semantic meaning.
	ObjectiveData(objective ModelObjective) any

	// PlanStopsUnit returns the [SolutionPlanStopsUnit] that the stop is
	// associated with.
	PlanStopsUnit() SolutionPlanStopsUnit
	// Previous returns the previous stop the vehicle visited before the stop.
	// If the stop is the first stop of a vehicle, the solution stop itself is
	// returned. If the stop is unplanned, the previous stop has no semantic
	// meaning and the stop itself is returned.
	Previous() SolutionStop
	// PreviousIndex returns the index of the previous solution stop the
	// vehicle visited before the stop. If the stop is the first stop of a
	// vehicle, the index of the stop itself is returned. If the stop is
	// unplanned, the previous stop has no semantic meaning and the index of
	// the stop itself is returned.
	PreviousIndex() int

	// Slack returns the slack of the stop as a time.Duration. Slack is defined
	// as the duration you can start the invoking stop later without
	// postponing the last stop of the vehicle. If the stop is unplanned,
	// the slack has no semantic meaning. Slack is a consequence of the
	// earliest start of stops, if no earliest start is set, the slack is
	// always zero.
	Slack() time.Duration
	// SlackValue returns the slack of the stop as a float64.
	SlackValue() float64

	// Vehicle returns the SolutionVehicle that visits the stop. If the stop
	// is unplanned, the vehicle has no semantic meaning and a panic will be
	// raised.
	Vehicle() SolutionVehicle
	// VehicleIndex returns the index of the SolutionVehicle that visits the
	// stop. If the stop is unplanned, a panic will be raised.
	VehicleIndex() int

	// Solution returns the Solution that the stop is part of.
	Solution() Solution
	// Start returns the start time of the stop. If the stop is unplanned, the
	// start time has no semantic meaning.
	Start() time.Time
	// StartValue returns the start time of the stop as a float64. If the stop
	// is unplanned, the start time has no semantic meaning. The returned
	// value is the number of Model.DurationUnit units since Model.Epoch.
	StartValue() float64
	// Position returns the position of the stop in the vehicle starting with
	// 0 for the first stop. If the stop is unplanned, a panic will be raised.
	Position() int

	// TravelDuration returns the travel duration of the stop as a
	// time.Duration. If the stop is unplanned, the travel duration has no
	// semantic meaning. The travel duration is the time it takes to get to
	// the invoking stop.
	TravelDuration() time.Duration
	// TravelDurationValue returns the travel duration of the stop as a
	// float64. If the stop is unplanned, the travel duration has no semantic
	// meaning. The travel duration is the time it takes to get to the
	// invoking stop. The returned value is the number of
	// Model.DurationUnit units.
	TravelDurationValue() float64

	// Value returns the value of the expression for the stop as a float64.
	// If the stop is unplanned, the value has no semantic meaning.
	Value(expression ModelExpression) float64
}

A SolutionStop is a stop that is planned to be visited by a vehicle. It is part of a SolutionPlanUnit and is based on a ModelStop.

type SolutionStopGenerator added in v0.24.1

type SolutionStopGenerator interface {
	Next() SolutionStop
}

SolutionStopGenerator is an iterator of solution stops.

func NewSolutionStopGenerator added in v0.24.1

func NewSolutionStopGenerator(
	move SolutionMoveStops,
	startAtFirst bool,
	endAtLast bool,
) SolutionStopGenerator

NewSolutionStopGenerator return a solution stop iterator of a move. If startAtFirst is true, the first stop will be first stop of the vehicle. If endAtLast is true, the last stop will be the last stop of the vehicle.

For example adding sequence A, B in a sequence 1 -> 2 -> 3 -> 4 -> 5 -> 6 where A goes before 4 and B goes before 5 will generate the following solution stops: 3 -> A -> 4 -> B -> 5 If startsAtFirst is true, the solution stops will start with 1: 1 -> 2 -> 3 -> A -> 4 -> B -> 5 If endAtLast is also true, the solution stops will end with 6: 1 -> 2 -> 3 -> A -> 4 -> B -> 5 -> 6.

For example:

   generator := NewSolutionStopGenerator(move, false, true)

	  for solutionStop := generator.Next(); solutionStop != nil; solutionStop = generator.Next() {
		  // Do something with solutionStop
   }

type SolutionStopViolationCheck

type SolutionStopViolationCheck interface {
	// DoesStopHaveViolations returns true if the stop violates the constraint.
	// The stop is not allowed to be nil. The stop must be part of the solution.
	// This method is only called if CheckedAt returns AtEachStop.
	DoesStopHaveViolations(stop SolutionStop) bool
}

SolutionStopViolationCheck is the interface that will be invoked on every update of a planned solution stop. The method DoesStopHaveViolations will be called to check if the stop violates the constraint. If the method returns true the solution will not be accepted. If un-planning can result in a violation of the constraint one of the violation checks must be implemented.

type SolutionStops

type SolutionStops []SolutionStop

SolutionStops is a slice of SolutionStop.

type SolutionUnPlanObserver added in v1.0.4

type SolutionUnPlanObserver interface {
	// OnUnPlan is called when a planUnit is going to be un-planned.
	OnUnPlan(planUnit SolutionPlanStopsUnit)
	// OnUnPlanFailed is called when a planUnit has failed to be un-planned.
	OnUnPlanFailed(planUnit SolutionPlanStopsUnit)
	// OnUnPlanSucceeded is called when a planUnit has succeeded to be un-planned.
	OnUnPlanSucceeded(planUnit SolutionPlanStopsUnit)
}

SolutionUnPlanObserver is an interface that can be implemented to observe the plan units un-planning process.

type SolutionUnPlanObservers added in v1.0.4

type SolutionUnPlanObservers []SolutionUnPlanObserver

SolutionUnPlanObservers is a slice of SolutionUnPlanObserver.

type SolutionVehicle

type SolutionVehicle interface {
	// FirstMove creates a move that adds the given plan unit to the
	// vehicle after the first solution stop of the vehicle. The move is
	// first feasible move after the first solution stop based on the
	// estimates of the constraint, this move is not necessarily executable.
	FirstMove(SolutionPlanUnit) SolutionMove

	// BestMove returns the best move for the given solution plan unit on
	// the invoking vehicle. The best move is the move that has the lowest
	// score. If there are no moves available for the given solution plan
	// unit, a move is returned which is not executable, SolutionMoveStops.IsExecutable.
	BestMove(context.Context, SolutionPlanUnit) SolutionMove

	// Duration returns the duration of the vehicle. The duration is the
	// time the vehicle is on the road. The duration is the time between
	// the start time and the end time.
	Duration() time.Duration
	// DurationValue returns the duration value of the vehicle. The duration
	// value is the value of the duration of the vehicle. The duration value
	// is the value in model duration units.
	DurationValue() float64

	// End returns the end time of the vehicle. The end time is the time
	// the vehicle ends at the end stop.
	End() time.Time
	// EndValue returns the end value of the vehicle. The end value is the
	// value of the end of the last stop. The end value is the value in
	// model duration units since the model epoch.
	EndValue() float64

	// First returns the first stop of the vehicle. The first stop is the
	// start stop.
	First() SolutionStop

	// Index returns the index of the vehicle in the solution.
	Index() int
	// IsEmpty returns true if the vehicle is empty, false otherwise. A
	// vehicle is empty if it does not have any stops. The start and end
	// stops are not considered.
	IsEmpty() bool

	// Last returns the last stop of the vehicle. The last stop is the end
	// stop.
	Last() SolutionStop

	// ModelVehicle returns the modeled vehicle type of the vehicle.
	ModelVehicle() ModelVehicle

	// NumberOfStops returns the number of stops in the vehicle. The start
	// and end stops are not considered.
	NumberOfStops() int

	// SolutionStops returns the stops in the vehicle. The start and end
	// stops are included in the returned stops.
	SolutionStops() SolutionStops
	// Start returns the start time of the vehicle. The start time is
	// the time the vehicle starts at the start stop, it has been set
	// in the factory method of the vehicle Solution.NewVehicle.
	Start() time.Time
	// StartValue returns the start value of the vehicle. The start value
	// is the value of the start of the first stop. The start value is
	// the value in model duration units since the model epoch.
	StartValue() float64

	// Unplan removes all stops from the vehicle. The start and end stops
	// are not removed. Fixed stops are not removed.
	Unplan() (bool, error)
}

SolutionVehicle is a vehicle in a solution.

type SolutionVehicleViolationCheck

type SolutionVehicleViolationCheck interface {
	// DoesVehicleHaveViolations returns true if the vehicle violates the
	// constraint. The vehicle is not allowed to be nil. The vehicle must be
	// part of the solution. This method is only called if CheckedAt returns
	// AtEachVehicle.
	DoesVehicleHaveViolations(vehicle SolutionVehicle) bool
}

SolutionVehicleViolationCheck is the interface that will be invoked on every update of a last planned solution stop of a vehicle. The method DoesVehicleHaveViolations will be called to check if the vehicle violates the constraint. If the method returns true the solution will not be accepted. If un-planning can result in a violation of the constraint one of the violation checks must be implemented.

type SolutionVehicles

type SolutionVehicles []SolutionVehicle

SolutionVehicles is a slice of solution vehicles.

type SolutionViolationCheck

type SolutionViolationCheck interface {
	// DoesSolutionHaveViolations returns true if the solution violates the
	// constraint. The solution is not allowed to be nil. This method is only
	// called if CheckedAt returns AtEachSolution.
	DoesSolutionHaveViolations(solution Solution) bool
}

SolutionViolationCheck is the interface that will be invoked once all updates on a solution have been executed. The method DoesSolutionHaveViolations will be called to check if the vehicle violates the constraint. If the method returns true the solution will not be accepted. If un-planning can result in a violation of the constraint one of the violation checks must be implemented.

type Solutions

type Solutions []Solution

Solutions is a slice of solutions.

type SolveEvents added in v1.3.0

type SolveEvents struct {
	// ContextDone is fired when the context is done for any reason.
	ContextDone *events.BaseEvent1[SolveInformation]

	// Done is fired when the solver is done.
	Done *events.BaseEvent1[SolveInformation]

	// Iterated is fired when the solver has iterated.
	Iterated *events.BaseEvent1[SolveInformation]
	// Iterating is fired when the solver is iterating.
	Iterating *events.BaseEvent1[SolveInformation]

	// NewBestSolution is fired when a new best solution is found.
	NewBestSolution *events.BaseEvent1[SolveInformation]

	// OperatorExecuted is fired when a solve-operator has been executed.
	OperatorExecuted *events.BaseEvent1[SolveInformation]
	// OperatorExecuting is fired when a solve-operator is executing.
	OperatorExecuting *events.BaseEvent1[SolveInformation]

	// Reset is fired when the solver is reset.
	Reset *events.BaseEvent2[Solution, SolveInformation]

	// Start is fired when the solver is started.
	Start *events.BaseEvent1[SolveInformation]
}

SolveEvents is a struct that contains events that are fired during a solve invocation.

func NewSolveEvents added in v1.3.0

func NewSolveEvents() SolveEvents

NewSolveEvents creates a new instance of SolveEvents.

type SolveInformation added in v1.3.0

type SolveInformation interface {
	// DeltaScore returns the delta score of the last executed solve operator.
	DeltaScore() float64

	// Iteration returns the current iteration.
	Iteration() int

	// Solver returns the solver.
	Solver() Solver
	// SolveOperators returns the solve-operators that has been executed in
	// the current iteration.
	SolveOperators() SolveOperators
	// Start returns the start time of the solver.
	Start() time.Time
}

SolveInformation contains information about the current solve.

type SolveObserver added in v1.3.0

type SolveObserver interface {
	SolutionObserver
	SolutionUnPlanObserver

	// Register registers the solver to the solve observer.
	Register(solver Solver) error

	// FileName returns the file name of the solve observer.
	FileName() string
}

SolveObserver is an observer for the solve process.

func NewSolveObserver added in v1.3.0

func NewSolveObserver(fileName string) (SolveObserver, error)

NewSolveObserver returns a new solve observer. The solve observer can be used to observe the solve process. The solve observer writes to the given file name.

The solve observer writes the following columns: - The first column is the type of event. The type of event can be one of:

  • `+` for a plan event.

  • `-` for an unplan event.

  • `~` for a failed event.

  • `b` for a new best solution event.

  • 'o' for the objective definition event.

  • `r` for a reset event.

  • The second column is the time since the solve process started in nanoseconds.

  • The third column is the step. The step is used to group events together. The step is incremented for each unplan event.

  • The next columns are dependent on the event type.

  • For an objective definition event, the next columns are:

  • The number of terms of the objective.

  • For each term of the objective the factor and name of the objective.

  • For a plan event, the next columns are:

  • The previous stop ID.

  • The stop ID.

  • The next stop ID.

  • For each term of the objective the score

  • The score after planning.

  • The estimated impact on the objective of planning.

  • For an unplan event, the next columns are:

  • The previous stop ID.

  • The stop ID.

  • The next stop ID.

  • For each term of the objective the score

  • The score after un-planning.

  • For a failed event, the next column is the reason for the failure.

  • For a reset event, the next columns are:

  • The score of the work solution.

  • The score of the solution resetting to.

  • For a new best solution event, the next columns are:

  • For each term of the objective the score

  • Last column is the score of the new best solution

    To use the observer add it to the model the following way:

    solver, err := nextroute.NewSolver(model, solverOptions) solveObserver, err := observers.NewSolveObserver("solve.log") solveObserver.Register(solver)

type SolveOperator added in v1.3.0

type SolveOperator interface {
	// CanResultInImprovement returns true if the solve-operator can result in
	// an improvement compared to the best solution. The solver uses this
	// information to determine if the best solution should be replaced by
	// the new solution.
	CanResultInImprovement() bool

	// Execute executes the solve-operator. The Execute method is called by the
	// solver. The Execute method is passed a SolveInformation instance that
	// contains information about the current solution and the solver. The
	// Execute method should modify the current solution.
	Execute(context.Context, SolveInformation) error

	// Probability returns the probability of the solve-operator.
	// The probability is a value between 0 and 1. The solver uses the
	// probability to determine if the solve-operator should be executed in
	// the current iteration. Each iteration the solver will execute a
	// solve-operator with a probability equal to the probability of the
	// solve-operator. The probability is set by the SetProbability method.
	Probability() float64

	// SetProbability sets the probability of the solve-operator. Returns an
	// error if the probability is not in the range [0, 1].
	SetProbability(probability float64) error
	// Parameters returns the solve-parameters of the solve-operator.
	Parameters() SolveParameters
}

SolveOperator is a solve-operator. A solve-operator is a function that modifies the current solution. The function is executed with a certain probability. The probability is set by the SetProbability method. The probability is used by the solver to determine if the solve-operator should be executed. The probability is a value between 0 and 1. The manipulation of the solution is implemented in the Execute method. The Execute method will be invoked by the solver. The Execute method receives a SolveInformation instance that contains information about the current solution and the solver. The Execute method should modify the current solution. The Execute method should not modify the SolveInformation instance. The Execute method should not modify the SolveOperator instance.

func NewSolveOperator added in v1.3.0

func NewSolveOperator(
	probability float64,
	canResultInImprovement bool,
	parameters SolveParameters,
) SolveOperator

NewSolveOperator returns a new solve operator.

type SolveOperatorAnd added in v1.3.0

type SolveOperatorAnd interface {
	SolveOperator

	// Operators returns the solve-operators that will be executed in each
	// iteration.
	Operators() SolveOperators
}

SolveOperatorAnd is a solve-operator which executes a set of solve-operators in each iteration.

func NewSolverOperatorAnd added in v1.3.0

func NewSolverOperatorAnd(
	probability float64,
	operators SolveOperators,
) (SolveOperatorAnd, error)

NewSolverOperatorAnd creates a new solve-and-operator for nextroute.

type SolveOperatorOr added in v1.3.0

type SolveOperatorOr interface {
	SolveOperator

	// Operators returns the solve-operators one will be selected from in
	// each loop.
	Operators() SolveOperators
}

SolveOperatorOr is a solve-operator. A solver operator or is a solve-operator that executes n loops in each iteration of a solver. In each loop a random solve-operator is selected using the probability of the solve-operator. If there are 3 operators one with probability 0.1, one with probability 0.2 and one with probability 0.3 then the first operator has a 0.1/0.6 chance to be selected, the second operator has a 0.2/0.6 chance to be selected and the third operator has a 0.3/0.6 chance to be selected.

func NewSolverOperatorOr added in v1.3.0

func NewSolverOperatorOr(
	probability float64,
	operators SolveOperators,
) (SolveOperatorOr, error)

NewSolverOperatorOr creates a new solve-or-operator for nextroute.

type SolveOperatorPlan added in v1.3.0

type SolveOperatorPlan interface {
	SolveOperator

	// GroupSize returns the group size of the solve operator.
	GroupSize() SolveParameter
}

SolveOperatorPlan is a solve-operator that tries to plan all unplanned plan-units in each iteration. The group-size is a solve-parameter which can be configured by the user. Group-size determines how many random plan-units are selected for which the best move is determined. The best move is then executed. In one iteration of the solve run, the operator will continue to select a random group-size number of unplanned plan-units and execute the best move until all unplanned plan-units are planned or no more moves can be executed. In an unconstrained model all plan-units will be planned after one iteration of this operator.

func NewSolveOperatorPlan added in v1.3.0

func NewSolveOperatorPlan(
	groupSize SolveParameter,
) (SolveOperatorPlan, error)

NewSolveOperatorPlan creates a new solve operator for nextroute that plans units.

type SolveOperatorRestart added in v1.3.0

type SolveOperatorRestart interface {
	SolveOperator

	// MaximumIterations returns the maximum iterations of the solve operator.
	MaximumIterations() SolveParameter
}

SolveOperatorRestart is a solve operator that restarts the solver. The operator will set the working solution to the best solution found so far after MaximumIterations number of iterations without finding a better solution.

func NewSolveOperatorRestart added in v1.3.0

func NewSolveOperatorRestart(
	maximumIterations SolveParameter,
) (SolveOperatorRestart, error)

NewSolveOperatorRestart creates a new solve operator for nextroute that restarts the solver.

type SolveOperatorUnPlan added in v1.3.0

type SolveOperatorUnPlan interface {
	SolveOperator

	// NumberOfUnits returns the number of units of the solve operator.
	NumberOfUnits() SolveParameter
}

SolveOperatorUnPlan is a solve operator that un-plans units.

func NewSolveOperatorUnPlan added in v1.3.0

func NewSolveOperatorUnPlan(
	numberOfUnits SolveParameter,
) (SolveOperatorUnPlan, error)

NewSolveOperatorUnPlan creates a new solve operator for nextroute that un-plans units.

type SolveOperators added in v1.3.0

type SolveOperators []SolveOperator

SolveOperators is a slice of solve-operators.

type SolveOptions

type SolveOptions struct {
	Iterations int           `json:"iterations"  usage:"maximum number of iterations, -1 assumes no limit" default:"-1"`
	Duration   time.Duration `json:"duration"  usage:"maximum duration of solver in seconds" default:"30s"`
}

SolveOptions holds the options for the solve process.

type SolveOptionsFactory added in v1.3.0

type SolveOptionsFactory func(
	information ParallelSolveInformation,
) (SolveOptions, error)

SolveOptionsFactory is a factory type for creating new solve options. This factory is used by the parallel solver to create new solve options for a new run of a solver.

func DefaultSolveOptionsFactory added in v1.3.0

func DefaultSolveOptionsFactory() SolveOptionsFactory

DefaultSolveOptionsFactory creates a new SolveOptionsFactory. This factory is used by the parallel solver to create new solve options for a new run of a solver within the parallel solver. The default will limit the run to a random draw in the range [200, 2000] iterations and 30 seconds.

func NewSolveOptionsFactory added in v1.3.0

func NewSolveOptionsFactory(iterations int, duration time.Duration) SolveOptionsFactory

NewSolveOptionsFactory creates a new SolveOptionsFactory which is independent of the state of the parallel solver. This factory will produce SolveOptions which limit a search run in a cycle to the given number of iterations and duration.

type SolveParameter added in v1.3.0

type SolveParameter interface {
	// Update updates the parameter based on the given solve information.
	// Update is invoked after each iteration of the solver.
	Update(SolveInformation)

	// Value returns the current value of the parameter.
	Value() int
}

SolveParameter is an interface for a parameter that can change during the solving. The parameter can be used to control the behavior of the solver and it's operators.

func NewConstSolveParameter added in v1.3.0

func NewConstSolveParameter(value int) SolveParameter

NewConstSolveParameter creates a new constant solve parameter for nextroute. A const solve parameter is a parameter that does not change during the solving. SolveParameter.Value will always return the same value.

func NewSolveParameter added in v1.3.0

func NewSolveParameter(
	startValue int,
	deltaAfterIterations int,
	delta int,
	minValue int,
	maxValue int,
	snapBackAfterImprovement bool,
	zigzag bool,
) (SolveParameter, error)

NewSolveParameter creates a new solve parameter for nextroute. A solve parameter is a parameter that can change during the solving. The parameter can be used to control the behavior of the solver and it's operators. This solve-parameter will change its value after a given number of iterations. The parameter will change its value by a given delta. The parameter will never be smaller than the given min value and never be bigger than the given max value. If snapBackAfterImprovement is true the parameter will snap back to the start value after an improvement of the best solution. If zigzag is true the parameter will zigzag between min and max value like a jig saw.

type SolveParameters added in v1.3.0

type SolveParameters []SolveParameter

SolveParameters is a slice of solve parameters.

type Solver

type Solver interface {
	Progressioner
	// AddSolveOperators adds a number of solve-operators to the solver.
	AddSolveOperators(...SolveOperator)

	// BestSolution returns the best solution found so far.
	BestSolution() Solution

	// HasBestSolution returns true if the solver has a best solution.
	HasBestSolution() bool
	// HasWorkSolution returns true if the solver has a work solution.
	HasWorkSolution() bool

	// Model returns the model used by the solver.
	Model() Model

	// Random returns the random number generator used by the solver.
	Random() *rand.Rand
	// Reset will reset the solver to use solution as work solution.
	Reset(solution Solution, solveInformation SolveInformation)

	// Solve starts the solving process using the given options. It returns the
	// solutions as a channel.
	Solve(context.Context, SolveOptions, ...Solution) (SolutionChannel, error)
	// SolveEvents returns the solve-events used by the solver.
	SolveEvents() SolveEvents
	// SolveOperators returns the solve-operators used by the solver.
	SolveOperators() SolveOperators

	// WorkSolution returns the current work solution.
	WorkSolution() Solution
}

Solver is the interface for the Adaptive Local Neighborhood Search algorithm (ALNS) solver.

func NewSkeletonSolver added in v1.3.0

func NewSkeletonSolver(model Model) (Solver, error)

NewSkeletonSolver creates a new solver for nextroute.

func NewSolver

func NewSolver(
	model Model,
	options SolverOptions,
) (Solver, error)

NewSolver creates a new solver. The solver can be used to solve a solution. The solution passed to the solver is the starting point of the solver. The solver will try to improve the solution.

type SolverFactory

type SolverFactory func(
	information ParallelSolveInformation,
	solution Solution) (Solver, error)

SolverFactory is a factory type for creating new solver. This factory is used by the parallel solver to create new solver for a new run.

func DefaultSolverFactory added in v1.3.0

func DefaultSolverFactory() SolverFactory

DefaultSolverFactory creates a new SolverFactory.

type SolverOptions

type SolverOptions struct {
	Unplan  IntParameterOptions `json:"unplan"  usage:"unplan parameter"`
	Plan    IntParameterOptions `json:"plan"  usage:"plan parameter"`
	Restart IntParameterOptions `json:"restart"  usage:"restart parameter"`
}

SolverOptions are the options for the solver and it's operators.

type StopDurationExpression

type StopDurationExpression interface {
	DurationExpression
	// SetDuration sets the duration for the given stop.
	SetDuration(ModelStop, time.Duration)
}

StopDurationExpression is a ModelExpression that returns a duration per stop and allows to set the duration per stop.

func NewStopDurationExpression

func NewStopDurationExpression(
	name string,
	duration time.Duration,
) StopDurationExpression

NewStopDurationExpression creates a new duration expression.

type StopExpression

type StopExpression interface {
	DefaultExpression

	// SetValue sets the value of the expression for the given to stop.
	SetValue(
		stop ModelStop,
		value float64,
	)
}

StopExpression is an expression that has a value for each to stop.

func NewStopExpression

func NewStopExpression(
	name string,
	defaultValue float64,
) StopExpression

NewStopExpression returns an expression whose value is based on the to stop in Value method. Expression values are calculated by calling the expression's Value method which takes a vehicle type, a from stop and a to stop as arguments.

type StopPosition

type StopPosition interface {
	// Previous denotes the upcoming stop's previous stop if the associated move
	// involving the stop position is executed. It's worth noting that
	// the previous stop may not have been planned yet.
	Previous() SolutionStop

	// Next denotes the upcoming stop's next stop if the associated move
	// involving the stop position is executed. It's worth noting that
	// the next stop may not have been planned yet.
	Next() SolutionStop

	// Stop returns the stop which is not yet part of the solution. This stop
	// is not planned yet if the move where the invoking stop position belongs
	// to, has not been executed yet.
	Stop() SolutionStop
}

StopPosition is the definition of the change in the solution for a specific stop. The change is defined by a Next and a Stop. The Next is a stop which is already part of the solution (it is planned) and the Stop is a stop which is not yet part of the solution (it is not planned). A stop position states that the stop should be moved from the unplanned set to the planned set by positioning it directly before the Next.

type StopPositions

type StopPositions []StopPosition

StopPositions is a slice of stop positions.

type StopPositionsHint

type StopPositionsHint interface {
	// HasNextStopPositions returns true if the hint contains next positions.
	HasNextStopPositions() bool

	// NextStopPositions returns the next positions.
	NextStopPositions() StopPositions

	// SkipVehicle returns true if the solver should skip the vehicle. The
	// solver will use the hint if it is available.
	SkipVehicle() bool
}

StopPositionsHint is an interface that can be used to give a hint to the solver about the next stop position. This can be used to speed up the solver. The solver will use the hint if it is available. Hints are generated by the estimate function of a constraint.

func NoPositionsHint

func NoPositionsHint() StopPositionsHint

NoPositionsHint returns a new StopPositionsHint that does not skip the vehicle and does not contain a next stop. The solver will try to find the next stop.

func SkipVehiclePositionsHint

func SkipVehiclePositionsHint() StopPositionsHint

SkipVehiclePositionsHint returns a new StopPositionsHint that skips the vehicle.

type StopTimeExpression

type StopTimeExpression interface {
	ModelExpression
	// Time returns the time for the given stop.
	Time(stop ModelStop) time.Time
	// SetTime sets the time for the given stop.
	SetTime(ModelStop, time.Time)
}

StopTimeExpression is a ModelExpression that returns a time per stop and allows to set the time per stop.

func NewStopTimeExpression

func NewStopTimeExpression(
	name string,
	time time.Time,
) StopTimeExpression

NewStopTimeExpression creates a new duration expression.

type SumExpression

type SumExpression interface {
	ModelExpression

	// AddExpression adds an expression to the sum.
	AddExpression(expression ModelExpression)

	// Expressions returns the expressions that are part of the sum.
	Expressions() ModelExpressions
}

SumExpression is an expression that returns the sum of the values of the given expressions.

func NewSumExpression

func NewSumExpression(expressions ModelExpressions) SumExpression

NewSumExpression returns a new SumExpression that calculates the sum of the values of the given expressions.

type TemporalReference added in v0.23.1

type TemporalReference int

TemporalReference is a representation of OnArrival, OnEnd or OnStart as an enum.

const (
	// OnStart refers to the Start at a stop.
	OnStart TemporalReference = iota
	// OnEnd refers to the End at a stop.
	OnEnd
	// OnArrival refers to the Arrival at a stop.
	OnArrival = 2
)

type TermExpression

type TermExpression interface {
	ModelExpression

	// Expression returns the expression.
	Expression() ModelExpression

	// Factor returns the factor.
	Factor() float64
}

TermExpression is an expression that returns the product of the given factor and the value of the given expression.

func NewTermExpression

func NewTermExpression(
	factor float64,
	expression ModelExpression,
) TermExpression

NewTermExpression returns a new TermExpression that calculates the product of the given factor and the value of the given expression.

type TimeDependentDurationExpression added in v0.23.1

type TimeDependentDurationExpression interface {
	DurationExpression

	// DefaultExpression returns the default expression.
	DefaultExpression() DurationExpression

	// IsDependentOnTime returns true if the expression is dependent on time.
	// The expression is dependent on time if the expression is not the same
	// for all time intervals.
	IsDependentOnTime() bool

	// SatisfiesTriangleInequality returns true if the expression satisfies
	// the triangle inequality. The triangular inequality states that for any
	// three points A, B, and C, the distance from A to C cannot be greater
	// than the sum of the distances from A to B and from B to C.
	SatisfiesTriangleInequality() bool

	// SetExpression sets the expression for the given time interval
	// [start, end). If the interval overlaps with an existing interval,
	// the existing interval is replaced. Both start and end must be on the
	// minute boundary. Expression is not allowed to contain negative values.
	SetExpression(start, end time.Time, expression DurationExpression) error

	// SetSatisfiesTriangleInequality sets whether the expression satisfies
	// the triangle inequality. The triangular inequality states that for any
	// three points A, B, and C, the distance from A to C cannot be greater
	// than the sum of the distances from A to B and from B to C.
	SetSatisfiesTriangleInequality(satisfies bool)

	// Expressions returns all expressions defined to be valid in a time
	// interval. The returned slice is a defensive copy of the internal slice,
	// so modifying it will not affect the collection.
	Expressions() []DurationExpression

	// ExpressionAtTime returns the expression for the given time.
	ExpressionAtTime(time.Time) DurationExpression
	// ExpressionAtValue returns the expression for the given value.
	ExpressionAtValue(float64) DurationExpression

	// ValueAtTime returns the value for the given time.
	ValueAtTime(
		time time.Time,
		vehicleType ModelVehicleType,
		from, to ModelStop,
	) float64
	// ValueAtValue returns the value for the given value.
	ValueAtValue(
		value float64,
		vehicleType ModelVehicleType,
		from, to ModelStop,
	) float64
}

TimeDependentDurationExpression is a DurationExpression that returns a value based on time on top of a base expression.

func NewTimeDependentDurationExpression added in v0.23.1

func NewTimeDependentDurationExpression(
	model Model,
	defaultExpression DurationExpression,
) (TimeDependentDurationExpression, error)

NewTimeDependentDurationExpression creates a TimeDependentDurationExpression, which takes a default expression as input. This default expression is used when the time is not within any of the intervals set by the SetExpression method.

The [TimeDependentDurationExpression.SetExpression] method can be used to define expressions for intervals of time, which are inclusive of the start time and exclusive of the end time. For example, if the interval is [9:30, 10:30), the expression is valid for all times from 9:30 up to (but not including) 10:30. Note that the interval must be on the minute boundary, and the start time must be before the end time.

The overall interval defined by the minimum of all start times and the maximum of all end times cannot exceed more than one week. The default expression is used for all times that go outside the defined intervals and may not contain any negative values.

func NewTimeIndependentDurationExpression added in v0.23.1

func NewTimeIndependentDurationExpression(
	expression DurationExpression,
) TimeDependentDurationExpression

NewTimeIndependentDurationExpression creates a TimeDependentDurationExpression which is not dependent on time. This expression has the same interface as the time dependent expression but the time is not used in any of the calculations. All values originate from the base expression.

type TimeExpression

type TimeExpression interface {
	ModelExpression
	// Time returns the time for the given parameters.
	Time(ModelVehicleType, ModelStop, ModelStop) time.Time
}

TimeExpression is a ModelExpression that returns a time.

func NewTimeExpression

func NewTimeExpression(
	expression ModelExpression,
	epoch time.Time,
) TimeExpression

NewTimeExpression creates a new time expression.

type TravelDurationExpression

type TravelDurationExpression interface {
	DurationExpression
	// DistanceExpression returns the distance expression.
	DistanceExpression() DistanceExpression
	// Speed returns the speed.
	Speed() common.Speed
}

TravelDurationExpression is an expression that returns a duration based on a distance and a speed.

func NewTravelDurationExpression

func NewTravelDurationExpression(
	distanceExpression DistanceExpression,
	speed common.Speed,
) TravelDurationExpression

NewTravelDurationExpression creates a new travel duration expression.

type TravelDurationObjective

type TravelDurationObjective interface {
	ModelObjective
}

TravelDurationObjective is an objective that uses the travel duration as an objective.

func NewTravelDurationObjective

func NewTravelDurationObjective() TravelDurationObjective

NewTravelDurationObjective returns a new TravelDurationObjective that uses the travel duration as an objective.

type UnPlannedObjective

type UnPlannedObjective interface {
	ModelObjective
}

UnPlannedObjective is an objective that uses the un-planned stops as an objective. Each unplanned stop is scored by the given expression.

func NewUnPlannedObjective

func NewUnPlannedObjective(expression StopExpression) UnPlannedObjective

NewUnPlannedObjective returns a new UnPlannedObjective that uses the un-planned stops as an objective. Each unplanned stop is scored by the given expression.

type VehicleFromToExpression

type VehicleFromToExpression interface {
	DefaultExpression

	// SetValue sets the value of the expression for the given vehicle type,
	// from and to stops.
	SetValue(
		vehicle ModelVehicleType,
		from ModelStop,
		to ModelStop,
		value float64,
	)
}

VehicleFromToExpression is an expression that has a value for each combination of vehicle type, from and to stop.

func NewVehicleTypeFromToExpression

func NewVehicleTypeFromToExpression(
	name string,
	defaultValue float64,
) VehicleFromToExpression

NewVehicleTypeFromToExpression returns an expression whose value is based on the vehicle type, from and to stops in Value method. Expression values are calculated by calling the expression's Value method which takes a vehicle type, a from stop and a to stop as arguments.

type VehicleStatistics

type VehicleStatistics interface {
	// FirstToLastSeconds returns the travel time from the first location to the
	// last location of a vehicle.
	FirstToLastSeconds() float64
	// FromFirstSeconds returns the travel time in seconds from the first
	// location to all stops as statistics.
	FromFirstSeconds() common.Statistics

	// Report returns a report of the statistics.
	Report() string

	// ToLastSeconds returns the travel time in seconds from all stops to the
	// last location as statistics.
	ToLastSeconds() common.Statistics
}

VehicleStatistics provides statistics for a vehicle.

func NewVehicleStatistics

func NewVehicleStatistics(vehicle ModelVehicle) VehicleStatistics

NewVehicleStatistics creates a new VehicleStatistics instance.

type VehicleTypeDistanceExpression added in v0.23.2

type VehicleTypeDistanceExpression interface {
	DistanceExpression
	VehicleTypeExpression

	SetDistance(ModelVehicleType, common.Distance)
	DistanceForVehicleType(ModelVehicleType) common.Distance
}

VehicleTypeDistanceExpression is an expression that returns a distance per vehicle type and allows to set the duration per vehicle.

func NewVehicleTypeDistanceExpression added in v0.23.2

func NewVehicleTypeDistanceExpression(
	name string,
	defaultValue common.Distance,
) VehicleTypeDistanceExpression

NewVehicleTypeDistanceExpression returns a NewVehicleTypeDistanceExpression whose value is based on the vehicle type in Value method and expresses a distance. Expression values are calculated by calling the expression's Value method which takes a vehicle type, a from stop and a to stop as arguments.

type VehicleTypeDurationExpression

type VehicleTypeDurationExpression interface {
	DurationExpression
	VehicleTypeExpression
	// SetDuration sets the duration for the given vehicle type.
	SetDuration(ModelVehicleType, time.Duration)
	DurationForVehicleType(ModelVehicleType) time.Duration
}

VehicleTypeDurationExpression is a ModelExpression that returns a duration per vehicle type and allows to set the duration per vehicle type.

func NewVehicleTypeDurationExpression

func NewVehicleTypeDurationExpression(
	name string,
	duration time.Duration,
) VehicleTypeDurationExpression

NewVehicleTypeDurationExpression creates a new duration expression.

type VehicleTypeExpression

type VehicleTypeExpression interface {
	DefaultExpression
	ValueForVehicleType(ModelVehicleType) float64
}

VehicleTypeExpression is the base expression for VehicleTypeExpressions.

type VehicleTypeValueExpression added in v0.23.2

type VehicleTypeValueExpression interface {
	VehicleTypeExpression
	// SetValue sets the value of the expression for the given vehicle type.
	SetValue(
		vehicle ModelVehicleType,
		value float64,
	)
}

VehicleTypeValueExpression is a ModelExpression that returns a value per vehicle type and allows to set the value per vehicle type.

func NewVehicleTypeExpression

func NewVehicleTypeExpression(
	name string,
	defaultValue float64,
) VehicleTypeValueExpression

NewVehicleTypeExpression returns a VehicleTypeExpression whose value is based on the vehicle type in Value method. Expression values are calculated by calling the expression's Value method which takes a vehicle type, a from stop and a to stop as arguments.

type VehiclesDurationObjective added in v0.26.0

type VehiclesDurationObjective interface {
	ModelObjective
}

VehiclesDurationObjective is an objective that uses the vehicle duration as an objective.

func NewVehiclesDurationObjective added in v0.26.0

func NewVehiclesDurationObjective() VehiclesDurationObjective

NewVehiclesDurationObjective returns a new VehiclesDurationObjective that uses the vehicle duration as an objective.

type VehiclesObjective

type VehiclesObjective interface {
	ModelObjective
	// ActivationPenalty returns the activation penalty expression.
	ActivationPenalty() VehicleTypeExpression
}

VehiclesObjective is an objective that uses the number of vehicles as an objective. Each vehicle that is not empty is scored by the given expression. A vehicle is empty if it has no stops assigned to it (except for the first and last visit).

func NewVehiclesObjective

func NewVehiclesObjective(expression VehicleTypeExpression) VehiclesObjective

NewVehiclesObjective returns a new VehiclesObjective that uses the number of vehicles as an objective. Each vehicle that is not empty is scored by the given expression. A vehicle is empty if it has no stops assigned to it (except for the first and last visit).

Source Files

Directories

Path Synopsis
Package check provides a plugin that allows you check models and solutions.
Package check provides a plugin that allows you check models and solutions.
Package common contains common types and functions used by the nextroute.
Package common contains common types and functions used by the nextroute.
Package factory is a package containing factory functions for creating next-route models.
Package factory is a package containing factory functions for creating next-route models.
Package schema provides the input and output schema for nextroute.
Package schema provides the input and output schema for nextroute.

Jump to

Keyboard shortcuts

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