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

The following examples show how to use org.apache.commons.math3.exception.MathInternalError. 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: DSCompiler.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Evaluate Taylor expansion of a derivative structure.
 * @param ds array holding the derivative structure
 * @param dsOffset offset of the derivative structure in its array
 * @param delta parameters offsets (Δx, Δy, ...)
 * @return value of the Taylor expansion at x + Δx, y + Δy, ...
 * @throws MathArithmeticException if factorials becomes too large
 */
public double taylor(final double[] ds, final int dsOffset, final double ... delta)
   throws MathArithmeticException {
    double value = 0;
    for (int i = getSize() - 1; i >= 0; --i) {
        final int[] orders = getPartialDerivativeOrders(i);
        double term = ds[dsOffset + i];
        for (int k = 0; k < orders.length; ++k) {
            if (orders[k] > 0) {
                try {
                    term *= FastMath.pow(delta[k], orders[k]) /
                    CombinatoricsUtils.factorial(orders[k]);
                } catch (NotPositiveException e) {
                    // this cannot happen
                    throw new MathInternalError(e);
                }
            }
        }
        value += term;
    }
    return value;
}
 
Example #2
Source File: DSCompiler.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Evaluate Taylor expansion of a derivative structure.
 * @param ds array holding the derivative structure
 * @param dsOffset offset of the derivative structure in its array
 * @param delta parameters offsets (&Delta;x, &Delta;y, ...)
 * @return value of the Taylor expansion at x + &Delta;x, y + &Delta;y, ...
 * @throws MathArithmeticException if factorials becomes too large
 */
public double taylor(final double[] ds, final int dsOffset, final double ... delta)
   throws MathArithmeticException {
    double value = 0;
    for (int i = getSize() - 1; i >= 0; --i) {
        final int[] orders = getPartialDerivativeOrders(i);
        double term = ds[dsOffset + i];
        for (int k = 0; k < orders.length; ++k) {
            if (orders[k] > 0) {
                try {
                    term *= FastMath.pow(delta[k], orders[k]) /
                    CombinatoricsUtils.factorial(orders[k]);
                } catch (NotPositiveException e) {
                    // this cannot happen
                    throw new MathInternalError(e);
                }
            }
        }
        value += term;
    }
    return value;
}
 
Example #3
Source File: ArcsSet.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Add an arc limit to a BSP tree under construction.
 * @param tree BSP tree under construction
 * @param alpha arc limit
 * @param isStart if true, the limit is the start of an arc
 */
private void addArcLimit(final BSPTree<Sphere1D> tree, final double alpha, final boolean isStart) {

    final LimitAngle limit = new LimitAngle(new S1Point(alpha), !isStart, getTolerance());
    final BSPTree<Sphere1D> node = tree.getCell(limit.getLocation(), getTolerance());
    if (node.getCut() != null) {
        // this should never happen
        throw new MathInternalError();
    }

    node.insertCut(limit);
    node.setAttribute(null);
    node.getPlus().setAttribute(Boolean.FALSE);
    node.getMinus().setAttribute(Boolean.TRUE);

}
 
