org.apache.commons.math3.exception.TooManyIterationsException Java Examples

The following examples show how to use org.apache.commons.math3.exception.TooManyIterationsException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 * @throws NoFeasibleSolutionException if there is no feasible solution?
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example #2
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public PointValuePair doOptimize()
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {
    final SimplexTableau tableau =
        new SimplexTableau(getFunction(),
                           getConstraints(),
                           getGoalType(),
                           isRestrictedToNonNegative(),
                           epsilon,
                           maxUlps,
                           cutOff);

    solvePhase1(tableau);
    tableau.dropPhase1Objective();

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }
    return tableau.getSolution();
}
 
Example #3
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 * @throws NoFeasibleSolutionException if there is no feasible solution?
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example #4
Source File: KolmogorovSmirnovTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Computes \( 1 + 2 \sum_{i=1}^\infty (-1)^i e^{-2 i^2 t^2} \) stopping when successive partial
 * sums are within {@code tolerance} of one another, or when {@code maxIterations} partial sums
 * have been computed. If the sum does not converge before {@code maxIterations} iterations a
 * {@link TooManyIterationsException} is thrown.
 *
 * @param t argument
 * @param tolerance Cauchy criterion for partial sums
 * @param maxIterations maximum number of partial sums to compute
 * @return Kolmogorov sum evaluated at t
 * @throws TooManyIterationsException if the series does not converge
 */
public double ksSum(double t, double tolerance, int maxIterations) {
    // TODO: for small t (say less than 1), the alternative expansion in part 3 of [1]
    // from class javadoc should be used.
    final double x = -2 * t * t;
    int sign = -1;
    long i = 1;
    double partialSum = 0.5d;
    double delta = 1;
    while (delta > tolerance && i < maxIterations) {
        delta = FastMath.exp(x * i * i);
        partialSum += sign * delta;
        sign *= -1;
        i++;
    }
    if (i == maxIterations) {
        throw new TooManyIterationsException(maxIterations);
    }
    return partialSum * 2;
}
 
Example #5
Source File: UserServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CharSequence generateRandomPassword() {
  for (int genLoopIndex = 0; genLoopIndex < GEN_LOOP_LIMIT; ++genLoopIndex) {
    int len = random.ints(GEN_BOUNDS.getLeft(), GEN_BOUNDS.getRight()).findFirst().getAsInt();
    StringBuilder sb = new StringBuilder(len);

    for (int i = 0; i < len; ++i) {
      sb.append(GEN_CHARS.charAt(random.nextInt(GEN_CHARS.length())));
    }

    String result = sb.toString();

    if (matchPasswordPattern(result)) {
      return result;
    }
  }

  throw new TooManyIterationsException(GEN_LOOP_LIMIT);
}
 
Example #6
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 * @throws NoFeasibleSolutionException if there is no feasible solution?
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example #7
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Solves Phase 1 of the Simplex method.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 * @throws NoFeasibleSolutionException if there is no feasible solution?
 */
