Example usage for java.util.stream IntStream iterate

List of usage examples for java.util.stream IntStream iterate

Introduction

In this page you can find the example usage for java.util.stream IntStream iterate.

Prototype

public static IntStream iterate(final int seed, final IntUnaryOperator f) 

Source Link

Document

Returns an infinite sequential ordered IntStream produced by iterative application of a function f to an initial element seed , producing a Stream consisting of seed , f(seed) , f(f(seed)) , etc.

Usage

From source file:Main.java

public static void main(String[] args) {
    IntStream i = IntStream.iterate(1, n -> n + 1);
    i.limit(10).forEach(System.out::println);
}

From source file:Main.java

public static void main(String[] args) {
    SecureRandom secureRandom = new SecureRandom(new byte[] { 1, 3, 3, 7 });
    int[] randoms = IntStream.generate(secureRandom::nextInt).filter(n -> n > 0).limit(10).toArray();
    System.out.println(Arrays.toString(randoms));

    int[] nums = IntStream.iterate(1, n -> n * 2).limit(11).toArray();
    System.out.println(Arrays.toString(nums));
}

From source file:jsdp.app.inventory.univariate.CapacitatedStochasticLotSizing.java

public static void main(String args[]) {

    boolean simulate = true;

    /*******************************************************************
     * Problem parameters//from w  w  w.  j a va 2 s. c o m
     */
    double fixedOrderingCost = 40;
    double proportionalOrderingCost = 0;
    double holdingCost = 1;
    double penaltyCost = 2;
    double maxOrderQuantity = 50;

    double[] meanDemand = { 20, 50, 20, 10, 20, 50 };
    double coefficientOfVariation = 0.2;
    double truncationQuantile = 0.99;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToObj(i -> new NormalDist(meanDemand[i], meanDemand[i] * coefficientOfVariation))
            //.mapToObj(i -> new PoissonDist(meanDemand[i]))
            .toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(1 - truncationQuantile)).toArray();
    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(truncationQuantile)).toArray();
    double initialInventory = 0;

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 1; //Stepsize must be 1 for discrete distributions
    double minState = -250;
    double maxState = 250;
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        for (double i = state.getInitialState(); i <= StateImpl.getMaxState()
                && i <= state.getInitialState() + maxOrderQuantity; i += StateImpl.getStepSize()) {
            feasibleActions.add(new ActionImpl(state, i - state.getInitialState()));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = s -> new ActionImpl(s, 0);

    // Immediate Value Function

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double orderingCost = a.getAction() > 0 ? (fixedOrderingCost + a.getAction() * proportionalOrderingCost)
                : 0;
        double holdingAndPenaltyCost = holdingCost * Math.max(fs.getInitialState(), 0)
                + penaltyCost * Math.max(-fs.getInitialState(), 0);
        return orderingCost + holdingAndPenaltyCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedDemand = ((StateImpl) initialState).getInitialState() + ((ActionImpl) action).getAction()
                - ((StateImpl) finalState).getInitialState();
        return realizedDemand;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 200;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            HashType.HASHTABLE);

    System.out.println("--------------Backward recursion--------------");
    recursion.runBackwardRecursionMonitoring();
    System.out.println();
    double ETC = recursion.getExpectedCost(initialInventory);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialInventory);
    double action = recursion.getOptimalAction(initialState).getAction();
    long percent = recursion.getMonitoringInterfaceBackward().getPercentCPU();
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + recursion.getMonitoringInterfaceBackward().getTime());
    System.out
            .println("Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    System.out.println();

    /*******************************************************************
     * Charting
     */
    System.out.println("--------------Charting--------------");
    int targetPeriod = 0; //If targetPeriod > 0 then no sampling!
    plotOptimalPolicyAction(targetPeriod, recursion); //Plot optimal policy action
    BackwardRecursionImpl recursionPlot = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            HashType.HASHTABLE);
    plotOptimalPolicyCost(targetPeriod, recursionPlot); //Plot optimal policy cost      
    System.out.println();

    /*******************************************************************
     * Simulation
     */
    System.out.println("--------------Simulation--------------");
    double confidence = 0.95; //Simulation confidence level 
    double errorTolerance = 0.0001; //Simulation error threshold

    if (simulate && samplingScheme == SamplingScheme.NONE)
        simulate(distributions, fixedOrderingCost, holdingCost, penaltyCost, proportionalOrderingCost,
                initialInventory, recursion, confidence, errorTolerance);
    else {
        if (!simulate)
            System.out.println("Simulation disabled.");
        if (samplingScheme != SamplingScheme.NONE)
            System.out.println(
                    "Cannot simulate a sampled solution, please disable sampling: set samplingScheme == SamplingScheme.NONE.");
    }
}

