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

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

Introduction

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

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

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

Usage

From source file:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java

/**
 * Convert list of pair string and integer to JSON array
 * @return JSON array list of pair string and integer
 * @throws IOException IO exception/*from www . j  a va  2  s.  co  m*/
 */
private static JSONArray listPairtoJSONArray(List<Pair<String, Integer>> listpair) throws IOException {
    JSONArray arr = new JSONArray();

    if (listpair.isEmpty() || listpair.equals(null)) {
        throw new IOException("List pair is empty");
    }
    for (Pair<String, Integer> pair : listpair) {
        JSONObject obj = new JSONObject();
        obj.put("actionId", pair.getLeft());
        obj.put("times", pair.getRight());
        arr.add(obj);
    }
    return arr;
}

From source file:de.tudarmstadt.tk.statistics.importer.ExternalResultsReader.java

public static List<SampleData> splitData(SampleData data, StatsConfig config) {

    List<SampleData> splitted = new ArrayList<SampleData>();

    //Use lists instead of sets to maintain order of model metadata
    ArrayList<String> featureSets = new ArrayList<String>();
    ArrayList<String> classifiers = new ArrayList<String>();
    for (Pair<String, String> metadata : data.getModelMetadata()) {
        if (!classifiers.contains(metadata.getLeft())) {
            classifiers.add(metadata.getLeft());
        }/*from w  ww . ja  v a2  s  .c om*/
        if (!featureSets.contains(metadata.getRight())) {
            featureSets.add(metadata.getRight());
        }
    }

    //Only separate data if there's more than one independent variable
    if (!(featureSets.size() > 1 && classifiers.size() > 1)) {
        splitted.add(data);
        return splitted;
    }

    List<String> it = (config
            .getFixIndependentVariable() == StatsConfigConstants.INDEPENDENT_VARIABLES_VALUES.Classifier)
                    ? classifiers
                    : featureSets;
    for (String fixed : it) {
        ArrayList<Pair<String, String>> modelMetadata = new ArrayList<Pair<String, String>>();
        HashMap<String, ArrayList<ArrayList<Double>>> samples = new HashMap<String, ArrayList<ArrayList<Double>>>();
        HashMap<String, ArrayList<Double>> sampleAverages = new HashMap<String, ArrayList<Double>>();
        for (int i = 0; i < data.getModelMetadata().size(); i++) {
            Pair<String, String> model = data.getModelMetadata().get(i);
            boolean eq = (config
                    .getFixIndependentVariable() == StatsConfigConstants.INDEPENDENT_VARIABLES_VALUES.Classifier)
                            ? model.getLeft().equals(fixed)
                            : model.getRight().equals(fixed);
            if (eq) {
                modelMetadata.add(model);
                for (String measure : data.getSamples().keySet()) {
                    if (!samples.containsKey(measure)) {
                        samples.put(measure, new ArrayList<ArrayList<Double>>());
                        sampleAverages.put(measure, new ArrayList<Double>());
                    }
                    samples.get(measure).add(data.getSamples().get(measure).get(i));
                    sampleAverages.get(measure).add(data.getSamplesAverage().get(measure).get(i));
                }
            }
        }
        ArrayList<Pair<String, String>> baselineModelData = new ArrayList<Pair<String, String>>();
        if (data.isBaselineEvaluation()) {
            Pair<String, String> baselineModel = null;
            for (int i = 0; i < data.getBaselineModelMetadata().size(); i++) {
                boolean eq = (config
                        .getFixIndependentVariable() == StatsConfigConstants.INDEPENDENT_VARIABLES_VALUES.Classifier)
                                ? data.getBaselineModelMetadata().get(i).getLeft().equals(fixed)
                                : data.getBaselineModelMetadata().get(i).getRight().equals(fixed);
                if (eq) {
                    baselineModel = data.getBaselineModelMetadata().get(i);
                    break;
                }
            }
            if (baselineModel != null) {
                baselineModelData.add(baselineModel);
                int modelIndex = modelMetadata.indexOf(baselineModel);
                modelMetadata.remove(modelIndex);
                modelMetadata.add(0, baselineModel);
                for (String measure : data.getSamples().keySet()) {
                    ArrayList<Double> s = samples.get(measure).get(modelIndex);
                    samples.get(measure).remove(modelIndex);
                    samples.get(measure).add(0, s);
                    double a = sampleAverages.get(measure).get(modelIndex);
                    sampleAverages.get(measure).remove(modelIndex);
                    sampleAverages.get(measure).add(0, a);
                }
            } else {
                logger.log(Level.ERROR,
                        "Missing baseline model! Please check if baseline indicators are set correctly in the input file, and if they correspond correctly to the fixIndependentVariable property in the configuration. In case of both varying feature sets and classifiers, baseline indicators have to be set multiple times.");
                System.err.println(
                        "Missing baseline model! Please check if baseline indicators are set correctly in the input file, and if they correspond correctly to the fixIndependentVariable property in the configuration. In case of both varying feature sets and classifiers, baseline indicators have to be set multiple times.");
                System.exit(1);
            }
        }
        SampleData newData = new SampleData(null, samples, sampleAverages, data.getDatasetNames(),
                modelMetadata, baselineModelData, data.getPipelineType(), data.getnFolds(),
                data.getnRepetitions());
        splitted.add(newData);
    }
    return splitted;
}

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//  w  ww  .  j  a  v  a 2  s. c om
 */
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.github.rvesse.airline.utils.predicates.restrictions.AbstractParsedOptionRestrictionBasedFinder.java

