Example usage for org.apache.commons.lang3.tuple Pair getRight

List of usage examples for org.apache.commons.lang3.tuple Pair getRight

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getRight.

Prototype

public abstract R getRight();

Source Link

Document

Gets the right element from this pair.

When treated as a key-value pair, this is the value.

Usage

From source file:com.act.lcms.db.io.report.IonAnalysisInterchangeModel.java

/**
 * This function takes in a single LCMS result (in the IonAnalysisInterchangeModel format) and extracts all the
 * molecule hits from the file and applies a filter function on the model.
 * @param replicateModel The IonAnalysisInterchangeModel to be analyzed
 * @param hitOrMissFilterAndTransformer This filter function takes in single/multiple HitOrMiss objects from replicates and
 *                                      performs a transformation operation on them to produce one HitOrMiss object
 *                                      and a boolean to keep the transformed molecule in the resulting model.
 * @return  A resultant model that contains a list of inchis that are valid molecule hits in the input file and
 *          pass all the thresholds.//  w  w w .  j a  v a  2  s .  com
 * @throws IOException
 */
public static IonAnalysisInterchangeModel filterAndOperateOnMoleculesFromModel(
        IonAnalysisInterchangeModel replicateModel, HitOrMissFilterAndTransformer hitOrMissFilterAndTransformer)
        throws IOException {

    List<ResultForMZ> resultsForMZs = new ArrayList<>();

    // Iterate through every mass charge
    // TODO: Consider using a parallel stream here
    for (int i = 0; i < replicateModel.getResults().size(); i++) {
        ResultForMZ representativeMZ = replicateModel.getResults().get(i);
        Double representativeMassCharge = representativeMZ.getMz();
        int totalNumberOfMoleculesInMassChargeResult = representativeMZ.getMolecules().size();

        ResultForMZ resultForMZ = new ResultForMZ(representativeMassCharge);
        resultForMZ.setId(representativeMZ.getId());

        // TODO: Take out the isValid field since it does not convey useful information for such post processing files.
        resultForMZ.setIsValid(representativeMZ.getIsValid());

        // For each mass charge, iterate through each molecule under the mass charge
        for (int j = 0; j < totalNumberOfMoleculesInMassChargeResult; j++) {
            Pair<HitOrMiss, Boolean> transformedAndIsRetainedMolecule;

            List<HitOrMiss> molecules = replicateModel.getResults().get(i).getMolecules();
            HitOrMiss molecule = molecules.get(j);
            transformedAndIsRetainedMolecule = hitOrMissFilterAndTransformer.apply(molecule);

            // Check if the filter function  wants to throw out the molecule. If not, then add the molecule to the final result.
            if (transformedAndIsRetainedMolecule.getRight()) {
                resultForMZ.addMolecule(transformedAndIsRetainedMolecule.getLeft());
            }
        }

        resultsForMZs.add(resultForMZ);
    }

    IonAnalysisInterchangeModel resultModel = new IonAnalysisInterchangeModel();
    resultModel.setResults(resultsForMZs);
    return resultModel;
}

From source file:mase.deprecated.HybridGroupController.java

public HybridGroupController(Pair<AgentController, List<Integer>>[] controllers) {
    //this.allocations = controllers;
    AgentController[] temp = new AgentController[100];
    int count = 0;
    for (Pair<AgentController, List<Integer>> p : controllers) {
        for (Integer i : p.getRight()) {
            //System.out.println(i);
            temp[i] = p.getLeft().clone();
            count++;//from www  .j  av a 2  s.c  o m
        }
    }

    acs = Arrays.copyOf(temp, count);
}

From source file:com.teambrmodding.neotech.registries.recipes.SolidifierRecipe.java

/**
 * Used to get the output of this recipe
 *
 * @param input The input object//from  w w  w .  j av a 2 s.c  o m
 * @return The output object
 */
@Nullable
@Override
public ItemStack getOutput(Pair<SolidifierMode, FluidStack> input) {
    if (input == null || input.getRight().getFluid() == null)
        return null;

    if (isValidInput(input))
        return getItemStackFromString(outputItemStack);

    return null;
}

From source file:flens.input.SocketInput.java

@Override
public void tearDown(Pair<String, DataInputStream> in2) throws IOException {
    in2.getRight().close();
}

From source file:fr.cvlaminck.merging.impl.strategy.ImmutableObjectMergingStrategy.java

/**
 * Create an immutable object merging strategy.
 *
 * @since 1.1//  w  w w  .  j  ava  2s  .c  om
 */