From source file:jsdp.app.control.clqg.univariate.CLQG.java

public static void main(String args[]) {

    /*******************************************************************
     * Problem parameters/*from ww  w .  ja v a2  s .  c o  m*/
     */

    int T = 20; // Horizon length
    double G = 1; // Input transition
    double Phi = 1; // State transition
    double R = 1; // Input cost
    double Q = 1; // State cost
    double Ulb = -1; // Action constraint
    double Uub = 20; // Action constraint
    double noiseStd = 5; // Standard deviation of the noise

    double[] noiseStdArray = new double[T];
    Arrays.fill(noiseStdArray, noiseStd);
    double truncationQuantile = 0.975;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(noiseStdArray.length)
            .mapToObj(i -> new NormalDist(0, noiseStdArray[i]))

            .toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], 1 - truncationQuantile)).toArray();

    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], truncationQuantile)).toArray();

    double initialX = 0; // Initial state

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 0.5; //Stepsize must be 1 for discrete distributions
    double minState = -25;
    double maxState = 100;
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = (Function<State, ArrayList<Action>> & Serializable) s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        double maxAction = Math.min(Uub, (StateImpl.getMaxState() - Phi * state.getInitialState()) / G);
        double minAction = Math.max(Ulb, (StateImpl.getMinState() - Phi * state.getInitialState()) / G);
        for (double actionPointer = minAction; actionPointer <= maxAction; actionPointer += StateImpl
                .getStepSize()) {
            feasibleActions.add(new ActionImpl(state, actionPointer));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = (Function<State, Action> & Serializable) s -> new ActionImpl(s,
            0.0);

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double inputCost = Math.pow(a.getAction(), 2) * R;
        double stateCost = Math.pow(fs.getInitialState(), 2) * Q;
        return inputCost + stateCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedNoise = ((StateImpl) finalState).getInitialState()
                - ((StateImpl) initialState).getInitialState() * Phi - ((ActionImpl) action).getAction() * G;
        return realizedNoise;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 50;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    StopWatch timer = new StopWatch();
    OperatingSystemMXBean osMBean;
    try {
        osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
        long nanoBefore = System.nanoTime();
        long cpuBefore = osMBean.getProcessCpuTime();

        timer.start();
        recursion.runBackwardRecursionMonitoring();
        timer.stop();

        long cpuAfter = osMBean.getProcessCpuTime();
        long nanoAfter = System.nanoTime();

        long percent;
        if (nanoAfter > nanoBefore)
            percent = ((cpuAfter - cpuBefore) * 100L) / (nanoAfter - nanoBefore);
        else
            percent = 0;

        System.out.println(
                "Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println();
    double ETC = recursion.getExpectedCost(initialX);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialX);
    double action = recursion.getOptimalAction(initialState).getAction();
    System.out.println("Expected total cost (assuming an initial state " + initialX + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + timer);
    System.out.println();
}

From source file:jsdp.app.inventory.univariate.StochasticLotSizing.java

public static void main(String args[]) {

    boolean simulate = true;

    /*******************************************************************
     * Problem parameters/* w w  w.  j a v  a 2  s  .  c  o m*/
     */
    double fixedOrderingCost = 300;
    double proportionalOrderingCost = 0;
    double holdingCost = 1;
    double penaltyCost = 10;

    double[] meanDemand = { 10, 20, 15, 20, 15, 10 };
    double coefficientOfVariation = 0.2;
    double truncationQuantile = 0.999;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            //.mapToObj(i -> new NormalDist(meanDemand[i],meanDemand[i]*coefficientOfVariation))
            .mapToObj(i -> new PoissonDist(meanDemand[i])).toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(1 - truncationQuantile)).toArray();
    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(truncationQuantile)).toArray();

    double initialInventory = 0;

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 1; //Stepsize must be 1 for discrete distributions
    double minState = -50; //Inventory level lower bound in each period
    double maxState = 150; //Inventory level upper bound in each period
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        for (double i = state.getInitialState(); i <= StateImpl.getMaxState(); i += StateImpl.getStepSize()) {
            feasibleActions.add(new ActionImpl(state, i - state.getInitialState()));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = s -> new ActionImpl(s, 0.0);

    // Immediate Value Function

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double orderingCost = a.getAction() > 0 ? (fixedOrderingCost + a.getAction() * proportionalOrderingCost)
                : 0;
        double holdingAndPenaltyCost = holdingCost * Math.max(fs.getInitialState(), 0)
                + penaltyCost * Math.max(-fs.getInitialState(), 0);
        return orderingCost + holdingAndPenaltyCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedDemand = ((StateImpl) initialState).getInitialState() + ((ActionImpl) action).getAction()
                - ((StateImpl) finalState).getInitialState();
        return realizedDemand;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 100;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    recursion.runBackwardRecursionMonitoring();
    System.out.println();
    double ETC = recursion.getExpectedCost(initialInventory);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialInventory);
    double action = recursion.getOptimalAction(initialState).getAction();
    long percent = recursion.getMonitoringInterfaceBackward().getPercentCPU();
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + recursion.getMonitoringInterfaceBackward().getTime());
    System.out
            .println("Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    System.out.println();

    /*******************************************************************
     * Charting
     */
    System.out.println("--------------Charting--------------");
    int targetPeriod = 0;
    plotOptimalPolicyAction(targetPeriod, recursion); //Plot optimal policy action
    BackwardRecursionImpl recursionPlot = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, targetPeriod > 0 ? SamplingScheme.NONE : samplingScheme,
            maxSampleSize, reductionFactorPerStage, HashType.THASHMAP);
    plotOptimalPolicyCost(targetPeriod, recursionPlot); //Plot optimal policy cost 
    System.out.println();

    /*******************************************************************
     * Simulation
     */
    System.out.println("--------------Simulation--------------");
    double confidence = 0.95; //Simulation confidence level 
    double errorTolerance = 0.0001; //Simulation error threshold

    if (simulate && samplingScheme == SamplingScheme.NONE)
        simulate(distributions, fixedOrderingCost, holdingCost, penaltyCost, proportionalOrderingCost,
                initialInventory, recursion, confidence, errorTolerance);
    else {
        if (!simulate)
            System.out.println("Simulation disabled.");
        if (samplingScheme != SamplingScheme.NONE)
            System.out.println(
                    "Cannot simulate a sampled solution, please disable sampling: set samplingScheme == SamplingScheme.NONE.");
    }
}

