Search in sources :

Example 1 with GammaDist

use of umontreal.ssj.probdist.GammaDist in project Stochastic-Inventory by RobinChen121.

the class MultiItemCashG method main.

public static void main(String[] args) {
    double[] price = { 2, 10 };
    // higher margin vs lower margin
    double[] variCost = { 1, 2 };
    // initial cash
    double iniCash = 10;
    // initial inventory
    int[] iniInventory = { 0, 0 };
    // compute G(d)
    int d = 1;
    int T = 4;
    // mean demand is shape * scale and variance is shape * scale^2
    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];
    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();
    double truncationQuantile = 0.9999;
    int stepSize = 1;
    int maxInventoryState = 200;
    int Qbound = 40;
    double discountFactor = 1;
    // get shape possibilities for a product in each period
    // normal dist for one product
    GammaDist[] distributions = new GammaDist[T];
    for (int t = 0; t < T; t++) distributions[t] = new GammaDist(demand[d - 1][t] * beta[d - 1], beta[d - 1]);
    // build action list for this item
    Function<State, double[]> buildActionList = s -> {
        return DoubleStream.iterate(0, i -> i + stepSize).limit(Qbound + 1).toArray();
    };
    // Immediate Value Function
    ImmediateValueFunction<State, Double, Double, Double> immediateValue = (IniState, action, randomDemand) -> {
        double revenue = 0;
        revenue = (price[d - 1] - variCost[d - 1]) * Math.min(IniState.getIniInventory() + action, randomDemand);
        if (IniState.getPeriod() == T) {
            revenue += (salPrice[d - 1] - variCost[d - 1]) * Math.max(IniState.getIniInventory() + action - randomDemand, 0);
        }
        return revenue;
    };
    // State Transition Function
    // need change
    StateTransitionFunction<State, Double, Double, State> stateTransition = (IniState, action, randomDemand) -> {
        double endInventory = IniState.getIniInventory() + action - randomDemand;
        endInventory = Math.max(0, endInventory);
        endInventory = endInventory > maxInventoryState ? maxInventoryState : endInventory;
        endInventory = (int) endInventory;
        return new State(IniState.getPeriod() + 1, endInventory);
    };
    double[][][] pmf = new GetPmf(distributions, truncationQuantile, stepSize).getpmf();
    /**
     *****************************************************************
     * Solve
     */
    RecursionG recursion = new RecursionG(pmf, buildActionList, stateTransition, immediateValue);
    int period = 1;
    State iniState = new State(period, iniInventory[d - 1]);
    long currTime = System.currentTimeMillis();
    double finalValue = iniCash + recursion.getExpectedValue(iniState);
    System.out.println("final optimal cash  is " + finalValue);
    System.out.println("optimal order quantity in the first priod is :  Q = " + recursion.getAction(iniState));
    double time = (System.currentTimeMillis() - currTime) / 1000;
    System.out.println("running time is " + time + "s");
    System.out.println("a* in each period:");
    double[] optY = recursion.getOptY();
    optY[0] = iniState.getIniInventory() + recursion.getAction(iniState);
    System.out.println(Arrays.toString(optY));
}
Also used : ImmediateValueFunction(sdp.inventory.ImmediateValue.ImmediateValueFunction) Arrays(java.util.Arrays) GammaDist(umontreal.ssj.probdist.GammaDist) NormalDist(umontreal.ssj.probdist.NormalDist) Function(java.util.function.Function) StateTransitionFunction(sdp.inventory.StateTransition.StateTransitionFunction) ArrayList(java.util.ArrayList) DoubleStream(java.util.stream.DoubleStream) GetPmf(sdp.inventory.GetPmf) OptDirection(sdp.inventory.Recursion.OptDirection) RecursionG(sdp.cash.multiItem.RecursionG) State(sdp.inventory.State) Recursion(sdp.inventory.Recursion) BiNormalDist(umontreal.ssj.probdistmulti.BiNormalDist) WriteToExcel(sdp.write.WriteToExcel) RecursionG(sdp.cash.multiItem.RecursionG) GammaDist(umontreal.ssj.probdist.GammaDist) State(sdp.inventory.State) GetPmf(sdp.inventory.GetPmf)

Example 2 with GammaDist

use of umontreal.ssj.probdist.GammaDist in project Stochastic-Inventory by RobinChen121.

the class CashConstraintG method main.

