Search in sources :

Example 1 with Pair

use of org.apache.commons.math3.util.Pair in project hadoop by apache.

the class LogsCLI method getContainerLogFiles.

private List<Pair<PerContainerLogFileInfo, String>> getContainerLogFiles(Configuration conf, String containerIdStr, String nodeHttpAddress) throws IOException {
    List<Pair<PerContainerLogFileInfo, String>> logFileInfos = new ArrayList<>();
    Client webServiceClient = Client.create();
    try {
        WebResource webResource = webServiceClient.resource(WebAppUtils.getHttpSchemePrefix(conf) + nodeHttpAddress);
        ClientResponse response = webResource.path("ws").path("v1").path("node").path("containers").path(containerIdStr).path("logs").accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
        if (response.getStatusInfo().getStatusCode() == ClientResponse.Status.OK.getStatusCode()) {
            try {
                JSONArray array = new JSONArray();
                JSONObject json = response.getEntity(JSONObject.class);
                Object logsInfoObj = json.get("containerLogsInfo");
                if (logsInfoObj instanceof JSONObject) {
                    array.put((JSONObject) logsInfoObj);
                } else if (logsInfoObj instanceof JSONArray) {
                    JSONArray logsArray = (JSONArray) logsInfoObj;
                    for (int i = 0; i < logsArray.length(); i++) {
                        array.put(logsArray.getJSONObject(i));
                    }
                }
                for (int i = 0; i < array.length(); i++) {
                    JSONObject log = array.getJSONObject(i);
                    String aggregateType = log.has("logAggregationType") ? log.getString("logAggregationType") : "N/A";
                    Object ob = log.get("containerLogInfo");
                    if (ob instanceof JSONArray) {
                        JSONArray obArray = (JSONArray) ob;
                        for (int j = 0; j < obArray.length(); j++) {
                            logFileInfos.add(new Pair<PerContainerLogFileInfo, String>(generatePerContainerLogFileInfoFromJSON(obArray.getJSONObject(j)), aggregateType));
                        }
                    } else if (ob instanceof JSONObject) {
                        logFileInfos.add(new Pair<PerContainerLogFileInfo, String>(generatePerContainerLogFileInfoFromJSON((JSONObject) ob), aggregateType));
                    }
                }
            } catch (Exception e) {
                System.err.println("Unable to parse json from webservice. Error:");
                System.err.println(e.getMessage());
                throw new IOException(e);
            }
        }
    } catch (ClientHandlerException | UniformInterfaceException ex) {
        System.err.println("Unable to fetch log files list");
        throw new IOException(ex);
    }
    return logFileInfos;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) ClientHandlerException(com.sun.jersey.api.client.ClientHandlerException) ArrayList(java.util.ArrayList) JSONArray(org.codehaus.jettison.json.JSONArray) WebResource(com.sun.jersey.api.client.WebResource) IOException(java.io.IOException) PerContainerLogFileInfo(org.apache.hadoop.yarn.logaggregation.PerContainerLogFileInfo) ParseException(org.apache.commons.cli.ParseException) UniformInterfaceException(com.sun.jersey.api.client.UniformInterfaceException) YarnException(org.apache.hadoop.yarn.exceptions.YarnException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) ClientHandlerException(com.sun.jersey.api.client.ClientHandlerException) UniformInterfaceException(com.sun.jersey.api.client.UniformInterfaceException) JSONObject(org.codehaus.jettison.json.JSONObject) JSONObject(org.codehaus.jettison.json.JSONObject) YarnClient(org.apache.hadoop.yarn.client.api.YarnClient) Client(com.sun.jersey.api.client.Client) Pair(org.apache.commons.math3.util.Pair)

Example 2 with Pair

use of org.apache.commons.math3.util.Pair in project Rocket.Chat.Android by RocketChat.

the class MessageOptionsDialogFragment method setUpDialog.

