org.apache.commons.math3.fitting.leastsquares.LevenbergMarquardtOptimizer Java Examples

The following examples show how to use org.apache.commons.math3.fitting.leastsquares.LevenbergMarquardtOptimizer. 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: GaussianCurveFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected LevenbergMarquardtOptimizer getOptimizer(Collection<WeightedObservedPoint> observations) {
    // Prepare least-squares problem.
    final int len = observations.size();
    final double[] target  = new double[len];
    final double[] weights = new double[len];

    int i = 0;
    for (WeightedObservedPoint obs : observations) {
        target[i]  = obs.getY();
        weights[i] = obs.getWeight();
        ++i;
    }

    final AbstractCurveFitter.TheoreticalValuesFunction model
        = new AbstractCurveFitter.TheoreticalValuesFunction(FUNCTION,
                                                            observations);

    final double[] startPoint = initialGuess != null ?
        initialGuess :
        // Compute estimation.
        new ParameterGuesser(observations).guess();

    // Return a new optimizer set up to fit a Gaussian curve to the
    // observed points.
    return LevenbergMarquardtOptimizer.create()
        .withMaxEvaluations(Integer.MAX_VALUE)
        .withMaxIterations(maxIter)
        .withStartPoint(startPoint)
        .withTarget(target)
        .withWeight(new DiagonalMatrix(weights))
        .withModelAndJacobian(model.getModelFunction(),
                              model.getModelFunctionJacobian());
}
 
Example #2
Source File: TrilaterationTest.java    From trilateration with MIT License 5 votes vote down vote up
private void testCase() {
	TrilaterationFunction trilaterationFunction = new TrilaterationFunction(positions, distances);
	LinearLeastSquaresSolver lSolver = new LinearLeastSquaresSolver(trilaterationFunction);
	NonLinearLeastSquaresSolver nlSolver = new NonLinearLeastSquaresSolver(trilaterationFunction, new LevenbergMarquardtOptimizer());

	linearCalculatedPosition = lSolver.solve();
	nonLinearOptimum = nlSolver.solve();
}
 
