use of sdp.write.WriteToExcel in project Stochastic-Inventory by RobinChen121.
the class MultiItemCashLookPolicy method main.
public static void main(String[] args) {
double[] price = { 10, 5 };
// higher margin vs lower margin
double[] variCost = { 4, 2 };
// initial cash
double iniCash = 25;
// initial inventory
int iniInventory1 = 0;
int iniInventory2 = 0;
// higher average demand vs lower average demand
double[][] demand = { { 6, 6 }, { 8, 8 } };
// higher variance vs lower variance
double[] coe = { 0.5, 0.25 };
double[] salPrice = { 2, 1 };
// horizon length
int T = demand[0].length;
double truncationQuantile = 0.999;
int stepSize = 1;
double minCashState = 0;
double maxCashState = 10000;
int minInventoryState = 0;
int maxInventoryState = 200;
int Qbound = 100;
double discountFactor = 1;
double Rmin = 25;
double Rmax = 80;
int incre = 2;
int rowNum = (int) ((Rmax - Rmin) / incre) + 2;
int row = 0;
double[][] optResults = new double[rowNum][5];
for (iniCash = Rmin; iniCash <= Rmax; iniCash = iniCash + incre) {
// get demand possibilities for each period
Distribution[][] distributions = new Distribution[demand.length][T];
for (int t = 0; t < T; t++) {
for (int i = 0; i < demand.length; i++) {
distributions[t][i] = new PoissonDist(demand[i][t]);
}
}
double[][][] pmf = new GetPmf(distributions, truncationQuantile, stepSize).getpmfMulti();
// build action list for two items
Function<CashStateMulti, ArrayList<Actions>> buildActionList = s -> {
ArrayList<Actions> actions = new ArrayList<>();
for (int i = 0; i < Qbound; i++) for (int j = 0; j < Qbound; j++) {
if (variCost[0] * i + variCost[1] * j < s.getIniCash() + 0.1) {
Actions thisAction = new Actions(i, j);
actions.add(thisAction);
}
}
return actions;
};
// Immediate Value Function
ImmediateValueFunction<CashStateMulti, Actions, Demands, Double> immediateValue = (IniState, Actions, RandomDemands) -> {
double action1 = Actions.getFirstAction();
double action2 = Actions.getSecondAction();
double demand1 = RandomDemands.getFirstDemand();
double demand2 = RandomDemands.getSecondDemand();
double endInventory1 = Math.max(0, IniState.getIniInventory1() + action1 - demand1);
double endInventory2 = Math.max(0, IniState.getIniInventory2() + action2 - demand2);
double revenue = price[0] * (IniState.getIniInventory1() + action1 - endInventory1) + price[1] * (IniState.getIniInventory2() + action2 - endInventory2);
double orderingCosts = variCost[0] * action1 + variCost[1] * action2;
double salValue = 0;
if (IniState.getPeriod() == T - 1) {
salValue = salPrice[0] * endInventory1 + salPrice[1] * endInventory2;
}
return revenue - orderingCosts + salValue;
};
// State Transition Function
StateTransitionFunction<CashStateMulti, Actions, Demands, CashStateMulti> stateTransition = (IniState, Actions, RandomDemands) -> {
double endInventory1 = IniState.getIniInventory1() + Actions.getFirstAction() - RandomDemands.getFirstDemand();
endInventory1 = Math.max(0, endInventory1);
double endInventory2 = IniState.getIniInventory2() + Actions.getSecondAction() - RandomDemands.getSecondDemand();
endInventory2 = Math.max(0, endInventory2);
double nextCash = IniState.getIniCash() + immediateValue.apply(IniState, Actions, RandomDemands);
nextCash = nextCash > maxCashState ? maxCashState : nextCash;
nextCash = nextCash < minCashState ? minCashState : nextCash;
endInventory1 = endInventory1 > maxInventoryState ? maxInventoryState : endInventory1;
endInventory2 = endInventory2 < minInventoryState ? minInventoryState : endInventory2;
// rounding states to save computing time
nextCash = (int) nextCash;
endInventory1 = (int) endInventory1;
endInventory2 = (int) endInventory2;
return new CashStateMulti(IniState.getPeriod() + 1, endInventory1, endInventory2, nextCash);
};
/**
*****************************************************************
* Solve
*/
CashRecursionMulti recursion = new CashRecursionMulti(discountFactor, pmf, buildActionList, stateTransition, immediateValue, T);
int period = 1;
CashStateMulti iniState = new CashStateMulti(period, iniInventory1, iniInventory2, iniCash);
long currTime = System.currentTimeMillis();
double finalValue = iniCash + recursion.getExpectedValueMulti(iniState);
System.out.println("final optimal cash is " + finalValue);
System.out.println("optimal order quantity in the first priod is : Q1 = " + recursion.getAction(iniState).getFirstAction() + ", Q2 = " + recursion.getAction(iniState).getSecondAction());
double time = (System.currentTimeMillis() - currTime) / 1000;
System.out.println("running time is " + time + "s");
/**
*****************************************************************
* Simulating sdp results
*
* simulating results a little lower than SDP
*/
int sampleNum = 10000;
CashSimulationMulti simuation = new CashSimulationMulti(sampleNum, distributions, discountFactor, recursion, stateTransition, immediateValue);
double simFinalValue = simuation.simulateSDPGivenSamplNumMulti(iniState);
System.out.println(simFinalValue);
/**
*****************************************************************
* try to find some ordering patters from optTable
*
* output results to excel
*/
double Q1 = recursion.getAction(iniState).getFirstAction();
double Q2 = recursion.getAction(iniState).getSecondAction();
System.out.println("");
optResults[row][0] = iniInventory1;
optResults[row][1] = iniInventory2;
optResults[row][2] = iniCash;
optResults[row][3] = Q1;
optResults[row][4] = Q2;
row++;
}
System.out.println("**************************************************");
WriteToExcel wr = new WriteToExcel();
String fileName = "optTable2.xls";
String headString = "x1" + "\t" + "x2" + "\t" + "R" + "\t" + "Q1" + "\t" + "Q2";
wr.writeArrayToExcel(optResults, fileName, headString);
}
use of sdp.write.WriteToExcel in project Stochastic-Inventory by RobinChen121.
the class CashConstraintLookPolicy method main.
public static void main(String[] args) {
double[] meanDemand = { 2, 3, 8 };
// double[] meanDemand = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20};
double iniInventory = 8;
double iniCash = 100;
double fixOrderCost = 10;
double variCost = 1;
double price = 8;
double depositeRate = 0;
double salvageValue = 0.5;
double holdingCost = 0;
FindCCrieria criteria = FindCCrieria.XRELATE;
// costs like wages or rents which is required to pay in each period
double overheadCost = 0;
// rate from revenue to pay overhead wages
double overheadRate = 0;
// maximum ordering quantity when having enough cash
double maxOrderQuantity = 200;
double truncationQuantile = 0.9999;
int stepSize = 1;
double minInventoryState = 0;
double maxInventoryState = 500;
// can affect results, should be smaller than minus fixedOrderCost
double minCashState = -100;
double maxCashState = 2000;
double discountFactor = 1;
double xmin = 0;
double xmax = 10;
double Rmin = fixOrderCost;
double Rmax = 40;
int row = 0;
int column = 0;
int columnNum = (int) (Rmax - Rmin + 1) + 1;
// ((Rmax - Rmin + 1)/2) + 2;
int rowNum = (int) ((xmax - xmin + 1) / 1) + 1;
double[][] resultTable = new double[rowNum][columnNum];
for (iniInventory = xmax; iniInventory >= xmin; iniInventory--) {
column = 0;
for (iniCash = Rmin; iniCash <= Rmax; iniCash = iniCash + 1) {
// get demand possibilities for each period
int T = meanDemand.length;
Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(T).mapToObj(i -> new PoissonDist(meanDemand[i])).toArray(Distribution[]::new);
double[][][] pmf = new GetPmf(distributions, truncationQuantile, stepSize).getpmf();
// feasible actions
Function<CashState, double[]> getFeasibleAction = s -> {
double maxQ = (int) Math.min(maxOrderQuantity, Math.max(0, (s.getIniCash() - overheadCost - fixOrderCost) / variCost));
return DoubleStream.iterate(0, i -> i + stepSize).limit((int) maxQ + 1).toArray();
};
// immediate value
ImmediateValueFunction<CashState, Double, Double, Double> immediateValue = (state, action, randomDemand) -> {
double revenue = price * Math.min(state.getIniInventory() + action, randomDemand);
double fixedCost = action > 0 ? fixOrderCost : 0;
double variableCost = variCost * action;
double deposite = (state.getIniCash() - fixedCost - variableCost) * (1 + depositeRate);
double inventoryLevel = state.getIniInventory() + action - randomDemand;
double holdCosts = holdingCost * Math.max(inventoryLevel, 0);
double cashIncrement = (1 - overheadRate) * revenue + deposite - holdCosts - overheadCost - state.getIniCash();
double salValue = state.getPeriod() == T ? salvageValue * Math.max(inventoryLevel, 0) : 0;
cashIncrement += salValue;
return cashIncrement;
};
// state transition function
StateTransitionFunction<CashState, Double, Double, CashState> stateTransition = (state, action, randomDemand) -> {
double nextInventory = Math.max(0, state.getIniInventory() + action - randomDemand);
double nextCash = state.getIniCash() + immediateValue.apply(state, action, randomDemand);
nextCash = nextCash > maxCashState ? maxCashState : nextCash;
nextCash = nextCash < minCashState ? minCashState : nextCash;
nextInventory = nextInventory > maxInventoryState ? maxInventoryState : nextInventory;
nextInventory = nextInventory < minInventoryState ? minInventoryState : nextInventory;
// cash is integer or not
nextCash = Math.round(nextCash * 1) / 1;
return new CashState(state.getPeriod() + 1, nextInventory, nextCash);
};
/**
*****************************************************************
* Solve
*/
CashRecursion recursion = new CashRecursion(OptDirection.MAX, pmf, getFeasibleAction, stateTransition, immediateValue, discountFactor);
int period = 1;
CashState initialState = new CashState(period, iniInventory, iniCash);
long currTime = System.currentTimeMillis();
recursion.setTreeMapCacheAction();
double finalValue = iniCash + recursion.getExpectedValue(initialState);
System.out.println("final optimal cash is " + finalValue);
double optQ = recursion.getAction(initialState);
System.out.println("optimal order quantity in the first priod is : " + optQ);
double time = (System.currentTimeMillis() - currTime) / 1000;
System.out.println("running time is " + time + "s");
System.out.println("initial inventory is " + iniInventory);
System.out.println("initial cash is " + iniCash);
resultTable[0][column + 1] = iniCash;
resultTable[row + 1][0] = iniInventory;
// finalValue - iniCash;
resultTable[row + 1][column + 1] = optQ;
System.out.println("**********************************************************");
// /*******************************************************************
// * Simulating sdp results
// * parameter vales like price, variCost, holdingCost etc.
// * are only for compute L(y), not very necessary
// */
// int sampleNum = 10000;
//
// CashSimulation simuation = new CashSimulation(distributions, sampleNum, recursion, discountFactor,
// fixOrderCost, price, variCost, holdingCost, salvageValue); // no need to add overheadCost in this class
// double simFinalValue = simuation.simulateSDPGivenSamplNum(initialState);
// double error = 0.0001;
// double confidence = 0.95;
// simuation.simulateSDPwithErrorConfidence(initialState, error, confidence);
//
column++;
}
row++;
}
WriteToExcel wr = new WriteToExcel();
wr.writeArrayToExcel(resultTable, "resultTable.xls");
}
use of sdp.write.WriteToExcel in project Stochastic-Inventory by RobinChen121.
the class CashConstraintXR method main.
public static void main(String[] args) {
double[] meanDemand = { 8, 8, 8, 8 };
double iniInventory = 0;
double iniCash = 30;
double fixOrderCost = 0;
double variCost = 2;
double price = 4;
double depositeRate = 0;
double salvageValue = 1;
double holdingCost = 0;
FindCCrieria criteria = FindCCrieria.XRELATE;
// costs like wages or rents which is required to pay in each period
double overheadCost = 0;
// rate from revenue to pay overhead wages
double overheadRate = 0;
// maximum ordering quantity when having enough cash
double maxOrderQuantity = 200;
double truncationQuantile = 0.99;
int stepSize = 1;
double minInventoryState = 0;
double maxInventoryState = 500;
// can affect results, should be smaller than minus fixedOrderCost
double minCashState = -100;
double maxCashState = 2000;
double discountFactor = 1;
// get demand possibilities for each period
int T = meanDemand.length;
Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(T).mapToObj(i -> new GammaDist(meanDemand[i], 2)).toArray(Distribution[]::new);
double[][][] pmf = new GetPmf(distributions, truncationQuantile, stepSize).getpmf();
// feasible actions
Function<CashStateXR, double[]> getFeasibleAction = s -> {
double maxY = s.getIniR() / variCost < s.getIniInventory() ? s.getIniInventory() : s.getIniR() / variCost;
int length = (int) (maxY - s.getIniInventory()) + 1;
return DoubleStream.iterate(s.getIniInventory(), i -> i + stepSize).limit(length).toArray();
};
// immediate value
ImmediateValueFunction<CashStateXR, Double, Double, Double> immediateValue = (state, actionY, randomDemand) -> {
double revenue = price * Math.min(actionY, randomDemand);
double action = actionY - state.getIniInventory();
double fixedCost = actionY > state.getIniInventory() ? fixOrderCost : 0;
double variableCost = variCost * action;
double initCash = state.getIniR() - variCost * state.getIniInventory();
// (1+d)(S-cy)
double deposite = (initCash - fixedCost - variableCost) * (1 + depositeRate);
double inventoryLevel = actionY - randomDemand;
double holdCosts = holdingCost * Math.max(inventoryLevel, 0);
double cashIncrement = (1 - overheadRate) * revenue + deposite - holdCosts - overheadCost - initCash;
double salValue = state.getPeriod() == T ? salvageValue * Math.max(inventoryLevel, 0) : 0;
cashIncrement += salValue;
return cashIncrement;
};
// state transition function
StateTransitionFunction<CashStateXR, Double, Double, CashStateXR> stateTransition = (state, actionY, randomDemand) -> {
if (randomDemand < 0)
System.out.println(randomDemand);
double nextInventory = Math.max(0, actionY - randomDemand);
double initCash = state.getIniR() - variCost * state.getIniInventory();
double nextCash = initCash + immediateValue.apply(state, actionY, randomDemand);
nextCash = nextCash > maxCashState ? maxCashState : nextCash;
nextCash = nextCash < minCashState ? minCashState : nextCash;
nextInventory = nextInventory > maxInventoryState ? maxInventoryState : nextInventory;
nextInventory = nextInventory < minInventoryState ? minInventoryState : nextInventory;
// cash is integer or not
nextCash = Math.round(nextCash * 1) / 1;
double nextR = nextCash + variCost * nextInventory;
return new CashStateXR(state.getPeriod() + 1, nextInventory, nextR, variCost);
};
/**
*****************************************************************
* Solve
*/
CashRecursionXR recursion = new CashRecursionXR(OptDirection.MAX, pmf, getFeasibleAction, stateTransition, immediateValue, discountFactor);
int period = 1;
CashStateXR initialState = new CashStateXR(period, iniInventory, iniCash, variCost);
long currTime = System.currentTimeMillis();
recursion.setTreeMapCacheAction();
double finalValue = iniCash + recursion.getExpectedValue(initialState);
System.out.println("final optimal cash is " + finalValue);
System.out.println("optimal order quantity in the first priod is : " + recursion.getAction(initialState));
double time = (System.currentTimeMillis() - currTime) / 1000.0;
System.out.println("running time is " + time + "s");
/**
*****************************************************************
* Simulating sdp results
* parameter vales like price, variCost, holdingCost etc.
* are only for compute L(y), not very necessary
*/
int sampleNum = 10000;
CashSimulationXR simuation = new CashSimulationXR(distributions, sampleNum, recursion, discountFactor, fixOrderCost, price, variCost, holdingCost, // no need to add overheadCost in this class
salvageValue);
double simFinalValue = simuation.simulateSDPGivenSamplNum(initialState);
double error = 0.0001;
double confidence = 0.95;
simuation.simulateSDPwithErrorConfidence(initialState, error, confidence);
/**
*****************************************************************
* get optimal table of SDP,
* and output it to a excel file
*/
// System.out.println("");
// double[][] optTable = recursion.getOptTable();
// WriteToExcel wr = new WriteToExcel();
// String headString = "period" + "\t" + "x" + "\t" + "S" + "\t" + "R" + "\t" + "y";
// wr.writeArrayToExcel(optTable, "optTable.xls", headString);
/**
*****************************************************************
* get a* in each period
*/
RecursionG recursion2 = new RecursionG(pmf, distributions, price, variCost, depositeRate, salvageValue);
currTime = System.currentTimeMillis();
double[] optY = recursion2.getOptY();
System.out.println();
// if 1000, then it will be integer
time = (System.currentTimeMillis() - currTime) / 1000.0;
System.out.println("a* in each period: ");
System.out.println(Arrays.toString(optY));
System.out.printf("running time is %.3f s", time);
System.out.println();
/**
*****************************************************************
* simulate a* in each period
*/
simuation.simulateAStar(optY, initialState);
}
use of sdp.write.WriteToExcel in project Stochastic-Inventory by RobinChen121.
the class ChanceCashTesting method main.
public static void main(String[] args) {
WriteToExcel wr = new WriteToExcel();
String fileName = "JointChanceSAA.xls";
String headString = "demand mode" + "\t" + "SAA obj" + "\t" + "time" + "t" + "sim SAA obj" + "\t" + "sim obj error" + "\t" + "sim SAA service rate" + "\t" + "sim service error" + "sim time" + "\t" + "extend SAA obj" + "\t" + "time" + "t" + "sim extend SAA obj" + "\t" + "t" + "obj error" + "t" + "sim extend SAA service" + "\t" + "service error" + "t" + "sim time";
double[][] meanDemands = { { 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30 }, { 46, 49, 50, 50, 49, 46, 42, 38, 33, 28, 23, 18 }, { 8, 11, 14, 18, 23, 28, 33, 38, 42, 46, 49, 50 }, { 47, 30, 13, 6, 13, 30, 47, 54, 47, 30, 13, 6 }, { 36, 30, 24, 21, 24, 30, 36, 39, 36, 30, 24, 21 }, { 63, 27, 10, 24, 1, 23, 33, 35, 67, 7, 14, 41 }, { 1, 15, 46, 140, 80, 147, 134, 74, 84, 109, 47, 88 }, { 14, 24, 71, 118, 49, 86, 152, 117, 226, 208, 78, 59 }, { 13, 35, 79, 43, 44, 59, 22, 55, 61, 34, 50, 95 }, { 15, 56, 19, 84, 136, 67, 67, 155, 87, 164, 19, 67 } };
double iniCash = 40;
double iniI = 0;
double trunQuantile = 0.999;
// the higher value results in slower running speed. maximum negative possibility rate is 1 - serviceRate.
double serviceRate = 0.9;
// meanDemands[0].length;
int T = 6;
int[] sampleNums = new int[T];
double[] prices = new double[T];
double[] variCostUnits = new double[T];
double[] overheadCosts = new double[T];
double[] seasonalPrice = { 14, 20, 18, 15 };
double[] seasonalVariCost = { 10, 15, 16, 12 };
// for use in normal distribution
double sigmasCoe = 0.25;
int sampleTotalNumber = 3000;
// sample number in simulation
int sampleNum = 100;
// number of samples in each period
int sampleNumPeriod = 5;
Arrays.fill(sampleNums, sampleNumPeriod);
for (int t = 0; t < T; t++) {
int m = t % 4;
prices[t] = seasonalPrice[m];
variCostUnits[t] = seasonalVariCost[m];
}
Arrays.fill(prices, 20);
Arrays.fill(variCostUnits, 10);
// overhead costs
Arrays.fill(overheadCosts, 100);
double holdCostUnit = 1;
double salvageValueUnit = 5;
// maximum ordering quantity when having enough cash
double maxOrderQuantity = 300;
int[] sampleNumsRolling = new int[T];
Arrays.fill(sampleNumsRolling, 5);
// rolling horizon length
int rollingLength = 4;
int instanceNum = meanDemands.length;
int runNum = 10;
for (int m = 0; m < instanceNum; m++) {
for (int k = 0; k < runNum; k++) {
int instanceIndex = m;
Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(T).mapToObj(i -> new PoissonDist(meanDemands[instanceIndex][i])).toArray(// Poisson demand
Distribution[]::new);
double meanDemandSum = Arrays.stream(meanDemands[m]).sum();
double rollingDemandSum = Arrays.stream(meanDemands[m]).limit(rollingLength).sum();
double portion = rollingDemandSum / meanDemandSum;
double rollingServiceRate = Math.pow(serviceRate, portion);
// generate scenarios, samples in each period form a scenario tree
Sampling sampling = new Sampling();
double[][] scenarios = sampling.generateLHSamples(distributions, sampleNums);
// sample without replacement
Random rd = new Random();
double[][] demandSamples = new double[sampleTotalNumber][T];
for (int i = 0; i < sampleTotalNumber; i++) {
for (int t = 0; t < T; t++) {
int index = rd.nextInt(sampleNumPeriod);
demandSamples[i][t] = scenarios[t][index];
}
}
/**
* solve the problem by SAA
*/
int negativeScenarioNumRequire = (int) (sampleTotalNumber * (1 - serviceRate));
LostSaleChanceTesting model = new LostSaleChanceTesting(distributions, demandSamples, iniCash, iniI, prices, variCostUnits, salvageValueUnit, holdCostUnit, overheadCosts, serviceRate);
long currTime = System.currentTimeMillis();
double[] resultSAA;
double time1;
double positiveScenario;
double survivalProb;
double lostRate;
NumberFormat nf = NumberFormat.getPercentInstance();
nf.setMinimumFractionDigits(5);
DecimalFormat df = new DecimalFormat("###, ###");
resultSAA = model.solveMaxSurvival();
time1 = (System.currentTimeMillis() - currTime) / 1000.00;
currTime = System.currentTimeMillis();
System.out.println("**********************************************");
System.out.println("result of SAA-scenario tree before sorting scenarios: ");
System.out.println("running time is " + time1 + "s");
System.out.printf("first stage decison Q is: %.2f\n", resultSAA[0]);
positiveScenario = resultSAA[1];
System.out.printf("Objective value is: %.0f in %d scenarios\n", resultSAA[1], sampleTotalNumber);
survivalProb = 100 * resultSAA[1] / sampleTotalNumber;
System.out.printf("Survival probability is: %.5f%%\n", survivalProb);
System.out.println("lost sale scenario number in the solution is : " + resultSAA[2]);
System.out.println("maximum lost sale scenario number allowed is: " + negativeScenarioNumRequire);
lostRate = resultSAA[2] / (double) sampleTotalNumber;
System.out.println("lost sale rate of SAA is: " + nf.format(lostRate));
System.out.println("lost sale max required rate is: " + nf.format(1 - serviceRate));
System.out.println();
/**
* solve the problem by extended formulation of SAA,
* sort scenarios in the whole planning horizon
*/
currTime = System.currentTimeMillis();
double[] resultExtendSAA;
// same result with soveSort or solveSort2, but less computational time
resultExtendSAA = model.solveSortWholeTesting();
time1 = (System.currentTimeMillis() - currTime) / 1000.00;
currTime = System.currentTimeMillis();
System.out.println("**********************************************");
System.out.println("after sorting scenarios in the whole planning horizon, result of SAA-scenario tree: ");
System.out.println("running time is " + time1 + "s");
System.out.printf("first stage decison Q is: %.2f\n", resultExtendSAA[0]);
positiveScenario = resultExtendSAA[1];
System.out.printf("Objective value is: %.0f in %d scenarios\n", positiveScenario, sampleTotalNumber);
survivalProb = 100 * resultExtendSAA[1] / sampleTotalNumber;
System.out.printf("Survival probability is: %.5f%%\n", survivalProb);
System.out.println("lost sale scenario number in the solution is : " + resultExtendSAA[2]);
System.out.println("maximum lost sale scenario number allowed is: " + negativeScenarioNumRequire);
lostRate = resultExtendSAA[2] / (double) sampleTotalNumber;
System.out.println("lost sale rate of SAA is: " + nf.format(lostRate));
System.out.println("lost sale max required rate is: " + nf.format(1 - serviceRate));
System.out.println();
/**
* for simulation class
*/
int stepSize = 1;
double fixOrderCost = 0;
double depositeRate = 0;
double minInventoryState = 0;
double maxInventoryState = 500;
// can affect results, should be smaller than minus fixedOrderCost
double minCashState = -1000;
double maxCashState = 2000;
double discountFactor = 1;
double[][][] pmf = new GetPmf(distributions, trunQuantile, stepSize).getpmf();
// immediate value
ImmediateValueFunction<CashState, Double, Double, Double> immediateValue = (state, action, randomDemand) -> {
int t = state.getPeriod() - 1;
double revenue = prices[t] * Math.min(state.getIniInventory() + action, randomDemand);
double fixedCost = action > 0 ? fixOrderCost : 0;
double variableCost = variCostUnits[t] * action;
double deposite = (state.getIniCash() - fixedCost - variableCost) * (1 + depositeRate);
double inventoryLevel = state.getIniInventory() + action - randomDemand;
double holdCosts = holdCostUnit * Math.max(inventoryLevel, 0);
double cashIncrement = revenue + deposite - holdCosts - overheadCosts[t] - state.getIniCash();
double salValue = state.getPeriod() == T ? salvageValueUnit * Math.max(inventoryLevel, 0) : 0;
cashIncrement += salValue;
return cashIncrement;
};
// state transition function
StateTransitionFunction<CashState, Double, Double, CashState> stateTransition = (state, action, randomDemand) -> {
double nextInventory = Math.max(0, state.getIniInventory() + action - randomDemand);
double nextCash = state.getIniCash() + immediateValue.apply(state, action, randomDemand);
nextCash = nextCash > maxCashState ? maxCashState : nextCash;
nextCash = nextCash < minCashState ? minCashState : nextCash;
nextInventory = nextInventory > maxInventoryState ? maxInventoryState : nextInventory;
nextInventory = nextInventory < minInventoryState ? minInventoryState : nextInventory;
// cash is integer or not
// the right should be a decimal
nextCash = Math.round(nextCash * 1) / 1;
return new CashState(state.getPeriod() + 1, nextInventory, nextCash);
};
int period = 1;
CashState initialState = new CashState(period, iniI, iniCash);
// no need to add overheadCost in this class
CashSimulation simulation1 = new CashSimulation(distributions, sampleNum, immediateValue, stateTransition);
/**
* solve the problem by rolling horizon of extended SAA
*/
// number of scenarios for rolling SAA
sampleNum = 100;
currTime = System.currentTimeMillis();
System.out.println("**********************************************");
System.out.println("after rolling horizon for length " + rollingLength + ", result of SAA-scenario tree: ");
double[] resultRolling;
// include scenarios in the whole planning horizon
double[][] scenariosRolling = sampling.generateLHSamples(distributions, sampleNums);
resultRolling = simulation1.rollingHoirzonFurtherExtendSAA(rollingLength, initialState, rollingServiceRate, sampleNumsRolling, prices, variCostUnits, overheadCosts, salvageValueUnit, holdCostUnit, scenariosRolling, sampleNum);
time1 = (System.currentTimeMillis() - currTime) / 1000.00;
System.out.println("running time is " + time1 + "s");
System.out.println("final simulated survival probability of rolling further SAA in " + df.format(sampleNum) + " samples is: " + nf.format(resultRolling[0]));
/**
* Simulate the restult of SAA
*/
double error;
double thisServiceRate;
double[] result1;
result1 = simulation1.simulateSAATesting(initialState, resultSAA[0], serviceRate, demandSamples, prices, variCostUnits, overheadCosts, salvageValueUnit, holdCostUnit, sampleNum);
System.out.println("final simulated survival probability of SAA in " + df.format(sampleNum) + " samples is: " + nf.format(result1[0]));
error = 1.96 * Math.sqrt(result1[1] * (1 - result1[1]) / sampleNum);
thisServiceRate = 1 - result1[1];
System.out.println("final simulated service sale rate of SAA " + " is: " + nf.format(thisServiceRate) + " with error " + nf.format(error));
System.out.println();
/**
* Simulate the result of extended SAA
*/
result1 = simulation1.simulateExtendSAAWholeTesting(initialState, resultExtendSAA[0], serviceRate, demandSamples, prices, variCostUnits, overheadCosts, salvageValueUnit, holdCostUnit, sampleNum);
System.out.println("final simulated survival probability of extended SAA(sort whole planning horizon) in " + df.format(sampleNum) + " samples is: " + nf.format(result1[0]));
error = 1.96 * Math.sqrt(result1[1] * (1 - result1[1]) / sampleNum);
thisServiceRate = 1 - result1[1];
System.out.println("final simulated service rate of extended SAA(sort whole planning horizon) " + " is: " + nf.format(thisServiceRate) + " with error " + nf.format(error));
}
}
System.out.println();
}
use of sdp.write.WriteToExcel in project Stochastic-Inventory by RobinChen121.
the class MultiItemYR method main.
public static void main(String[] args) {
double[] price = { 2, 10 };
// higher margin vs lower margin
double[] variCost = { 1, 2 };
double depositeRate = 0;
// initial cash
double iniCash = 10;
// initial inventory
int iniInventory1 = 0;
int iniInventory2 = 0;
// gamma distribution:mean demand is shape / beta and variance is shape / beta^2
// beta = 1 / scale
// shape = demand * beta
// variance = demand / beta
// gamma in ssj: alpha is alpha, and lambda is beta(beta)
// horizon length
int T = 4;
double[] meanDemands = new double[] { 10, 3 };
// higher average demand vs lower average demand
double[][] demand = new double[2][T];
// higher variance vs lower variance
double[] beta = { 10, 1 };
double d1 = meanDemands[0];
double d2 = meanDemands[1];
double v1 = variCost[0];
double v2 = variCost[1];
double p1 = price[0];
double p2 = price[1];
for (int t = 0; t < T; t++) {
demand[0][t] = d1;
demand[1][t] = d2;
}
double[] salPrice = Arrays.stream(variCost).map(a -> a * 0.5).toArray();
// number of products
int m = demand.length;
// for (int index = 5; index <= 10; index++) {
// price[1] = index;
// may affect poisson results
double truncationQuantile = 0.9999;
int stepSize = 1;
double minCashState = 0;
double maxCashState = 10000;
int minInventoryState = 0;
int maxInventoryState = 200;
int Qbound = 20;
double discountFactor = 1;
// get demand possibilities for each period
Distribution[][] distributions = new GammaDist[m][T];
// Distribution[][] distributions = new NormalDist[m][T];
for (int i = 0; i < m; i++) for (int t = 0; t < T; t++) {
distributions[i][t] = new GammaDist(demand[i][t] * beta[i], beta[i]);
// distributions[i][t] = new PoissonDist(demand[i][t]);
// distributions[i][t]= new NormalDist(demand[i][t], 0.1 * demand[i][t]);
}
// build action list (y1, y2) for pai(y1, y2, R)
Function<CashStateMultiYR, ArrayList<double[]>> buildActionListPai = s -> {
ArrayList<double[]> actions = new ArrayList<>();
double Ybound = Qbound;
for (double i = 0; i < Ybound; i = i + 1) for (double j = 0; j < Ybound; j = j + 1) {
double[] thisActions = { i, j };
actions.add(thisActions);
}
return actions;
};
// build action list (y1, y2) for V(x1, x2, w)
Function<CashStateMulti, ArrayList<double[]>> buildActionListV = s -> {
ArrayList<double[]> actions = new ArrayList<>();
int miny1 = (int) s.getIniInventory1();
int miny2 = (int) s.getIniInventory2();
double iniR = s.getIniCash() + v1 * s.getIniInventory1() + v2 * s.getIniInventory2();
for (double i = miny1; i < miny1 + Qbound; i = i + 1) for (double j = miny2; j < miny2 + Qbound; j = j + 1) {
if (v1 * i + v2 * j < iniR + 0.1) {
double[] thisActions = { i, j };
actions.add(thisActions);
}
}
return actions;
};
BoundaryFuncton<CashStateMulti, Double> boundFinalCash = (IniState) -> {
return IniState.getIniCash() + salPrice[0] * IniState.getIniInventory1() + salPrice[1] * IniState.getIniInventory2();
};
// State Transition Function: from pai^n(y1, y2, R) to V^{n+1}(x1, x2, w)
StateTransitionFunctionV<CashStateMultiYR, double[], CashStateMulti> stateTransition = (IniState, RandomDemands) -> {
double endInventory1 = IniState.getIniInventory1() - RandomDemands[0];
endInventory1 = Math.max(0, endInventory1);
double endInventory2 = IniState.getIniInventory2() - RandomDemands[1];
endInventory2 = Math.max(0, endInventory2);
double revenue1 = p1 * Math.min(IniState.getIniInventory1(), RandomDemands[0]);
double revenue2 = p2 * Math.min(IniState.getIniInventory2(), RandomDemands[1]);
double nextW = revenue1 + revenue2 + (1 + depositeRate) * (IniState.getIniR() - v1 * IniState.getIniInventory1() - // revise
v2 * IniState.getIniInventory2());
endInventory1 = Math.round(endInventory1 * 10) / 10;
endInventory2 = Math.round(endInventory2 * 10) / 10;
nextW = Math.round(nextW * 10) / 10;
nextW = nextW > maxCashState ? maxCashState : nextW;
nextW = nextW < minCashState ? minCashState : nextW;
endInventory1 = endInventory1 > maxInventoryState ? maxInventoryState : endInventory1;
endInventory2 = endInventory2 < minInventoryState ? minInventoryState : endInventory2;
return new CashStateMulti(IniState.getPeriod() + 1, endInventory1, endInventory2, nextW);
};
GetPmfMulti PmfMulti = new GetPmfMulti(distributions, truncationQuantile, stepSize);
/**
*****************************************************************
* Solve
*/
CashRecursionV recursion = new CashRecursionV(discountFactor, PmfMulti, buildActionListV, buildActionListPai, stateTransition, boundFinalCash, T, variCost);
int period = 1;
CashStateMulti iniState = new CashStateMulti(period, iniInventory1, iniInventory2, iniCash);
long currTime = System.currentTimeMillis();
double finalValue = recursion.getExpectedValueV(iniState);
System.out.println("final optimal cash is " + finalValue);
System.out.println("optimal order quantity in the first priod is : y1 = " + recursion.getAction(iniState)[0] + ", y2 = " + recursion.getAction(iniState)[1]);
double time = (System.currentTimeMillis() - currTime) / 1000.0;
System.out.println("running time is " + time + "s");
CashStateR iniState2 = new CashStateR(period, iniCash);
double[] optY = recursion.getYStar(iniState2);
System.out.println("optimal order quantity y* in the first priod is : " + Arrays.toString(optY));
/**
*****************************************************************
* Simulate
*
* basically, this simulation is testing for Theorem 1:
* optimal ordering decisions depend on y*(R)
*/
int sampleNum = 10000;
currTime = System.currentTimeMillis();
CashSimulationY simulation = new CashSimulationY(sampleNum, distributions, discountFactor, recursion, stateTransition);
double simFinalValue = simulation.simulateSDPGivenSamplNum(iniState, variCost);
double gap = (simFinalValue - finalValue) / finalValue;
System.out.printf("optimality gap for this policy y* is %.2f%%\n", gap * 100);
time = (System.currentTimeMillis() - currTime) / 1000.0;
System.out.println("running time is " + time + "s");
//
// /*******************************************************************
// * Compute a1* and a2*
// *
// * and simulate their results to test Theorem 2
// *
// */
// double[][][] pmf1 = new GetPmf(distributions[0], truncationQuantile, stepSize).getpmf();
// Distribution[] distributions1 = distributions[0];
// double[][][] pmf2 = new GetPmf(distributions[1], truncationQuantile, stepSize).getpmf();
// Distribution[] distributions2 = distributions[1];
// RecursionG recursionG1 = new RecursionG(pmf1, distributions1, price[0], variCost[0], 0, salPrice[0]);
// RecursionG recursionG2 = new RecursionG(pmf2, distributions2, price[1], variCost[1], 0, salPrice[1]);
// double[] opta1 = recursionG1.getOptY();
// double[] opta2 = recursionG2.getOptY();
// System.out.println("a1* in each period:");
// DecimalFormat df = new DecimalFormat("0.00");
// Arrays.stream(opta1).forEach(e -> System.out.print(df.format(e) + " " ));
// System.out.println("");
// System.out.println("a2* in each period:");
// Arrays.stream(opta2).forEach(e -> System.out.print(df.format(e) + " " ));
// double simFinalValue2 = simulation.simulateSDPGivenSamplNuma1a2(iniState, variCost, opta1, opta2);
// double gap2 = (simFinalValue2 - finalValue) / finalValue;
// System.out.printf("optimality gap for this policy a* is %.2f%%\n", gap2 * 100);
//
// double[] mean = new double[] {demand[0][0], demand[1][0]};
// double[] variance = new double[] {demand[0][0] / beta[0], demand[1][0] / beta[1]};
// double[][] optTable = recursion.getOptTableDetail2(mean, variance, price, opta1, opta2);
//
// double[] gaps = new double[] {gap, gap2};
// WriteToExcel wr = new WriteToExcel();
// String fileName = "run" + ".xls";
// String headString =
// "meanD1" + "\t" + "meanD2" + "\t" + "variance1" + "\t" + "variance2" + "\t" +
// "period" + "\t" + "x1" + "\t" + "x2" + "\t" + "w" + "\t" +
// "p1" + "\t" + "p2" + "\t" +
// "c1" + "\t" + "c2" + "\t" + "R" + "\t" + "y1*"+ "\t" + "y2*" + "\t" +
// "cashSituation" + "\t" + "alpha" + "\t" + "yHead1" + "\t" + "yHead2" + "\t" + "a1*" + "\t" + "a2*" +
// "\t" + "Theorem1Gap" + "Theorem2Gap";
// wr.writeArrayToExcel2(optTable, fileName, headString, gaps);
// System.out.println("alpha in the first period: " + optTable[0][10]);
// System.out.println("*******************************");
}
Aggregations