public ImmutableObjectMergingStrategy(Class<?> object, Pair... strategies) {
    final MutableObjectMergingStrategy objectMergingStrategy = new MutableObjectMergingStrategy(object);
    //All pairs that do not math the requirements will be simply ignored
    for (Pair strategy : strategies) {
        if (strategy.getRight() instanceof String) {
            //If we have a Pair<String, String> then the user has described a strategy specific to a field
            if (strategy.getLeft() instanceof String)
                objectMergingStrategy.setSpecificStrategyForField((String) strategy.getLeft(),
                        (String) strategy.getRight());
            //If we have a Pair<Object, String> then the user has described a default strategy
            if (strategy.getLeft() instanceof Class)
                objectMergingStrategy.setDefaultStrategyForType((Class<?>) strategy.getLeft(),
                        (String) strategy.getRight());
        }
    }
    this.wrappedObjectMergingStrategy = objectMergingStrategy;
}

From source file:com.act.analysis.surfactant.SurfactantAnalysis.java

/**
 * Perform all analysis for a molecule, returning a map of all available features.
 * @param inchi The molecule to analyze.
 * @param display True if the molecule should be displayed; set to false for non-interactive analysis.
 * @return A map of all features for this molecule.
 * @throws Exception/*from  w  w  w  .ja v  a  2  s.  c  o  m*/
 */
public static Map<FEATURES, Double> performAnalysis(String inchi, boolean display) throws Exception {
    SurfactantAnalysis surfactantAnalysis = new SurfactantAnalysis();
    surfactantAnalysis.init(inchi);

    // Start with simple structural analyses.
    Pair<Integer, Integer> farthestAtoms = surfactantAnalysis.findFarthestContributingAtomPair();
    Double longestVectorLength = surfactantAnalysis.computeDistance(farthestAtoms.getLeft(),
            farthestAtoms.getRight());

    // Then compute the atom distances to the longest vector (lv) and produce lv-normal planes at each atom.
    Pair<Map<Integer, Double>, Map<Integer, Plane>> results = surfactantAnalysis
            .computeAtomDistanceToLongestVectorAndNormalPlanes();
    // Find the max distance so we can calculate the maxDist/|lv| ratio, or "skinny" factor.
    double maxDistToLongestVector = 0.0;
    Map<Integer, Double> distancesToLongestVector = results.getLeft();
    for (Map.Entry<Integer, Double> e : distancesToLongestVector.entrySet()) {
        maxDistToLongestVector = Math.max(maxDistToLongestVector, e.getValue());
    }

    // A map of the molecule features we'll eventually output.
    Map<FEATURES, Double> features = new HashMap<>();

    // Explore the lv endpoint and min/max logP atom neighborhoods, and merge those features into the complete map.
    Map<FEATURES, Double> neighborhoodFeatures = surfactantAnalysis.exploreExtremeNeighborhoods();
    features.putAll(neighborhoodFeatures);

    /* Perform regression analysis on the projection of the molecules onto lv, where their y-axis is their logP value.
     * Higher |slope| may mean more extreme logP differences at the ends. */
    Double slope = surfactantAnalysis.performRegressionOverLVProjectionOfLogP();

    /* Compute the logP surface of the molecule (seems to require a JFrame?), and collect those features.  We consider
     * the number of closest surface components to each atom so we can guess at how much interior atoms actually
     * contribute to the molecule's solubility. */
    JFrame jFrame = new JFrame();
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    Map<FEATURES, Double> surfaceFeatures = surfactantAnalysis.computeSurfaceFeatures(jFrame, true);
    features.putAll(surfaceFeatures);

    features.put(FEATURES.LOGP_TRUE, surfactantAnalysis.plugin.getlogPTrue()); // Save absolute logP since we calculated it.
    features.put(FEATURES.GEO_LV_FD_RATIO, maxDistToLongestVector / longestVectorLength);
    features.put(FEATURES.REG_ABS_SLOPE, slope);

    Map<FEATURES, Double> additionalFeatures = surfactantAnalysis.calculateAdditionalFilteringFeatures();
    features.putAll(additionalFeatures);

    List<FEATURES> sortedFeatures = new ArrayList<>(features.keySet());
    Collections.sort(sortedFeatures);

    // Print these for easier progress tracking.
    System.out.format("features:\n");
    for (FEATURES f : sortedFeatures) {
        System.out.format("  %s = %f\n", f, features.get(f));
    }

    if (display) {
        jFrame.pack();
        jFrame.setVisible(true);
    }

    return features;
}

From source file:com.act.lcms.db.analysis.ConfigurableAnalysis.java