From source file:jsdp.app.lotsizing.sS_jsdp.java

public static void main(String[] args) {
    //Factor must be 1 for discrete distributions
    sS_State.setStateBoundaries(1, -100, 100);

    double fixedOrderingCost = 50;
    double proportionalOrderingCost = 0;
    double holdingCost = 1;
    double penaltyCost = 4;

    double[] demand = { 20, 30, 20, 40 };

    /*Distribution[] distributions = IntStream.iterate(0, i -> i + 1)
                                      .limit(demand.length)
                                      .mapToObj(i -> new NormalDist(demand[i],demand[i]*0.4))
                                      .toArray(Distribution[]::new);*/

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(demand.length)
            .mapToObj(i -> new PoissonDist(demand[i])).toArray(Distribution[]::new);

    double minDemand = 0;
    double maxDemand = sS_State.getMaxInventory() - sS_State.getMinInventory();

    double initialInventory = 0;
    sS_StateSpaceSampleIterator.SamplingScheme samplingScheme = sS_StateSpaceSampleIterator.SamplingScheme.NONE;
    int maxSampleSize = 25;

    System.out.println("--------------Forward recursion--------------");
    simpleTestForward(fixedOrderingCost, proportionalOrderingCost, holdingCost, penaltyCost, distributions,
            minDemand, maxDemand, initialInventory);
    System.out.println("--------------Backward recursion--------------");
    simpleTestBackward(fixedOrderingCost, proportionalOrderingCost, holdingCost, penaltyCost, distributions,
            minDemand, maxDemand, initialInventory, samplingScheme, maxSampleSize);
    System.out.println("--------------Cost function plot--------------");
    int targetPeriod = 0;
    boolean printCostFunctionValues = false;
    boolean latexOutput = false;
    plotCostFunction(targetPeriod, fixedOrderingCost, proportionalOrderingCost, holdingCost, penaltyCost,
            distributions, minDemand, maxDemand, printCostFunctionValues, latexOutput, samplingScheme,
            maxSampleSize);//from  w  ww .  j  a  v  a  2  s . c  o m
}

From source file:com.wrmsr.kleist.util.Itertools.java

public static IntStream count(int first, int step) {
    return IntStream.iterate(first, i -> i + step);
}

From source file:com.github.nginate.commons.testing.Unique.java

@SafeVarargs
@SuppressWarnings("varargs")
private static Stream<Character> getCharsStream(Pair<Character, Character>... fromToInclusivePairs) {
    int[] validChars = Arrays.stream(fromToInclusivePairs)
            .flatMapToInt(fromTo -> IntStream.rangeClosed(fromTo.getLeft(), fromTo.getRight())).toArray();
    return IntStream.iterate(0, i -> i + 1)
            .map(i -> validChars[i - validChars.length * (i / validChars.length)])
            .mapToObj(charCode -> (char) charCode);
}