protected void solvePhase1(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {

    // make sure we're in Phase 1
    if (tableau.getNumArtificialVariables() == 0) {
        return;
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // if W is not zero then we have no feasible solution
    if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
        throw new NoFeasibleSolutionException();
    }
}
 
Example #8
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs one iteration of the Simplex method on the given model.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 */
protected void doIteration(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException {

    incrementIterationCount();

    Integer pivotCol = getPivotColumn(tableau);
    Integer pivotRow = getPivotRow(tableau, pivotCol);
    if (pivotRow == null) {
        throw new UnboundedSolutionException();
    }

    // set the pivot element to 1
    double pivotVal = tableau.getEntry(pivotRow, pivotCol);
    tableau.divideRow(pivotRow, pivotVal);

    // set the rest of the pivot column to 0
    for (int i = 0; i < tableau.getHeight(); i++) {
        if (i != pivotRow) {
            final double multiplier = tableau.getEntry(i, pivotCol);
            tableau.subtractRow(i, pivotRow, multiplier);
        }
    }
}
 
Example #9
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs one iteration of the Simplex method on the given model.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 */
protected void doIteration(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException {

    incrementIterationCount();

    Integer pivotCol = getPivotColumn(tableau);
    Integer pivotRow = getPivotRow(tableau, pivotCol);
    if (pivotRow == null) {
        throw new UnboundedSolutionException();
    }

    // set the pivot element to 1
    double pivotVal = tableau.getEntry(pivotRow, pivotCol);
    tableau.divideRow(pivotRow, pivotVal);

    // set the rest of the pivot column to 0
    for (int i = 0; i < tableau.getHeight(); i++) {
        if (i != pivotRow) {
            final double multiplier = tableau.getEntry(i, pivotCol);
            tableau.subtractRow(i, pivotRow, multiplier);
        }
    }
}
 
Example #10
Source File: KolmogorovSmirnovTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Computes \( 1 + 2 \sum_{i=1}^\infty (-1)^i e^{-2 i^2 t^2} \) stopping when successive partial
 * sums are within {@code tolerance} of one another, or when {@code maxIterations} partial sums
 * have been computed. If the sum does not converge before {@code maxIterations} iterations a
 * {@link TooManyIterationsException} is thrown.
 *
 * @param t argument
 * @param tolerance Cauchy criterion for partial sums
 * @param maxIterations maximum number of partial sums to compute
 * @return Kolmogorov sum evaluated at t
 * @throws TooManyIterationsException if the series does not converge
 */
public double ksSum(double t, double tolerance, int maxIterations) {
    // TODO: for small t (say less than 1), the alternative expansion in part 3 of [1]
    // from class javadoc should be used.
    final double x = -2 * t * t;
    int sign = -1;
    long i = 1;
    double partialSum = 0.5d;
    double delta = 1;
    while (delta > tolerance && i < maxIterations) {
        delta = FastMath.exp(x * i * i);
        partialSum += sign * delta;
        sign *= -1;
        i++;
    }
    if (i == maxIterations) {
        throw new TooManyIterationsException(maxIterations);
    }
    return partialSum * 2;
}
 
Example #11
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public PointValuePair doOptimize()
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {
    final SimplexTableau tableau =
        new SimplexTableau(getFunction(),
                           getConstraints(),
                           getGoalType(),
                           isRestrictedToNonNegative(),
                           epsilon,
                           maxUlps,
                           cutOff);

    solvePhase1(tableau);
    tableau.dropPhase1Objective();

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }
    return tableau.getSolution();
}
 
Example #12
Source File: BaseOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs the optimization.
 *
 * @return a point/value pair that satisfies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize()
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #13
Source File: AbstractOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs the optimization.
 *
 * @return a point/value pair that satifies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize()
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #14
Source File: SimplexSolverTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSolutionCallback() {
    // re-use the problem from testcase for MATH-288
    // it normally requires 5 iterations
    
    LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );

    List<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
    constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
    constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
    constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
    constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
    constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));

    final SimplexSolver solver = new SimplexSolver();
    final SolutionCallback callback = new SolutionCallback();
    
    Assert.assertNull(callback.getSolution());
    Assert.assertFalse(callback.isSolutionOptimal());

    try {
        solver.optimize(new MaxIter(3), f, new LinearConstraintSet(constraints),
                        GoalType.MAXIMIZE, new NonNegativeConstraint(true), callback);
        Assert.fail("expected TooManyIterationsException");
    } catch (TooManyIterationsException ex) {
        // expected
    }
    
    final PointValuePair solution = callback.getSolution();
    Assert.assertNotNull(solution);
    Assert.assertTrue(validSolution(solution, constraints, 1e-4));
    Assert.assertFalse(callback.isSolutionOptimal());
    // the solution is clearly not optimal: optimal = 10.0
    Assert.assertEquals(7.0, solution.getValue(), 1e-4);
}
 