public static void main(String[] args) {
    double[] meanDemand = { 10, 10, 10, 10 };
    double variCost = 1;
    double price = 2;
    double depositeRate = 0;
    double salvageValue = variCost * 0.5;
    double truncationQuantile = 0.9999;
    int stepSize = 1;
    double coe = 1;
    double beta = 1;
    // get demand possibilities for each period
    // gamma distribution:mean demand is shape / scale and variance is shape / scale^2
    // rate = 1 / scale
    // shape = demand * rate
    // variance = demand / rate
    // gamma in ssj: alpha is shape, and lambda is beta(rate)
    int T = meanDemand.length;
    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(T).mapToObj(i -> new GammaDist(meanDemand[i] * beta, beta)).toArray(Distribution[]::new);
    double[][][] pmf = new GetPmf(distributions, truncationQuantile, stepSize).getpmf();
    /**
     *****************************************************************
     * Solve
     */
    RecursionG recursion = new RecursionG(pmf, distributions, price, variCost, depositeRate, salvageValue);
    long currTime = System.currentTimeMillis();
    double[] optY = recursion.getOptY();
    System.out.println("a* in each period:");
    System.out.print("[");
    DecimalFormat df = new DecimalFormat("0.00");
    Arrays.stream(optY).forEach(e -> System.out.print(df.format(e) + " "));
    System.out.println("]");
    // if 1000, then it will be integer
    double time = (System.currentTimeMillis() - currTime) / 1000.0;
    System.out.printf("running time is %.3f s", time);
    System.out.println("");
    System.out.println("*********************************************");
}
Also used : IntStream(java.util.stream.IntStream) RecursionG(sdp.cash.RecursionG) Arrays(java.util.Arrays) BiFunction(java.util.function.BiFunction) GammaDist(umontreal.ssj.probdist.GammaDist) DecimalFormat(java.text.DecimalFormat) NormalDist(umontreal.ssj.probdist.NormalDist) Function(java.util.function.Function) StateTransitionFunction(sdp.inventory.StateTransition.StateTransitionFunction) GetPmf(sdp.inventory.GetPmf) StateY(sdp.cash.StateY) State(sdp.inventory.State) PoissonDist(umontreal.ssj.probdist.PoissonDist) Distribution(umontreal.ssj.probdist.Distribution) RecursionG(sdp.cash.RecursionG) GammaDist(umontreal.ssj.probdist.GammaDist) Distribution(umontreal.ssj.probdist.Distribution) DecimalFormat(java.text.DecimalFormat) GetPmf(sdp.inventory.GetPmf)

Example 3 with GammaDist

use of umontreal.ssj.probdist.GammaDist 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);
}
Also used : IntStream(java.util.stream.IntStream) ImmediateValueFunction(sdp.inventory.ImmediateValue.ImmediateValueFunction) RecursionG(sdp.cash.RecursionG) FindCCrieria(cash.strongconstraint.FindsCS.FindCCrieria) Arrays(java.util.Arrays) DiscreteDistribution(umontreal.ssj.probdist.DiscreteDistribution) WriteToCsv(sdp.write.WriteToCsv) GammaDist(umontreal.ssj.probdist.GammaDist) NormalDist(umontreal.ssj.probdist.NormalDist) Function(java.util.function.Function) StateTransitionFunction(sdp.inventory.StateTransition.StateTransitionFunction) ArrayList(java.util.ArrayList) DoubleStream(java.util.stream.DoubleStream) GetPmf(sdp.inventory.GetPmf) CashRecursionXR(sdp.cash.CashRecursionXR) TreeMap(java.util.TreeMap) CashStateXR(sdp.cash.CashStateXR) Map(java.util.Map) OptDirection(sdp.cash.CashRecursionXR.OptDirection) Printable(java.awt.print.Printable) WriteToExcel(sdp.write.WriteToExcel) CashSimulationXR(sdp.cash.CashSimulationXR) PoissonDist(umontreal.ssj.probdist.PoissonDist) Distribution(umontreal.ssj.probdist.Distribution) RecursionG(sdp.cash.RecursionG) GammaDist(umontreal.ssj.probdist.GammaDist) FindCCrieria(cash.strongconstraint.FindsCS.FindCCrieria) CashRecursionXR(sdp.cash.CashRecursionXR) CashStateXR(sdp.cash.CashStateXR) CashSimulationXR(sdp.cash.CashSimulationXR) DiscreteDistribution(umontreal.ssj.probdist.DiscreteDistribution) Distribution(umontreal.ssj.probdist.Distribution) GetPmf(sdp.inventory.GetPmf)

Example 4 with GammaDist

use of umontreal.ssj.probdist.GammaDist in project Stochastic-Inventory by RobinChen121.

the class GetPmfMulti method getPmf.