Example #4
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrderMatrix() {
    UnivariateDifferentiableMatrixFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateMatrixFunction() {
                public double[][] value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #5
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrderMatrix() {
    UnivariateDifferentiableMatrixFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateMatrixFunction() {
                public double[][] value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #6
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrder() {
    UnivariateDifferentiableFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateFunction() {
                public double value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #7
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrderVector() {
    UnivariateDifferentiableVectorFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateVectorFunction() {
                public double[] value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #8
Source File: AbstractRegion.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Filter the parts of an hyperplane belonging to the boundary.
 * <p>The filtering consist in splitting the specified
 * sub-hyperplane into several parts lying in inside and outside
 * cells of the tree. The principle is to call this method twice for
 * each cut sub-hyperplane in the tree, once one the plus node and
 * once on the minus node. The parts that have the same flag
 * (inside/inside or outside/outside) do not belong to the boundary
 * while parts that have different flags (inside/outside or
 * outside/inside) do belong to the boundary.</p>
 * @param node current BSP tree node
 * @param sub sub-hyperplane to characterize
 * @param characterization placeholder where to put the characterized parts
 */
private void characterize(final BSPTree<S> node, final SubHyperplane<S> sub,
                          final SubHyperplane<S>[] characterization) {
    if (node.getCut() == null) {
        // we have reached a leaf node
        final boolean inside = (Boolean) node.getAttribute();
        if (inside) {
            if (characterization[1] == null) {
                characterization[1] = sub;
            } else {
                characterization[1] = characterization[1].reunite(sub);
            }
        } else {
            if (characterization[0] == null) {
                characterization[0] = sub;
            } else {
                characterization[0] = characterization[0].reunite(sub);
            }
        }
    } else {
        final Hyperplane<S> hyperplane = node.getCut().getHyperplane();
        switch (sub.side(hyperplane)) {
        case PLUS:
            characterize(node.getPlus(), sub, characterization);
            break;
        case MINUS:
            characterize(node.getMinus(), sub, characterization);
            break;
        case BOTH:
            final SubHyperplane.SplitSubHyperplane<S> split = sub.split(hyperplane);
            characterize(node.getPlus(),  split.getPlus(),  characterization);
            characterize(node.getMinus(), split.getMinus(), characterization);
            break;
        default:
            // this should not happen
            throw new MathInternalError();
        }
    }
}
 
Example #9
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrderVector() {
    UnivariateDifferentiableVectorFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateVectorFunction() {
                public double[] value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #10
Source File: Combinations.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public Iterator<int[]> iterator() {
    if (k == 0 ||
        k == n) {
        return new SingletonIterator(MathArrays.natural(k));
    }

    switch (iterationOrder) {
    case LEXICOGRAPHIC:
        return new LexicographicIterator(n, k);
    default:
        throw new MathInternalError(); // Should never happen.
    }
}
 
Example #11
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrder() {
    UnivariateDifferentiableFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateFunction() {
                public double value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #12
Source File: ResizableDoubleArray.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The expansion mode determines whether the internal storage
 * array grows additively or multiplicatively when it is expanded.
 *
 * @return the expansion mode.
 * @deprecated As of 3.1. Return value to be changed to
 * {@link ExpansionMode} in 4.0.
 */
@Deprecated
public int getExpansionMode() {
    switch (expansionMode) {
    case MULTIPLICATIVE:
        return MULTIPLICATIVE_MODE;
    case ADDITIVE:
        return ADDITIVE_MODE;
    default:
        throw new MathInternalError(); // Should never happen.
    }
}
 
Example #13
Source File: EmpiricalDistribution.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Computes the empirical distribution from the provided
 * array of numbers.
 *
 * @param in the input data array
 * @exception NullArgumentException if in is null
 */
public void load(double[] in) throws NullArgumentException {
    DataAdapter da = new ArrayDataAdapter(in);
    try {
        da.computeStats();
        // new adapter for the second pass
        fillBinStats(new ArrayDataAdapter(in));
    } catch (IOException ex) {
        // Can't happen
        throw new MathInternalError();
    }
    loaded = true;

}
 
Example #14
Source File: ResizableDoubleArray.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The expansion mode determines whether the internal storage
 * array grows additively or multiplicatively when it is expanded.
 *
 * @return the expansion mode.
 * @deprecated As of 3.1. Return value to be changed to
 * {@link ExpansionMode} in 4.0.
 */
@Deprecated
public int getExpansionMode() {
    switch (expansionMode) {
    case MULTIPLICATIVE:
        return MULTIPLICATIVE_MODE;
    case ADDITIVE:
        return ADDITIVE_MODE;
    default:
        throw new MathInternalError(); // Should never happen.
    }
}
 
Example #15
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrderMatrix() {
    UnivariateDifferentiableMatrixFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateMatrixFunction() {
                public double[][] value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #16
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = FastMath.round(c);
            while (iterator.hasNext()) {
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = FastMath.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw new MathInternalError();
    }
}
 
Example #17
Source File: AbstractRegion.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Filter the parts of an hyperplane belonging to the boundary.
 * <p>The filtering consist in splitting the specified
 * sub-hyperplane into several parts lying in inside and outside
 * cells of the tree. The principle is to call this method twice for
 * each cut sub-hyperplane in the tree, once one the plus node and
 * once on the minus node. The parts that have the same flag
 * (inside/inside or outside/outside) do not belong to the boundary
 * while parts that have different flags (inside/outside or
 * outside/inside) do belong to the boundary.</p>
 * @param node current BSP tree node
 * @param sub sub-hyperplane to characterize
 * @param characterization placeholder where to put the characterized parts
 */
private void characterize(final BSPTree<S> node, final SubHyperplane<S> sub,
                          final Characterization<S> characterization) {
    if (node.getCut() == null) {
        // we have reached a leaf node
        final boolean inside = (Boolean) node.getAttribute();
        characterization.add(sub, inside);
    } else {
        final Hyperplane<S> hyperplane = node.getCut().getHyperplane();
        switch (sub.side(hyperplane)) {
        case PLUS:
            characterize(node.getPlus(), sub, characterization);
            break;
        case MINUS:
            characterize(node.getMinus(), sub, characterization);
            break;
        case BOTH:
            final SubHyperplane.SplitSubHyperplane<S> split = sub.split(hyperplane);
            characterize(node.getPlus(),  split.getPlus(),  characterization);
            characterize(node.getMinus(), split.getMinus(), characterization);
            break;
        default:
            // this should not happen
            throw new MathInternalError();
        }
    }
}
 
Example #18
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrderVector() {
    UnivariateDifferentiableVectorFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateVectorFunction() {
                public double[] value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #19
Source File: EmpiricalDistribution.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Computes the empirical distribution from the provided
 * array of numbers.
 *
 * @param in the input data array
 * @exception NullArgumentException if in is null
 */
public void load(double[] in) throws NullArgumentException {
    DataAdapter da = new ArrayDataAdapter(in);
    try {
        da.computeStats();
        // new adapter for the second pass
        fillBinStats(new ArrayDataAdapter(in));
    } catch (IOException ex) {
        // Can't happen
        throw new MathInternalError();
    }
    loaded = true;

}
 
Example #20
Source File: JGenProg2017_0022_t.java    From coming with MIT License 5 votes vote down vote up
/** Filter the parts of an hyperplane belonging to the boundary.
 * <p>The filtering consist in splitting the specified
 * sub-hyperplane into several parts lying in inside and outside
 * cells of the tree. The principle is to call this method twice for
 * each cut sub-hyperplane in the tree, once one the plus node and
 * once on the minus node. The parts that have the same flag
 * (inside/inside or outside/outside) do not belong to the boundary
 * while parts that have different flags (inside/outside or
 * outside/inside) do belong to the boundary.</p>
 * @param node current BSP tree node
 * @param sub sub-hyperplane to characterize
 * @param characterization placeholder where to put the characterized parts
 */
private void characterize(final BSPTree<S> node, final SubHyperplane<S> sub,
                          final Characterization<S> characterization) {
    if (node.getCut() == null) {
        // we have reached a leaf node
        final boolean inside = (Boolean) node.getAttribute();
        characterization.add(sub, inside);
    } else {
        final Hyperplane<S> hyperplane = node.getCut().getHyperplane();
        switch (sub.side(hyperplane)) {
        case PLUS:
            characterize(node.getPlus(), sub, characterization);
            break;
        case MINUS:
            characterize(node.getMinus(), sub, characterization);
            break;
        case BOTH:
            final SubHyperplane.SplitSubHyperplane<S> split = sub.split(hyperplane);
            characterize(node.getPlus(),  split.getPlus(),  characterization);
            characterize(node.getMinus(), split.getMinus(), characterization);
            break;
        default:
            // this should not happen
            throw new MathInternalError();
        }
    }
}
 
Example #21
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrder() {
    UnivariateDifferentiableFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateFunction() {
                public double value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #22
Source File: FiniteDifferencesDifferentiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=NumberIsTooLargeException.class)
public void testWrongOrder() {
    UnivariateDifferentiableFunction f =
            new FiniteDifferencesDifferentiator(3, 0.01).differentiate(new UnivariateFunction() {
                public double value(double x) {
                    // this exception should not be thrown because wrong order
                    // should be detected before function call
                    throw new MathInternalError();
                }
            });
    f.value(new DerivativeStructure(1, 3, 0, 1.0));
}
 
Example #23
Source File: NPEfix_00119_t.java    From coming with MIT License 4 votes vote down vote up
/** Visit the BSP tree nodes.
 * @param visitor object visiting the tree nodes
 */
public void visit(final BSPTreeVisitor<S> visitor) {
    if (cut == null) {
        visitor.visitLeafNode(this);
    } else {
        switch (visitor.visitOrder(this)) {
        case PLUS_MINUS_SUB:
            plus.visit(visitor);
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case PLUS_SUB_MINUS:
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            break;
        case MINUS_PLUS_SUB:
            minus.visit(visitor);
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case MINUS_SUB_PLUS:
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            break;
        case SUB_PLUS_MINUS:
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            minus.visit(visitor);
            break;
        case SUB_MINUS_PLUS:
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            plus.visit(visitor);
            break;
        default:
            throw new MathInternalError();
        }

    }
}
 
Example #24
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rank <code>data</code> using the natural ordering on Doubles, with
 * NaN values handled according to <code>nanStrategy</code> and ties
 * resolved using <code>tiesStrategy.</code>
 *
 * @param data array to be ranked
 * @return array of ranks
 * @throws NotANumberException if the selected {@link NaNStrategy} is {@code FAILED}
 * and a {@link Double#NaN} is encountered in the input data
 */
public double[] rank(double[] data) {

    // Array recording initial positions of data to be ranked
    IntDoublePair[] ranks = new IntDoublePair[data.length];
    for (int i = 0; i < data.length; i++) {
        ranks[i] = new IntDoublePair(data[i], i);
    }

    // Recode, remove or record positions of NaNs
    List<Integer> nanPositions = null;
    switch (nanStrategy) {
        case MAXIMAL: // Replace NaNs with +INFs
            recodeNaNs(ranks, Double.POSITIVE_INFINITY);
            break;
        case MINIMAL: // Replace NaNs with -INFs
            recodeNaNs(ranks, Double.NEGATIVE_INFINITY);
            break;
        case REMOVED: // Drop NaNs from data
            ranks = removeNaNs(ranks);
            break;
        case FIXED:   // Record positions of NaNs
            nanPositions = getNanPositions(ranks);
            break;
        case FAILED:
            nanPositions = getNanPositions(ranks);
            if (nanPositions.size() > 0) {
                throw new NotANumberException();
            }
            break;
        default: // this should not happen unless NaNStrategy enum is changed
            throw new MathInternalError();
    }

    // Sort the IntDoublePairs
    Arrays.sort(ranks);

    // Walk the sorted array, filling output array using sorted positions,
    // resolving ties as we go
    double[] out = new double[ranks.length];
    int pos = 1;  // position in sorted array
    out[ranks[0].getPosition()] = pos;
    List<Integer> tiesTrace = new ArrayList<Integer>();
    tiesTrace.add(ranks[0].getPosition());
    for (int i = 1; i < ranks.length; i++) {
        if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) {
            // tie sequence has ended (or had length 1)
            pos = i + 1;
            if (tiesTrace.size() > 1) {  // if seq is nontrivial, resolve
                resolveTie(out, tiesTrace);
            }
            tiesTrace = new ArrayList<Integer>();
            tiesTrace.add(ranks[i].getPosition());
        } else {
            // tie sequence continues
            tiesTrace.add(ranks[i].getPosition());
        }
        out[ranks[i].getPosition()] = pos;
    }
    if (tiesTrace.size() > 1) {  // handle tie sequence at end
        resolveTie(out, tiesTrace);
    }
    if (nanStrategy == NaNStrategy.FIXED) {
        restoreNaNs(out, nanPositions);
    }
    return out;
}
 
Example #25
Source File: GaussNewtonOptimizer.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public PointVectorValuePair doOptimize() {
    final ConvergenceChecker<PointVectorValuePair> checker
        = getConvergenceChecker();

    // Computation will be useless without a checker (see "for-loop").
    if (checker == null) {
        throw new NullArgumentException();
    }

    final double[] targetValues = getTarget();
    final int nR = targetValues.length; // Number of observed data.

    final RealMatrix weightMatrix = getWeight();
    // Diagonal of the weight matrix.
    final double[] residualsWeights = new double[nR];
    for (int i = 0; i < nR; i++) {
        residualsWeights[i] = weightMatrix.getEntry(i, i);
    }

    final double[] currentPoint = getStartPoint();
    final int nC = currentPoint.length;

    // iterate until convergence is reached
    PointVectorValuePair current = null;
    int iter = 0;
    for (boolean converged = false; !converged;) {
        ++iter;

        // evaluate the objective function and its jacobian
        PointVectorValuePair previous = current;
        // Value of the objective function at "currentPoint".
        final double[] currentObjective = computeObjectiveValue(currentPoint);
        final double[] currentResiduals = computeResiduals(currentObjective);
        final RealMatrix weightedJacobian = computeWeightedJacobian(currentPoint);
        current = new PointVectorValuePair(currentPoint, currentObjective);

        // build the linear problem
        final double[]   b = new double[nC];
        final double[][] a = new double[nC][nC];
        for (int i = 0; i < nR; ++i) {

            final double[] grad   = weightedJacobian.getRow(i);
            final double weight   = residualsWeights[i];
            final double residual = currentResiduals[i];

            // compute the normal equation
            final double wr = weight * residual;
            for (int j = 0; j < nC; ++j) {
                b[j] += wr * grad[j];
            }

            // build the contribution matrix for measurement i
            for (int k = 0; k < nC; ++k) {
                double[] ak = a[k];
                double wgk = weight * grad[k];
                for (int l = 0; l < nC; ++l) {
                    ak[l] += wgk * grad[l];
                }
            }
        }

        try {
            // solve the linearized least squares problem
            RealMatrix mA = new BlockRealMatrix(a);
            DecompositionSolver solver = useLU ?
                    new LUDecomposition(mA).getSolver() :
                    new QRDecomposition(mA).getSolver();
            final double[] dX = solver.solve(new ArrayRealVector(b, false)).toArray();
            // update the estimated parameters
            for (int i = 0; i < nC; ++i) {
                currentPoint[i] += dX[i];
            }
        } catch (SingularMatrixException e) {
            throw new ConvergenceException(LocalizedFormats.UNABLE_TO_SOLVE_SINGULAR_PROBLEM);
        }

        // Check convergence.
        if (previous != null) {
            converged = checker.converged(iter, previous, current);
            if (converged) {
                cost = computeCost(currentResiduals);
                // Update (deprecated) "point" field.
                point = current.getPoint();
                return current;
            }
        }
    }
    // Must never happen.
    throw new MathInternalError();
}
 
Example #26
Source File: NPEfix_00125_s.java    From coming with MIT License 4 votes vote down vote up
/** Visit the BSP tree nodes.
 * @param visitor object visiting the tree nodes
 */
public void visit(final BSPTreeVisitor<S> visitor) {
    if (cut == null) {
        visitor.visitLeafNode(this);
    } else {
        switch (visitor.visitOrder(this)) {
        case PLUS_MINUS_SUB:
            plus.visit(visitor);
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case PLUS_SUB_MINUS:
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            break;
        case MINUS_PLUS_SUB:
            minus.visit(visitor);
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case MINUS_SUB_PLUS:
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            break;
        case SUB_PLUS_MINUS:
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            minus.visit(visitor);
            break;
        case SUB_MINUS_PLUS:
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            plus.visit(visitor);
            break;
        default:
            throw new MathInternalError();
        }

    }
}
 
Example #27
Source File: NPEfix_00121_s.java    From coming with MIT License 4 votes vote down vote up
/** Visit the BSP tree nodes.
 * @param visitor object visiting the tree nodes
 */
public void visit(final BSPTreeVisitor<S> visitor) {
    if (cut == null) {
        visitor.visitLeafNode(this);
    } else {
        switch (visitor.visitOrder(this)) {
        case PLUS_MINUS_SUB:
            plus.visit(visitor);
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case PLUS_SUB_MINUS:
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            break;
        case MINUS_PLUS_SUB:
            minus.visit(visitor);
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case MINUS_SUB_PLUS:
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            break;
        case SUB_PLUS_MINUS:
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            minus.visit(visitor);
            break;
        case SUB_MINUS_PLUS:
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            plus.visit(visitor);
            break;
        default:
            throw new MathInternalError();
        }

    }
}
 
Example #28
Source File: NPEfix_00122_t.java    From coming with MIT License 4 votes vote down vote up
/** Visit the BSP tree nodes.
 * @param visitor object visiting the tree nodes
 */
public void visit(final BSPTreeVisitor<S> visitor) {
    if (cut == null) {
        visitor.visitLeafNode(this);
    } else {
        switch (visitor.visitOrder(this)) {
        case PLUS_MINUS_SUB:
            plus.visit(visitor);
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case PLUS_SUB_MINUS:
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            break;
        case MINUS_PLUS_SUB:
            minus.visit(visitor);
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case MINUS_SUB_PLUS:
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            break;
        case SUB_PLUS_MINUS:
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            minus.visit(visitor);
            break;
        case SUB_MINUS_PLUS:
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            plus.visit(visitor);
            break;
        default:
            throw new MathInternalError();
        }

    }
}
 
Example #29
Source File: RandomDataImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * <strong>Algorithm Description:</strong> hex strings are generated in
 * 40-byte segments using a 3-step process.
 * <ol>
 * <li>
 * 20 random bytes are generated using the underlying
 * <code>SecureRandom</code>.</li>
 * <li>
 * SHA-1 hash is applied to yield a 20-byte binary digest.</li>
 * <li>
 * Each byte of the binary digest is converted to 2 hex digits.</li>
 * </ol>
 * </p>
 */
public String nextSecureHexString(int len) {
    if (len <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.LENGTH, len);
    }

    // Get SecureRandom and setup Digest provider
    SecureRandom secRan = getSecRan();
    MessageDigest alg = null;
    try {
        alg = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        // this should never happen
        throw new MathInternalError(ex);
    }
    alg.reset();

    // Compute number of iterations required (40 bytes each)
    int numIter = (len / 40) + 1;

    StringBuilder outBuffer = new StringBuilder();
    for (int iter = 1; iter < numIter + 1; iter++) {
        byte[] randomBytes = new byte[40];
        secRan.nextBytes(randomBytes);
        alg.update(randomBytes);

        // Compute hash -- will create 20-byte binary hash
        byte[] hash = alg.digest();

        // Loop over the hash, converting each byte to 2 hex digits
        for (int i = 0; i < hash.length; i++) {
            Integer c = Integer.valueOf(hash[i]);

            /*
             * Add 128 to byte value to make interval 0-255 This guarantees
             * <= 2 hex digits from toHexString() toHexString would
             * otherwise add 2^32 to negative arguments
             */
            String hex = Integer.toHexString(c.intValue() + 128);

            // Keep strings uniform length -- guarantees 40 bytes
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            outBuffer.append(hex);
        }
    }
    return outBuffer.toString().substring(0, len);
}
 
Example #30
Source File: NPEfix_00122_s.java    From coming with MIT License 4 votes vote down vote up
/** Visit the BSP tree nodes.
 * @param visitor object visiting the tree nodes
 */
public void visit(final BSPTreeVisitor<S> visitor) {
    if (cut == null) {
        visitor.visitLeafNode(this);
    } else {
        switch (visitor.visitOrder(this)) {
        case PLUS_MINUS_SUB:
            plus.visit(visitor);
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case PLUS_SUB_MINUS:
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            break;
        case MINUS_PLUS_SUB:
            minus.visit(visitor);
            plus.visit(visitor);
            visitor.visitInternalNode(this);
            break;
        case MINUS_SUB_PLUS:
            minus.visit(visitor);
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            break;
        case SUB_PLUS_MINUS:
            visitor.visitInternalNode(this);
            plus.visit(visitor);
            minus.visit(visitor);
            break;
        case SUB_MINUS_PLUS:
            visitor.visitInternalNode(this);
            minus.visit(visitor);
            plus.visit(visitor);
            break;
        default:
            throw new MathInternalError();
        }

    }
}