public static void runAnalysis(DB db, File lcmsDir, String outputPrefix, List<AnalysisStep> steps,
        boolean makeHeatmaps, Double fontScale, boolean useSNR) throws SQLException, Exception {
    HashMap<String, Plate> platesByBarcode = new HashMap<>();
    HashMap<Integer, Plate> platesById = new HashMap<>();
    Map<Integer, Pair<List<ScanData<LCMSWell>>, Double>> lcmsResults = new HashMap<>();
    Map<Integer, Pair<List<ScanData<StandardWell>>, Double>> standardResults = new HashMap<>();
    Map<Integer, Double> intensityGroupMaximums = new HashMap<>();
    for (AnalysisStep step : steps) {
        // There's no trace analysis to perform for non-sample steps.
        if (step.getKind() != AnalysisStep.KIND.SAMPLE) {
            continue;
        }/*  w  ww.ja  v a  2s.  c  o  m*/

        Plate p = platesByBarcode.get(step.getPlateBarcode());
        if (p == null) {
            p = Plate.getPlateByBarcode(db, step.getPlateBarcode());
            if (p == null) {
                throw new IllegalArgumentException(
                        String.format("Found invalid plate barcode '%s' for analysis component %d",
                                step.getPlateBarcode(), step.getIndex()));
            }
            platesByBarcode.put(p.getBarcode(), p);
            platesById.put(p.getId(), p);
        }

        Pair<Integer, Integer> coords = Utils.parsePlateCoordinates(step.getPlateCoords());
        List<Pair<String, Double>> searchMZs = Collections
                .singletonList(Pair.of("Configured m/z value", step.getExactMass()));
        Double maxIntesnsity = null;
        switch (p.getContentType()) {
        case LCMS:
            // We don't know which of the scans are positive samples and which are negatives, so call them all positive.
            List<LCMSWell> lcmsSamples = Collections.singletonList(LCMSWell.getInstance()
                    .getByPlateIdAndCoordinates(db, p.getId(), coords.getLeft(), coords.getRight()));
            Pair<List<ScanData<LCMSWell>>, Double> lcmsScanData = AnalysisHelper.processScans(db, lcmsDir,
                    searchMZs, ScanData.KIND.POS_SAMPLE, platesById, lcmsSamples,
                    step.getUseFineGrainedMZTolerance(), SEARCH_IONS, EMPTY_SET, useSNR);
            lcmsResults.put(step.getIndex(), lcmsScanData);
            maxIntesnsity = lcmsScanData.getRight();
            break;
        case STANDARD:
            List<StandardWell> standardSamples = Collections
                    .singletonList(StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db,
                            p.getId(), coords.getLeft(), coords.getRight()));
            Pair<List<ScanData<StandardWell>>, Double> standardScanData = AnalysisHelper.processScans(db,
                    lcmsDir, searchMZs, ScanData.KIND.STANDARD, platesById, standardSamples,
                    step.getUseFineGrainedMZTolerance(), SEARCH_IONS, EMPTY_SET, useSNR);
            standardResults.put(step.getIndex(), standardScanData);
            maxIntesnsity = standardScanData.getRight();
            break;
        default:
            throw new IllegalArgumentException(
                    String.format("Invalid plate content kind %s for plate %s in analysis component %d",
                            p.getContentType(), p.getBarcode(), step.getIndex()));
        }
        Double existingMax = intensityGroupMaximums.get(step.getIntensityRangeGroup());
        if (existingMax == null || existingMax < maxIntesnsity) { // TODO: is this the right max intensity?
            intensityGroupMaximums.put(step.getIntensityRangeGroup(), maxIntesnsity);
        }
    }

    // Prep the chart labels/types, write out the data, and plot the charts.
    File dataFile = new File(outputPrefix + ".data");
    List<Gnuplotter.PlotConfiguration> plotConfigurations = new ArrayList<>(steps.size());
    int numGraphs = 0;
    try (FileOutputStream fos = new FileOutputStream(dataFile)) {
        for (AnalysisStep step : steps) {
            if (step.getKind() == AnalysisStep.KIND.HEADER) {
                // TODO: change the Gnuplotter API to add headings and update this.
                plotConfigurations.add(new Gnuplotter.PlotConfiguration(
                        Gnuplotter.PlotConfiguration.KIND.HEADER, step.getLabel(), null, null));
                continue;
            }
            if (step.getKind() == AnalysisStep.KIND.SEPARATOR_LARGE
                    || step.getKind() == AnalysisStep.KIND.SEPARATOR_SMALL) {
                // TODO: change the Gnuplotter API to add headings and update this.
                plotConfigurations.add(new Gnuplotter.PlotConfiguration(
                        Gnuplotter.PlotConfiguration.KIND.SEPARATOR, "", null, null));
                continue;
            }
            Plate p = platesByBarcode.get(step.getPlateBarcode());
            Double maxIntensity = intensityGroupMaximums.get(step.getIntensityRangeGroup());
            switch (p.getContentType()) {
            case LCMS:
                Pair<List<ScanData<LCMSWell>>, Double> lcmsPair = lcmsResults.get(step.getIndex());
                if (lcmsPair.getLeft().size() > 1) {
                    System.err.format("Found multiple scan files for LCMW well %s @ %s, using first\n",
                            step.getPlateBarcode(), step.getPlateCoords());
                }
                AnalysisHelper.writeScanData(fos, lcmsDir, maxIntensity, lcmsPair.getLeft().get(0),
                        makeHeatmaps, false);
                break;
            case STANDARD:
                Pair<List<ScanData<StandardWell>>, Double> stdPair = standardResults.get(step.getIndex());
                if (stdPair.getLeft().size() > 1) {
                    System.err.format("Found multiple scan files for standard well %s @ %s, using first\n",
                            step.getPlateBarcode(), step.getPlateCoords());
                }
                AnalysisHelper.writeScanData(fos, lcmsDir, maxIntensity, stdPair.getLeft().get(0), makeHeatmaps,
                        false);
                break;
            default:
                // This case represents a bug, so it's a RuntimeException.
                throw new RuntimeException(
                        String.format("Found unexpected content type %s for plate %s on analysis step %d",
                                p.getContentType(), p.getBarcode(), step.getIndex()));
            }
            plotConfigurations.add(new Gnuplotter.PlotConfiguration(Gnuplotter.PlotConfiguration.KIND.GRAPH,
                    step.getLabel(), numGraphs, maxIntensity));
            numGraphs++;
        }

        String fmt = "pdf";
        File imgFile = new File(outputPrefix + "." + fmt);
        Gnuplotter plotter = fontScale == null ? new Gnuplotter() : new Gnuplotter(fontScale);
        if (makeHeatmaps) {
            plotter.plotHeatmap(dataFile.getAbsolutePath(), imgFile.getAbsolutePath(), fmt, null, null,
                    plotConfigurations, imgFile + ".gnuplot");
        } else {
            plotter.plot2D(dataFile.getAbsolutePath(), imgFile.getAbsolutePath(), "time", "intensity", fmt,
                    null, null, plotConfigurations, imgFile + ".gnuplot");
        }
    }
}