public double[][] getPmf(int t) {
    stepSize = 1;
    if (t > 4)
        stepSize = 4;
    if (distributionGeneral[0][t] instanceof NormalDist) {
        NormalDist distribution1 = new NormalDist(distributionGeneral[0][t].getMean(), distributionGeneral[0][t].getStandardDeviation());
        NormalDist distribution2 = new NormalDist(distributionGeneral[1][t].getMean(), distributionGeneral[1][t].getStandardDeviation());
        double[] supportLB = new double[2];
        double[] supportUB = new double[2];
        supportLB[0] = (int) distribution1.inverseF(1 - truncationQuantile);
        supportUB[0] = (int) distribution1.inverseF(truncationQuantile);
        supportLB[1] = (int) distribution2.inverseF(1 - truncationQuantile);
        supportUB[1] = (int) distribution2.inverseF(truncationQuantile);
        int demandLength1 = (int) ((supportUB[0] - supportLB[0] + 1) / stepSize);
        int demandLength2 = (int) ((supportUB[1] - supportLB[1] + 1) / stepSize);
        double[][] pmf = new double[demandLength1 * demandLength2][3];
        int index = 0;
        double probilitySum = (2 * truncationQuantile - 1) * (2 * truncationQuantile - 1);
        for (int i = 0; i < demandLength1; i++) for (int j = 0; j < demandLength2; j++) {
            pmf[index][0] = supportLB[0] + i * stepSize;
            pmf[index][1] = supportLB[1] + j * stepSize;
            pmf[index][2] = (distribution1.cdf(pmf[index][0] + 0.5 * stepSize) - distribution1.cdf(pmf[index][0] - 0.5 * stepSize)) * (distribution2.cdf(pmf[index][1] + 0.5 * stepSize) - distribution2.cdf(pmf[index][1] - 0.5 * stepSize)) / probilitySum;
            index++;
        }
        return pmf;
    }
    if (distributionGeneral[0][t] instanceof GammaDist) {
        double mean1 = distributionGeneral[0][t].getMean();
        double mean2 = distributionGeneral[1][t].getMean();
        double variance1 = distributionGeneral[0][t].getVariance();
        double variance2 = distributionGeneral[1][t].getVariance();
        double scale1 = mean1 / variance1;
        double shape1 = mean1 * scale1;
        double scale2 = mean2 / variance2;
        double shape2 = mean2 * scale2;
        GammaDist distribution1 = new GammaDist(shape1, scale1);
        GammaDist distribution2 = new GammaDist(shape2, scale2);
        double[] supportLB = new double[2];
        double[] supportUB = new double[2];
        supportLB[0] = (int) distribution1.inverseF(1 - truncationQuantile);
        supportUB[0] = (int) distribution1.inverseF(truncationQuantile);
        supportLB[1] = (int) distribution2.inverseF(1 - truncationQuantile);
        supportUB[1] = (int) distribution2.inverseF(truncationQuantile);
        int demandLength1 = (int) ((supportUB[0] - supportLB[0] + 1) / stepSize);
        int demandLength2 = (int) ((supportUB[1] - supportLB[1] + 1) / stepSize);
        double[][] pmf = new double[demandLength1 * demandLength2][3];
        int index = 0;
        double probilitySum = (2 * truncationQuantile - 1) * (2 * truncationQuantile - 1);
        for (int i = 0; i < demandLength1; i++) for (int j = 0; j < demandLength2; j++) {
            pmf[index][0] = supportLB[0] + i * stepSize;
            pmf[index][1] = supportLB[1] + j * stepSize;
            pmf[index][2] = (distribution1.cdf(pmf[index][0] + 0.5 * stepSize) - distribution1.cdf(pmf[index][0] - 0.5 * stepSize)) * (distribution2.cdf(pmf[index][1] + 0.5 * stepSize) - distribution2.cdf(pmf[index][1] - 0.5 * stepSize)) / probilitySum;
            index++;
        }
        return pmf;
    }
    if (distributionGeneral[0][t] instanceof PoissonDist) {
        PoissonDist distribution1 = new PoissonDist(distributionGeneral[0][t].getMean());
        PoissonDist distribution2 = new PoissonDist(distributionGeneral[1][t].getMean());
        double[] supportLB = new double[2];
        double[] supportUB = new double[2];
        supportLB[0] = (int) distribution1.inverseF(1 - truncationQuantile);
        supportUB[0] = (int) distribution1.inverseF(truncationQuantile);
        supportLB[1] = (int) distribution2.inverseF(1 - truncationQuantile);
        supportUB[1] = (int) distribution2.inverseF(truncationQuantile);
        int demandLength1 = (int) ((supportUB[0] - supportLB[0] + 1) / stepSize);
        int demandLength2 = (int) ((supportUB[1] - supportLB[1] + 1) / stepSize);
        double[][] pmf = new double[demandLength1 * demandLength2][3];
        int index = 0;
        double probilitySum = (2 * truncationQuantile - 1) * (2 * truncationQuantile - 1);
        for (int i = 0; i < demandLength1; i++) for (int j = 0; j < demandLength2; j++) {
            pmf[index][0] = supportLB[0] + i * stepSize;
            pmf[index][1] = supportLB[1] + j * stepSize;
            pmf[index][2] = distribution1.prob(i) * distribution2.prob(j) / probilitySum;
            index++;
        }
        return pmf;
    }
    if (distributionGeneral[0][t] instanceof UniformIntDist) {
        UniformIntDist distribution1 = (UniformIntDist) distributionGeneral[0][t];
        UniformIntDist distribution2 = (UniformIntDist) distributionGeneral[1][t];
        int demandLength1 = distribution1.getJ() - distribution1.getI() + 1;
        int demandLength2 = distribution2.getJ() - distribution2.getI() + 1;
        double[][] pmf = new double[demandLength1 * demandLength2][3];
        int index = 0;
        for (int i = distribution1.getXinf(); i <= distribution1.getXsup(); i++) for (int j = distribution2.getXinf(); j <= distribution2.getXsup(); j++) {
            pmf[index][0] = i;
            pmf[index][1] = j;
            pmf[index][2] = distribution1.prob(i) * distribution2.prob(j);
            index++;
        }
        return pmf;
    }
    return null;
}
Also used : PoissonDist(umontreal.ssj.probdist.PoissonDist) GammaDist(umontreal.ssj.probdist.GammaDist) UniformIntDist(umontreal.ssj.probdist.UniformIntDist) NormalDist(umontreal.ssj.probdist.NormalDist) BiNormalDist(umontreal.ssj.probdistmulti.BiNormalDist)

