haorenhui
2023-10-30 6d6cc10d9e8e242661da7fd655dec155a09d676c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
Quintiq file version 2.0
#parent: #root
Method FreezeZeroSlack (
  CapacityPlanningSuboptimizer_CapacityPlanningAlgorithm program,
  Boolean isunfreeze,
  const RunContextForCapacityPlanning runcontext,
  LibOpt_Scope scope
)
{
  Description:
  [*
    Check whether all slack variables of a certain type are zero after the first strategy level ( which only contains hard constraints ).
    If so, these slack variables can be frozen at zero as there is no longer a risk of an infeasible solution.
  *]
  TextBody:
  [*
    start := OS::PrecisionCounter(); 
    weightlevels := runcontext.WeightLevelNonFinancial(); 
    // Inactivate the DemandSlack if it is zero. The DemandSlack indicates an infeasibility in the balance constraint.
    // Even if the total slack is not zero, we still want to freeze all DemandSlacks that are zero
    // If we do not freeze them, the model after the CPLEX presolve will be much bigger and the optimization will take much longer
    justoptimizedhiddenslacklevel := this.CurrentSubOptimizerLevel().IsFirst();  
    
    nextlevelafterzero := this.FirstSubOptimizerLevel().NextSubOptimizerLevel().LevelNumber(); 
    debuginfo( 'Action:', ifexpr( isunfreeze, 'un-freezing slack variables', 'freezing slack variables' ) ); 
    debuginfo(  'next level after hidden slack = ', nextlevelafterzero ); 
    metaisskiplevelone := nextlevelafterzero > 1; // in below we only fix level 1 goals. So if we skip then ok to fix after level 0
    fixformeta := ( metaisskiplevelone and justoptimizedhiddenslacklevel ) 
                         or ( not metaisskiplevelone and this.CurrentSubOptimizerLevel().LevelNumber() = 1 ); 
                   
    lookforfixlevelone := ( not runcontext.IsMetaIteration() and this.CurrentSubOptimizerLevel().LevelNumber() = 1)
                            or ( runcontext.IsMetaIteration() and fixformeta ); 
    
    pispipsinrun := constnull( ProductInStockingPointInPeriodPlannings, constcontent ); 
    if ( justoptimizedhiddenslacklevel or lookforfixlevelone ) 
    {
      pispipsinrun := scope.GetPISPIPInOptimizerRun(); 
    }
    
    if ( justoptimizedhiddenslacklevel or isunfreeze ) // unfreeze used for sliding windows
    {
      count := 0; 
      varcount := 0;
      traverse( pispipsinrun, Elements.astype( ProductInStockingPointInPeriodPlanningLeaf ), pispip)
      {
        varcount++; 
        demandslackvar := program.DemandSlackVariables().Get( pispip );
        if( demandslackvar.OptimalValue()  < this.SmallestFeasibilityTolerance() )
        {
          this.FreezeZeroSlackVarUpperBound( demandslackvar, isunfreeze );
          count++; 
        }
      }
      debuginfo(  ifexpr( isunfreeze, 'un-', '' ), 'frozen nr of DemandSlack variables:', count, '/', varcount, '(', guard( 100* count/varcount, 0.0).Round( 2 ), '%)' ); 
    
      // Inactivate the maturation slacks
      traverse( pispipsinrun, Elements, pispip,
                pispip.ProductInStockingPoint_MP().IsOptShelfLife() 
                and pispip.ProductInStockingPoint_MP().Product_MP().HasMaturation() 
              )
      {
        traverse( pispip, ProductInStockingPoint_MP.OutgoingShelfLifeDay, oslday ) 
        {
          maturationslackvar := program.MaturationSlackVariables().Get( pispip, oslday ); 
          if( maturationslackvar.OptimalValue() < this.SmallestFeasibilityTolerance() )
          {
            this.FreezeZeroSlackVarUpperBound( maturationslackvar, isunfreeze ); 
          }
        }
      }
        
      // Inactivate the OperationInputGroup slacks if the TotalSlack is zero
      if( program.TotalSlackVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
      {
        traverse( scope.GetOperationInputGroupInOptimizerRunConst(), Elements, group )
        {
          operation := group.Operation();
          periods := this.GetPeriodsForOperation( scope, operation )
      
          traverse( periods, Elements, period )
          {
            traverse( group, OperationInput, input, input.GetIsProductInOptimizerRun( runcontext.IsPostProcessing() ) )
            {
              this.FreezeZeroSlackVarUpperBound( program.OperationInputGroupOverVariables().Get( input, period ), isunfreeze );
              this.FreezeZeroSlackVarUpperBound( program.OperationInputGroupUnderVariables().Get( input, period ), isunfreeze );
            }
          }
        }
      }
      
      // Inactivate the OperationInputSet slacks if the TotalSlack is zero
      if( program.TotalSlackVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
      {
        traverse( scope.GetOperationInputSetInOptimizerRunConst(), Elements, set )
        {
          operation := set.Operation();
          periods := this.GetPeriodsForOperation( scope, operation );
      
          traverse( periods, Elements, period )
          {
            this.FreezeZeroSlackVarUpperBound( program.OperationInputSetOverVariables().Get( set, period ), isunfreeze);
            this.FreezeZeroSlackVarUpperBound( program.OperationInputSetUnderVariables().Get( set, period ), isunfreeze );
          }
        }
      }
      
      // Inactivate the minimum shift pattern duration slacks.
      if( runcontext.UseShiftOptimization() )
      {
        traverse( scope.GetUnitInOptimizerRunConst(), Elements, unit, unit.GetUseShiftOptimization() )
        {
          traverse( unit.GetUnitForShiftOptimization(), Elements.UnitPeriod.astype(UnitPeriodTime), up )
          {
            traverse( up, Unit.UnitShiftPatternAllowed.ShiftPattern, sp ) 
            {
              minshiftdurationslackvar := program.ShiftPatternDurationSlackVariables().Get( sp, up );
              if( minshiftdurationslackvar.OptimalValue()  < this.SmallestFeasibilityTolerance() )
              {
                this.FreezeZeroSlackVarUpperBound( minshiftdurationslackvar, isunfreeze );
              }
            }
          }
        }
      }
    }
    
    if ( lookforfixlevelone or isunfreeze ) 
    {
      unitperiods := construct( UnitPeriods, constcontent );
      
      traverse( scope.GetUnitPeriodInOptimizerRun(), Elements, up )
      {
        unitperiods.Add( up );
        parentups := up.GetAllParentsOfUnitDimension();
        unitperiods := unitperiods.Union( parentups );
      }
      unitperiods := unitperiods.Unique();
      
      
      // Disable the UnitCapacityOverloaded slack if the TotalUnitCapacity slack is zero
      if( weightlevels.UnitCapacityLevel() = 1 )
      {
        if( program.TotalUnitCapacityVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {  
          // The variables are not defined for parent units with infinite capacity
          traverse( unitperiods, Elements, unitperiod, not unitperiod.Unit().HasChild() or not unitperiod.Unit().HasCapacityTypeInfinite() )
          {
            this.FreezeZeroSlackVarUpperBound( unitperiod.GetCapacityOverloadedVariable( program ), isunfreeze );
          }
        }
        
        if( program.TotalUnitSecondaryCapacityVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          // The variables are only defined for unit periods of type TransportQuantity with secondary capacity defined
          traverse( unitperiods, Elements, up,
                    ( not up.Unit().HasChild() or not up.Unit().HasCapacityTypeInfinite() )
                    and up.istype( UnitPeriodTransportQuantity )
                    and up.astype( UnitPeriodTransportQuantity ).HasSecondaryCapacityDefinition() )
          {
            this.FreezeZeroSlackVarUpperBound( program.UnitSecondaryCapacityOverloadedVariables().Get( up ), isunfreeze );
          }
        }              
      }
      
      
      
      
      // Inactivate the MinCampaignQtyUnder and MaxCampaignQtyOver slacks if the TotalCampaign slack is zero
      if( not runcontext.UseCampaignSequenceOptimizer() and weightlevels.CampaignLevel() = 1 )
      {
        if( program.TotalCampaignVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          traverse( scope.GetUnitInOptimizerRunConst(), Elements.CampaignType_MP, type )
          {
            // Only consider this campaign if at least one of its operations is part of this optimizer run
            traverse( type, Campaign_MP, campaign,
                      exists( campaign, OperationInCampaign.Operation, operation,
                              scope.Contains(  operation.OperationInOptimizerRun() ) ) )
            {
              this.FreezeZeroSlackVarUpperBound( program.MinCampaignQtyUnderVariables().Get( campaign ), isunfreeze ); 
      
              this.FreezeZeroSlackVarUpperBound( program.MaxCampaignQtyOverVariables().Get( campaign ), isunfreeze ); 
            }
          }
        }
      }
      
      // Inactivate the TripLotSizeUnder and PTLotSizeUnder and OperationInputLotSizeUnder slacks if the TotalLotSize slack is zero
      if( weightlevels.LotSizeLevel() = 1 )
      {
        count := 0; 
        if( program.TotalLotSizeVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          traverse( scope.GetTripInOptimizerRun(), Elements, trip,
                    trip.DepartureUnitPeriod().Period_MP().IsWithinLotSizeHorizon() )
          {
            unitperiod := trip.DepartureUnitPeriod();
            if( guard( unitperiod.HasLotSize(), false ) )
            {
              var := program.TripLotSizeUnderVariables().Get( trip );
              this.FreezeZeroSlackVarUpperBound( var, isunfreeze );
              
              varover := program.TripLotSizeOverVariables().Get( trip );
              this.FreezeZeroSlackVarUpperBound( varover, isunfreeze );
              count := count + 2; 
            }
          }
          traverse( scope.GetOperationInOptimizerRun(), Elements, operation,
                    operation.HasLotSize() )
          {
            periods := this.GetPeriodsForOperation( scope, operation )
            traverse( periods, Elements, period,
                      period.IsWithinLotSizeHorizon() )
            {
              varunder := program.PTLotSizeUnderVariables().Get( operation, period );
              this.FreezeZeroSlackVarUpperBound( varunder, isunfreeze ); 
              
              varover := program.PTLotSizeOverVariables().Get( operation, period );
              this.FreezeZeroSlackVarUpperBound( varover, isunfreeze ); 
              count := count + 2; 
            }
          }
                
          traverse( scope.GetOperationInOptimizerRun(), Elements, operation,
                    operation.HasInputLotSize() )
          {
            periods := this.GetPeriodsForOperation( scope, operation );
            periodsfordd := construct( Period_MPs, constcontent ); // periods for dependent demand
            
            traverse( periods, Elements, period )
            {
              // Consider all relevant periods for the dependent demand
              CapacityPlanningSuboptimizer::GetOperationDependentDemandPeriods( period, operation, &periodsfordd, this.GetPeriodsFromPeriodTaskOperation() ); // output set need not have unique membership
            }
            periodsfordd := periodsfordd.Unique(); 
            
            traverse( periodsfordd, Elements, period,
                        period.IsWithinLotSizeHorizon() )
            {
              traverse( operation, OperationInput, input,
                        ( input.HasRegularProductforOptimizer() or input.GetIsProductInOptimizerRun( runcontext.IsPostProcessing() ) )
                        and input.ProductInStockingPoint_MP().HasInputLotSize() )
              {
                var := program.OperationInputLotSizeUnderVariables().Get( input, period );
                this.FreezeZeroSlackVarUpperBound( var, isunfreeze );
                count++; 
              }
            }
          }
        }
        debuginfo(  ifexpr(  isunfreeze, 'un-', '' ), 'frozen nr of lot size slack variables:', count ); 
      }
      
      pispipswithinvspecification := null( ProductInStockingPointInPeriodPlannings, owning, constcontent ); // only set it if needed (performance)  
      if( weightlevels.MaximumInventoryLevel() = 1 )
      {
        if( program.TotalMaximumInventoryLevelVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          leafpispips := null( ProductInStockingPointInPeriodPlannings, constcontent, owning ); 
          pispipswithinvspecification := this.GetPISPIPsForInventorySpecifications( scope, false, &leafpispips );
      
          traverse( pispipswithinvspecification, Elements, pispip )
          {
            if( pispip.GetHasMaxLevel() )
            {
              maxinvqtyovervar := program.MaxInvQtyOverVariables().Get( pispip );
              this.FreezeZeroSlackVarUpperBound( maxinvqtyovervar, isunfreeze ); 
            }
          }
        }
      }
      
      // Inactivate the MinInvQtyUnder slack variables if the TotalMinimumInventoryLevel slack is zero
      if( weightlevels.MinimumInventoryLevel() = 1 )
      {
        if( program.TotalMinimumInventoryLevelVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          if ( isnull( pispipswithinvspecification ) ) // for performance we only set it once and if needed - check if it ha been set
          {
                leafpispips := null( ProductInStockingPointInPeriodPlannings, constcontent, owning );
                pispipswithinvspecification := this.GetPISPIPsForInventorySpecifications( scope, false, &leafpispips );
          }
          traverse( pispipswithinvspecification, Elements, pispip )
          {
            if( pispip.GetHasMinLevel() )
            {
              mininvqtyundervar := program.MinInvQtyUnderVariables().Get( pispip );
              this.FreezeZeroSlackVarUpperBound( mininvqtyundervar, isunfreeze );
            }
          }
        }
      }
      
      // Supply specifications can also be applied to higher level units which will not be part of unitsforoptimization
      // The supply specification should only be considered if at least one unit in this optimizer runs influences this supply specification
      supplyspecs := selectset( this.MacroPlan().GetUnits(), Elements.SupplySpecification, supplyspec,
                                exists( supplyspec, Unit.AllChildren.AsChildren, unit,
                                        scope.Contains(  unit.UnitInOptimizerRun() ) ) );
      
      // Inactivate the MaxSupplyQtyOver slack variables if the TotalMaximumSupply slack is zero
      if( weightlevels.MaximumSupplyLevel() = 1 )
      {
        if( program.TotalMaximumSupplyVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          traverse( supplyspecs, Elements, supplyspec )
          {
            var := program.MaxSupplyQtyOverVariables().Get( supplyspec );
            this.FreezeZeroSlackVarUpperBound( var, isunfreeze);
          }
        }
      }
      
      
      
      // Inactivate the MinSupplyQtyUnder slack variables if the TotalMinimumSupply slack is zero
      if( weightlevels.MinimumSupplyLevel() = 1 )
      {
        if( program.TotalMinimumSupplyVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          traverse( supplyspecs, Elements, supplyspec )
          {
            var := program.MinSupplyQtyUnderVariables().Get( supplyspec );
            this.FreezeZeroSlackVarUpperBound( var, isunfreeze );
          }
        }
      }
      
      
      // Inactivate the UnitCapacityNotMet slack variable if the TotalMinimumUnitCapacity is zero
      if( weightlevels.MinimumUnitCapacityLevel() = 1 )
      {
        if( program.TotalMinimumUnitCapacityVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          // The variables are not defined for parent units with infinite capacity
          traverse( unitperiods, Elements, unitperiod, not unitperiod.Unit().HasChild() or not unitperiod.Unit().HasCapacityTypeInfinite() )
          {
            this.FreezeZeroSlackVarUpperBound( unitperiod.GetCapacityNotMetVariable( program ), isunfreeze );
          }
        }
        
        if( program.TotalMinimumUnitSecondaryCapacityVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          // The variables are only defined for unit periods of type TransportQuantity with secondary capacity defined
          traverse( unitperiods, Elements, up,
                    ( not up.Unit().HasChild() or not up.Unit().HasCapacityTypeInfinite() )
                    and up.istype( UnitPeriodTransportQuantity )
                    and up.astype( UnitPeriodTransportQuantity ).HasSecondaryCapacityDefinition() )
          {
            this.FreezeZeroSlackVarUpperBound( program.UnitSecondaryCapacityNotMetVariables().Get( up ), isunfreeze )
          }
        }
      }
      
      // Inactivate the MaxPTQtyOver slack if the TotalProcessMaximumQuantity is zero
      if( weightlevels.ProcessMaximumQuantityLevel() = 1 )
      {
        if( program.TotalProcessMaximumQuantityVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          traverse( scope.GetOperationInOptimizerRun(), Elements, operation,
                    operation.HasMaximumQuantity() )
          {
            periods := this.GetPeriodsForOperation( scope, operation );
            traverse( periods, Elements, period )
            {
              var := program.MaxPTQtyOverVariables().Get( operation, period );
              this.FreezeZeroSlackVarUpperBound( var, isunfreeze );
            }
          }
        }
      }
      
      // Disable the StockingPointCapacityOverloaded slack if TotalStockingPointCapacity slack is zero
      if( weightlevels.StockingPointCapacityLevel() = 1 )
      {
        if( program.TotalStockingPointCapacityVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          traverse( scope.GetStockingPointInPeriodInOptimizerRun(), Elements, spip,
                    not spip.StockingPoint_MP().IsPlannedInfinite() )
          {
            this.FreezeZeroSlackVarUpperBound( program.StockingPointCapacityOverloadedVariables().Get( spip ), isunfreeze );
          }
        }
      }
      
      
      
      // Inactivate the CampaignPeriodOverloaded slack if the TotalUnitCapacity is zero
      if( not runcontext.UseCampaignSequenceOptimizer() and weightlevels.CampaignLevel() = 1 )
      {
        if( program.TotalUnitCapacityVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
        {
          traverse( scope.GetUnitInOptimizerRunConst(), Elements.CampaignType_MP, type )
          {
            // Only consider this campaign if at least one of its operations is part of this optimizer run
            traverse( type, Campaign_MP, campaign,
                      exists( campaign, OperationInCampaign.Operation, operation,
                              scope.Contains(  operation.OperationInOptimizerRun() ) ) )
            {
              // Only consider the campaingperiod if its unit period is part of this optimizer run
              traverse( campaign, PlanningCampaignPeriod, cp,
                        guard( scope.Contains(  cp.UnitPeriod().UnitPeriodInOptimizerRun() ), false ) )
              {
                this.FreezeZeroSlackVarUpperBound( program.CampaignPeriodOverloadedVariables().Get( cp ), isunfreeze);
              }
            }
          }
          
          transitionperiods := selectset( scope.GetUnitInOptimizerRun(), 
                                      Elements.TransitionType_MP.Transition_MP.TransitionPeriod_MP, 
                                      tp,
                                      guard( scope.Contains( tp.UnitPeriod().UnitPeriodInOptimizerRun() ), false )
                                      and guard( tp.UnitPeriod().GetIsWithinCampaignHorizonConstraint(), false )
                                      and exists( tp.Transition_MP(), OperationInTransition.OperationInTransitionType.Operation, operation,
                                                  scope.Contains( operation.OperationInOptimizerRun() ) ) )
    
          traverse( transitionperiods, Elements, tperiod )
          {
            this.FreezeZeroSlackVarUpperBound( program.TransitionPeriodOverloadedVariables().Get( tperiod ), isunfreeze ); 
          }
        }
      }
      
      // Inactivate the blending slacks if the TotalBlending is zero
      if( runcontext.UseBlending()
          and weightlevels.BlendingLevel() = 1
          and program.TotalBlendingVariables().Get().OptimalValue() < this.SmallestFeasibilityTolerance() )
      {
        traverse( scope.GetOperationInOptimizerRun(), Elements, operation, operation.IsBlending() )
        {
          periods := this.GetPeriodsForOperation( scope, operation );
          
          traverse( periods, Elements, period )
          {
            this.FreezeZeroSlackVarUpperBound( program.BlendingMaxOverVariables().Get( operation, period ), isunfreeze );
            
            this.FreezeZeroSlackVarUpperBound( program.BlendingMinUnderVariables().Get( operation, period ), isunfreeze );
          }
        }
      }
    }  
    end := OS::PrecisionCounter(); 
    debuginfo(  'Time for method:', (end-start)/OS::PrecisionCounterFrequency(), 'sec' );
  *]
  InterfaceProperties { Accessibility: 'Module' }
}