Example #3
Source File: LocationRangingService.java    From WiFi-RTT-Trilateration with MIT License 4 votes vote down vote up
@Override
public void onRangingResults(@NonNull List<RangingResult> rangingResultsList) {
    Log.d(TAG, "onRangingResults(): " + rangingResultsList);

    //  Ensure we have more APs in the list of ranging results than were present in the configuration
    if (rangingResultsList.size() >= configuration.getConfiguration().size()) {

        //  Sort the received ranging results by MAC address
        //  (order needs to match the order in the config, previously sorted by MAC address)
        Collections.sort(rangingResultsList, new Comparator<RangingResult>() {
            @Override
            public int compare(RangingResult o1, RangingResult o2) {
                return o1.getMacAddress().toString().compareTo(o2.getMacAddress().toString());
            }
        });

        //  Check that the received ranging results are valid and appropriate
        List<RangingResult> rangingResultsOfInterest = new ArrayList<>();
        rangingResultsOfInterest.clear();
        for (int i = 0; i < rangingResultsList.size(); i++) {
            RangingResult rangingResult = rangingResultsList.get(i);
            if (!configuration.getMacAddresses().contains(rangingResult.getMacAddress().toString())) {
                //  The Mac address found is not in our configuration
                showMessage("Unrecognised MAC address: " + rangingResult.getMacAddress().toString() + ", ignoring");
            } else {
                if (rangingResult.getStatus() == RangingResult.STATUS_SUCCESS) {
                    rangingResultsOfInterest.add(rangingResult);
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        ResponderLocation responderLocation = rangingResultsList.get(0).getUnverifiedResponderLocation();
                        if (responderLocation == null)
                            Log.d(TAG, "ResponderLocation is null (not supported)");
                        else
                            Log.d(TAG, "ResponderLocation is " + responderLocation.toString());
                    }
                } else if (rangingResult.getStatus() == RangingResult.STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC) {
                    showMessage("RangingResult failed (AP doesn't support IEEE80211 MC.");
                } else {
                    showMessage("RangingResult failed. (" + rangingResult.getMacAddress().toString() + ")");
                }
            }
        }
        //  rangingResultsOfInterest now contains the list of APs from whom we have received valid ranging results

        //  Check that every AP in our configuration returned a valid ranging result
        //  Potential enhancement: could remove any APs from the building map that we couldn't range to (need at least 2)
        if (rangingResultsOfInterest.size() != configuration.getConfiguration().size())
        {
            showMessage("Could not find all the APs defined in the configuration to range off of");
            if (!bStop)
                queueNextRangingRequest();
            return;
        }

        for (int i = 0; i < rangingResultsOfInterest.size(); i++)
        {
            ArrayList temp = historicalDistances.get(rangingResultsOfInterest.get(i).getMacAddress().toString());
            temp.add(rangingResultsOfInterest.get(i));
            if (temp.size() == Configuration.NUM_HISTORICAL_POINTS + 1)
                temp.remove(0);
            showMessage("Distance to " + rangingResultsOfInterest.get(i).getMacAddress().toString() +
                    " [Ave]: " + (int)weighted_average(historicalDistances.get(rangingResultsOfInterest.get(i).getMacAddress().toString())) + "mm");
            showMessage("Distance to " + rangingResultsOfInterest.get(i).getMacAddress().toString() +
                    " : " + rangingResultsOfInterest.get(i).getMacAddress().toString() + "mm");
        }

        //  historicalDistances now contains an arraylist of historic distances for each AP
        //  because of an earlier check, we know that every AP in the building map has an associated
        //  entry in the history of observed ranging results
        //  Create the positions and distances arrays required by the multilateration algorithm
        double[][] positions = new double[buildingMap.size()][3]; //  3 dimensions
        double[] distances = new double[buildingMap.size()];
        for (int i = 0; i < buildingMap.size(); i++)
        {
            positions[i] = buildingMap.get(i).getPosition();
            distances[i] = weighted_average(historicalDistances.get(rangingResultsOfInterest.get(i).getMacAddress().toString()));
        }

        try {
            NonLinearLeastSquaresSolver solver = new NonLinearLeastSquaresSolver(new TrilaterationFunction(positions, distances), new LevenbergMarquardtOptimizer());
            LeastSquaresOptimizer.Optimum optimum = solver.solve();
            double[] centroid = optimum.getPoint().toArray();
            Intent centroidIntent = new Intent(Constants.SERVICE_COMMS.LOCATION_COORDS);
            centroidIntent.putExtra(Constants.SERVICE_COMMS.LOCATION_COORDS, centroid);
            sendBroadcast(centroidIntent);
        }
        catch (Exception e)
        {
            showMessage("Error during trilateration: " + e.getMessage());
        }

    }
    else
    {
        showMessage("Could not find enough Ranging Results");
    }
    if (!bStop)
        queueNextRangingRequest();
}
 
Example #4
Source File: Multilateration.java    From BLE-Indoor-Positioning with Apache License 2.0 4 votes vote down vote up
public static LeastSquaresOptimizer.Optimum findOptimum(double[][] positions, double[] distances) {
    TrilaterationFunction trilaterationFunction = new TrilaterationFunction(positions, distances);
    LeastSquaresOptimizer leastSquaresOptimizer = new LevenbergMarquardtOptimizer();
    NonLinearLeastSquaresSolver solver = new NonLinearLeastSquaresSolver(trilaterationFunction, leastSquaresOptimizer);
    return solver.solve();
}
 
Example #5
Source File: AbstractCurveFitter.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates an optimizer set up to fit the appropriate curve.
 * <p>
 * The default implementation uses a {@link LevenbergMarquardtOptimizer
 * Levenberg-Marquardt} optimizer.
 * </p>
 * @return the optimizer to use for fitting the curve to the
 * given {@code points}.
 */
protected LeastSquaresOptimizer getOptimizer() {
    return new LevenbergMarquardtOptimizer();
}
 
Example #6
Source File: AbstractCurveFitter.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates an optimizer set up to fit the appropriate curve.
 * <p>
 * The default implementation uses a {@link LevenbergMarquardtOptimizer
 * Levenberg-Marquardt} optimizer.
 * </p>
 * @return the optimizer to use for fitting the curve to the
 * given {@code points}.
 */
protected LeastSquaresOptimizer getOptimizer() {
    return new LevenbergMarquardtOptimizer();
}