Multi-scenario Examples#
This section includes source code for all of the Gurobi multi-scenario examples.
The same source code can be found in the examples
directory of the
Gurobi distribution.
/* Copyright 2024, Gurobi Optimization, LLC */
/* Facility location: a company currently ships its product from 5 plants
to 4 warehouses. It is considering closing some plants to reduce
costs. What plant(s) should the company close, in order to minimize
transportation and fixed costs?
Since the plant fixed costs and the warehouse demands are uncertain, a
scenario approach is chosen.
Note that this example is similar to the facility_c.c example. Here we
added scenarios in order to illustrate the multi-scenario feature.
Based on an example from Frontline Systems:
http://www.solver.com/disfacility.htm
Used with permission.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "gurobi_c.h"
#define opencol(p) p
#define transportcol(w,p) nPlants*(w+1)+p
#define demandconstr(w) nPlants+w
#define MAXSTR 128
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBenv *modelenv = NULL;
GRBmodel *model = NULL;
double *cval = NULL;
double *rhs = NULL;
int *cbeg = NULL;
int *cind = NULL;
char **cname = NULL;
char *sense = NULL;
double maxFixed = -GRB_INFINITY;
double minFixed = GRB_INFINITY;
int cnamect = 0;
int error = 0;
int p, s, w, col;
int idx, rowct;
int nScenarios;
char vname[MAXSTR];
/* Number of plants, warehouses and scenarios */
const int nPlants = 5;
const int nWarehouses = 4;
/* Warehouse demand in thousands of units */
double Demand[] = { 15, 18, 14, 20 };
/* Plant capacity in thousands of units */
double Capacity[] = { 20, 22, 17, 19, 18 };
/* Fixed costs for each plant */
double FixedCosts[] =
{ 12000, 15000, 17000, 13000, 16000 };
/* Transportation costs per thousand units */
double TransCosts[4][5] = {
{ 4000, 2000, 3000, 2500, 4500 },
{ 2500, 2600, 3400, 3000, 4000 },
{ 1200, 1800, 2600, 4100, 3000 },
{ 2200, 2600, 3100, 3700, 3200 }
};
/* Compute minimal and maximal fixed cost */
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] > maxFixed)
maxFixed = FixedCosts[p];
if (FixedCosts[p] < minFixed)
minFixed = FixedCosts[p];
}
/* Create environment */
error = GRBloadenv(&env, "multiscenario.log");
if (error) goto QUIT;
/* Create initial model */
error = GRBnewmodel(env, &model, "multiscenario", nPlants * (nWarehouses + 1),
NULL, NULL, NULL, NULL, NULL);
if (error) goto QUIT;
modelenv = GRBgetenv(model);
/* Initialize decision variables for plant open variables */
for (p = 0; p < nPlants; p++) {
col = opencol(p);
error = GRBsetcharattrelement(model, GRB_CHAR_ATTR_VTYPE,
col, GRB_BINARY);
if (error) goto QUIT;
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ,
col, FixedCosts[p]);
if (error) goto QUIT;
sprintf(vname, "Open%i", p);
error = GRBsetstrattrelement(model, GRB_STR_ATTR_VARNAME,
col, vname);
if (error) goto QUIT;
}
/* Initialize decision variables for transportation decision variables:
how much to transport from a plant p to a warehouse w */
for (w = 0; w < nWarehouses; w++) {
for (p = 0; p < nPlants; p++) {
col = transportcol(w, p);
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ,
col, TransCosts[w][p]);
if (error) goto QUIT;
sprintf(vname, "Trans%i.%i", p, w);
error = GRBsetstrattrelement(model, GRB_STR_ATTR_VARNAME,
col, vname);
if (error) goto QUIT;
}
}
/* The objective is to minimize the total fixed and variable costs */
error = GRBsetintattr(model, GRB_INT_ATTR_MODELSENSE, GRB_MINIMIZE);
if (error) goto QUIT;
/* Make space for constraint data */
rowct = (nPlants > nWarehouses) ? nPlants : nWarehouses;
cbeg = malloc(sizeof(int) * rowct);
if (!cbeg) goto QUIT;
cind = malloc(sizeof(int) * (nPlants * (nWarehouses + 1)));
if (!cind) goto QUIT;
cval = malloc(sizeof(double) * (nPlants * (nWarehouses + 1)));
if (!cval) goto QUIT;
rhs = malloc(sizeof(double) * rowct);
if (!rhs) goto QUIT;
sense = malloc(sizeof(char) * rowct);
if (!sense) goto QUIT;
cname = calloc(rowct, sizeof(char*));
if (!cname) goto QUIT;
/* Production constraints
Note that the limit sets the production to zero if
the plant is closed */
idx = 0;
for (p = 0; p < nPlants; p++) {
cbeg[p] = idx;
rhs[p] = 0.0;
sense[p] = GRB_LESS_EQUAL;
cname[p] = malloc(sizeof(char) * MAXSTR);
if (!cname[p]) goto QUIT;
cnamect++;
sprintf(cname[p], "Capacity%i", p);
for (w = 0; w < nWarehouses; w++) {
cind[idx] = transportcol(w, p);
cval[idx++] = 1.0;
}
cind[idx] = opencol(p);
cval[idx++] = -Capacity[p];
}
error = GRBaddconstrs(model, nPlants, idx, cbeg, cind, cval, sense,
rhs, cname);
if (error) goto QUIT;
/* Demand constraints */
idx = 0;
for (w = 0; w < nWarehouses; w++) {
cbeg[w] = idx;
sense[w] = GRB_EQUAL;
sprintf(cname[w], "Demand%i", w);
for (p = 0; p < nPlants; p++) {
cind[idx] = transportcol(w, p);
cval[idx++] = 1.0;
}
}
error = GRBaddconstrs(model, nWarehouses, idx, cbeg, cind, cval, sense,
Demand, cname);
if (error) goto QUIT;
/* We constructed the base model, now we add 7 scenarios
Scenario 0: Represents the base model, hence, no manipulations.
Scenario 1: Manipulate the warehouses demands slightly (constraint right
hand sides).
Scenario 2: Double the warehouses demands (constraint right hand sides).
Scenario 3: Manipulate the plant fixed costs (objective coefficients).
Scenario 4: Manipulate the warehouses demands and fixed costs.
Scenario 5: Force the plant with the largest fixed cost to stay open
(variable bounds).
Scenario 6: Force the plant with the smallest fixed cost to be closed
(variable bounds). */
error = GRBsetintattr(model, GRB_INT_ATTR_NUMSCENARIOS, 7);
if (error) goto QUIT;
/* Scenario 0: Base model, hence, nothing to do except giving the
scenario a name */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, 0);
if (error) goto QUIT;
error = GRBsetstrattr(model, GRB_STR_ATTR_SCENNNAME, "Base model");
if (error) goto QUIT;
/* Scenario 1: Increase the warehouse demands by 10% */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, 1);
if (error) goto QUIT;
error = GRBsetstrattr(model, GRB_STR_ATTR_SCENNNAME,
"Increased warehouse demands");
if (error) goto QUIT;
for (w = 0; w < nWarehouses; w++) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_SCENNRHS,
demandconstr(w), Demand[w] * 1.1);
if (error) goto QUIT;
}
/* Scenario 2: Double the warehouse demands */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, 2);
if (error) goto QUIT;
error = GRBsetstrattr(model, GRB_STR_ATTR_SCENNNAME,
"Double the warehouse demands");
if (error) goto QUIT;
for (w = 0; w < nWarehouses; w++) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_SCENNRHS,
demandconstr(w), Demand[w] * 2.0);
if (error) goto QUIT;
}
/* Scenario 3: Decrease the plant fixed costs by 5% */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, 3);
if (error) goto QUIT;
error = GRBsetstrattr(model, GRB_STR_ATTR_SCENNNAME,
"Decreased plant fixed costs");
if (error) goto QUIT;
for (p = 0; p < nPlants; p++) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_SCENNOBJ,
opencol(p), FixedCosts[p] * 0.95);
if (error) goto QUIT;
}
/* Scenario 4: Combine scenario 1 and scenario 3 */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, 4);
if (error) goto QUIT;
error = GRBsetstrattr(model, GRB_STR_ATTR_SCENNNAME,
"Increased warehouse demands and decreased plant fixed costs");
for (w = 0; w < nWarehouses; w++) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_SCENNRHS,
demandconstr(w), Demand[w] * 1.1);
if (error) goto QUIT;
}
for (p = 0; p < nPlants; p++) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_SCENNOBJ,
opencol(p), FixedCosts[p] * 0.95);
if (error) goto QUIT;
}
/* Scenario 5: Force the plant with the largest fixed cost to stay
open */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, 5);
if (error) goto QUIT;
error = GRBsetstrattr(model, GRB_STR_ATTR_SCENNNAME,
"Force plant with largest fixed cost to stay open");
if (error) goto QUIT;
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] == maxFixed) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_SCENNLB,
opencol(p), 1.0);
if (error) goto QUIT;
break;
}
}
/* Scenario 6: Force the plant with the smallest fixed cost to be
closed */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, 6);
if (error) goto QUIT;
error = GRBsetstrattr(model, GRB_STR_ATTR_SCENNNAME,
"Force plant with smallest fixed cost to be closed");
if (error) goto QUIT;
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] == minFixed) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_SCENNUB,
opencol(p), 0.0);
if (error) goto QUIT;
break;
}
}
/* Guess at the starting point: close the plant with the highest
fixed costs; open all others */
/* First, open all plants */
for (p = 0; p < nPlants; p++) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_START, opencol(p), 1.0);
if (error) goto QUIT;
}
/* Now close the plant with the highest fixed cost */
printf("Initial guess:\n");
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] == maxFixed) {
error = GRBsetdblattrelement(model, GRB_DBL_ATTR_START, opencol(p), 0.0);
if (error) goto QUIT;
printf("Closing plant %i\n\n", p);
break;
}
}
/* Use barrier to solve root relaxation */
error = GRBsetintparam(modelenv,
GRB_INT_PAR_METHOD,
GRB_METHOD_BARRIER);
if (error) goto QUIT;
/* Solve multi-scenario model */
error = GRBoptimize(model);
if (error) goto QUIT;
error = GRBgetintattr(model, GRB_INT_ATTR_NUMSCENARIOS, &nScenarios);
if (error) goto QUIT;
/* Print solution for each */
for (s = 0; s < nScenarios; s++) {
char *scenarioName;
double scenNObjBound;
double scenNObjVal;
int modelSense = GRB_MINIMIZE;
/* Set the scenario number to query the information for this
scenario */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, s);
if (error) goto QUIT;
/* Collect result for the scenario */
error = GRBgetstrattr(model, GRB_STR_ATTR_SCENNNAME, &scenarioName);
if (error) goto QUIT;
error = GRBgetdblattr(model, GRB_DBL_ATTR_SCENNOBJBOUND, &scenNObjBound);
if (error) goto QUIT;
error = GRBgetdblattr(model, GRB_DBL_ATTR_SCENNOBJVAL, &scenNObjVal);
if (error) goto QUIT;
printf("\n\n------ Scenario %d (%s)\n", s, scenarioName);
/* Check if we found a feasible solution for this scenario */
if (modelSense * scenNObjVal >= GRB_INFINITY)
if (modelSense * scenNObjBound >= GRB_INFINITY)
/* Scenario was proven to be infeasible */
printf("\nINFEASIBLE\n");
else
/* We did not find any feasible solution - should not happen in
this case, because we did not set any limit (like a time
limit) on the optimization process */
printf("\nNO SOLUTION\n");
else {
printf("\nTOTAL COSTS: %g\n", scenNObjVal);
printf("SOLUTION:\n");
for (p = 0; p < nPlants; p++) {
double scenNX;
error = GRBgetdblattrelement(model, GRB_DBL_ATTR_SCENNX,
opencol(p), &scenNX);
if (error) goto QUIT;
if (scenNX > 0.5) {
printf("Plant %i open\n", p);
for (w = 0; w < nWarehouses; w++) {
error = GRBgetdblattrelement(model, GRB_DBL_ATTR_SCENNX,
transportcol(w, p), &scenNX);
if (error) goto QUIT;
if (scenNX > 0.0001)
printf(" Transport %g units to warehouse %i\n",
scenNX, w);
}
} else
printf("Plant %i closed!\n", p);
}
}
}
/* Print a summary table: for each scenario we add a single summary
line */
printf("\n\nSummary: Closed plants depending on scenario\n\n");
printf("%8s | %17s %13s\n", "", "Plant", "|");
printf("%8s |", "Scenario");
for (p = 0; p < nPlants; p++)
printf(" %5d", p);
printf(" | %6s %s\n", "Costs", "Name");
for (s = 0; s < nScenarios; s++) {
char *scenarioName;
double scenNObjBound;
double scenNObjVal;
int modelSense = GRB_MINIMIZE;
/* Set the scenario number to query the information for this scenario */
error = GRBsetintparam(modelenv, GRB_INT_PAR_SCENARIONUMBER, s);
if (error) goto QUIT;
/* collect result for the scenario */
error = GRBgetstrattr(model, GRB_STR_ATTR_SCENNNAME, &scenarioName);
if (error) goto QUIT;
error = GRBgetdblattr(model, GRB_DBL_ATTR_SCENNOBJBOUND, &scenNObjBound);
if (error) goto QUIT;
error = GRBgetdblattr(model, GRB_DBL_ATTR_SCENNOBJVAL, &scenNObjVal);
if (error) goto QUIT;
printf("%-8d |", s);
/* Check if we found a feasible solution for this scenario */
if (modelSense * scenNObjVal >= GRB_INFINITY)
if (modelSense * scenNObjBound >= GRB_INFINITY)
/* Scenario was proven to be infeasible */
printf(" %-30s| %6s %s\n", "infeasible", "-", scenarioName);
else
/* We did not find any feasible solution - should not happen in
this case, because we did not set any limit (like a time
limit) on the optimization process */
printf(" %-30s| %6s %s\n", "no solution found", "-", scenarioName);
else {
for (p = 0; p < nPlants; p++) {
double scenNX;
error = GRBgetdblattrelement(model, GRB_DBL_ATTR_SCENNX,
opencol(p), &scenNX);
if (scenNX > 0.5)
printf(" %5s", " ");
else
printf(" %5s", "x");
}
printf(" | %6g %s\n", scenNObjVal, scenarioName);
}
}
QUIT:
/* Error reporting */
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
exit(1);
}
/* Free data */
free(cbeg);
free(cind);
free(cval);
free(rhs);
free(sense);
for (p = 0; p < cnamect; p++)
free(cname[p]);
free(cname);
/* Free model */
GRBfreemodel(model);
/* Free environment */
GRBfreeenv(env);
return 0;
}
// Copyright 2024, Gurobi Optimization, LLC
// Facility location: a company currently ships its product from 5 plants
// to 4 warehouses. It is considering closing some plants to reduce
// costs. What plant(s) should the company close, in order to minimize
// transportation and fixed costs?
//
// Since the plant fixed costs and the warehouse demands are uncertain, a
// scenario approach is chosen.
//
// Note that this example is similar to the facility_c++.cpp example. Here
// we added scenarios in order to illustrate the multi-scenario feature.
//
// Based on an example from Frontline Systems:
// http://www.solver.com/disfacility.htm
// Used with permission.
#include "gurobi_c++.h"
#include <sstream>
#include <iomanip>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBEnv *env = 0;
GRBVar *open = 0;
GRBVar **transport = 0;
GRBConstr *demandConstr = 0;
int transportCt = 0;
try {
// Number of plants and warehouses
const int nPlants = 5;
const int nWarehouses = 4;
// Warehouse demand in thousands of units
double Demand[] = { 15, 18, 14, 20 };
// Plant capacity in thousands of units
double Capacity[] = { 20, 22, 17, 19, 18 };
// Fixed costs for each plant
double FixedCosts[] =
{ 12000, 15000, 17000, 13000, 16000 };
// Transportation costs per thousand units
double TransCosts[][nPlants] = {
{ 4000, 2000, 3000, 2500, 4500 },
{ 2500, 2600, 3400, 3000, 4000 },
{ 1200, 1800, 2600, 4100, 3000 },
{ 2200, 2600, 3100, 3700, 3200 }
};
double maxFixed = -GRB_INFINITY;
double minFixed = GRB_INFINITY;
int p;
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] > maxFixed)
maxFixed = FixedCosts[p];
if (FixedCosts[p] < minFixed)
minFixed = FixedCosts[p];
}
// Model
env = new GRBEnv();
GRBModel model = GRBModel(*env);
model.set(GRB_StringAttr_ModelName, "multiscenario");
// Plant open decision variables: open[p] == 1 if plant p is open.
open = model.addVars(nPlants, GRB_BINARY);
for (p = 0; p < nPlants; p++) {
ostringstream vname;
vname << "Open" << p;
open[p].set(GRB_DoubleAttr_Obj, FixedCosts[p]);
open[p].set(GRB_StringAttr_VarName, vname.str());
}
// Transportation decision variables: how much to transport from
// a plant p to a warehouse w
transport = new GRBVar* [nWarehouses];
int w;
for (w = 0; w < nWarehouses; w++) {
transport[w] = model.addVars(nPlants);
transportCt++;
for (p = 0; p < nPlants; p++) {
ostringstream vname;
vname << "Trans" << p << "." << w;
transport[w][p].set(GRB_DoubleAttr_Obj, TransCosts[w][p]);
transport[w][p].set(GRB_StringAttr_VarName, vname.str());
}
}
// The objective is to minimize the total fixed and variable costs
model.set(GRB_IntAttr_ModelSense, GRB_MINIMIZE);
// Production constraints
// Note that the right-hand limit sets the production to zero if
// the plant is closed
for (p = 0; p < nPlants; p++) {
GRBLinExpr ptot = 0;
for (w = 0; w < nWarehouses; w++) {
ptot += transport[w][p];
}
ostringstream cname;
cname << "Capacity" << p;
model.addConstr(ptot <= Capacity[p] * open[p], cname.str());
}
// Demand constraints
demandConstr = new GRBConstr[nWarehouses];
for (w = 0; w < nWarehouses; w++) {
GRBLinExpr dtot = 0;
for (p = 0; p < nPlants; p++)
dtot += transport[w][p];
ostringstream cname;
cname << "Demand" << w;
demandConstr[w] = model.addConstr(dtot == Demand[w], cname.str());
}
// We constructed the base model, now we add 7 scenarios
//
// Scenario 0: Represents the base model, hence, no manipulations.
// Scenario 1: Manipulate the warehouses demands slightly (constraint right
// hand sides).
// Scenario 2: Double the warehouses demands (constraint right hand sides).
// Scenario 3: Manipulate the plant fixed costs (objective coefficients).
// Scenario 4: Manipulate the warehouses demands and fixed costs.
// Scenario 5: Force the plant with the largest fixed cost to stay open
// (variable bounds).
// Scenario 6: Force the plant with the smallest fixed cost to be closed
// (variable bounds).
model.set(GRB_IntAttr_NumScenarios, 7);
// Scenario 0: Base model, hence, nothing to do except giving the
// scenario a name
model.set(GRB_IntParam_ScenarioNumber, 0);
model.set(GRB_StringAttr_ScenNName, "Base model");
// Scenario 1: Increase the warehouse demands by 10%
model.set(GRB_IntParam_ScenarioNumber, 1);
model.set(GRB_StringAttr_ScenNName, "Increased warehouse demands");
for (w = 0; w < nWarehouses; w++) {
demandConstr[w].set(GRB_DoubleAttr_ScenNRHS, Demand[w] * 1.1);
}
// Scenario 2: Double the warehouse demands
model.set(GRB_IntParam_ScenarioNumber, 2);
model.set(GRB_StringAttr_ScenNName, "Double the warehouse demands");
for (w = 0; w < nWarehouses; w++) {
demandConstr[w].set(GRB_DoubleAttr_ScenNRHS, Demand[w] * 2.0);
}
// Scenario 3: Decrease the plant fixed costs by 5%
model.set(GRB_IntParam_ScenarioNumber, 3);
model.set(GRB_StringAttr_ScenNName, "Decreased plant fixed costs");
for (p = 0; p < nPlants; p++) {
open[p].set(GRB_DoubleAttr_ScenNObj, FixedCosts[p] * 0.95);
}
// Scenario 4: Combine scenario 1 and scenario 3 */
model.set(GRB_IntParam_ScenarioNumber, 4);
model.set(GRB_StringAttr_ScenNName, "Increased warehouse demands and decreased plant fixed costs");
for (w = 0; w < nWarehouses; w++) {
demandConstr[w].set(GRB_DoubleAttr_ScenNRHS, Demand[w] * 1.1);
}
for (p = 0; p < nPlants; p++) {
open[p].set(GRB_DoubleAttr_ScenNObj, FixedCosts[p] * 0.95);
}
// Scenario 5: Force the plant with the largest fixed cost to stay
// open
model.set(GRB_IntParam_ScenarioNumber, 5);
model.set(GRB_StringAttr_ScenNName, "Force plant with largest fixed cost to stay open");
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] == maxFixed) {
open[p].set(GRB_DoubleAttr_ScenNLB, 1.0);
break;
}
}
// Scenario 6: Force the plant with the smallest fixed cost to be
// closed
model.set(GRB_IntParam_ScenarioNumber, 6);
model.set(GRB_StringAttr_ScenNName, "Force plant with smallest fixed cost to be closed");
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] == minFixed) {
open[p].set(GRB_DoubleAttr_ScenNUB, 0.0);
break;
}
}
// Guess at the starting point: close the plant with the highest
// fixed costs; open all others
// First, open all plants
for (p = 0; p < nPlants; p++)
open[p].set(GRB_DoubleAttr_Start, 1.0);
// Now close the plant with the highest fixed cost
cout << "Initial guess:" << endl;
for (p = 0; p < nPlants; p++) {
if (FixedCosts[p] == maxFixed) {
open[p].set(GRB_DoubleAttr_Start, 0.0);
cout << "Closing plant " << p << endl << endl;
break;
}
}
// Use barrier to solve root relaxation
model.set(GRB_IntParam_Method, GRB_METHOD_BARRIER);
// Solve multi-scenario model
model.optimize();
int nScenarios = model.get(GRB_IntAttr_NumScenarios);
// Print solution for each */
for (int s = 0; s < nScenarios; s++) {
int modelSense = GRB_MINIMIZE;
// Set the scenario number to query the information for this scenario
model.set(GRB_IntParam_ScenarioNumber, s);
// collect result for the scenario
double scenNObjBound = model.get(GRB_DoubleAttr_ScenNObjBound);
double scenNObjVal = model.get(GRB_DoubleAttr_ScenNObjVal);
cout << endl << endl << "------ Scenario " << s
<< " (" << model.get(GRB_StringAttr_ScenNName) << ")" << endl;
// Check if we found a feasible solution for this scenario
if (modelSense * scenNObjVal >= GRB_INFINITY)
if (modelSense * scenNObjBound >= GRB_INFINITY)
// Scenario was proven to be infeasible
cout << endl << "INFEASIBLE" << endl;
else
// We did not find any feasible solution - should not happen in
// this case, because we did not set any limit (like a time
// limit) on the optimization process
cout << endl << "NO SOLUTION" << endl;
else {
cout << endl << "TOTAL COSTS: " << scenNObjVal << endl;
cout << "SOLUTION:" << endl;
for (p = 0; p < nPlants; p++) {
double scenNX = open[p].get(GRB_DoubleAttr_ScenNX);
if (scenNX > 0.5) {
cout << "Plant " << p << " open" << endl;
for (w = 0; w < nWarehouses; w++) {
scenNX = transport[w][p].get(GRB_DoubleAttr_ScenNX);
if (scenNX > 0.0001)
cout << " Transport " << scenNX
<< " units to warehouse " << w << endl;
}
} else
cout << "Plant " << p << " closed!" << endl;
}
}
}
// Print a summary table: for each scenario we add a single summary
// line
cout << endl << endl << "Summary: Closed plants depending on scenario" << endl << endl;
cout << setw(8) << " " << " | " << setw(17) << "Plant" << setw(14) << "|" << endl;
cout << setw(8) << "Scenario" << " |";
for (p = 0; p < nPlants; p++)
cout << " " << setw(5) << p;
cout << " | " << setw(6) << "Costs" << " Name" << endl;
for (int s = 0; s < nScenarios; s++) {
int modelSense = GRB_MINIMIZE;
// Set the scenario number to query the information for this scenario
model.set(GRB_IntParam_ScenarioNumber, s);
// Collect result for the scenario
double scenNObjBound = model.get(GRB_DoubleAttr_ScenNObjBound);
double scenNObjVal = model.get(GRB_DoubleAttr_ScenNObjVal);
cout << left << setw(8) << s << right << " |";
// Check if we found a feasible solution for this scenario
if (modelSense * scenNObjVal >= GRB_INFINITY) {
if (modelSense * scenNObjBound >= GRB_INFINITY)
// Scenario was proven to be infeasible
cout << " " << left << setw(30) << "infeasible" << right;
else
// We did not find any feasible solution - should not happen in
// this case, because we did not set any limit (like a time
// limit) on the optimization process
cout << " " << left << setw(30) << "no solution found" << right;
cout << "| " << setw(6) << "-"
<< " " << model.get(GRB_StringAttr_ScenNName)
<< endl;
} else {
for (p = 0; p < nPlants; p++) {
double scenNX = open[p].get(GRB_DoubleAttr_ScenNX);
if (scenNX > 0.5)
cout << setw(6) << " ";
else
cout << " " << setw(5) << "x";
}
cout << " | " << setw(6) << scenNObjVal
<< " " << model.get(GRB_StringAttr_ScenNName)
<< endl;
}
}
}
catch (GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...) {
cout << "Exception during optimization" << endl;
}
delete[] open;
for (int i = 0; i < transportCt; ++i) {
delete[] transport[i];
}
delete[] transport;
delete[] demandConstr;
delete env;
return 0;
}
// Copyright 2024, Gurobi Optimization, LLC
// Facility location: a company currently ships its product from 5 plants
// to 4 warehouses. It is considering closing some plants to reduce
// costs. What plant(s) should the company close, in order to minimize
// transportation and fixed costs?
//
// Since the plant fixed costs and the warehouse demands are uncertain, a
// scenario approach is chosen.
//
// Note that this example is similar to the facility_cs.cs example. Here we
// added scenarios in order to illustrate the multi-scenario feature.
//
// Based on an example from Frontline Systems:
// http://www.solver.com/disfacility.htm
// Used with permission.
using System;
using Gurobi;
class multiscenario_cs
{
static void Main()
{
try {
// Warehouse demand in thousands of units
double[] Demand = new double[] { 15, 18, 14, 20 };
// Plant capacity in thousands of units
double[] Capacity = new double[] { 20, 22, 17, 19, 18 };
// Fixed costs for each plant
double[] FixedCosts =
new double[] { 12000, 15000, 17000, 13000, 16000 };
// Transportation costs per thousand units
double[,] TransCosts =
new double[,] { { 4000, 2000, 3000, 2500, 4500 },
{ 2500, 2600, 3400, 3000, 4000 },
{ 1200, 1800, 2600, 4100, 3000 },
{ 2200, 2600, 3100, 3700, 3200 } };
// Number of plants and warehouses
int nPlants = Capacity.Length;
int nWarehouses = Demand.Length;
double maxFixed = -GRB.INFINITY;
double minFixed = GRB.INFINITY;
for (int p = 0; p < nPlants; ++p) {
if (FixedCosts[p] > maxFixed)
maxFixed = FixedCosts[p];
if (FixedCosts[p] < minFixed)
minFixed = FixedCosts[p];
}
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.ModelName = "multiscenario";
// Plant open decision variables: open[p] == 1 if plant p is open.
GRBVar[] open = new GRBVar[nPlants];
for (int p = 0; p < nPlants; ++p) {
open[p] = model.AddVar(0, 1, FixedCosts[p], GRB.BINARY, "Open" + p);
}
// Transportation decision variables: how much to transport from
// a plant p to a warehouse w
GRBVar[,] transport = new GRBVar[nWarehouses,nPlants];
for (int w = 0; w < nWarehouses; ++w) {
for (int p = 0; p < nPlants; ++p) {
transport[w,p] = model.AddVar(0, GRB.INFINITY, TransCosts[w,p],
GRB.CONTINUOUS, "Trans" + p + "." + w);
}
}
// The objective is to minimize the total fixed and variable costs
model.ModelSense = GRB.MINIMIZE;
// Production constraints
// Note that the right-hand limit sets the production to zero if
// the plant is closed
for (int p = 0; p < nPlants; ++p) {
GRBLinExpr ptot = 0.0;
for (int w = 0; w < nWarehouses; ++w)
ptot.AddTerm(1.0, transport[w,p]);
model.AddConstr(ptot <= Capacity[p] * open[p], "Capacity" + p);
}
// Demand constraints
GRBConstr[] demandConstr = new GRBConstr[nWarehouses];
for (int w = 0; w < nWarehouses; ++w) {
GRBLinExpr dtot = 0.0;
for (int p = 0; p < nPlants; ++p)
dtot.AddTerm(1.0, transport[w,p]);
demandConstr[w] = model.AddConstr(dtot == Demand[w], "Demand" + w);
}
// We constructed the base model, now we add 7 scenarios
//
// Scenario 0: Represents the base model, hence, no manipulations.
// Scenario 1: Manipulate the warehouses demands slightly (constraint right
// hand sides).
// Scenario 2: Double the warehouses demands (constraint right hand sides).
// Scenario 3: Manipulate the plant fixed costs (objective coefficients).
// Scenario 4: Manipulate the warehouses demands and fixed costs.
// Scenario 5: Force the plant with the largest fixed cost to stay open
// (variable bounds).
// Scenario 6: Force the plant with the smallest fixed cost to be closed
// (variable bounds).
model.NumScenarios = 7;
// Scenario 0: Base model, hence, nothing to do except giving the
// scenario a name
model.Parameters.ScenarioNumber = 0;
model.ScenNName = "Base model";
// Scenario 1: Increase the warehouse demands by 10%
model.Parameters.ScenarioNumber = 1;
model.ScenNName = "Increased warehouse demands";
for (int w = 0; w < nWarehouses; w++) {
demandConstr[w].ScenNRHS = Demand[w] * 1.1;
}
// Scenario 2: Double the warehouse demands
model.Parameters.ScenarioNumber = 2;
model.ScenNName = "Double the warehouse demands";
for (int w = 0; w < nWarehouses; w++) {
demandConstr[w].ScenNRHS = Demand[w] * 2.0;
}
// Scenario 3: Decrease the plant fixed costs by 5%
model.Parameters.ScenarioNumber = 3;
model.ScenNName = "Decreased plant fixed costs";
for (int p = 0; p < nPlants; p++) {
open[p].ScenNObj = FixedCosts[p] * 0.95;
}
// Scenario 4: Combine scenario 1 and scenario 3 */
model.Parameters.ScenarioNumber = 4;
model.ScenNName = "Increased warehouse demands and decreased plant fixed costs";
for (int w = 0; w < nWarehouses; w++) {
demandConstr[w].ScenNRHS = Demand[w] * 1.1;
}
for (int p = 0; p < nPlants; p++) {
open[p].ScenNObj = FixedCosts[p] * 0.95;
}
// Scenario 5: Force the plant with the largest fixed cost to stay
// open
model.Parameters.ScenarioNumber = 5;
model.ScenNName = "Force plant with largest fixed cost to stay open";
for (int p = 0; p < nPlants; p++) {
if (FixedCosts[p] == maxFixed) {
open[p].ScenNLB = 1.0;
break;
}
}
// Scenario 6: Force the plant with the smallest fixed cost to be
// closed
model.Parameters.ScenarioNumber = 6;
model.ScenNName = "Force plant with smallest fixed cost to be closed";
for (int p = 0; p < nPlants; p++) {
if (FixedCosts[p] == minFixed) {
open[p].ScenNUB = 0.0;
break;
}
}
// Guess at the starting point: close the plant with the highest
// fixed costs; open all others
// First, open all plants
for (int p = 0; p < nPlants; ++p) {
open[p].Start = 1.0;
}
// Now close the plant with the highest fixed cost
Console.WriteLine("Initial guess:");
for (int p = 0; p < nPlants; ++p) {
if (FixedCosts[p] == maxFixed) {
open[p].Start = 0.0;
Console.WriteLine("Closing plant " + p + "\n");
break;
}
}
// Use barrier to solve root relaxation
model.Parameters.Method = GRB.METHOD_BARRIER;
// Solve multi-scenario model
model.Optimize();
int nScenarios = model.NumScenarios;
for (int s = 0; s < nScenarios; s++) {
int modelSense = GRB.MINIMIZE;
// Set the scenario number to query the information for this scenario
model.Parameters.ScenarioNumber = s;
// collect result for the scenario
double scenNObjBound = model.ScenNObjBound;
double scenNObjVal = model.ScenNObjVal;
Console.WriteLine("\n\n------ Scenario " + s
+ " (" + model.ScenNName + ")");
// Check if we found a feasible solution for this scenario
if (modelSense * scenNObjVal >= GRB.INFINITY)
if (modelSense * scenNObjBound >= GRB.INFINITY)
// Scenario was proven to be infeasible
Console.WriteLine("\nINFEASIBLE");
else
// We did not find any feasible solution - should not happen in
// this case, because we did not set any limit (like a time
// limit) on the optimization process
Console.WriteLine("\nNO SOLUTION");
else {
Console.WriteLine("\nTOTAL COSTS: " + scenNObjVal);
Console.WriteLine("SOLUTION:");
for (int p = 0; p < nPlants; p++) {
double scenNX = open[p].ScenNX;
if (scenNX > 0.5) {
Console.WriteLine("Plant " + p + " open");
for (int w = 0; w < nWarehouses; w++) {
scenNX = transport[w,p].ScenNX;
if (scenNX > 0.0001)
Console.WriteLine(" Transport " + scenNX
+ " units to warehouse " + w);
}
} else
Console.WriteLine("Plant " + p + " closed!");
}
}
}
// Print a summary table: for each scenario we add a single summary
// line
Console.WriteLine("\n\nSummary: Closed plants depending on scenario\n");
Console.WriteLine("{0,8} | {1,17} {2,13}", "", "Plant", "|");
Console.Write("{0,8} |", "Scenario");
for (int p = 0; p < nPlants; p++)
Console.Write("{0,6}", p);
Console.WriteLine(" | {0,6} Name", "Costs");
for (int s = 0; s < nScenarios; s++) {
int modelSense = GRB.MINIMIZE;
// Set the scenario number to query the information for this scenario
model.Parameters.ScenarioNumber = s;
// Collect result for the scenario
double scenNObjBound = model.ScenNObjBound;
double scenNObjVal = model.ScenNObjVal;
Console.Write("{0,-8} |", s);
// Check if we found a feasible solution for this scenario
if (modelSense * scenNObjVal >= GRB.INFINITY) {
if (modelSense * scenNObjBound >= GRB.INFINITY)
// Scenario was proven to be infeasible
Console.WriteLine(" {0,-30}| {1,6} " + model.ScenNName,
"infeasible", "-");
else
// We did not find any feasible solution - should not happen in
// this case, because we did not set any limit (like a time
// limit) on the optimization process
Console.WriteLine(" {0,-30}| {1,6} " + model.ScenNName,
"no solution found", "-");
} else {
for (int p = 0; p < nPlants; p++) {
double scenNX = open[p].ScenNX;
if (scenNX > 0.5)
Console.Write("{0,6}", " ");
else
Console.Write("{0,6}", "x");
}
Console.WriteLine(" | {0,6} "+ model.ScenNName, scenNObjVal);
}
}
// Dispose of model and env
model.Dispose();
env.Dispose();
} catch (GRBException e) {
Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
}
}
}
// Copyright 2024, Gurobi Optimization, LLC
// Facility location: a company currently ships its product from 5 plants
// to 4 warehouses. It is considering closing some plants to reduce
// costs. What plant(s) should the company close, in order to minimize
// transportation and fixed costs?
//
// Since the plant fixed costs and the warehouse demands are uncertain, a
// scenario approach is chosen.
//
// Note that this example is similar to the Facility.java example. Here we
// added scenarios in order to illustrate the multi-scenario feature.
//
// Based on an example from Frontline Systems:
// http://www.solver.com/disfacility.htm
// Used with permission.
import com.gurobi.gurobi.*;
public class Multiscenario {
public static void main(String[] args) {
try {
// Warehouse demand in thousands of units
double Demand[] = new double[] { 15, 18, 14, 20 };
// Plant capacity in thousands of units
double Capacity[] = new double[] { 20, 22, 17, 19, 18 };
// Fixed costs for each plant
double FixedCosts[] =
new double[] { 12000, 15000, 17000, 13000, 16000 };
// Transportation costs per thousand units
double TransCosts[][] =
new double[][] { { 4000, 2000, 3000, 2500, 4500 },
{ 2500, 2600, 3400, 3000, 4000 },
{ 1200, 1800, 2600, 4100, 3000 },
{ 2200, 2600, 3100, 3700, 3200 } };
// Number of plants and warehouses
int nPlants = Capacity.length;
int nWarehouses = Demand.length;
double maxFixed = -GRB.INFINITY;
double minFixed = GRB.INFINITY;
for (int p = 0; p < nPlants; ++p) {
if (FixedCosts[p] > maxFixed)
maxFixed = FixedCosts[p];
if (FixedCosts[p] < minFixed)
minFixed = FixedCosts[p];
}
// Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "multiscenario");
// Plant open decision variables: open[p] == 1 if plant p is open.
GRBVar[] open = new GRBVar[nPlants];
for (int p = 0; p < nPlants; ++p) {
open[p] = model.addVar(0, 1, FixedCosts[p], GRB.BINARY, "Open" + p);
}
// Transportation decision variables: how much to transport from
// a plant p to a warehouse w
GRBVar[][] transport = new GRBVar[nWarehouses][nPlants];
for (int w = 0; w < nWarehouses; ++w) {
for (int p = 0; p < nPlants; ++p) {
transport[w][p] = model.addVar(0, GRB.INFINITY, TransCosts[w][p],
GRB.CONTINUOUS, "Trans" + p + "." + w);
}
}
// The objective is to minimize the total fixed and variable costs
model.set(GRB.IntAttr.ModelSense, GRB.MINIMIZE);
// Production constraints
// Note that the right-hand limit sets the production to zero if
// the plant is closed
for (int p = 0; p < nPlants; ++p) {
GRBLinExpr ptot = new GRBLinExpr();
for (int w = 0; w < nWarehouses; ++w) {
ptot.addTerm(1.0, transport[w][p]);
}
GRBLinExpr limit = new GRBLinExpr();
limit.addTerm(Capacity[p], open[p]);
model.addConstr(ptot, GRB.LESS_EQUAL, limit, "Capacity" + p);
}
// Demand constraints
GRBConstr[] demandConstr = new GRBConstr[nWarehouses];
for (int w = 0; w < nWarehouses; ++w) {
GRBLinExpr dtot = new GRBLinExpr();
for (int p = 0; p < nPlants; ++p) {
dtot.addTerm(1.0, transport[w][p]);
}
demandConstr[w] = model.addConstr(dtot, GRB.EQUAL, Demand[w], "Demand" + w);
}
// We constructed the base model, now we add 7 scenarios
//
// Scenario 0: Represents the base model, hence, no manipulations.
// Scenario 1: Manipulate the warehouses demands slightly (constraint right
// hand sides).
// Scenario 2: Double the warehouses demands (constraint right hand sides).
// Scenario 3: Manipulate the plant fixed costs (objective coefficients).
// Scenario 4: Manipulate the warehouses demands and fixed costs.
// Scenario 5: Force the plant with the largest fixed cost to stay open
// (variable bounds).
// Scenario 6: Force the plant with the smallest fixed cost to be closed
// (variable bounds).
model.set(GRB.IntAttr.NumScenarios, 7);
// Scenario 0: Base model, hence, nothing to do except giving the
// scenario a name
model.set(GRB.IntParam.ScenarioNumber, 0);
model.set(GRB.StringAttr.ScenNName, "Base model");
// Scenario 1: Increase the warehouse demands by 10%
model.set(GRB.IntParam.ScenarioNumber, 1);
model.set(GRB.StringAttr.ScenNName, "Increased warehouse demands");
for (int w = 0; w < nWarehouses; w++) {
demandConstr[w].set(GRB.DoubleAttr.ScenNRHS, Demand[w] * 1.1);
}
// Scenario 2: Double the warehouse demands
model.set(GRB.IntParam.ScenarioNumber, 2);
model.set(GRB.StringAttr.ScenNName, "Double the warehouse demands");
for (int w = 0; w < nWarehouses; w++) {
demandConstr[w].set(GRB.DoubleAttr.ScenNRHS, Demand[w] * 2.0);
}
// Scenario 3: Decrease the plant fixed costs by 5%
model.set(GRB.IntParam.ScenarioNumber, 3);
model.set(GRB.StringAttr.ScenNName, "Decreased plant fixed costs");
for (int p = 0; p < nPlants; p++) {
open[p].set(GRB.DoubleAttr.ScenNObj, FixedCosts[p] * 0.95);
}
// Scenario 4: Combine scenario 1 and scenario 3 */
model.set(GRB.IntParam.ScenarioNumber, 4);
model.set(GRB.StringAttr.ScenNName, "Increased warehouse demands and decreased plant fixed costs");
for (int w = 0; w < nWarehouses; w++) {
demandConstr[w].set(GRB.DoubleAttr.ScenNRHS, Demand[w] * 1.1);
}
for (int p = 0; p < nPlants; p++) {
open[p].set(GRB.DoubleAttr.ScenNObj, FixedCosts[p] * 0.95);
}
// Scenario 5: Force the plant with the largest fixed cost to stay
// open
model.set(GRB.IntParam.ScenarioNumber, 5);
model.set(GRB.StringAttr.ScenNName, "Force plant with largest fixed cost to stay open");
for (int p = 0; p < nPlants; p++) {
if (FixedCosts[p] == maxFixed) {
open[p].set(GRB.DoubleAttr.ScenNLB, 1.0);
break;
}
}
// Scenario 6: Force the plant with the smallest fixed cost to be
// closed
model.set(GRB.IntParam.ScenarioNumber, 6);
model.set(GRB.StringAttr.ScenNName, "Force plant with smallest fixed cost to be closed");
for (int p = 0; p < nPlants; p++) {
if (FixedCosts[p] == minFixed) {
open[p].set(GRB.DoubleAttr.ScenNUB, 0.0);
break;
}
}
// Guess at the starting point: close the plant with the highest
// fixed costs; open all others
// First, open all plants
for (int p = 0; p < nPlants; ++p) {
open[p].set(GRB.DoubleAttr.Start, 1.0);
}
// Now close the plant with the highest fixed cost
System.out.println("Initial guess:");
for (int p = 0; p < nPlants; ++p) {
if (FixedCosts[p] == maxFixed) {
open[p].set(GRB.DoubleAttr.Start, 0.0);
System.out.println("Closing plant " + p + "\n");
break;
}
}
// Use barrier to solve root relaxation
model.set(GRB.IntParam.Method, GRB.METHOD_BARRIER);
// Solve multi-scenario model
model.optimize();
int nScenarios = model.get(GRB.IntAttr.NumScenarios);
// Print solution for each */
for (int s = 0; s < nScenarios; s++) {
int modelSense = GRB.MINIMIZE;
// Set the scenario number to query the information for this scenario
model.set(GRB.IntParam.ScenarioNumber, s);
// collect result for the scenario
double scenNObjBound = model.get(GRB.DoubleAttr.ScenNObjBound);
double scenNObjVal = model.get(GRB.DoubleAttr.ScenNObjVal);
System.out.println("\n\n------ Scenario " + s +
" (" + model.get(GRB.StringAttr.ScenNName) + ")");
// Check if we found a feasible solution for this scenario
if (modelSense * scenNObjVal >= GRB.INFINITY)
if (modelSense * scenNObjBound >= GRB.INFINITY)
// Scenario was proven to be infeasible
System.out.println("\nINFEASIBLE");
else
// We did not find any feasible solution - should not happen in
// this case, because we did not set any limit (like a time
// limit) on the optimization process
System.out.println("\nNO SOLUTION");
else {
System.out.println("\nTOTAL COSTS: " + scenNObjVal);
System.out.println("SOLUTION:");
for (int p = 0; p < nPlants; p++) {
double scenNX = open[p].get(GRB.DoubleAttr.ScenNX);
if (scenNX > 0.5) {
System.out.println("Plant " + p + " open");
for (int w = 0; w < nWarehouses; w++) {
scenNX = transport[w][p].get(GRB.DoubleAttr.ScenNX);
if (scenNX > 0.0001)
System.out.println(" Transport " + scenNX +
" units to warehouse " + w);
}
} else
System.out.println("Plant " + p + " closed!");
}
}
}
// Print a summary table: for each scenario we add a single summary
// line
System.out.println("\n\nSummary: Closed plants depending on scenario\n");
System.out.format("%8s | %17s %13s\n", "", "Plant", "|");
System.out.format("%8s |", "Scenario");
for (int p = 0; p < nPlants; p++)
System.out.format(" %5d", p);
System.out.format(" | %6s %s\n", "Costs", "Name");
for (int s = 0; s < nScenarios; s++) {
int modelSense = GRB.MINIMIZE;
// Set the scenario number to query the information for this scenario
model.set(GRB.IntParam.ScenarioNumber, s);
// Collect result for the scenario
double scenNObjBound = model.get(GRB.DoubleAttr.ScenNObjBound);
double scenNObjVal = model.get(GRB.DoubleAttr.ScenNObjVal);
System.out.format("%-8d |", s);
// Check if we found a feasible solution for this scenario
if (modelSense * scenNObjVal >= GRB.INFINITY) {
if (modelSense * scenNObjBound >= GRB.INFINITY)
// Scenario was proven to be infeasible
System.out.format(" %-30s| %6s %s\n",
"infeasible", "-", model.get(GRB.StringAttr.ScenNName));
else
// We did not find any feasible solution - should not happen in
// this case, because we did not set any limit (like a time
// limit) on the optimization process
System.out.format(" %-30s| %6s %s\n",
"no solution found", "-", model.get(GRB.StringAttr.ScenNName));
} else {
for (int p = 0; p < nPlants; p++) {
double scenNX = open[p].get(GRB.DoubleAttr.ScenNX);
if (scenNX > 0.5)
System.out.format("%6s", " ");
else
System.out.format("%6s", "x");
}
System.out.format(" | %6g %s\n", scenNObjVal, model.get(GRB.StringAttr.ScenNName));
}
}
// Dispose of model and environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
}
#!/usr/bin/env python3.11
# Copyright 2024, Gurobi Optimization, LLC
# Facility location: a company currently ships its product from 5 plants to
# 4 warehouses. It is considering closing some plants to reduce costs. What
# plant(s) should the company close, in order to minimize transportation
# and fixed costs?
#
# Since the plant fixed costs and the warehouse demands are uncertain, a
# scenario approach is chosen.
#
# Note that this example is similar to the facility.py example. Here we
# added scenarios in order to illustrate the multi-scenario feature.
#
# Note that this example uses lists instead of dictionaries. Since
# it does not work with sparse data, lists are a reasonable option.
#
# Based on an example from Frontline Systems:
# http://www.solver.com/disfacility.htm
# Used with permission.
import gurobipy as gp
from gurobipy import GRB
# Warehouse demand in thousands of units
demand = [15, 18, 14, 20]
# Plant capacity in thousands of units
capacity = [20, 22, 17, 19, 18]
# Fixed costs for each plant
fixedCosts = [12000, 15000, 17000, 13000, 16000]
maxFixed = max(fixedCosts)
minFixed = min(fixedCosts)
# Transportation costs per thousand units
transCosts = [
[4000, 2000, 3000, 2500, 4500],
[2500, 2600, 3400, 3000, 4000],
[1200, 1800, 2600, 4100, 3000],
[2200, 2600, 3100, 3700, 3200],
]
# Range of plants and warehouses
plants = range(len(capacity))
warehouses = range(len(demand))
# Model
m = gp.Model("multiscenario")
# Plant open decision variables: open[p] == 1 if plant p is open.
open = m.addVars(plants, vtype=GRB.BINARY, obj=fixedCosts, name="open")
# Transportation decision variables: transport[w,p] captures the
# optimal quantity to transport to warehouse w from plant p
transport = m.addVars(warehouses, plants, obj=transCosts, name="trans")
# You could use Python looping constructs and m.addVar() to create
# these decision variables instead. The following would be equivalent
# to the preceding two statements...
#
# open = []
# for p in plants:
# open.append(m.addVar(vtype=GRB.BINARY,
# obj=fixedCosts[p],
# name="open[%d]" % p))
#
# transport = []
# for w in warehouses:
# transport.append([])
# for p in plants:
# transport[w].append(m.addVar(obj=transCosts[w][p],
# name="trans[%d,%d]" % (w, p)))
# The objective is to minimize the total fixed and variable costs
m.ModelSense = GRB.MINIMIZE
# Production constraints
# Note that the right-hand limit sets the production to zero if the plant
# is closed
m.addConstrs(
(transport.sum("*", p) <= capacity[p] * open[p] for p in plants), "Capacity"
)
# Using Python looping constructs, the preceding would be...
#
# for p in plants:
# m.addConstr(sum(transport[w][p] for w in warehouses)
# <= capacity[p] * open[p], "Capacity[%d]" % p)
# Demand constraints
demandConstr = m.addConstrs(
(transport.sum(w) == demand[w] for w in warehouses), "Demand"
)
# ... and the preceding would be ...
# for w in warehouses:
# m.addConstr(sum(transport[w][p] for p in plants) == demand[w],
# "Demand[%d]" % w)
# We constructed the base model, now we add 7 scenarios
#
# Scenario 0: Represents the base model, hence, no manipulations.
# Scenario 1: Manipulate the warehouses demands slightly (constraint right
# hand sides).
# Scenario 2: Double the warehouses demands (constraint right hand sides).
# Scenario 3: Manipulate the plant fixed costs (objective coefficients).
# Scenario 4: Manipulate the warehouses demands and fixed costs.
# Scenario 5: Force the plant with the largest fixed cost to stay open
# (variable bounds).
# Scenario 6: Force the plant with the smallest fixed cost to be closed
# (variable bounds).
m.NumScenarios = 7
# Scenario 0: Base model, hence, nothing to do except giving the scenario a
# name
m.Params.ScenarioNumber = 0
m.ScenNName = "Base model"
# Scenario 1: Increase the warehouse demands by 10%
m.Params.ScenarioNumber = 1
m.ScenNName = "Increased warehouse demands"
for w in warehouses:
demandConstr[w].ScenNRhs = demand[w] * 1.1
# Scenario 2: Double the warehouse demands
m.Params.ScenarioNumber = 2
m.ScenNName = "Double the warehouse demands"
for w in warehouses:
demandConstr[w].ScenNRhs = demand[w] * 2.0
# Scenario 3: Decrease the plant fixed costs by 5%
m.Params.ScenarioNumber = 3
m.ScenNName = "Decreased plant fixed costs"
for p in plants:
open[p].ScenNObj = fixedCosts[p] * 0.95
# Scenario 4: Combine scenario 1 and scenario 3
m.Params.ScenarioNumber = 4
m.ScenNName = "Increased warehouse demands and decreased plant fixed costs"
for w in warehouses:
demandConstr[w].ScenNRhs = demand[w] * 1.1
for p in plants:
open[p].ScenNObj = fixedCosts[p] * 0.95
# Scenario 5: Force the plant with the largest fixed cost to stay open
m.Params.ScenarioNumber = 5
m.ScenNName = "Force plant with largest fixed cost to stay open"
open[fixedCosts.index(maxFixed)].ScenNLB = 1.0
# Scenario 6: Force the plant with the smallest fixed cost to be closed
m.Params.ScenarioNumber = 6
m.ScenNName = "Force plant with smallest fixed cost to be closed"
open[fixedCosts.index(minFixed)].ScenNUB = 0.0
# Save model
m.write("multiscenario.lp")
# Guess at the starting point: close the plant with the highest fixed costs;
# open all others
# First open all plants
for p in plants:
open[p].Start = 1.0
# Now close the plant with the highest fixed cost
p = fixedCosts.index(maxFixed)
open[p].Start = 0.0
print(f"Initial guess: Closing plant {p}\n")
# Use barrier to solve root relaxation
m.Params.Method = 2
# Solve multi-scenario model
m.optimize()
# Print solution for each scenario
for s in range(m.NumScenarios):
# Set the scenario number to query the information for this scenario
m.Params.ScenarioNumber = s
print(f"\n\n------ Scenario {s} ({m.ScenNName})")
# Check if we found a feasible solution for this scenario
if m.ModelSense * m.ScenNObjVal >= GRB.INFINITY:
if m.ModelSense * m.ScenNObjBound >= GRB.INFINITY:
# Scenario was proven to be infeasible
print("\nINFEASIBLE")
else:
# We did not find any feasible solution - should not happen in
# this case, because we did not set any limit (like a time
# limit) on the optimization process
print("\nNO SOLUTION")
else:
print(f"\nTOTAL COSTS: {m.ScenNObjVal:g}")
print("SOLUTION:")
for p in plants:
if open[p].ScenNX > 0.5:
print(f"Plant {p} open")
for w in warehouses:
if transport[w, p].ScenNX > 0:
print(
f" Transport {transport[w, p].ScenNX:g} units to warehouse {w}"
)
else:
print(f"Plant {p} closed!")
# Print a summary table: for each scenario we add a single summary line
print("\n\nSummary: Closed plants depending on scenario\n")
print(f"{'':8} | {'Plant':>17} {'|':>13}")
tableStr = [f"{'Scenario':8} |"]
tableStr += [f"{p:>5}" for p in plants]
tableStr += [f"| {'Costs':>6} Name"]
print(" ".join(tableStr))
for s in range(m.NumScenarios):
# Set the scenario number to query the information for this scenario
m.Params.ScenarioNumber = s
tableStr = f"{s:<8} |"
# Check if we found a feasible solution for this scenario
if m.ModelSense * m.ScenNObjVal >= GRB.INFINITY:
if m.ModelSense * m.ScenNObjBound >= GRB.INFINITY:
# Scenario was proven to be infeasible
print(tableStr, f"{'infeasible':<30}| {'-':>6} {m.ScenNName:<}")
else:
# We did not find any feasible solution - should not happen in
# this case, because we did not set any limit (like a time
# limit) on the optimization process
print(tableStr, f"{'no solution found':<30}| {'-':>6} {m.ScenNName:<}")
else:
for p in plants:
if open[p].ScenNX > 0.5:
tableStr += f" {' ':>5}"
else:
tableStr += f" {'x':>5}"
print(tableStr, f"| {m.ScenNObjVal:6g} {m.ScenNName:<}")
' Copyright 2024, Gurobi Optimization, LLC
' Facility location: a company currently ships its product from 5 plants
' to 4 warehouses. It is considering closing some plants to reduce
' costs. What plant(s) should the company close, in order to minimize
' transportation and fixed costs?
'
' Since the plant fixed costs and the warehouse demands are uncertain, a
' scenario approach is chosen.
'
' Note that this example is similar to the facility_vb.vb example. Here we
' added scenarios in order to illustrate the multi-scenario feature.
'
' Based on an example from Frontline Systems:
' http://www.solver.com/disfacility.htm
' Used with permission.
Imports System
Imports Gurobi
Class multiscenario_vb
Shared Sub Main()
Try
' Warehouse demand in thousands of units
Dim Demand As Double() = New Double() {15, 18, 14, 20}
' Plant capacity in thousands of units
Dim Capacity As Double() = New Double() {20, 22, 17, 19, 18}
' Fixed costs for each plant
Dim FixedCosts As Double() = New Double() {12000, 15000, 17000, 13000, 16000}
' Transportation costs per thousand units
Dim TransCosts As Double(,) = New Double(,) { {4000, 2000, 3000, 2500, 4500}, _
{2500, 2600, 3400, 3000, 4000}, _
{1200, 1800, 2600, 4100, 3000}, _
{2200, 2600, 3100, 3700, 3200}}
' Number of plants and warehouses
Dim nPlants As Integer = Capacity.Length
Dim nWarehouses As Integer = Demand.Length
Dim maxFixed As Double = -GRB.INFINITY
Dim minFixed As Double = GRB.INFINITY
For p As Integer = 0 To nPlants - 1
If FixedCosts(p) > maxFixed Then maxFixed = FixedCosts(p)
If FixedCosts(p) < minFixed Then minFixed = FixedCosts(p)
Next
' Model
Dim env As GRBEnv = New GRBEnv()
Dim model As GRBModel = New GRBModel(env)
model.ModelName = "multiscenario"
' Plant open decision variables: open(p) == 1 if plant p is open.
Dim open As GRBVar() = New GRBVar(nPlants - 1) {}
For p As Integer = 0 To nPlants - 1
open(p) = model.AddVar(0, 1, FixedCosts(p), GRB.BINARY, "Open" & p)
Next
' Transportation decision variables: how much to transport from a plant
' p to a warehouse w
Dim transport As GRBVar(,) = New GRBVar(nWarehouses - 1, nPlants - 1) {}
For w As Integer = 0 To nWarehouses - 1
For p As Integer = 0 To nPlants - 1
transport(w, p) = model.AddVar(0, GRB.INFINITY, TransCosts(w, p), _
GRB.CONTINUOUS, "Trans" & p & "." & w)
Next
Next
' The objective is to minimize the total fixed and variable costs
model.ModelSense = GRB.MINIMIZE
' Production constraints
' Note that the right-hand limit sets the production to zero if
' the plant is closed
For p As Integer = 0 To nPlants - 1
Dim ptot As GRBLinExpr = 0.0
For w As Integer = 0 To nWarehouses - 1
ptot.AddTerm(1.0, transport(w, p))
Next
model.AddConstr(ptot <= Capacity(p) * open(p), "Capacity" & p)
Next
' Demand constraints
Dim demandConstr As GRBConstr() = New GRBConstr(nWarehouses - 1) {}
For w As Integer = 0 To nWarehouses - 1
Dim dtot As GRBLinExpr = 0.0
For p As Integer = 0 To nPlants - 1
dtot.AddTerm(1.0, transport(w, p))
Next
demandConstr(w) = model.AddConstr(dtot = Demand(w), "Demand" & w)
Next
' We constructed the base model, now we add 7 scenarios
'
' Scenario 0: Represents the base model, hence, no manipulations.
' Scenario 1: Manipulate the warehouses demands slightly (constraint right
' hand sides).
' Scenario 2: Double the warehouses demands (constraint right hand sides).
' Scenario 3: Manipulate the plant fixed costs (objective coefficients).
' Scenario 4: Manipulate the warehouses demands and fixed costs.
' Scenario 5: Force the plant with the largest fixed cost to stay open
' (variable bounds).
' Scenario 6: Force the plant with the smallest fixed cost to be closed
' (variable bounds).
model.NumScenarios = 7
' Scenario 0: Base model, hence, nothing to do except giving the
' scenario a name
model.Parameters.ScenarioNumber = 0
model.ScenNName = "Base model"
' Scenario 1: Increase the warehouse demands by 10%
model.Parameters.ScenarioNumber = 1
model.ScenNName = "Increased warehouse demands"
For w As Integer = 0 To nWarehouses - 1
demandConstr(w).ScenNRHS = Demand(w) * 1.1
Next
' Scenario 2: Double the warehouse demands
model.Parameters.ScenarioNumber = 2
model.ScenNName = "Double the warehouse demands"
For w As Integer = 0 To nWarehouses - 1
demandConstr(w).ScenNRHS = Demand(w) * 2.0
Next
' Scenario 3: Decrease the plant fixed costs by 5%
model.Parameters.ScenarioNumber = 3
model.ScenNName = "Decreased plant fixed costs"
For p As Integer = 0 To nPlants - 1
open(p).ScenNObj = FixedCosts(p) * 0.95
Next
' Scenario 4: Combine scenario 1 and scenario 3 */
model.Parameters.ScenarioNumber = 4
model.ScenNName = "Increased warehouse demands and decreased plant fixed costs"
For w As Integer = 0 To nWarehouses - 1
demandConstr(w).ScenNRHS = Demand(w) * 1.1
Next
For p As Integer = 0 To nPlants - 1
open(p).ScenNObj = FixedCosts(p) * 0.95
Next
' Scenario 5: Force the plant with the largest fixed cost to stay
' open
model.Parameters.ScenarioNumber = 5
model.ScenNName = "Force plant with largest fixed cost to stay open"
For p As Integer = 0 To nPlants - 1
If FixedCosts(p) = maxFixed Then
open(p).ScenNLB = 1.0
Exit For
End If
Next
' Scenario 6: Force the plant with the smallest fixed cost to be
' closed
model.Parameters.ScenarioNumber = 6
model.ScenNName = "Force plant with smallest fixed cost to be closed"
For p As Integer = 0 To nPlants - 1
If FixedCosts(p) = minFixed Then
open(p).ScenNUB = 0.0
Exit For
End If
Next
' Guess at the starting point: close the plant with the highest fixed
' costs; open all others
' First, open all plants
For p As Integer = 0 To nPlants - 1
open(p).Start = 1.0
Next
' Now close the plant with the highest fixed cost
Console.WriteLine("Initial guess:")
For p As Integer = 0 To nPlants - 1
If FixedCosts(p) = maxFixed Then
open(p).Start = 0.0
Console.WriteLine("Closing plant " & p & vbLf)
Exit For
End If
Next
' Use barrier to solve root relaxation
model.Parameters.Method = GRB.METHOD_BARRIER
' Solve multi-scenario model
model.Optimize()
Dim nScenarios As Integer = model.NumScenarios
For s As Integer = 0 To nScenarios - 1
Dim modelSense As Integer = GRB.MINIMIZE
' Set the scenario number to query the information for this scenario
model.Parameters.ScenarioNumber = s
' collect result for the scenario
Dim scenNObjBound As Double = model.ScenNObjBound
Dim scenNObjVal As Double = model.ScenNObjVal
Console.WriteLine(vbLf & vbLf & "------ Scenario " & s & " (" & model.ScenNName & ")")
' Check if we found a feasible solution for this scenario
If modelSense * scenNObjVal >= GRB.INFINITY Then
If modelSense * scenNObjBound >= GRB.INFINITY Then
' Scenario was proven to be infeasible
Console.WriteLine(vbLf & "INFEASIBLE")
Else
' We did not find any feasible solution - should not happen in
' this case, because we did not set any limit (like a time
' limit) on the optimization process
Console.WriteLine(vbLf & "NO SOLUTION")
End If
Else
Console.WriteLine(vbLf & "TOTAL COSTS: " & scenNObjVal)
Console.WriteLine("SOLUTION:")
For p As Integer = 0 To nPlants - 1
Dim scenNX As Double = open(p).ScenNX
If scenNX > 0.5 Then
Console.WriteLine("Plant " & p & " open")
For w As Integer = 0 To nWarehouses - 1
scenNX = transport(w, p).ScenNX
If scenNX > 0.0001 Then Console.WriteLine(" Transport " & scenNX & " units to warehouse " & w)
Next
Else
Console.WriteLine("Plant " & p & " closed!")
End If
Next
End If
Next
' Print a summary table: for each scenario we add a single summary line
Console.WriteLine(vbLf & vbLf & "Summary: Closed plants depending on scenario" & vbLf)
Console.WriteLine("{0,8} | {1,17} {2,13}", "", "Plant", "|")
Console.Write("{0,8} |", "Scenario")
For p As Integer = 0 To nPlants - 1
Console.Write("{0,6}", p)
Next
Console.WriteLine(" | {0,6} Name", "Costs")
For s As Integer = 0 To nScenarios - 1
Dim modelSense As Integer = GRB.MINIMIZE
' Set the scenario number to query the information for this scenario
model.Parameters.ScenarioNumber = s
' Collect result for the scenario
Dim scenNObjBound As Double = model.ScenNObjBound
Dim scenNObjVal As Double = model.ScenNObjVal
Console.Write("{0,-8} |", s)
' Check if we found a feasible solution for this scenario
If modelSense * scenNObjVal >= GRB.INFINITY Then
If modelSense * scenNObjBound >= GRB.INFINITY Then
' Scenario was proven to be infeasible
Console.WriteLine(" {0,-30}| {1,6} " & model.ScenNName, "infeasible", "-")
Else
' We did not find any feasible solution - should not happen in
' this case, because we did not set any limit (like a Time
' limit) on the optimization process
Console.WriteLine(" {0,-30}| {1,6} " & model.ScenNName, "no solution found", "-")
End If
Else
For p As Integer = 0 To nPlants - 1
Dim scenNX As Double = open(p).ScenNX
If scenNX > 0.5 Then
Console.Write("{0,6}", " ")
Else
Console.Write("{0,6}", "x")
End If
Next
Console.WriteLine(" | {0,6} " & model.ScenNName, scenNObjVal)
End If
Next
model.Dispose()
env.Dispose()
Catch e As GRBException
Console.WriteLine("Error code: " & e.ErrorCode & ". " + e.Message)
End Try
End Sub
End Class