private void setUpDialog(final BottomSheetDialog bottomSheetDialog, String messageId) {
    RocketChatCache cache = new RocketChatCache(bottomSheetDialog.getContext());
    String hostname = cache.getSelectedServerHostname();
    EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname);
    MessageRepository messageRepository = new RealmMessageRepository(hostname);
    Disposable disposable = messageRepository.getById(messageId).flatMap(it -> {
        if (!it.isPresent()) {
            return Single.just(Pair.<Message, Boolean>create(null, false));
        }
        Message message = it.get();
        return Single.zip(Single.just(message), editMessageInteractor.isAllowed(message), Pair::create);
    }).subscribeOn(AndroidSchedulers.from(BackgroundLooper.get())).observeOn(AndroidSchedulers.mainThread()).subscribe(pair -> {
        if (pair.second) {
            bottomSheetDialog.findViewById(R.id.message_options_info).setVisibility(View.GONE);
            View editView = bottomSheetDialog.findViewById(R.id.message_options_edit_action);
            editView.setVisibility(View.VISIBLE);
            editView.setOnClickListener(view -> internalListener.onEdit(pair.first));
        } else {
            ((TextView) bottomSheetDialog.findViewById(R.id.message_options_info)).setText(R.string.message_options_no_permissions_info);
        }
    }, throwable -> {
        ((TextView) bottomSheetDialog.findViewById(R.id.message_options_info)).setText(R.string.message_options_no_message_info);
        Logger.report(throwable);
    });
    compositeDisposable.add(disposable);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) MessageRepository(chat.rocket.core.repositories.MessageRepository) BottomSheetDialog(android.support.design.widget.BottomSheetDialog) RealmPublicSettingRepository(chat.rocket.persistence.realm.repositories.RealmPublicSettingRepository) Bundle(android.os.Bundle) UserRepository(chat.rocket.core.repositories.UserRepository) RocketChatCache(chat.rocket.android.RocketChatCache) RoomRepository(chat.rocket.core.repositories.RoomRepository) Dialog(android.app.Dialog) NonNull(android.support.annotation.NonNull) Single(io.reactivex.Single) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) RealmRoomRoleRepository(chat.rocket.persistence.realm.repositories.RealmRoomRoleRepository) PermissionRepository(chat.rocket.core.repositories.PermissionRepository) PublicSettingRepository(chat.rocket.core.repositories.PublicSettingRepository) PermissionInteractor(chat.rocket.core.interactors.PermissionInteractor) View(android.view.View) RoomRoleRepository(chat.rocket.core.repositories.RoomRoleRepository) R(chat.rocket.android.R) RealmRoomRepository(chat.rocket.persistence.realm.repositories.RealmRoomRepository) BottomSheetDialogFragment(android.support.design.widget.BottomSheetDialogFragment) DialogInterface(android.content.DialogInterface) Logger(chat.rocket.android.helper.Logger) EditMessageInteractor(chat.rocket.core.interactors.EditMessageInteractor) Message(chat.rocket.core.models.Message) RealmMessageRepository(chat.rocket.persistence.realm.repositories.RealmMessageRepository) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) TextView(android.widget.TextView) Pair(android.support.v4.util.Pair) RealmUserRepository(chat.rocket.persistence.realm.repositories.RealmUserRepository) BackgroundLooper(chat.rocket.android.BackgroundLooper) RealmPermissionRepository(chat.rocket.persistence.realm.repositories.RealmPermissionRepository) Message(chat.rocket.core.models.Message) EditMessageInteractor(chat.rocket.core.interactors.EditMessageInteractor) RocketChatCache(chat.rocket.android.RocketChatCache) MessageRepository(chat.rocket.core.repositories.MessageRepository) RealmMessageRepository(chat.rocket.persistence.realm.repositories.RealmMessageRepository) RealmMessageRepository(chat.rocket.persistence.realm.repositories.RealmMessageRepository) TextView(android.widget.TextView) View(android.view.View) TextView(android.widget.TextView)

Example 3 with Pair

use of org.apache.commons.math3.util.Pair in project AntennaPod by AntennaPod.

the class CustomMRControllerDialog method fetchArt.