Example #15
Source File: GaussianCurveFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=TooManyIterationsException.class)
public void testWithMaxIterations2() {
    final int maxIter = 1; // Too few iterations.
    final double[] init = { 3.5e6, 4.2, 0.1 };

    GaussianCurveFitter fitter = GaussianCurveFitter.create();
    double[] parameters = fitter
        .withMaxIterations(maxIter)
        .withStartPoint(init)
        .fit(createDataset(DATASET1).toList());
}
 
Example #16
Source File: GaussianCurveFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=TooManyIterationsException.class)
public void testWithMaxIterations2() {
    final int maxIter = 1; // Too few iterations.
    final double[] init = { 3.5e6, 4.2, 0.1 };

    GaussianCurveFitter fitter = GaussianCurveFitter.create();
    fitter.withMaxIterations(maxIter)
          .withStartPoint(init)
          .fit(createDataset(DATASET1).toList());
}
 
Example #17
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Runs one iteration of the Simplex method on the given model.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 */
protected void doIteration(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException {

    incrementIterationCount();

    Integer pivotCol = getPivotColumn(tableau);
    Integer pivotRow = getPivotRow(tableau, pivotCol);
    if (pivotRow == null) {
        throw new UnboundedSolutionException();
    }

    tableau.performRowOperations(pivotCol, pivotRow);
}
 
Example #18
Source File: BaseOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs the optimization.
 *
 * @return a point/value pair that satifies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize()
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #19
Source File: BaseOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs the optimization.
 *
 * @return a point/value pair that satisfies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize()
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #20
Source File: SimplexSolverTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSolutionCallback() {
    // re-use the problem from testcase for MATH-288
    // it normally requires 5 iterations
    
    LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );

    List<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
    constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
    constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
    constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
    constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
    constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));

    final SimplexSolver solver = new SimplexSolver();
    final SolutionCallback callback = new SolutionCallback();
    
    Assert.assertNull(callback.getSolution());
    Assert.assertFalse(callback.isSolutionOptimal());

    try {
        solver.optimize(new MaxIter(3), f, new LinearConstraintSet(constraints),
                        GoalType.MAXIMIZE, new NonNegativeConstraint(true), callback);
        Assert.fail("expected TooManyIterationsException");
    } catch (TooManyIterationsException ex) {
        // expected
    }
    
    final PointValuePair solution = callback.getSolution();
    Assert.assertNotNull(solution);
    Assert.assertTrue(validSolution(solution, constraints, 1e-4));
    Assert.assertFalse(callback.isSolutionOptimal());
    // the solution is clearly not optimal: optimal = 10.0
    Assert.assertEquals(7.0, solution.getValue(), 1e-4);
}
 
Example #21
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Runs one iteration of the Simplex method on the given model.
 *
 * @param tableau Simple tableau for the problem.
 * @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
 * @throws UnboundedSolutionException if the model is found not to have a bounded solution.
 */
protected void doIteration(final SimplexTableau tableau)
    throws TooManyIterationsException,
           UnboundedSolutionException {

    incrementIterationCount();

    Integer pivotCol = getPivotColumn(tableau);
    Integer pivotRow = getPivotRow(tableau, pivotCol);
    if (pivotRow == null) {
        throw new UnboundedSolutionException();
    }

    tableau.performRowOperations(pivotCol, pivotRow);
}
 
