Java Code Examples for com.google.common.collect.Range#encloses()

The following examples show how to use com.google.common.collect.Range#encloses() . 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: FilterParser.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@MethodParser("random")
public RandomFilter parseRandom(Element el) throws InvalidXMLException {
  Node node = new Node(el);
  Range<Double> chance;
  try {
    chance = Range.closedOpen(0d, XMLUtils.parseNumber(node, Double.class));
  } catch (InvalidXMLException e) {
    chance = XMLUtils.parseNumericRange(node, Double.class);
  }

  Range<Double> valid = Range.closed(0d, 1d);
  if (valid.encloses(chance)) {
    return new RandomFilter(chance);
  } else {
    double lower = chance.hasLowerBound() ? chance.lowerEndpoint() : Double.NEGATIVE_INFINITY;
    double upper = chance.hasUpperBound() ? chance.upperEndpoint() : Double.POSITIVE_INFINITY;
    double invalid;
    if (!valid.contains(lower)) {
      invalid = lower;
    } else {
      invalid = upper;
    }

    throw new InvalidXMLException("chance value (" + invalid + ") is not between 0 and 1", el);
  }
}
 
Example 2
Source File: ScrollUtil.java    From jetpad-projectional-open-source with Apache License 2.0 6 votes vote down vote up
static int moveDelta(Range<Integer> container, Range<Integer> range) {
  if (container.encloses(range)) return 0;
  if (container.upperEndpoint() - container.lowerEndpoint() < range.upperEndpoint() - range.lowerEndpoint()) {
    return container.lowerEndpoint() - range.lowerEndpoint();
  }

  if (container.contains(range.upperEndpoint())) {
    return container.lowerEndpoint() - range.lowerEndpoint();
  }

  if (container.contains(range.lowerEndpoint())) {
    return container.upperEndpoint() - range.upperEndpoint();
  }

  if (container.upperEndpoint() < range.lowerEndpoint()) {
    return container.upperEndpoint() - range.upperEndpoint();
  } else if (container.lowerEndpoint() > range.upperEndpoint()) {
    return container.lowerEndpoint() - range.lowerEndpoint();
  } else {
    throw new IllegalStateException("This can't happen");
  }
}
 
Example 3
Source File: RexSimplify.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Weakens a term so that it checks only what is not implied by predicates.
 *
 * <p>The term is broken into "ref comparison constant",
 * for example "$0 &lt; 5".
 *
 * <p>Examples:
 * <ul>
 *
 * <li>{@code residue($0 < 10, [$0 < 5])} returns {@code true}
 *
 * <li>{@code residue($0 < 10, [$0 < 20, $0 > 0])} returns {@code $0 < 10}
 * </ul>
 */
private <C extends Comparable<C>> Range<C> residue(RexNode ref, Range<C> r0, List<RexNode> predicates,
        Class<C> clazz) {
    for (RexNode predicate : predicates) {
        switch (predicate.getKind()) {
        case EQUALS:
        case LESS_THAN:
        case LESS_THAN_OR_EQUAL:
        case GREATER_THAN:
        case GREATER_THAN_OR_EQUAL:
            final RexCall call = (RexCall) predicate;
            if (call.getOperands().get(0).equals(ref) && call.getOperands().get(1) instanceof RexLiteral) {
                final RexLiteral literal = (RexLiteral) call.getOperands().get(1);
                final C c1 = literal.getValueAs(clazz);
                final Range<C> r1 = range(predicate.getKind(), c1);
                if (r0.encloses(r1)) {
                    // Given these predicates, term is always satisfied.
                    // e.g. r0 is "$0 < 10", r1 is "$0 < 5"
                    return Range.all();
                }
                if (r0.isConnected(r1)) {
                    return r0.intersection(r1);
                }
                // Ranges do not intersect. Return null meaning the empty range.
                return null;
            }
        }
    }
    return r0;
}
 