From source file:com.spotify.heroic.HeroicCore.java

static boolean awaitLifeCycles(final String op, final CoreComponent primary, final Duration await,
        final List<LifeCycleNamedHook<AsyncFuture<Void>>> hooks)
        throws InterruptedException, ExecutionException {
    log.info("[{}] {} lifecycle(s)...", op, hooks.size());

    final AsyncFramework async = primary.async();

    final List<AsyncFuture<Void>> futures = new ArrayList<>();
    final List<Pair<AsyncFuture<Void>, LifeCycleHook<AsyncFuture<Void>>>> pairs = new ArrayList<>();

    for (final LifeCycleNamedHook<AsyncFuture<Void>> hook : hooks) {
        log.trace("[{}] {}", op, hook.id());

        final AsyncFuture<Void> future;

        try {/*from w  ww .  ja  v a  2 s .co m*/
            future = hook.get();
        } catch (Exception e) {
            futures.add(async.failed(e));
            break;
        }

        if (log.isTraceEnabled()) {
            final Stopwatch w = Stopwatch.createStarted();

            future.onFinished(() -> {
                log.trace("[{}] {}, took {}us", op, hook.id(), w.elapsed(TimeUnit.MICROSECONDS));
            });
        }

        futures.add(future);
        pairs.add(Pair.of(future, hook));
    }

    try {
        async.collect(futures).get(await.getDuration(), await.getUnit());
    } catch (final TimeoutException e) {
        log.error("Operation timed out");

        for (final Pair<AsyncFuture<Void>, LifeCycleHook<AsyncFuture<Void>>> pair : pairs) {
            if (!pair.getLeft().isDone()) {
                log.error("{}: did not finish in time: {}", op, pair.getRight());
            }
        }

        return false;
    }

    log.info("[{}] {} lifecycle(s) done", op, hooks.size());
    return true;
}

From source file:flens.input.GraphiteInput.java

@Override
public void tearDown(Pair<String, BufferedReader> in2) throws IOException {
    in2.getRight().close();
}

From source file:cc.recommenders.evaluation.distribution.calc.F1AndSizeWorker.java

@Override
public void call2() {
    evaluator.reinit();/*  www.  jav a2  s.  co m*/

    ICallsRecommender<Query> rec = minerFactory.get().createRecommender(getTrainingData());
    evaluator.query(rec, getValidationData());

    Pair<double[], Integer> res = evaluator.getRawResults();
    task.f1s = res.getLeft();
    task.sizeInB = res.getRight();
}