Example #22
Source File: EventServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
@Transactional
public void addRecurrentEventsByMonths(
    Event event,
    int periodicity,
    int endType,
    int repetitionsNumber,
    LocalDate endDate,
    int monthRepeatType) {

  int weekNo = 1 + (event.getStartDateTime().getDayOfMonth() - 1) / 7;
  Duration duration = Duration.between(event.getStartDateTime(), event.getEndDateTime());
  Event lastEvent = event;
  BiFunction<Integer, LocalDateTime, Boolean> breakConditionFunc;
  Function<LocalDateTime, LocalDateTime> nextStartDateTimeFunc;
  LocalDateTime nextStartDateTime;

  if (endType == RecurrenceConfigurationRepository.END_TYPE_REPET) {
    breakConditionFunc = (iteration, dateTime) -> iteration >= repetitionsNumber;
  } else {
    breakConditionFunc = (iteration, dateTime) -> dateTime.toLocalDate().isAfter(endDate);
  }

  if (monthRepeatType == RecurrenceConfigurationRepository.REPEAT_TYPE_MONTH) {
    nextStartDateTimeFunc =
        dateTime ->
            dateTime
                .withDayOfMonth(1)
                .plusMonths(periodicity)
                .withDayOfMonth(event.getStartDateTime().getDayOfMonth());
  } else {
    nextStartDateTimeFunc =
        dateTime -> {
          LocalDateTime baseNextDateTime = dateTime.withDayOfMonth(1).plusMonths(periodicity);
          dateTime =
              baseNextDateTime.with(
                  TemporalAdjusters.dayOfWeekInMonth(
                      weekNo, event.getStartDateTime().getDayOfWeek()));

          if (!dateTime.getMonth().equals(baseNextDateTime.getMonth()) && weekNo > 1) {
            dateTime =
                baseNextDateTime.with(
                    TemporalAdjusters.dayOfWeekInMonth(
                        weekNo - 1, event.getStartDateTime().getDayOfWeek()));
          }

          return dateTime;
        };
  }

  for (int iteration = 0; ; ++iteration) {
    if (iteration > ITERATION_LIMIT) {
      throw new TooManyIterationsException(iteration);
    }

    nextStartDateTime = nextStartDateTimeFunc.apply(lastEvent.getStartDateTime());

    if (breakConditionFunc.apply(iteration, nextStartDateTime)) {
      break;
    }

    Event copy = eventRepo.copy(lastEvent, false);
    copy.setParentEvent(event);
    copy.setStartDateTime(nextStartDateTime);
    copy.setEndDateTime(nextStartDateTime.plus(duration));
    lastEvent = eventRepo.save(copy);
  }
}
 