Example 5 with GammaDist

use of umontreal.ssj.probdist.GammaDist 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("*******************************");
}
Also used : RecursionG(sdp.cash.RecursionG) Arrays(java.util.Arrays) ReadExcel(sdp.write.ReadExcel) CashRecursionV(sdp.cash.multiItem.CashRecursionV) GammaDist(umontreal.ssj.probdist.GammaDist) DecimalFormat(java.text.DecimalFormat) NormalDist(umontreal.ssj.probdist.NormalDist) CashStateMultiYR(sdp.cash.multiItem.CashStateMultiYR) Function(java.util.function.Function) CashSimulationMultiXR(sdp.cash.multiItem.CashSimulationMultiXR) ImmediateValueFunctionV(sdp.inventory.ImmediateValue.ImmediateValueFunctionV) ArrayList(java.util.ArrayList) StateTransitionFunctionV(sdp.inventory.StateTransition.StateTransitionFunctionV) GetPmf(sdp.inventory.GetPmf) CashStateR(sdp.cash.multiItem.CashStateR) GetPmfMulti(sdp.cash.multiItem.GetPmfMulti) WriteToExcel(sdp.write.WriteToExcel) CashStateMulti(sdp.cash.multiItem.CashStateMulti) PoissonDist(umontreal.ssj.probdist.PoissonDist) BoundaryFuncton(sdp.inventory.FinalCash.BoundaryFuncton) Distribution(umontreal.ssj.probdist.Distribution) CashSimulationY(sdp.cash.multiItem.CashSimulationY) GammaDist(umontreal.ssj.probdist.GammaDist) ArrayList(java.util.ArrayList) CashRecursionV(sdp.cash.multiItem.CashRecursionV) CashStateMulti(sdp.cash.multiItem.CashStateMulti) CashSimulationY(sdp.cash.multiItem.CashSimulationY) CashStateMultiYR(sdp.cash.multiItem.CashStateMultiYR) GetPmfMulti(sdp.cash.multiItem.GetPmfMulti) CashStateR(sdp.cash.multiItem.CashStateR)

Aggregations

GammaDist (umontreal.ssj.probdist.GammaDist)9 Arrays (java.util.Arrays)8 Function (java.util.function.Function)8 ArrayList (java.util.ArrayList)7 GetPmf (sdp.inventory.GetPmf)7 WriteToExcel (sdp.write.WriteToExcel)7 Distribution (umontreal.ssj.probdist.Distribution)7 NormalDist (umontreal.ssj.probdist.NormalDist)7 RecursionG (sdp.cash.RecursionG)6 StateTransitionFunction (sdp.inventory.StateTransition.StateTransitionFunction)6 PoissonDist (umontreal.ssj.probdist.PoissonDist)6 DecimalFormat (java.text.DecimalFormat)5 GetPmfMulti (sdp.cash.multiItem.GetPmfMulti)5 CashSimulationY (sdp.cash.multiItem.CashSimulationY)4 CashStateMulti (sdp.cash.multiItem.CashStateMulti)4 BoundaryFuncton (sdp.inventory.FinalCash.BoundaryFuncton)4 CashSimulationMultiXR (sdp.cash.multiItem.CashSimulationMultiXR)3 ImmediateValueFunction (sdp.inventory.ImmediateValue.ImmediateValueFunction)3 StateTransitionFunctionV (sdp.inventory.StateTransition.StateTransitionFunctionV)3 UniformIntDist (umontreal.ssj.probdist.UniformIntDist)3