private Pair<Bitmap, Integer> fetchArt(@NonNull MediaDescriptionCompat description) {
    Bitmap iconBitmap = description.getIconBitmap();
    Uri iconUri = description.getIconUri();
    Bitmap art = null;
    if (iconBitmap != null) {
        art = iconBitmap;
    } else if (iconUri != null) {
        try {
            art = Glide.with(getContext().getApplicationContext()).load(iconUri.toString()).asBitmap().diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY).into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
        } catch (InterruptedException | ExecutionException e) {
            Log.e(TAG, "Image art load failed", e);
        }
    }
    int backgroundColor = 0;
    if (art != null && art.getWidth() * 9 < art.getHeight() * 16) {
        // Portrait art requires dominant color as background color.
        Palette palette = new Palette.Builder(art).maximumColorCount(1).generate();
        backgroundColor = palette.getSwatches().isEmpty() ? 0 : palette.getSwatches().get(0).getRgb();
    }
    return new Pair<>(art, backgroundColor);
}
Also used : Palette(android.support.v7.graphics.Palette) Bitmap(android.graphics.Bitmap) Uri(android.net.Uri) Pair(android.support.v4.util.Pair)

Example 4 with Pair

use of org.apache.commons.math3.util.Pair in project jstructure by JonStargaryen.

the class SVDSuperimposer method align.

@Override
public StructureAlignmentResult align(AtomContainer reference, AtomContainer query) {
    AtomContainer originalReference = reference;
    AtomContainer originalCandidate = query;
    Pair<GroupContainer, GroupContainer> atomContainerPair = AbstractAlignmentAlgorithm.comparableGroupContainerPair(reference, query, minimalSetOfAtomNames, maximalSetOfAtomNames);
    reference = atomContainerPair.getLeft();
    query = atomContainerPair.getRight();
    // calculate centroids
    double[] centroid1 = reference.calculate().centroid().getValue();
    double[] centroid2 = query.calculate().centroid().getValue();
    // center atoms
    reference.calculate().center();
    query.calculate().center();
    // compose covariance matrix and calculate SVD
    RealMatrix matrix1 = convertToMatrix(reference);
    RealMatrix matrix2 = convertToMatrix(query);
    RealMatrix covariance = matrix2.transpose().multiply(matrix1);
    SingularValueDecomposition svd = new SingularValueDecomposition(covariance);
    // R = (V * U')'
    RealMatrix ut = svd.getU().transpose();
    RealMatrix rotationMatrix = svd.getV().multiply(ut).transpose();
    // check if reflection
    if (new LUDecomposition(rotationMatrix).getDeterminant() < 0) {
        RealMatrix v = svd.getV().transpose();
        v.setEntry(2, 0, (0 - v.getEntry(2, 0)));
        v.setEntry(2, 1, (0 - v.getEntry(2, 1)));
        v.setEntry(2, 2, (0 - v.getEntry(2, 2)));
        rotationMatrix = v.transpose().multiply(ut).transpose();
    }
    double[][] rotation = rotationMatrix.getData();
    // calculate translation
    double[] translation = LinearAlgebra.on(centroid1).subtract(LinearAlgebra.on(centroid2).multiply(rotation)).getValue();
    logger.trace("rotation matrix\n{}\ntranslation vector\n{}", Arrays.deepToString(rotationMatrix.getData()), Arrays.toString(translation));
    /* transform 2nd atom select - employ neutral translation (3D vector of zeros), because the atoms are already
        * centered and calculate RMSD */
    query.calculate().transform(new Transformation(rotation));
    double rmsd = calculateRmsd(reference, query);
    // return alignment
    return new StructureAlignmentResult(originalReference, originalCandidate, query, rmsd, translation, rotation);
}
Also used : Transformation(de.bioforscher.jstructure.mathematics.Transformation) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) RealMatrix(org.apache.commons.math3.linear.RealMatrix) AtomContainer(de.bioforscher.jstructure.model.structure.container.AtomContainer) LUDecomposition(org.apache.commons.math3.linear.LUDecomposition) SingularValueDecomposition(org.apache.commons.math3.linear.SingularValueDecomposition) GroupContainer(de.bioforscher.jstructure.model.structure.container.GroupContainer)

Example 5 with Pair

use of org.apache.commons.math3.util.Pair in project GDSC-SMLM by aherbert.