Example 4
Source File: RexSimplify.java    From Quicksql with MIT License 5 votes vote down vote up
/** Weakens a term so that it checks only what is not implied by predicates.
 *
 * <p>The term is broken into "ref comparison constant",
 * for example "$0 &lt; 5".
 *
 * <p>Examples:
 * <ul>
 *
 * <li>{@code residue($0 < 10, [$0 < 5])} returns {@code true}
 *
 * <li>{@code residue($0 < 10, [$0 < 20, $0 > 0])} returns {@code $0 < 10}
 * </ul>
 */
private <C extends Comparable<C>> Range<C> residue(RexNode ref, Range<C> r0,
    List<RexNode> predicates, Class<C> clazz) {
  for (RexNode predicate : predicates) {
    switch (predicate.getKind()) {
    case EQUALS:
    case LESS_THAN:
    case LESS_THAN_OR_EQUAL:
    case GREATER_THAN:
    case GREATER_THAN_OR_EQUAL:
      final RexCall call = (RexCall) predicate;
      if (call.operands.get(0).equals(ref)
          && call.operands.get(1) instanceof RexLiteral) {
        final RexLiteral literal = (RexLiteral) call.operands.get(1);
        final C c1 = literal.getValueAs(clazz);
        final Range<C> r1 = range(predicate.getKind(), c1);
        if (r0.encloses(r1)) {
          // Given these predicates, term is always satisfied.
          // e.g. r0 is "$0 < 10", r1 is "$0 < 5"
          return Range.all();
        }
        if (r0.isConnected(r1)) {
          return r0.intersection(r1);
        }
        // Ranges do not intersect. Return null meaning the empty range.
        return null;
      }
    }
  }
  return r0;
}
 
Example 5
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("random")
public Filter parseRandom(Element el) throws InvalidXMLException {
    Node node = new Node(el);
    Range<Double> chance;
    try {
        chance = Range.closedOpen(0d, XMLUtils.parseNumber(node, Double.class));
    } catch(InvalidXMLException e) {
        chance = XMLUtils.parseNumericRange(node, Double.class);
    }

    Range<Double> valid = Range.closed(0d, 1d);
    if (valid.encloses(chance)) {
        return proto.isNoOlderThan(ProtoVersions.EVENT_QUERIES) ? new RandomFilter(chance)
                                                                : new LegacyRandomFilter(chance);
    } else {
        double lower = chance.hasLowerBound() ? chance.lowerEndpoint() : Double.NEGATIVE_INFINITY;
        double upper = chance.hasUpperBound() ? chance.upperEndpoint() : Double.POSITIVE_INFINITY;
        double invalid;
        if(!valid.contains(lower)) {
            invalid = lower;
        } else {
            invalid = upper;
        }

        throw new InvalidXMLException("chance value (" + invalid + ") is not between 0 and 1", el);
    }
}
 