@Override
public boolean evaluate(Pair<OptionMetadata, Object> parsedOption) {
    return CollectionUtils.exists(parsedOption.getLeft().getRestrictions(), getRestrictionPredicate());
}

From source file:com.videaps.cube.solving.moving.PrepareNotationDelegate.java

public void execute(DelegateExecution execution) throws Exception {
    String notation = (String) execution.getVariable("notation");
    Pair<String, String> pair = split(notation);

    String face = pair.getLeft();
    execution.setVariable("face", face);

    String direction = pair.getRight();
    execution.setVariable("direction", direction);
}

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

@Override
public void call2() {
    evaluator.reinit();/*from   www.j av a2s. 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();
}

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

/**
 * Is the input valid for an output/*from   w  ww. j ava 2s .c o  m*/
 *
 * @param input The input object
 * @return True if there is an output
 */
@Override
public boolean isValidInput(Pair<SolidifierMode, FluidStack> input) {
    return input.getLeft() == requiredMode && !(input == null || input.getRight().getFluid() == null)
            && getFluidStackFromString(inputFluidStack).getFluid().getName()
                    .equalsIgnoreCase(input.getRight().getFluid().getName())
            && input.getRight().amount >= getFluidStackFromString(inputFluidStack).amount;
}

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  w  w . ja va2s .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:alfio.manager.location.DefaultLocationManager.java

@Override
@Cacheable/* w  ww  . j  av a2 s. c om*/
public TimeZone getTimezone(Pair<String, String> location) {
    return getTimezone(location.getLeft(), location.getRight());
}

From source file:appeng.client.render.renderable.ItemRenderable.java

@Override
public void renderTileEntityAt(T te, double x, double y, double z, float partialTicks, int destroyStage) {
    Pair<ItemStack, Matrix4f> pair = f.apply(te);
    if (pair != null && pair.getLeft() != null) {
        GlStateManager.pushMatrix();//from   w  w  w  .j av a 2s. c o m
        if (pair.getRight() != null) {
            FloatBuffer matrix = BufferUtils.createFloatBuffer(16);
            pair.getRight().store(matrix);
            matrix.flip();
            GlStateManager.multMatrix(matrix);
        }
        Minecraft.getMinecraft().getRenderItem().renderItem(pair.getLeft(), TransformType.GROUND);
        GlStateManager.popMatrix();
    }
}