Example usage for com.google.common.collect Range contains

List of usage examples for com.google.common.collect Range contains

Introduction

In this page you can find the example usage for com.google.common.collect Range contains.

Prototype

public boolean contains(C value) 

Source Link

Document

Returns true if value is within the bounds of this range.

Usage

From source file:io.github.msdk.featdet.chromatogrambuilder.HighestDataPointConnector.java

void addScan(RawDataFile dataFile, MsScan scan) {

    // Load data points
    mzBuffer = scan.getMzValues(mzBuffer);
    intensityBuffer = scan.getIntensityValues(intensityBuffer);
    numOfDataPoints = scan.getNumberOfDataPoints();

    // Sort m/z peaks by descending intensity
    DataPointSorter.sortDataPoints(mzBuffer, intensityBuffer, numOfDataPoints, SortingProperty.INTENSITY,
            SortingDirection.DESCENDING);

    // A set of already connected chromatograms in each iteration
    connectedChromatograms.clear();//  w  w w .jav a  2  s. co  m

    for (int i = 0; i < numOfDataPoints; i++) {

        if (intensityBuffer[i] < noiseLevel)
            continue;

        // Search for best chromatogram, which has the highest _last_ data
        // point
        BuildingChromatogram bestChromatogram = null;

        for (BuildingChromatogram testChrom : buildingChromatograms) {

            Range<Double> toleranceRange = mzTolerance.getToleranceRange(testChrom.getLastMz());

            if (toleranceRange.contains(mzBuffer[i])) {
                if ((bestChromatogram == null)
                        || (testChrom.getLastIntensity() > bestChromatogram.getLastIntensity())) {
                    bestChromatogram = testChrom;
                }
            }

        }

        // If we found best chromatogram, check if it is already connected.
        // In such case, we may discard this mass and continue. If we
        // haven't found a chromatogram, we can create a new one.
        if (bestChromatogram != null) {
            if (connectedChromatograms.contains(bestChromatogram)) {
                continue;
            }
        } else {
            bestChromatogram = new BuildingChromatogram();
        }

        // Add this mzPeak to the chromatogram
        ChromatographyInfo rt = scan.getChromatographyInfo();
        Preconditions.checkNotNull(rt);
        bestChromatogram.addDataPoint(rt, mzBuffer[i], intensityBuffer[i]);

        // Move the chromatogram to the set of connected chromatograms
        connectedChromatograms.add(bestChromatogram);

    }

    // Process those chromatograms which were not connected to any m/z peak
    for (BuildingChromatogram testChrom : buildingChromatograms) {

        // Skip those which were connected
        if (connectedChromatograms.contains(testChrom)) {
            continue;
        }

        // Check if we just finished a long-enough segment
        if (testChrom.getBuildingSegmentLength() >= minimumTimeSpan) {
            testChrom.commitBuildingSegment();

            // Move the chromatogram to the set of connected chromatograms
            connectedChromatograms.add(testChrom);
            continue;
        }

        // Check if we have any committed segments in the chromatogram
        if (testChrom.getNumberOfCommittedSegments() > 0) {
            testChrom.removeBuildingSegment();

            // Move the chromatogram to the set of connected chromatograms
            connectedChromatograms.add(testChrom);
            continue;
        }

    }

    // All remaining chromatograms in buildingChromatograms are discarded
    // and buildingChromatograms is replaced with connectedChromatograms
    buildingChromatograms.clear();
    buildingChromatograms.addAll(connectedChromatograms);

}

From source file:org.opentestsystem.authoring.testauth.validation.ScoringRuleParameterValidator.java

/**
 * validate dictionary values/*from   w  ww  .ja  v  a2  s.  com*/
 */