Example #23
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public PointValuePair doOptimize()
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {

    // reset the tableau to indicate a non-feasible solution in case
    // we do not pass phase 1 successfully
    if (solutionCallback != null) {
        solutionCallback.setTableau(null);
    }

    final SimplexTableau tableau =
        new SimplexTableau(getFunction(),
                           getConstraints(),
                           getGoalType(),
                           isRestrictedToNonNegative(),
                           epsilon,
                           maxUlps);

    solvePhase1(tableau);
    tableau.dropPhase1Objective();

    // after phase 1, we are sure to have a feasible solution
    if (solutionCallback != null) {
        solutionCallback.setTableau(tableau);
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // check that the solution respects the nonNegative restriction in case
    // the epsilon/cutOff values are too large for the actual linear problem
    // (e.g. with very small constraint coefficients), the solver might actually
    // find a non-valid solution (with negative coefficients).
    final PointValuePair solution = tableau.getSolution();
    if (isRestrictedToNonNegative()) {
        final double[] coeff = solution.getPoint();
        for (int i = 0; i < coeff.length; i++) {
            if (Precision.compareTo(coeff[i], 0, epsilon) < 0) {
                throw new NoFeasibleSolutionException();
            }
        }
    }
    return solution;
}
 
Example #24
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public PointValuePair doOptimize()
    throws TooManyIterationsException,
           UnboundedSolutionException,
           NoFeasibleSolutionException {

    // reset the tableau to indicate a non-feasible solution in case
    // we do not pass phase 1 successfully
    if (solutionCallback != null) {
        solutionCallback.setTableau(null);
    }

    final SimplexTableau tableau =
        new SimplexTableau(getFunction(),
                           getConstraints(),
                           getGoalType(),
                           isRestrictedToNonNegative(),
                           epsilon,
                           maxUlps);

    solvePhase1(tableau);
    tableau.dropPhase1Objective();

    // after phase 1, we are sure to have a feasible solution
    if (solutionCallback != null) {
        solutionCallback.setTableau(tableau);
    }

    while (!tableau.isOptimal()) {
        doIteration(tableau);
    }

    // check that the solution respects the nonNegative restriction in case
    // the epsilon/cutOff values are too large for the actual linear problem
    // (e.g. with very small constraint coefficients), the solver might actually
    // find a non-valid solution (with negative coefficients).
    final PointValuePair solution = tableau.getSolution();
    if (isRestrictedToNonNegative()) {
        final double[] coeff = solution.getPoint();
        for (int i = 0; i < coeff.length; i++) {
            if (Precision.compareTo(coeff[i], 0, epsilon) < 0) {
                throw new NoFeasibleSolutionException();
            }
        }
    }
    return solution;
}
 
Example #25
Source File: EventServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
@Transactional
public void addRecurrentEventsByWeeks(
    Event event,
    int periodicity,
    int endType,
    int repetitionsNumber,
    LocalDate endDate,
    Map<Integer, Boolean> daysCheckedMap) {

  List<DayOfWeek> dayOfWeekList =
      daysCheckedMap.keySet().stream().sorted().map(DayOfWeek::of).collect(Collectors.toList());
  Duration duration = Duration.between(event.getStartDateTime(), event.getEndDateTime());
  Event lastEvent = event;
  BiFunction<Integer, LocalDateTime, Boolean> breakCondition;

  if (endType == RecurrenceConfigurationRepository.END_TYPE_REPET) {
    breakCondition = (iteration, dateTime) -> iteration >= repetitionsNumber;
  } else {
    breakCondition = (iteration, dateTime) -> dateTime.toLocalDate().isAfter(endDate);
  }

  boolean loop = true;

  for (int iteration = 0; loop; ++iteration) {
    if (iteration > ITERATION_LIMIT) {
      throw new TooManyIterationsException(iteration);
    }

    LocalDateTime nextStartDateTime = lastEvent.getStartDateTime().plusWeeks(periodicity - 1L);

    for (DayOfWeek dayOfWeek : dayOfWeekList) {
      nextStartDateTime = nextStartDateTime.with(TemporalAdjusters.next(dayOfWeek));

      if (breakCondition.apply(iteration, nextStartDateTime)) {
        loop = false;
        break;
      }

      Event copy = eventRepo.copy(lastEvent, false);
      copy.setParentEvent(event);
      copy.setStartDateTime(nextStartDateTime);
      copy.setEndDateTime(nextStartDateTime.plus(duration));
      lastEvent = eventRepo.save(copy);
    }
  }
}
 
Example #26
Source File: BaseOptimizer.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Stores data and performs the optimization.
 * <p>
 * The list of parameters is open-ended so that sub-classes can extend it
 * with arguments specific to their concrete implementations.
 * <p>
 * When the method is called multiple times, instance data is overwritten
 * only when actually present in the list of arguments: when not specified,
 * data set in a previous call is retained (and thus is optional in
 * subsequent calls).
 * <p>
 * Important note: Subclasses <em>must</em> override
 * {@link #parseOptimizationData(OptimizationData[])} if they need to register
 * their own options; but then, they <em>must</em> also call
 * {@code super.parseOptimizationData(optData)} within that method.
 *
 * @param optData Optimization data.
 * This method will register the following data:
 * <ul>
 *  <li>{@link MaxEval}</li>
 *  <li>{@link MaxIter}</li>
 * </ul>
 * @return a point/value pair that satisfies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize(OptimizationData... optData)
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Parse options.
    parseOptimizationData(optData);

    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #27
Source File: Math_6_BaseOptimizer_s.java    From coming with MIT License 3 votes vote down vote up
/**
 * Stores data and performs the optimization.
 * <br/>
 * The list of parameters is open-ended so that sub-classes can extend it
 * with arguments specific to their concrete implementations.
 * <br/>
 * When the method is called multiple times, instance data is overwritten
 * only when actually present in the list of arguments: when not specified,
 * data set in a previous call is retained (and thus is optional in
 * subsequent calls).
 * <br/>
 * Important note: Subclasses <em>must</em> override
 * {@link #parseOptimizationData(OptimizationData[])} if they need to register
 * their own options; but then, they <em>must</em> also call
 * {@code super.parseOptimizationData(optData)} within that method.
 *
 * @param optData Optimization data.
 * This method will register the following data:
 * <ul>
 *  <li>{@link MaxEval}</li>
 *  <li>{@link MaxIter}</li>
 * </ul>
 * @return a point/value pair that satifies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize(OptimizationData... optData)
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Parse options.
    parseOptimizationData(optData);

    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #28
Source File: BaseOptimizer.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Stores data and performs the optimization.
 * <br/>
 * The list of parameters is open-ended so that sub-classes can extend it
 * with arguments specific to their concrete implementations.
 * <br/>
 * When the method is called multiple times, instance data is overwritten
 * only when actually present in the list of arguments: when not specified,
 * data set in a previous call is retained (and thus is optional in
 * subsequent calls).
 * <br/>
 * Important note: Subclasses <em>must</em> override
 * {@link #parseOptimizationData(OptimizationData[])} if they need to register
 * their own options; but then, they <em>must</em> also call
 * {@code super.parseOptimizationData(optData)} within that method.
 *
 * @param optData Optimization data.
 * This method will register the following data:
 * <ul>
 *  <li>{@link MaxEval}</li>
 *  <li>{@link MaxIter}</li>
 * </ul>
 * @return a point/value pair that satifies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize(OptimizationData... optData)
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Parse options.
    parseOptimizationData(optData);

    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #29
Source File: 1_BaseOptimizer.java    From SimFix with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Stores data and performs the optimization.
 * <br/>
 * The list of parameters is open-ended so that sub-classes can extend it
 * with arguments specific to their concrete implementations.
 * <br/>
 * When the method is called multiple times, instance data is overwritten
 * only when actually present in the list of arguments: when not specified,
 * data set in a previous call is retained (and thus is optional in
 * subsequent calls).
 * <br/>
 * Important note: Subclasses <em>must</em> override
 * {@link #parseOptimizationData(OptimizationData[])} if they need to register
 * their own options; but then, they <em>must</em> also call
 * {@code super.parseOptimizationData(optData)} within that method.
 *
 * @param optData Optimization data.
 * This method will register the following data:
 * <ul>
 *  <li>{@link MaxEval}</li>
 *  <li>{@link MaxIter}</li>
 * </ul>
 * @return a point/value pair that satifies the convergence criteria.
 * @throws TooManyEvaluationsException if the maximal number of
 * evaluations is exceeded.
 * @throws TooManyIterationsException if the maximal number of
 * iterations is exceeded.
 */
public PAIR optimize(OptimizationData... optData)
    throws TooManyEvaluationsException,
           TooManyIterationsException {
    // Parse options.
    parseOptimizationData(optData);

    // Reset counters.
    evaluations.resetCount();
    iterations.resetCount();
    // Perform optimization.
    return doOptimize();
}
 
Example #30
Source File: SimplexSolver.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @param optData Optimization data. In addition to those documented in
 * {@link LinearOptimizer#optimize(OptimizationData...)
 * LinearOptimizer}, this method will register the following data:
 * <ul>
 *  <li>{@link SolutionCallback}</li>
 *  <li>{@link PivotSelectionRule}</li>
 * </ul>
 *
 * @return {@inheritDoc}
 * @throws TooManyIterationsException if the maximal number of iterations is exceeded.
 */
@Override
public PointValuePair optimize(OptimizationData... optData)
    throws TooManyIterationsException {
    // Set up base class and perform computation.
    return super.optimize(optData);
}