the class ApacheLVMFitter method computeFit.

public FitStatus computeFit(double[] y, final double[] y_fit, double[] a, double[] a_dev) {
    int n = y.length;
    try {
        // Different convergence thresholds seem to have no effect on the resulting fit, only the number of
        // iterations for convergence
        final double initialStepBoundFactor = 100;
        final double costRelativeTolerance = 1e-10;
        final double parRelativeTolerance = 1e-10;
        final double orthoTolerance = 1e-10;
        final double threshold = Precision.SAFE_MIN;
        // Extract the parameters to be fitted
        final double[] initialSolution = getInitialSolution(a);
        // TODO - Pass in more advanced stopping criteria.
        // Create the target and weight arrays
        final double[] yd = new double[n];
        final double[] w = new double[n];
        for (int i = 0; i < n; i++) {
            yd[i] = y[i];
            w[i] = 1;
        }
        LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(initialStepBoundFactor, costRelativeTolerance, parRelativeTolerance, orthoTolerance, threshold);
        //@formatter:off
        LeastSquaresBuilder builder = new LeastSquaresBuilder().maxEvaluations(Integer.MAX_VALUE).maxIterations(getMaxEvaluations()).start(initialSolution).target(yd).weight(new DiagonalMatrix(w));
        if (f instanceof ExtendedNonLinearFunction && ((ExtendedNonLinearFunction) f).canComputeValuesAndJacobian()) {
            // Compute together, or each individually
            builder.model(new ValueAndJacobianFunction() {

                final ExtendedNonLinearFunction fun = (ExtendedNonLinearFunction) f;

                public Pair<RealVector, RealMatrix> value(RealVector point) {
                    final double[] p = point.toArray();
                    final Pair<double[], double[][]> result = fun.computeValuesAndJacobian(p);
                    return new Pair<RealVector, RealMatrix>(new ArrayRealVector(result.getFirst(), false), new Array2DRowRealMatrix(result.getSecond(), false));
                }

                public RealVector computeValue(double[] params) {
                    return new ArrayRealVector(fun.computeValues(params), false);
                }

                public RealMatrix computeJacobian(double[] params) {
                    return new Array2DRowRealMatrix(fun.computeJacobian(params), false);
                }
            });
        } else {
            // Compute separately
            builder.model(new MultivariateVectorFunctionWrapper((NonLinearFunction) f, a, n), new MultivariateMatrixFunctionWrapper((NonLinearFunction) f, a, n));
        }
        LeastSquaresProblem problem = builder.build();
        Optimum optimum = optimizer.optimize(problem);
        final double[] parameters = optimum.getPoint().toArray();
        setSolution(a, parameters);
        iterations = optimum.getIterations();
        evaluations = optimum.getEvaluations();
        if (a_dev != null) {
            try {
                double[][] covar = optimum.getCovariances(threshold).getData();
                setDeviationsFromMatrix(a_dev, covar);
            } catch (SingularMatrixException e) {
                // Matrix inversion failed. In order to return a solution 
                // return the reciprocal of the diagonal of the Fisher information 
                // for a loose bound on the limit 
                final int[] gradientIndices = f.gradientIndices();
                final int nparams = gradientIndices.length;
                GradientCalculator calculator = GradientCalculatorFactory.newCalculator(nparams);
                double[][] alpha = new double[nparams][nparams];
                double[] beta = new double[nparams];
                calculator.findLinearised(nparams, y, a, alpha, beta, (NonLinearFunction) f);
                FisherInformationMatrix m = new FisherInformationMatrix(alpha);
                setDeviations(a_dev, m.crlb(true));
            }
        }
        // Compute function value
        if (y_fit != null) {
            Gaussian2DFunction f = (Gaussian2DFunction) this.f;
            f.initialise0(a);
            f.forEach(new ValueProcedure() {

                int i = 0;

                public void execute(double value) {
                    y_fit[i] = value;
                }
            });
        }
        // As this is unweighted then we can do this to get the sum of squared residuals
        // This is the same as optimum.getCost() * optimum.getCost(); The getCost() function
        // just computes the dot product anyway.
        value = optimum.getResiduals().dotProduct(optimum.getResiduals());
    } catch (TooManyEvaluationsException e) {
        return FitStatus.TOO_MANY_EVALUATIONS;
    } catch (TooManyIterationsException e) {
        return FitStatus.TOO_MANY_ITERATIONS;
    } catch (ConvergenceException e) {
        // Occurs when QR decomposition fails - mark as a singular non-linear model (no solution)
        return FitStatus.SINGULAR_NON_LINEAR_MODEL;
    } catch (Exception e) {
        // TODO - Find out the other exceptions from the fitter and add return values to match. 
        return FitStatus.UNKNOWN;
    }
    return FitStatus.OK;
}
Also used : ValueProcedure(gdsc.smlm.function.ValueProcedure) ExtendedNonLinearFunction(gdsc.smlm.function.ExtendedNonLinearFunction) NonLinearFunction(gdsc.smlm.function.NonLinearFunction) LeastSquaresBuilder(org.apache.commons.math3.fitting.leastsquares.LeastSquaresBuilder) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) Gaussian2DFunction(gdsc.smlm.function.gaussian.Gaussian2DFunction) ValueAndJacobianFunction(org.apache.commons.math3.fitting.leastsquares.ValueAndJacobianFunction) DiagonalMatrix(org.apache.commons.math3.linear.DiagonalMatrix) RealVector(org.apache.commons.math3.linear.RealVector) ArrayRealVector(org.apache.commons.math3.linear.ArrayRealVector) ConvergenceException(org.apache.commons.math3.exception.ConvergenceException) SingularMatrixException(org.apache.commons.math3.linear.SingularMatrixException) TooManyIterationsException(org.apache.commons.math3.exception.TooManyIterationsException) LeastSquaresProblem(org.apache.commons.math3.fitting.leastsquares.LeastSquaresProblem) GradientCalculator(gdsc.smlm.fitting.nonlinear.gradient.GradientCalculator) Pair(org.apache.commons.math3.util.Pair) ArrayRealVector(org.apache.commons.math3.linear.ArrayRealVector) FisherInformationMatrix(gdsc.smlm.fitting.FisherInformationMatrix) MultivariateMatrixFunctionWrapper(gdsc.smlm.function.MultivariateMatrixFunctionWrapper) SingularMatrixException(org.apache.commons.math3.linear.SingularMatrixException) ConvergenceException(org.apache.commons.math3.exception.ConvergenceException) TooManyIterationsException(org.apache.commons.math3.exception.TooManyIterationsException) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) Optimum(org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer.Optimum) LevenbergMarquardtOptimizer(org.apache.commons.math3.fitting.leastsquares.LevenbergMarquardtOptimizer) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) RealMatrix(org.apache.commons.math3.linear.RealMatrix) MultivariateVectorFunctionWrapper(gdsc.smlm.function.MultivariateVectorFunctionWrapper) ExtendedNonLinearFunction(gdsc.smlm.function.ExtendedNonLinearFunction)

Aggregations

Pair (android.support.v4.util.Pair)79 ArrayList (java.util.ArrayList)54 Pair (org.apache.commons.math3.util.Pair)34 View (android.view.View)28 List (java.util.List)28 ActivityOptionsCompat (android.support.v4.app.ActivityOptionsCompat)19 Collectors (java.util.stream.Collectors)19 Intent (android.content.Intent)18 IntStream (java.util.stream.IntStream)17 MaxEval (org.apache.commons.math3.optim.MaxEval)17 Arrays (java.util.Arrays)16 TextView (android.widget.TextView)15 Map (java.util.Map)15 ObjectiveFunction (org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction)15 HashMap (java.util.HashMap)14 InitialGuess (org.apache.commons.math3.optim.InitialGuess)14 PointValuePair (org.apache.commons.math3.optim.PointValuePair)14 MultivariateOptimizer (org.apache.commons.math3.optim.nonlinear.scalar.MultivariateOptimizer)14 java.util (java.util)13 PowellOptimizer (org.apache.commons.math3.optim.nonlinear.scalar.noderiv.PowellOptimizer)13