admin
2025-01-22 7e31442f0e9b07764e9c6a9680d3d4aeba5fe1de
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
Quintiq file version 2.0
#parent: #root
Method InitConstraintsForBlending (
  CapacityPlanningSuboptimizer_CapacityPlanningAlgorithm program,
  const RunContextForCapacityPlanning runcontext,
  const LibOpt_Scope scope
) const
{
  Description:
  [*
    Initializes the constraints needed to satisfy blending requirements
    e.g. different alternative inputs have aluminium contents of 0.1-0.99, and the aluminium content in the output alloy must be between 0.2 and 0.5
  *]
  TextBody:
  [*
    // Constraint to set maximum and minimum amount of each blending element of output products
    
    // The maximum blending quantity:
    // The sum of the content of this ingredient over all of the input quantities of the operation
    // plus the nominal quantity of all the recipeproducts of all inputs of this operation times the nominal quantity of this ingredient in the recipe of those recipe products times the input quantity
    // must be less than or equal to the maximum fraction times the total production quantity plus the slack variable (BlendingMaxOver): 
    
    // ∑_(input∈Operation)〖uomconversion(input,operation) * contentformax(operation,ingredient) * OperationDemandQty( input,period )〗
    // + ∑_(input ∈ Operation , recipeproduct ∈ input , ingredient'∈ recipeproduct.Product.Recipe ∧ ingredient' = ingredient)
    //    〖uomconversion(input,operation) * nominalqtyproduct(operation,recipeproduct) * nominalqtyingredient(ingredient',recipeproduct) * OperationDemandQty( input,period )〗
    // ≤ maxquantity(operation,ingredient) * QtyInFactor(operation) * PTQty(operation,period)
    //   + BlendingMaxOver(operation,period)           ∀operation,ingredient,period
    
    // The minimum blending quantity:
    // The sum of the content of this ingredient over all of the input quantities of the operation
    // plus the nominal quantity of all the recipeproducts of all inputs of this operation times the nominal quantity of this ingredient in the recipe of those recipe products times the input quantity
    // must be greater than or equal to the minimum fraction times the total production quantity minus the slack variable (BlendingMinUnder): 
    
    // ∑_(input∈Operation)〖uomconversion(input,operation) * contentformin(operation,ingredient) * OperationDemandQty( input,period )〗
    // + ∑_(input ∈ Operation , recipeproduct ∈ input , ingredient'∈ recipeproduct.Product.Recipe ∧ ingredient' = ingredient)
    //    〖uomconversion(input,operation) * nominalqtyproduct(operation,recipeproduct) * nominalqtyingredient(ingredient',recipeproduct) * OperationDemandQty( input,period )〗
    // ≥ minquantity(operation,ingredient) * QtyInFactor(operation) * PTQty(operation,period)
    //   - BlendingMinUnder(operation,period)           ∀operation,ingredient,period
    
    if( runcontext.UseBlending() )
    {
      collectvaluesmodel := runcontext.IsMetaIteration(); 
      totalblendingviolation := 0.0; 
      
      varname_ptqty := typeof( MPPTQtyVariable );
      varname_blendingmaxover := typeof( MPBlendingMaxOverVariable );
      varname_blendingminunder := typeof( MPBlendingMinUnderVariable );
      varname_partialoperationdemandqty := typeof( MPPartialOperationDemandQtyVariable );
      varname_operationdemandqty := typeof( MPOperationDemandQtyVariable );
      
      constname_blendingrecipeingredientmax := typeof( MPBlendingRecipeIngredientMaxConstraint );
      constname_blendingrecipeingredientmin := typeof( MPBlendingRecipeIngredientMinConstraint );
      
      scalefactor_ptqty_var := CapacityPlanningSuboptimizer::GetVariableScaleFactor( varname_ptqty );
      scalefactor_partialoperationdeamndqty_var := CapacityPlanningSuboptimizer::GetVariableScaleFactor( varname_partialoperationdemandqty ); 
      scalefactor_demandqty_var := CapacityPlanningSuboptimizer::GetVariableScaleFactor( varname_operationdemandqty );  
      scalefactor_periodtask_maxconstraint := this.ScaleConstraintTerm( varname_ptqty , constname_blendingrecipeingredientmax );
      scalefactor_blendingmaxover_maxconstraint := this.ScaleConstraintTerm( varname_blendingmaxover, constname_blendingrecipeingredientmax );
      scalefactor_periodtask_minconstraint := this.ScaleConstraintTerm( varname_ptqty, constname_blendingrecipeingredientmin );
      scalefactor_blendingminunder_minconstraint := this.ScaleConstraintTerm( varname_blendingminunder, constname_blendingrecipeingredientmin );
      scalefactor_partialoperationdemandqty_maxconstraint := this.ScaleConstraintTerm( varname_partialoperationdemandqty, constname_blendingrecipeingredientmax )
      scalefactor_partialoperationdemandqty_minconstraint := this.ScaleConstraintTerm( varname_partialoperationdemandqty, constname_blendingrecipeingredientmin )
      scalefactor_operationdemandqty_maxconstraint := this.ScaleConstraintTerm( varname_operationdemandqty, constname_blendingrecipeingredientmax )
      scalefactor_operationdemandqty_minconstraint := this.ScaleConstraintTerm( varname_operationdemandqty, constname_blendingrecipeingredientmin )
      
      scalefactor_blendingmaxover_blendingconstr := this.ScaleConstraintTerm( typeof( MPBlendingMaxOverVariable ), typeof( MPTotalBlendingConstraint ) );
      scalefactor_blendingminunder_blendingconstr := this.ScaleConstraintTerm( typeof( MPBlendingMinUnderVariable ), typeof( MPTotalBlendingConstraint  ) );
      
      traverse( scope.GetOperationInOptimizerRunConst(), Elements, operation,
                operation.IsBlending() 
                and not exists( operation, OperationInput, input,  // If any of the inputs is excluded from the optimizer run, then blending cannot be considered for this operation
                                input.ProductInStockingPoint_MP().Product_MP().HasRecipe() 
                                and not input.GetIsProductInOptimizerRun( runcontext.IsPostProcessing() ) ) )
      {
        // Assume that all outputs always have same recipe
        // Only select the output where the product is included.
        output := select( operation, OperationOutput, ro,
                          ro.ProductInStockingPoint_MP().Product_MP().HasRecipe()
                          and ( ro.HasRegularProductforOptimizer() or ro.GetIsProductInOptimizerRun( runcontext.IsPostProcessing() ) ) 
                          );
    
        //quantityinfactor takes into account the case where 1 ton of inputs gives 0.1 tons of output
        //this is to make the comparison to work in ratio 1:1
        //Therefore we also assume all inputs has recipe
        quantityinfactor := operation.QuantityInFactor();
    
        periods := this.GetPeriodsForOperation( scope, operation );
    
        traverse( periods, Elements, period )
        {
          ptvar := program.PTQtyVariables().Get( operation, period );   // PTQty also means the sum of new supply quantity of the period task. This is for the assumption of all outputs have same recipe.
          pt := constnull( PeriodTaskOperation ); 
          ptvarvaluefrommodel := 0.0; 
          if ( collectvaluesmodel or this.GetPeriodsFromPeriodTaskOperation() ) 
          {
            pt := select(  operation, PeriodTaskOperationInScope, pto, pto.UnitPeriod().Period_MP() = period ); 
            ptvarvaluefrommodel := guard( pt.Quantity() / scalefactor_ptqty_var, 0.0 ) ;
          }
           // Get the effective recipe for the period
          recipewitheffectivedate_output := output.ProductInStockingPoint_MP().Product_MP().GetRecipeWithEffectiveDateConst( period.StartDate() );
          
          largestviolationmax := 0.0; 
          largestviolationmin := 0.0; 
          if( not isnull( recipewitheffectivedate_output ) )
          {
            traverse( recipewitheffectivedate_output, Recipe.BaseRecipeIngredient, outputingredient )
            {
              // maxconstraint constraint UoM: Unit
              maxconstraint := program.BlendingRecipeIngredientMaxConstraints().New( output, period, outputingredient );
              maxconstraint.Sense( '<=' );
              // RHS UoM: Unit
              maxconstraint.RHSValue( 0.0 );
              // Term: -quantityinfactor * maximum * PTQty variable
              // UoM:         [-]        *   [-]   *    [Unit]
              maxquantity := outputingredient.Maximum();
              coefmax := 1.0 * quantityinfactor * maxquantity * scalefactor_periodtask_maxconstraint; 
              maxconstraint.NewTerm( -coefmax, ptvar );
      
              maxquantity_rhsmodel := coefmax * ptvarvaluefrommodel; 
              maxquantity_lhsmodel := 0.0; 
      
              // Add a slack variable that is penalized in the blending goal
              // UoM: Unit
              maxconstraint.NewTerm( -1.0 * scalefactor_blendingmaxover_maxconstraint, program.BlendingMaxOverVariables().Get( operation, period ) );
      
              // minconstraint constraint UoM: Unit
              minconstraint := program.BlendingRecipeIngredientMinConstraints().New( output, period, outputingredient );
              minconstraint.Sense( '>=' );
              // RHS UoM: Unit
              minconstraint.RHSValue( 0.0 );
              // Term: -quantityinfactor * minimum * PTQty variable
              // UoM:         [-]        *   [-]   *    [Unit]
              minquantity := outputingredient.Minimum();
              coefmin := 1.0 * quantityinfactor * minquantity * scalefactor_periodtask_minconstraint; 
              minconstraint.NewTerm( -coefmin, ptvar );
      
              minquantity_rhsmodel := coefmin * ptvarvaluefrommodel; 
              minquantity_lhsmodel := 0.0; 
      
              // Add a slack variable that is penalized in the blending goal
              // Uom: Unit
              minconstraint.NewTerm( 1.0 * scalefactor_blendingminunder_minconstraint,
                                     program.BlendingMinUnderVariables().Get( operation, period ) );
      
              // The input should have a recipe
              // Only include those inputs where the product is included.
              traverse( operation, OperationInput, input,
                        input.ProductInStockingPoint_MP().Product_MP().HasRecipe() )
              {
                dd := constnull(  DependentDemand );
                if ( collectvaluesmodel or this.GetPeriodsFromPeriodTaskOperation() ) 
                {
                  dd := select(  pt, DependentDemand, d, true, d.ProcessInput() = input ); 
                }         
    
                // Get the effective recipe for the period
                recipewitheffectivedate_input := input.ProductInStockingPoint_MP().Product_MP().GetRecipeWithEffectiveDateConst( period.StartDate() );
                
                if( not isnull( recipewitheffectivedate_input ) )
                {
                  recipename := recipewitheffectivedate_input.RecipeName();        
                  inputingredient := outputingredient.GetInputIngredient( recipename );
                         
                  contentformin := guard( inputingredient.Nominal(),0.0 );
                  contentformax := guard( inputingredient.Nominal(), 0.0 );
        
                  if( operation.HasLeadTime() )     // Get the dependent demands that is located at different period compared to period of period task.
                  {
                    pispipperiods := construct( Period_MPs, constcontent );
                    // in case using periodtasks we can directly get the dep demand periods - otherwise call less efficient method that gets dd periods for periodtask(operation, period) i.e. 'pt'
                    if ( this.GetPeriodsFromPeriodTaskOperation() ) 
                    {
                      traverse( pt, DependentDemand.ProductInStockingPointInPeriodPlanningLeaf.Period_MP, ddperiod ) 
                      {
                        pispipperiods.Add( ddperiod ); 
                      }
                    }
                    else
                    {
                      CapacityPlanningSuboptimizer::GetOperationDependentDemandPeriods( period, operation, &pispipperiods, this.GetPeriodsFromPeriodTaskOperation() ); // less efficient
                    }
                    
                    firsttime := true; 
                    uomconversion := input.UnitConversionFactor();
                    coefmax := uomconversion * contentformax * scalefactor_partialoperationdemandqty_maxconstraint;
                    coefmin := uomconversion * contentformin * scalefactor_partialoperationdemandqty_minconstraint; 
                    traverse( pispipperiods, Elements, pispipperiod )
                    {
                      demandvar := program.PartialOperationDemandQtyVariables().Get( input, pispipperiod, period );
        
                      // Term:   uomconversion   * content * PartialOperationDemandQty variable
                      // UoM: [Input PISP to Unit] *   [-]              [Input PISP UoM]
                      maxconstraint.NewTerm( coefmax, demandvar );
                      minconstraint.NewTerm( coefmin, demandvar );
                      
                      if ( collectvaluesmodel and firsttime and not isnull( dd ) ) 
                      {
                        firsttime := false; 
                        maxquantity_lhsmodel := maxquantity_lhsmodel + coefmax * dd.Quantity() / scalefactor_partialoperationdeamndqty_var; 
                        minquantity_lhsmodel := minquantity_lhsmodel + coefmin * dd.Quantity() / scalefactor_partialoperationdeamndqty_var;
                      }
                    }
                  }
                  else
                  {
                    demandvar := program.OperationDemandQtyVariables().Get( input, period );
                    uomconversion := input.UnitConversionFactor();
        
                    // Term:   uomconversion   * content * OperationDemandQty variable
                    // UoM: [Input PISP to Unit] *   [-]              [Input PISP UoM]
                    coefmax :=  uomconversion * contentformax * scalefactor_operationdemandqty_maxconstraint; 
                    coefmin :=  uomconversion * contentformin * scalefactor_operationdemandqty_minconstraint; 
                    maxconstraint.NewTerm( coefmax, demandvar );
                    minconstraint.NewTerm( coefmin, demandvar );
                    if ( collectvaluesmodel and not isnull( dd ) ) 
                    {
                      maxquantity_lhsmodel := maxquantity_lhsmodel + coefmax * dd.Quantity() /  scalefactor_demandqty_var; 
                      minquantity_lhsmodel := minquantity_lhsmodel + coefmin * dd.Quantity() / scalefactor_demandqty_var;
                    }
                  }
                }    
              }
              
              violationmax := maxvalue(  0.0, maxquantity_lhsmodel - maxquantity_rhsmodel ) / scalefactor_blendingmaxover_maxconstraint; 
              violationmin := maxvalue(  0.0, minquantity_rhsmodel - minquantity_lhsmodel ) / scalefactor_blendingminunder_minconstraint; 
    
              largestviolationmax := maxvalue( largestviolationmax, scalefactor_blendingmaxover_blendingconstr * violationmax ); 
              largestviolationmin := maxvalue(  largestviolationmin, scalefactor_blendingminunder_blendingconstr * violationmin ); 
            } // end outputingredient
          } // end if not isnull recipe
          totalblendingviolation := totalblendingviolation + largestviolationmax + largestviolationmin; 
        } // period
      }
      if ( collectvaluesmodel ) 
      {
        // workaround because we cannot write to attribute
        this.StoreValueInProgram( program, 'collectvalues_model_TotalBlendingViolation', totalblendingviolation ); 
      }
    } // if end blending
  *]
  InterfaceProperties { Accessibility: 'Module' }
}