Example 6
Source File: BasicFormatMatcher.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public boolean matches(FileSystem fs, FileAttributes attributes) throws IOException{
  if (ranges.isEmpty() || attributes.isDirectory()) {
    return false;
  }
  // walk all the way down in the symlinks until a hard entry is reached
  FileAttributes current = attributes;
  while (current.isSymbolicLink()) {
    current = fs.getFileAttributes(attributes.getSymbolicLink());
  }
  // if hard entry is not a file nor can it be a symlink then it is not readable simply deny matching.
  if (!current.isRegularFile()) {
    return false;
  }

  final Range<Long> fileRange = Range.closedOpen( 0L, attributes.size());

  try (FSInputStream is = fs.open(attributes.getPath())) {
    for(RangeMagics rMagic : ranges) {
      Range<Long> r = rMagic.range;
      if (!fileRange.encloses(r)) {
        continue;
      }
      int len = (int) (r.upperEndpoint() - r.lowerEndpoint());
      byte[] bytes = new byte[len];
      is.setPosition(r.lowerEndpoint());
      IOUtils.readFully(is, bytes);
      for (byte[] magic : rMagic.magics) {
        if (Arrays.equals(magic, bytes)) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example 7
Source File: ASTVisitors.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addFieldstoTree() {

			if (!fieldLineRanges.isEmpty()) {

				final Table<FieldDeclaration, ASTNode, ArrayList<String>> fieldNodes = HashBasedTable.create();

				// Conflate field node ranges
				for (final Range<Integer> lineRange : fieldLineRanges.asRanges()) {

					// Bizarrely RangeSet uses closedOpen ranges
					final int startLine = lineRange.lowerEndpoint();
					final int endLine = lineRange.upperEndpoint() - 1;

					// Add ranges to allFolds along with first
					// non-empty line of comment
					final Integer startChar = lineToFieldRanges.get(startLine).lowerEndpoint();
					final Integer endChar = lineToFieldRanges.get(endLine).upperEndpoint();
					final Range<Integer> conflatedRange = Range.closed(startChar, endChar);
					allFolds.add(conflatedRange);

					// Get tokens in conflated range
					final ArrayList<String> tokens = Lists.newArrayList();
					for (final Range<Integer> range : fieldIdentifiers.keySet()) {
						if (conflatedRange.encloses(range))
							tokens.addAll(fieldIdentifiers.get(range));
					}

					// Create single block node and add tokens
					final VariableDeclarationFragment fragment = cu.getAST().newVariableDeclarationFragment();
					final FieldDeclaration node = cu.getAST().newFieldDeclaration(fragment);
					final ASTNode parent = fieldLineParentNodes.get(startLine);
					node.setSourceRange(startChar, endChar - startChar + 1);
					fieldNodes.put(node, parent, tokens);
				}

				// Add conflated field nodes to tree
				tree.addNodes(fieldNodes);
			}
		}
 
Example 8
Source File: RexSimplify.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Weakens a term so that it checks only what is not implied by predicates.
 *
 * <p>The term is broken into "ref comparison constant",
 * for example "$0 &lt; 5".
 *
 * <p>Examples:
 * <ul>
 *
 * <li>{@code residue($0 < 10, [$0 < 5])} returns {@code true}
 *
 * <li>{@code residue($0 < 10, [$0 < 20, $0 > 0])} returns {@code $0 < 10}
 * </ul>
 */
private <C extends Comparable<C>> Range<C> residue(RexNode ref, Range<C> r0,
    List<RexNode> predicates, Class<C> clazz) {
  Range<C> result = r0;
  for (RexNode predicate : predicates) {
    switch (predicate.getKind()) {
    case EQUALS:
    case LESS_THAN:
    case LESS_THAN_OR_EQUAL:
    case GREATER_THAN:
    case GREATER_THAN_OR_EQUAL:
      final RexCall call = (RexCall) predicate;
      if (call.operands.get(0).equals(ref)
          && call.operands.get(1) instanceof RexLiteral) {
        final RexLiteral literal = (RexLiteral) call.operands.get(1);
        final C c1 = literal.getValueAs(clazz);
        final Range<C> r1 = range(predicate.getKind(), c1);
        if (result.encloses(r1)) {
          // Given these predicates, term is always satisfied.
          // e.g. r0 is "$0 < 10", r1 is "$0 < 5"
          result = Range.all();
          continue;
        }
        if (result.isConnected(r1)) {
          result = result.intersection(r1);
          continue;
        }
        // Ranges do not intersect. Return null meaning the empty range.
        return null;
      }
    }
  }
  return result;
}
 
Example 9
Source File: TICVisualizerWindow.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
void updateTitle() {

    NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat();
    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();

    StringBuffer mainTitle = new StringBuffer();
    StringBuffer subTitle = new StringBuffer();

    // If all data files have m/z range less than or equal to range of
    // the plot (mzMin, mzMax), then call this TIC, otherwise XIC
    Set<RawDataFile> fileSet = ticDataSets.keySet();
    String ticOrXIC = "TIC";

    // Enlarge range a bit to avoid rounding errors
    Range<Double> mzRange2 = Range.range(mzRange.lowerEndpoint() - 1, BoundType.CLOSED,
        mzRange.upperEndpoint() + 1, BoundType.CLOSED);
    for (RawDataFile df : fileSet) {
      if (!mzRange2.encloses(df.getDataMZRange())) {
        ticOrXIC = "XIC";
        break;
      }
    }

    if (plotType == TICPlotType.BASEPEAK) {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("Base peak chromatogram");
      } else {
        mainTitle.append("XIC (base peak)");
      }
    } else {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("TIC");
      } else {
        mainTitle.append("XIC");
      }
    }

    mainTitle.append(", m/z: " + mzFormat.format(mzRange.lowerEndpoint()) + " - "
        + mzFormat.format(mzRange.upperEndpoint()));

    CursorPosition pos = getCursorPosition();

    if (pos != null) {
      subTitle.append("Selected scan #");
      subTitle.append(pos.getScanNumber());
      if (ticDataSets.size() > 1) {
        subTitle.append(" (" + pos.getDataFile() + ")");
      }
      subTitle.append(", RT: " + rtFormat.format(pos.getRetentionTime()));
      if (plotType == TICPlotType.BASEPEAK) {
        subTitle.append(", base peak: " + mzFormat.format(pos.getMzValue()) + " m/z");
      }
      subTitle.append(", IC: " + intensityFormat.format(pos.getIntensityValue()));
    }

    // update window title
    RawDataFile files[] = ticDataSets.keySet().toArray(new RawDataFile[0]);
    Arrays.sort(files, new SimpleSorter());
    String dataFileNames = Joiner.on(",").join(files);
    setTitle("Chromatogram: [" + dataFileNames + "; " + mzFormat.format(mzRange.lowerEndpoint())
        + " - " + mzFormat.format(mzRange.upperEndpoint()) + " m/z" + "]");

    // update plot title
    ticPlot.setTitle(mainTitle.toString(), subTitle.toString());

  }
 
Example 10
Source File: FileDownloader.java    From rubix with Apache License 2.0 4 votes vote down vote up
protected List<FileDownloadRequestChain> getFileDownloadRequestChains(ConcurrentMap<String, DownloadRequestContext> contextMap)
    throws IOException
{
  List<FileDownloadRequestChain> readRequestChainList = new ArrayList<FileDownloadRequestChain>();
  for (Map.Entry<String, DownloadRequestContext> entry : contextMap.entrySet()) {
    Path path = new Path(entry.getKey());
    DownloadRequestContext context = entry.getValue();

    FileSystem fs = FileSystem.get(path.toUri(), conf);
    fs.initialize(path.toUri(), conf);

    String localPath = CacheUtil.getLocalPath(entry.getKey(), conf);
    log.debug("Processing Request for File : " + path.toString() + " LocalFile : " + localPath);
    ByteBuffer directWriteBuffer = bufferPool.getBuffer(diskReadBufferSize);

    FileDownloadRequestChain requestChain = new FileDownloadRequestChain(bookKeeper, fs, localPath,
        directWriteBuffer, conf, context.getRemoteFilePath(), context.getFileSize(),
        context.getLastModifiedTime());

    Range<Long> previousRange = null;
    for (Range<Long> range : context.getRanges().asRanges()) {
      // align range to block boundary
      long startBlock = toStartBlock(range.lowerEndpoint(), conf);
      long endBlock = toEndBlock(range.upperEndpoint(), conf);

      // We can get cases where multiple reads are part of same Block
      Range<Long> currentRange = Range.closedOpen(startBlock, endBlock);
      if (previousRange != null && previousRange.encloses(currentRange)) {
        // already covered in previous request
        continue;
      }

      previousRange = currentRange;

      // Avoid duplicate warm-ups
      List<BlockLocation> blockLocations = null;

      try {
        blockLocations = bookKeeper.getCacheStatus(
                new CacheStatusRequest(
                        context.getRemoteFilePath(),
                        context.getFileSize(),
                        context.getLastModifiedTime(),
                        startBlock,
                        endBlock));
      }
      catch (Exception e) {
        log.warn("Error communicating with bookKeeper", e);
        // Exception is not expected as RemoteFetchProcessor ensures to not start processing until BookKeeper has initialized
        // recover from this, requeue the requests for this file and continue with next file
        remoteFetchProcessor.addToProcessQueueSafe(context.getRemoteFilePath(), context.getRanges().asRanges(), context.getFileSize(), context.getLastModifiedTime());
        requestChain = null;
        break;
      }

      for (int i = 0; i < blockLocations.size(); i++) {
        if (!blockLocations.get(i).getLocation().equals(Location.LOCAL)) {
          continue;
        }

        long block = startBlock + i;
        long startPosition = toBlockStartPosition(block, conf);
        long endPosition = Math.min(toBlockStartPosition(block + 1, conf), context.getFileSize());
        ReadRequest readRequest = new ReadRequest(startPosition, endPosition, startPosition, endPosition, null, 0, context.getFileSize());
        requestChain.addReadRequest(readRequest);
      }
    }

    if (requestChain != null) {
      log.debug("Request added for file: " + requestChain.getRemotePath() + " Number of Requests : " +
              requestChain.getReadRequests().size());

      readRequestChainList.add(requestChain);
    }
  }

  return readRequestChainList;
}
 
Example 11
Source File: TICVisualizerWindow.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
void updateTitle() {

    NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat();
    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();

    StringBuffer mainTitle = new StringBuffer();
    StringBuffer subTitle = new StringBuffer();

    // If all data files have m/z range less than or equal to range of
    // the plot (mzMin, mzMax), then call this TIC, otherwise XIC
    Set<RawDataFile> fileSet = ticDataSets.keySet();
    String ticOrXIC = "TIC";

    // Enlarge range a bit to avoid rounding errors
    Range<Double> mzRange2 = Range.range(mzRange.lowerEndpoint() - 1, BoundType.CLOSED,
        mzRange.upperEndpoint() + 1, BoundType.CLOSED);
    for (RawDataFile df : fileSet) {
      if (!mzRange2.encloses(df.getDataMZRange())) {
        ticOrXIC = "XIC";
        break;
      }
    }

    if (plotType == TICPlotType.BASEPEAK) {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("Base peak chromatogram");
      } else {
        mainTitle.append("XIC (base peak)");
      }
    } else {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("TIC");
      } else {
        mainTitle.append("XIC");
      }
    }

    mainTitle.append(", m/z: " + mzFormat.format(mzRange.lowerEndpoint()) + " - "
        + mzFormat.format(mzRange.upperEndpoint()));

    CursorPosition pos = getCursorPosition();

    if (pos != null) {
      subTitle.append("Selected scan #");
      subTitle.append(pos.getScanNumber());
      if (ticDataSets.size() > 1) {
        subTitle.append(" (" + pos.getDataFile() + ")");
      }
      subTitle.append(", RT: " + rtFormat.format(pos.getRetentionTime()));
      if (plotType == TICPlotType.BASEPEAK) {
        subTitle.append(", base peak: " + mzFormat.format(pos.getMzValue()) + " m/z");
      }
      subTitle.append(", IC: " + intensityFormat.format(pos.getIntensityValue()));
    }

    // update window title
    RawDataFile files[] = ticDataSets.keySet().toArray(new RawDataFile[0]);
    Arrays.sort(files, new SimpleSorter());
    String dataFileNames = Joiner.on(",").join(files);
    setTitle("Chromatogram: [" + dataFileNames + "; " + mzFormat.format(mzRange.lowerEndpoint())
        + " - " + mzFormat.format(mzRange.upperEndpoint()) + " m/z" + "]");

    // update plot title
    ticPlot.setTitle(mainTitle.toString(), subTitle.toString());

  }