private <N extends Number> void validateDictionaryValues(
        final ComputationRuleParameter computationRuleParameter,
        final List<ScoringRuleDictionaryElement> dictionaryValues, final Errors errors) {
    final ComputationRuleType fieldType = computationRuleParameter.getComputationRuleType();
    final String paramName = computationRuleParameter.getParameterName();
    if (CollectionUtils.isEmpty(dictionaryValues)) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_REQUIRED, fieldType,
                paramName);
    }

    final Map<String, Collection<ScoringRuleDictionaryElement>> duplicates = Maps.filterEntries(
            Multimaps.index(dictionaryValues, DICTIONARY_ELEMENT_TO_KEY_TRANSFORMER).asMap(),
            KEY_DUPLICATE_FILTER);
    if (!duplicates.isEmpty()) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_DUPLICATES, paramName,
                duplicates.keySet().toString());
    }

    for (int i = 0; i < dictionaryValues.size(); i++) {
        final ScoringRuleDictionaryElement scoringRuleDictionaryElement = dictionaryValues.get(i);
        String key = scoringRuleDictionaryElement.getKey();
        final String value = scoringRuleDictionaryElement.getValue();
        try {
            errors.pushNestedPath(DICTIONARY + "[" + i + "]");

            final DictionaryIndexType dictionaryIndex = computationRuleParameter.getDictionaryIndexType();

            final boolean indexIsInteger = dictionaryIndex == DictionaryIndexType.INTEGER;
            if (!rejectIfEmpty(key, errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY,
                    indexIsInteger ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, i + 1)
                    && indexIsInteger) {
                if (!StringUtils.isNumeric(key)) {
                    rejectValue(errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY + MSG_INVALID, fieldType,
                            paramName, key, dictionaryIndex);
                }
            }

            key = StringUtils.defaultIfBlank(key, String.valueOf(i + 1));

            final boolean valueIsNumeric = NUMERIC_TYPES.contains(fieldType);
            if (!rejectIfEmpty(value, errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE,
                    valueIsNumeric ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, key)
                    && valueIsNumeric) {
                final String min = computationRuleParameter.getMinimumValue();
                final String max = computationRuleParameter.getMaximumValue();
                try {
                    if (fieldType == ComputationRuleType.FLOAT) {
                        final Float floatValue = Float.parseFloat(value);
                        final Range<Float> floatRange = buildFloatRange(min, max);
                        if (floatRange != null && !floatRange.contains(floatValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    } else {
                        final Long longValue = Long.parseLong(value);
                        final Range<Long> longRange = buildLongRange(min, max);
                        if (longRange != null && !longRange.contains(longValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    }
                } catch (final NumberFormatException e) {
                    rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_NUMBER,
                            fieldType, paramName, key, value);
                }
            } else if (ComputationRuleType.BOOLEAN.equals(fieldType)
                    && !Boolean.FALSE.toString().equals(value.toString())
                    && !Boolean.TRUE.toString().equals(value.toString())) {
                rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_BOOLEAN,
                        fieldType, paramName, key, value);
            }
        } finally {
            errors.popNestedPath();
        }
    }
}

From source file:io.github.mzmine.datamodel.SimpleFeatureTable.java

/** {@inheritDoc} */
@Override//from w w w  .  j a  v a2 s . c o  m
public List<FeatureTableRow> getRowsInsideRange(Range<Float> rtRange, Range<Double> mzRange) {
    List<FeatureTableRow> result = new ArrayList<FeatureTableRow>();
    for (FeatureTableRow row : featureTableRows) {
        Float rowRT = row.getRT();
        if ((rowRT != null) && rtRange.contains(rowRT) && mzRange.contains(row.getMz()))
            result.add(row);
    }
    return result;
}

From source file:net.sf.mzmine.modules.peaklistmethods.identification.customdbsearch.CustomDBSearchTask.java

private void processOneLine(String values[]) {

    int numOfColumns = Math.min(fieldOrder.length, values.length);

    String lineID = null, lineName = null, lineFormula = null;
    double lineMZ = 0, lineRT = 0;

    for (int i = 0; i < numOfColumns; i++) {
        if (fieldOrder[i] == FieldItem.FIELD_ID)
            lineID = values[i];//  w  ww . ja v a2s  . co  m
        if (fieldOrder[i] == FieldItem.FIELD_NAME)
            lineName = values[i];
        if (fieldOrder[i] == FieldItem.FIELD_FORMULA)
            lineFormula = values[i];
        if (fieldOrder[i] == FieldItem.FIELD_MZ)
            lineMZ = Double.parseDouble(values[i]);
        if (fieldOrder[i] == FieldItem.FIELD_RT)
            lineRT = Double.parseDouble(values[i]);
    }

    SimplePeakIdentity newIdentity = new SimplePeakIdentity(lineName, lineFormula, dataBaseFile.getName(),
            lineID, null);

    for (PeakListRow peakRow : peakList.getRows()) {

        Range<Double> mzRange = mzTolerance.getToleranceRange(peakRow.getAverageMZ());
        Range<Double> rtRange = rtTolerance.getToleranceRange(peakRow.getAverageRT());

        boolean mzMatches = (lineMZ == 0d) || mzRange.contains(lineMZ);
        boolean rtMatches = (lineRT == 0d) || rtRange.contains(lineRT);

        if (mzMatches && rtMatches) {

            logger.finest("Found compound " + lineName + " (m/z " + lineMZ + ", RT " + lineRT + ")");

            // add new identity to the row
            peakRow.addPeakIdentity(newIdentity, false);

            // Notify the GUI about the change in the project
            MZmineCore.getProjectManager().getCurrentProject().notifyObjectChanged(peakRow, false);

        }
    }

}

From source file:org.apache.kylin.storage.cache.StreamSQLResult.java

public StreamSQLResult(List<ITuple> rows, Range<Long> timeCovered, TblColRef partitionCol) {

    sortedRows = Maps.newTreeMap();/* ww w . j a v a 2  s.c o  m*/
    for (ITuple row : rows) {

        if (partitionCol != null) {
            long t = Tuple.getTs(row, partitionCol);

            //will only cache rows that are within the time range
            if (timeCovered.contains(t)) {
                if (!this.sortedRows.containsKey(t)) {
                    this.sortedRows.put(t, Lists.newArrayList(row));
                } else {
                    this.sortedRows.get(t).add(row);
                }
            }
        } else {
            if (!this.sortedRows.containsKey(0L)) {
                this.sortedRows.put(0L, Lists.<ITuple>newArrayList());
            }
            this.sortedRows.get(0L).add(row);
        }
    }
    this.timeCovered = timeCovered;
}

From source file:org.noroomattheinn.visibletesla.stats.StatsRepository.java

public synchronized void loadExistingData(final Recorder r, final Range<Long> period) {
    loadExistingData(new Recorder() {
        @Override//from   ww w.j  a va 2s  .c om
        public void recordElement(long time, String type, double val) {
            if (period.contains(time))
                r.recordElement(time, type, val);
        }
    });
}

From source file:com.techshroom.wood.module.ModuleDependencySolver.java

ImmutableList<Module> computeDependencyOrder() {
    // Fast-track no module case
    if (this.moduleMap.isEmpty()) {
        return ImmutableList.of();
    }//from w w w  . ja va  2s  .co m
    // If a node goes from A->B, A must be loaded AFTER B
    MutableGraph<ModuleMetadata> depGraph = GraphBuilder.directed().allowsSelfLoops(false)
            .expectedNodeCount(this.moduleMap.size()).build();
    // Insert all nodes before connecting
    this.moduleMap.values().stream().map(Module::getMetadata).forEach(depGraph::addNode);
    for (Module factory : this.moduleMap.values()) {
        ModuleMetadata data = factory.getMetadata();
        data.getLoadAfterModules().forEach(dep -> {
            Range<SemVer> acceptable = dep.getVersionRange();
            // Here, we must load data after meta, put data->meta
            depGraph.nodes().stream().filter(meta -> acceptable.contains(meta.getVersion())).findAny()
                    .ifPresent(meta -> {
                        // Do a check for existing edges going the other
                        // way
                        if (depGraph.edges().contains(EndpointPair.ordered(meta, data))) {
                            throw new IllegalStateException("Cannot have a two-way dependency. Found between "
                                    + Modules.getBasicRepresentation(data) + " and "
                                    + Modules.getBasicRepresentation(meta));
                        }
                        depGraph.putEdge(data, meta);
                    });
        });
        data.getLoadBeforeModules().forEach(dep -> {
            Range<SemVer> acceptable = dep.getVersionRange();
            // Here, we must load data before meta, put meta->data
            depGraph.nodes().stream().filter(meta -> acceptable.contains(meta.getVersion())).findAny()
                    .ifPresent(meta -> {
                        // Do a check for existing edges going the other
                        // way
                        if (depGraph.edges().contains(EndpointPair.ordered(data, meta))) {
                            throw new IllegalStateException("Cannot have a two-way dependency. Found between "
                                    + Modules.getBasicRepresentation(data) + " and "
                                    + Modules.getBasicRepresentation(meta));
                        }
                        depGraph.putEdge(meta, data);
                    });
        });
        data.getRequiredModules().forEach(dep -> {
            Range<SemVer> acceptable = dep.getVersionRange();
            // Here, we must load data after meta, put data->meta
            ModuleMetadata result = depGraph.nodes().stream()
                    .filter(meta -> acceptable.contains(meta.getVersion())).findAny().orElseThrow(() -> {
                        return new IllegalStateException("Missing required dependency " + dep);
                    });
            // Do a check for existing edges going the other
            // way
            if (depGraph.edges().contains(EndpointPair.ordered(result, data))) {
                throw new IllegalStateException("Cannot have a two-way dependency. Found between "
                        + Modules.getBasicRepresentation(data) + " and "
                        + Modules.getBasicRepresentation(result));
            }
            depGraph.putEdge(data, result);
        });
    }
    // Modules in dependency-loading order
    List<ModuleMetadata> dependencyOrder = new LinkedList<>();
    // The outDegree is the number of dependencies
    Set<ModuleMetadata> noDeps = depGraph.nodes().stream().filter(m -> depGraph.outDegree(m) == 0)
            .collect(Collectors.toSet());
    checkState(!noDeps.isEmpty(), "There must be at least one module with no dependencies.");
    // this set tracks encountered modules (i.e. child nodes)
    // that have not been known as satisfied by things in depedencyOrder
    Set<ModuleMetadata> encounteredNotSatisfied = new HashSet<>();
    // this set tracks satisfied modules
    // (but not yet added to dependencyOrder)
    // that have not been processed to find other modules
    Set<ModuleMetadata> satisfiedNotProcessed = new HashSet<>(noDeps);
    // Snapshots the last round hashcode for checks
    int lastDepOrderSize = 0;
    while (!satisfiedNotProcessed.isEmpty() || lastDepOrderSize != Objects.hash(dependencyOrder,
            encounteredNotSatisfied, satisfiedNotProcessed)) {
        lastDepOrderSize = Objects.hash(dependencyOrder, encounteredNotSatisfied, satisfiedNotProcessed);
        // Process satisfied modules
        for (ModuleMetadata node : satisfiedNotProcessed) {
            dependencyOrder.add(node);
            // Load modules that depend on `node`
            // insert them into encountered
            depGraph.predecessors(node).forEach(dependent -> {
                encounteredNotSatisfied.add(dependent);
            });
        }
        // Clear satisfiedNotProcessed, after processing
        satisfiedNotProcessed.clear();
        // Process encountered nodes
        for (ModuleMetadata node : encounteredNotSatisfied) {
            // Calculate the load-after deps that might be satisfiable
            // Basically does a ID check against the available
            // dependencies.
            Set<ModuleDependency> satisfiableLoadAfters = getSatisfiableLoadAfters(depGraph.nodes(),
                    node.getLoadAfterModules());
            Set<ModuleDependency> deps = Sets.union(satisfiableLoadAfters, node.getRequiredModules());
            if (allDependenciesSatisified(dependencyOrder, deps)) {
                satisfiedNotProcessed.add(node);
            }
        }
        // Remove all satisfied
        encounteredNotSatisfied.removeAll(satisfiedNotProcessed);
    }
    if (encounteredNotSatisfied.size() > 0) {
        throw new IllegalStateException("Unsatisfied dependencies: " + encounteredNotSatisfied);
    }
    return FluentIterable.from(dependencyOrder).transform(ModuleMetadata::getId).transform(this.moduleMap::get)
            .toList();
}

From source file:io.github.msdk.datamodel.impl.SimpleFeatureTable.java

/** {@inheritDoc} */
@Override// w  w  w  . j  a  v a  2 s.  c  om
public List<FeatureTableRow> getRowsInsideRange(Range<Double> rtRange, Range<Double> mzRange) {
    List<FeatureTableRow> result = new ArrayList<FeatureTableRow>();
    for (FeatureTableRow row : featureTableRows) {
        ChromatographyInfo rowChromatographyInfo = row.getChromatographyInfo();
        if (rtRange.contains((double) rowChromatographyInfo.getRetentionTime())
                && mzRange.contains(row.getMz()))
            result.add(row);
    }
    return result;
}

From source file:org.opentestsystem.authoring.testauth.validation.AbstractDomainValidator.java

/**
 * when an ItemSelectionAlgorithmParameter is defined as a numeric type (FLOAT or INTEGER), every instance
 * must be of that numeric type and fall within the range boundary of the ItemSelectionAlgorithmParameter MIN & MAX values
 *//*from   w  w  w.  j  a  v  a 2  s.co m*/
private void rejectIfNotWithinNumericConstraints(final String fieldValue, final String parametersFieldName,
        final Errors errors, final ItemSelectionAlgorithmParameter parameter, final Object... errorArgs) {
    try {
        if (parameter.getItemSelectionType() == ItemSelectionType.FLOAT) {
            final Float floatValue = Float.parseFloat(fieldValue);
            final Range<Float> floatRange = buildFloatRange(parameter.getMinimumValue(),
                    parameter.getMaximumValue());
            if (floatRange != null && !floatRange.contains(floatValue)) {
                rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_OUT_OF_RANGE,
                        flattenArgs(errorArgs, buildRangeConstraintString(parameter.getMinimumValue(),
                                parameter.getMaximumValue())));
            }
        } else {
            final Long longValue = Long.parseLong(fieldValue);
            final Range<Long> longRange = buildLongRange(parameter.getMinimumValue(),
                    parameter.getMaximumValue());
            if (longRange != null && !longRange.contains(longValue)) {
                rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_OUT_OF_RANGE,
                        flattenArgs(errorArgs, buildRangeConstraintString(parameter.getMinimumValue(),
                                parameter.getMaximumValue())));
            }
        }
    } catch (final NumberFormatException e) {
        rejectValue(errors, "", getErrorMessageRoot() + parametersFieldName + MSG_PARSEABLE_NUMBER, errorArgs);
    }
}

From source file:com.programmablefun.ide.editor.CodeLineStyler.java

private Range findMultiLineComment(int pos) {
    for (Range r : multiLineComments) {
        if (r.contains(pos)) {
            return r;
        }/*from   w w w  .  ja va  2s.com*/
    }
    return null;
}