LotSizingDataModel.Solver 2.1.0
Solver-independent modeling, execution, monitoring and adapter infrastructure.
Loading...
Searching...
No Matches
PhysicalFleetFormulation.cs
Go to the documentation of this file.
1using LotSizingDataModel.Core.PhysicalModel;
2using LotSizingDataModel.Instance;
6
8
9internal static class PhysicalFleetFormulation
10{
11 private readonly record struct Site(WarehouseReferenceKind Kind, int Id)
12 {
13 internal Site(WarehouseReference reference) : this(reference.Kind, reference.ReferenceId) { }
14 public override string ToString() => $"{(int)Kind}_{Id}";
15 }
16
17 private sealed record Trip(Site Origin, Site Destination, int Duration, AssignedTransportLane? Lane, decimal Cost)
18 {
19 internal string Label => Lane is null ? $"empty_{Origin}_{Destination}" : $"loaded_l{Lane.Id}";
20 }
21
22 private static bool Enabled(LotSizingInstance instance, StandardLotSizingFormulationOptions options) =>
23 options.IncludeTransport && instance.SupplyChain.TransportResources.Any(resource => resource.PhysicalFleet is not null);
24
25 private static IEnumerable<Trip> Trips(LotSizingInstance instance, TransportResource resource, PhysicalTransportFleet fleet)
26 {
27 foreach (var lane in instance.SupplyChain.GetTransportLanes(resource.Id))
28 yield return new(new(lane.Origin), new(lane.Destination), lane.LeadTime, lane, 0);
29 foreach (var move in fleet.EmptyMovements)
30 yield return new(new(move.Origin!), new(move.Destination!), move.Duration, null, move.CostPerVehicle ?? 0);
31 }
32
33 private static string Key(TransportResource resource, string label, int period) =>
34 $"fleet_r{resource.Id}_{label}_t{period}";
35
36 private static string DomainKey(string name) => $"{MathematicalDecisionCategory.PhysicalFleet}|coordinate={name}";
37
38 private static string FlowKey(TransportResource resource, AssignedTransportLane lane, int item, int period)
39 {
44 return key.Add(MathematicalDomainKeySegment.Period, period).Build();
45 }
46
48 {
49 public override string FamilyId => "physicalFleet";
50 public override bool IsEnabled(LotSizingInstance instance, StandardLotSizingFormulationOptions options) => Enabled(instance, options);
51 protected override ValueTask BuildFamilyAsync(LotSizingInstance instance, MathematicalModelBuildContext context,
52 StandardLotSizingFormulationOptions options, CancellationToken cancellationToken)
53 {
54 foreach (var resource in instance.SupplyChain.TransportResources)
55 {
56 if (resource.PhysicalFleet is not { } fleet) continue;
57 var trips = Trips(instance, resource, fleet).ToArray();
58 var sites = trips.SelectMany(trip => new[] { trip.Origin, trip.Destination })
59 .Concat(fleet.InitialAllocation.Select(row => new Site(row.Warehouse!))).Distinct().ToArray();
60 for (var period = 1; period <= instance.PlanningHorizon; period++)
61 {
62 cancellationToken.ThrowIfCancellationRequested();
63 foreach (var label in trips.Select(trip => trip.Label).Concat(sites.Select(site => $"stock_{site}")))
64 {
65 var key = Key(resource, label, period);
66 context.AddVariable(key, DomainKey(key), MathematicalVariableType.Integer, 0, fleet.VehicleCount);
67 }
68 }
69 }
70 return ValueTask.CompletedTask;
71 }
72 }
73
75 {
76 public override string ConstraintFamilyId => "physicalFleet";
77 public override bool IsEnabled(LotSizingInstance instance, StandardLotSizingFormulationOptions options) => Enabled(instance, options);
78 protected override ValueTask BuildConstraintsAsync(LotSizingInstance instance, MathematicalModelBuildContext context,
79 StandardLotSizingFormulationOptions options, CancellationToken cancellationToken)
80 {
81 foreach (var resource in instance.SupplyChain.TransportResources)
82 {
83 if (resource.PhysicalFleet is not { } fleet) continue;
84 var trips = Trips(instance, resource, fleet).ToArray();
85 var initial = fleet.InitialAllocation.ToDictionary(row => new Site(row.Warehouse!), row => row.Count);
86 var sites = trips.SelectMany(trip => new[] { trip.Origin, trip.Destination }).Concat(initial.Keys).Distinct().ToArray();
87 var outbound = trips.ToLookup(trip => trip.Origin);
88 var inbound = trips.ToLookup(trip => trip.Destination);
89 var characteristics = instance.SupplyChain.TransportCharacteristics.Where(item => item.TransportResourceId == resource.Id).ToArray();
90 for (var period = 1; period <= instance.PlanningHorizon; period++)
91 {
92 cancellationToken.ThrowIfCancellationRequested();
93 foreach (var trip in trips)
94 {
95 if (trip.Lane is not { } lane) continue;
96 var charge = new LinearExpressionBuilder();
97 foreach (var item in characteristics)
98 {
99 var consumption = item.UnitCapacityConsumption?[period] ?? 1;
100 if (consumption <= 0)
101 throw new InvalidOperationException($"La flotte {resource.Id} exige une consommation de capacité positive pour l’article {item.ItemId}, période {period}.");
102 charge.Add(context.GetVariable(FlowKey(resource, lane, item.ItemId, period)), consumption);
103 }
104 charge.Subtract(context.GetVariable(DomainKey(Key(resource, trip.Label, period))), (double)fleet.CapacityPerVehicle);
105 AddConstraint(context, Key(resource, $"load_l{lane.Id}", period), charge.Build(),
106 MathematicalConstraintSense.LessThanOrEqual, 0);
107 }
108
109 foreach (var site in sites)
110 {
111 var available = new LinearExpressionBuilder();
112 var balance = new LinearExpressionBuilder();
113 var opening = period == 1 ? initial.GetValueOrDefault(site) : 0;
114 if (period > 1)
115 {
116 var previous = context.GetVariable(DomainKey(Key(resource, $"stock_{site}", period - 1)));
117 available.Subtract(previous);
118 balance.Subtract(previous);
119 }
120 foreach (var trip in outbound[site])
121 {
122 var departure = context.GetVariable(DomainKey(Key(resource, trip.Label, period)));
123 available.Add(departure);
124 balance.Add(departure);
125 }
126 foreach (var trip in inbound[site])
127 {
128 if (trip.Duration >= period) continue;
129 var arrival = context.GetVariable(DomainKey(Key(resource, trip.Label, period - trip.Duration)));
130 balance.Subtract(arrival);
131 // Zero-delay trips arrive in this period but cannot finance another departure in it.
132 if (trip.Duration > 0) available.Subtract(arrival);
133 }
134 balance.Add(context.GetVariable(DomainKey(Key(resource, $"stock_{site}", period))));
135 AddConstraint(context, Key(resource, $"balance_{site}", period), balance.Build(),
136 MathematicalConstraintSense.Equal, opening);
137 if (outbound[site].Any())
138 AddConstraint(context, Key(resource, $"available_{site}", period), available.Build(),
139 MathematicalConstraintSense.LessThanOrEqual, opening);
140 }
141 }
142 }
143 return ValueTask.CompletedTask;
144 }
145 }
146
148 {
149 public override string TermFamilyId => "physicalFleetEmptyTripCost";
150 public override bool IsEnabled(LotSizingInstance instance, StandardLotSizingFormulationOptions options) => Enabled(instance, options);
151 protected override ValueTask BuildTermsAsync(LotSizingInstance instance, MathematicalModelBuildContext context,
152 LinearExpressionBuilder expressionBuilder, StandardLotSizingFormulationOptions options, CancellationToken cancellationToken)
153 {
154 foreach (var resource in instance.SupplyChain.TransportResources)
155 {
156 if (resource.PhysicalFleet is not { } fleet) continue;
157 foreach (var trip in Trips(instance, resource, fleet).Where(trip => trip.Cost > 0))
158 for (var period = 1; period <= instance.PlanningHorizon; period++)
159 {
160 cancellationToken.ThrowIfCancellationRequested();
161 AddCostTerm(context, expressionBuilder, DomainKey(Key(resource, trip.Label, period)), (double)trip.Cost);
162 }
163 }
164 return ValueTask.CompletedTask;
165 }
166 }
167}
Provides a fluent builder for linear expressions.
Builds stable business-domain keys for mathematical variables and constraints.
MathematicalDomainKeyBuilder Add(string name, string value)
Adds a text segment.
Provides the shared state required while constructing a solver-independent mathematical model.
override ValueTask BuildConstraintsAsync(LotSizingInstance instance, MathematicalModelBuildContext context, StandardLotSizingFormulationOptions options, CancellationToken cancellationToken)
override string ConstraintFamilyId
Gets the unique identifier of the constraint family.
override bool IsEnabled(LotSizingInstance instance, StandardLotSizingFormulationOptions options)
Determines whether this constraint family is enabled.
override string TermFamilyId
Gets the unique identifier of the objective-term family.
override ValueTask BuildTermsAsync(LotSizingInstance instance, MathematicalModelBuildContext context, LinearExpressionBuilder expressionBuilder, StandardLotSizingFormulationOptions options, CancellationToken cancellationToken)
override bool IsEnabled(LotSizingInstance instance, StandardLotSizingFormulationOptions options)
Determines whether this objective-term family is enabled.
override ValueTask BuildFamilyAsync(LotSizingInstance instance, MathematicalModelBuildContext context, StandardLotSizingFormulationOptions options, CancellationToken cancellationToken)
override bool IsEnabled(LotSizingInstance instance, StandardLotSizingFormulationOptions options)
Determines whether this variable family is enabled for the supplied instance and formulation options.
override string FamilyId
Gets the unique identifier of the variable family.
Creates canonical domain-key fragments shared by standard formulation builders and provides warehouse...
static MathematicalDomainKeyBuilder AddDestinationWarehouse(MathematicalDomainKeyBuilder builder, WarehouseReference warehouse)
Adds a destination warehouse reference.
static MathematicalDomainKeyBuilder AddOriginWarehouse(MathematicalDomainKeyBuilder builder, WarehouseReference warehouse)
Adds an origin warehouse reference.
Provides common validation and helper methods for one constraint family of the standard lot-sizing fo...
static void AddConstraint(MathematicalModelBuildContext context, string name, LinearExpression expression, MathematicalConstraintSense sense, double rightHandSide, string domainKey="", string description="")
Adds one linear constraint to the mathematical model.
Configures the standard solver-independent mixed-integer lot-sizing formulation.
Provides common validation and helper methods for one objective-term family of the standard lot-sizin...
static void AddCostTerm(MathematicalModelBuildContext context, LinearExpressionBuilder expressionBuilder, string domainKey, double coefficient)
Adds one variable cost term to the shared objective.
Provides common validation and variable-registration helpers for one variable family of the standard ...
Provides the canonical mathematical domain-key categories used to identify lot-sizing decision famili...
const string Transport
Identifies transported-quantity decision variables.
Provides the canonical mathematical domain-key segment names used by lot-sizing variables and constra...
const string TransportResource
Transport-resource identifier segment.
MathematicalConstraintSense
Identifies the relational sense of a mathematical constraint.
MathematicalVariableType
Identifies the domain of a mathematical decision variable.