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

The following examples show how to use com.google.common.collect.Range#isConnected() . 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: ScanAlignment.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * get overlapping MZ range (lowerBound - mzTol and upperbound+ mzTol)
 * 
 * @param mzTol
 * @param a
 * @param b
 * @return
 */
public static Range<Double> getOverlapMZ(MZTolerance mzTol, DataPoint[] a, DataPoint[] b) {
  Range<Double> ra = getMZRange(a);
  Range<Double> rb = getMZRange(b);

  // no overlap
  if (!ra.isConnected(rb))
    return Range.singleton(0d);

  Range<Double> intersect = ra.intersection(rb);
  // add mzTol
  double min = intersect.lowerEndpoint();
  min = mzTol.getToleranceRange(min).lowerEndpoint();
  double max = intersect.upperEndpoint();
  max = mzTol.getToleranceRange(max).upperEndpoint();
  return Range.closed(min, max);

}
 
Example 2
Source File: ScanAlignment.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * get overlapping MZ range (lowerBound - mzTol and upperbound+ mzTol)
 * 
 * @param mzTol
 * @param a
 * @param b
 * @return
 */
public static Range<Double> getOverlapMZ(MZTolerance mzTol, DataPoint[] a, DataPoint[] b) {
  Range<Double> ra = getMZRange(a);
  Range<Double> rb = getMZRange(b);

  // no overlap
  if (!ra.isConnected(rb))
    return Range.singleton(0d);

  Range<Double> intersect = ra.intersection(rb);
  // add mzTol
  double min = intersect.lowerEndpoint();
  min = mzTol.getToleranceRange(min).lowerEndpoint();
  double max = intersect.upperEndpoint();
  max = mzTol.getToleranceRange(max).upperEndpoint();
  return Range.closed(min, max);

}
 
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: RangeUtils.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a range that is contained in between the both ranges.
 * 
 * @param r1
 * @param r2
 * @return The connected range. Null if there is no connected range.
 */
public static @Nullable Range<Double> getConnected(@Nonnull Range<Double> r1,
    @Nonnull Range<Double> r2) {

  if (!r1.isConnected(r2))
    return null;

  double lower =
      (r1.lowerEndpoint() > r2.lowerEndpoint()) ? r1.lowerEndpoint() : r2.lowerEndpoint();
  double upper =
      (r1.upperEndpoint() > r2.upperEndpoint()) ? r2.upperEndpoint() : r1.upperEndpoint();

  return Range.closed(lower, upper);
}
 
Example 5
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 6
Source File: ManagedCursorImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * Given a list of entries, filter out the entries that have already been individually deleted.
 *
 * @param entries
 *            a list of entries
 * @return a list of entries not containing deleted messages
 */
List<Entry> filterReadEntries(List<Entry> entries) {
    lock.readLock().lock();
    try {
        Range<PositionImpl> entriesRange = Range.closed((PositionImpl) entries.get(0).getPosition(),
                (PositionImpl) entries.get(entries.size() - 1).getPosition());
        if (log.isDebugEnabled()) {
            log.debug("[{}] [{}] Filtering entries {} - alreadyDeleted: {}", ledger.getName(), name, entriesRange,
                    individualDeletedMessages);
        }

        if (individualDeletedMessages.isEmpty() || !entriesRange.isConnected(individualDeletedMessages.span())) {
            // There are no individually deleted messages in this entry list, no need to perform filtering
            if (log.isDebugEnabled()) {
                log.debug("[{}] [{}] No filtering needed for entries {}", ledger.getName(), name, entriesRange);
            }
            return entries;
        } else {
            // Remove from the entry list all the entries that were already marked for deletion
            return Lists.newArrayList(Collections2.filter(entries, entry -> {
                boolean includeEntry = !individualDeletedMessages.contains(
                        ((PositionImpl) entry.getPosition()).getLedgerId(),
                        ((PositionImpl) entry.getPosition()).getEntryId());
                if (!includeEntry) {
                    if (log.isDebugEnabled()) {
                        log.debug("[{}] [{}] Filtering entry at {} - already deleted", ledger.getName(), name,
                                entry.getPosition());
                    }

                    entry.release();
                }
                return includeEntry;
            }));
        }
    } finally {
        lock.readLock().unlock();
    }
}
 
Example 7
Source File: RangeParser.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private List<Range<Long>> ensureSatisfiable(Range<Long> requested, Range<Long> content) {
  if (requested.isConnected(content)) {
    return singletonList(requested.intersection(content));
  }
  else {
    return UNSATISFIABLE;
  }
}
 
Example 8
Source File: RangeUtils.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a range that is contained in between the both ranges.
 * 
 * @param r1
 * @param r2
 * @return The connected range. Null if there is no connected range.
 */
public static @Nullable Range<Double> getConnected(@Nonnull Range<Double> r1, @Nonnull Range<Double> r2){
  
  if(!r1.isConnected(r2))
    return null;
  
  double lower = (r1.lowerEndpoint() > r2.lowerEndpoint()) ? r1.lowerEndpoint() : r2.lowerEndpoint();
  double upper = (r1.upperEndpoint() > r2.upperEndpoint()) ? r2.upperEndpoint() : r1.upperEndpoint();
  
  return Range.closed(lower, upper);
}
 
Example 9
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 10
Source File: SlaAlgorithm.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
public Number calculate(Iterable<IScheduledTask> tasks, Range<Long> timeFrame) {
  // Given the set of tasks do the following:
  // - index all available tasks by InstanceId (JobKey + instance ID);
  // - combine individual task ITaskEvent lists into the instance based timeline to represent
  //   all available history for a given task instance;
  // - convert instance timeline into the SlaState intervals.
  Map<InstanceId, List<Interval>> instanceSlaTimeline =
      Maps.transformValues(
          Multimaps.index(tasks, TO_ID).asMap(),
          Functions.compose(TASK_EVENTS_TO_INTERVALS, TO_SORTED_EVENTS));

  // Given the instance timeline converted to SlaState-based time intervals, aggregate the
  // platform uptime per given timeFrame.
  long aggregateUptime = 0;
  long aggregateTotal = 0;
  for (List<Interval> intervals : instanceSlaTimeline.values()) {
    long instanceUptime = elapsedFromRange(timeFrame);
    long instanceTotal = instanceUptime;
    for (Interval interval : intervals) {
      if (timeFrame.isConnected(interval.range)) {
        long intersection = elapsedFromRange(timeFrame.intersection(interval.range));
        if (interval.state == SlaState.REMOVED) {
          instanceUptime -= intersection;
          instanceTotal -= intersection;
        } else if (interval.state == SlaState.DOWN) {
          instanceUptime -= intersection;
        }
      }
    }
    aggregateUptime += instanceUptime;
    aggregateTotal += instanceTotal;
  }

  // Calculate effective platform uptime or default to 100.0 if no instances are running yet.
  return aggregateTotal > 0 ? (double) aggregateUptime * 100 / aggregateTotal : 100.0;
}
 
Example 11
Source File: RangeUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * remove from self the elements that exist in other
 * @return
 */
public static <C extends Comparable<?>> List<Range<C>> remove(Range<C> self, Range<C> other) {

    // mimic the following logic in guava 18:
    //        RangeSet<C> rangeSet = TreeRangeSet.create();
    //        rangeSet.add(self);
    //        rangeSet.remove(other);
    //        return Lists.newArrayList(rangeSet.asRanges());

    if (other == null || !self.isConnected(other)) {
        return Collections.singletonList(self);
    }

    Range<C> share = self.intersection(other);
    if (share.isEmpty()) {
        return Collections.singletonList(self);
    }

    List<Range<C>> ret = Lists.newArrayList();

    //see left part
    if (!self.hasLowerBound()) {
        if (share.hasLowerBound()) {
            if (share.lowerBoundType() == BoundType.CLOSED) {
                ret.add(Range.lessThan(share.lowerEndpoint()));
            } else {
                ret.add(Range.atMost(share.lowerEndpoint()));
            }
        }
    } else {
        if (self.lowerEndpoint() != share.lowerEndpoint()) {
            if (self.lowerBoundType() == BoundType.CLOSED) {
                if (share.lowerBoundType() == BoundType.CLOSED) {
                    ret.add(Range.closedOpen(self.lowerEndpoint(), share.lowerEndpoint()));
                } else {
                    ret.add(Range.closed(self.lowerEndpoint(), share.lowerEndpoint()));
                }
            } else {
                if (share.lowerBoundType() == BoundType.CLOSED) {
                    ret.add(Range.open(self.lowerEndpoint(), share.lowerEndpoint()));
                } else {
                    ret.add(Range.openClosed(self.lowerEndpoint(), share.lowerEndpoint()));
                }
            }
        } else {
            if (self.lowerBoundType() == BoundType.CLOSED && share.lowerBoundType() == BoundType.OPEN) {
                ret.add(Range.closed(self.lowerEndpoint(), share.lowerEndpoint()));
            }
        }
    }

    //see right part 
    if (!self.hasUpperBound()) {
        if (share.hasUpperBound()) {
            if (share.upperBoundType() == BoundType.CLOSED) {
                ret.add(Range.greaterThan(share.upperEndpoint()));
            } else {
                ret.add(Range.atLeast(share.upperEndpoint()));
            }
        }
    } else {
        if (self.upperEndpoint() != share.upperEndpoint()) {
            if (self.upperBoundType() == BoundType.CLOSED) {
                if (share.upperBoundType() == BoundType.CLOSED) {
                    ret.add(Range.openClosed(share.upperEndpoint(), self.upperEndpoint()));
                } else {
                    ret.add(Range.closed(share.upperEndpoint(), self.upperEndpoint()));
                }
            } else {
                if (share.upperBoundType() == BoundType.CLOSED) {
                    ret.add(Range.open(share.upperEndpoint(), self.upperEndpoint()));
                } else {
                    ret.add(Range.closedOpen(share.upperEndpoint(), self.upperEndpoint()));
                }
            }
        } else {
            if (self.upperBoundType() == BoundType.CLOSED && share.upperBoundType() == BoundType.OPEN) {
                ret.add(Range.closed(self.upperEndpoint(), share.upperEndpoint()));
            }
        }
    }

    return ret;

}
 
Example 12
Source File: TsConditionExtractor.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
private static Range<Long> extractTsConditionInternal(TupleFilter filter, TblColRef colRef) {
    if (filter == null) {
        return Range.all();
    }

    if (filter instanceof LogicalTupleFilter) {
        if (filter.getOperator() == TupleFilter.FilterOperatorEnum.AND) {
            Range<Long> ret = Range.all();
            for (TupleFilter child : filter.getChildren()) {
                Range childRange = extractTsConditionInternal(child, colRef);
                if (childRange != null) {
                    if (ret.isConnected(childRange) && !ret.intersection(childRange).isEmpty()) {
                        ret = ret.intersection(childRange);
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            }
            return ret.isEmpty() ? null : ret;
        } else {
            //for conditions like date > DATE'2000-11-11' OR date < DATE '1999-01-01'
            //we will use Ranges.all() rather than two ranges to represent them
            return Range.all();
        }
    }

    if (filter instanceof CompareTupleFilter) {
        CompareTupleFilter compareTupleFilter = (CompareTupleFilter) filter;
        if (compareTupleFilter.getColumn() == null)// column will be null at filters like " 1<>1"
            return Range.all();

        if (compareTupleFilter.getColumn().equals(colRef)) {
            Object firstValue = compareTupleFilter.getFirstValue();
            long t;
            switch (compareTupleFilter.getOperator()) {
            case EQ:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.closed(t, t);
            case LT:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.lessThan(t);
            case LTE:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.atMost(t);
            case GT:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.greaterThan(t);
            case GTE:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.atLeast(t);
            case NEQ:
            case IN://not handled for now
                break;
            default:
            }
        }
    }
    return Range.all();
}
 
Example 13
Source File: AnnotationUtils.java    From dataflow-java with Apache License 2.0 4 votes vote down vote up
/**
 * Determines the effect of the given allele at the given position within a
 * transcript. Currently, this routine is relatively primitive: it only works
 * with SNPs and only computes effects on coding regions of the transcript.
 * This utility currently does not handle any splice sites well, including
 * splice site disruption and codons which span two exons.
 *
 * @param variantStart 0-based absolute start for the variant.
 * @param allele Bases to substitute at {@code variantStart}.
 * @param transcript The affected transcript.
 * @param transcriptBases The reference bases which span the provided
 *     {@code transcript}. Must match the exact length of the
 *     {@code transcript.position}.
 * @return The effect of this variant on the given transcript, or null if
 *     unknown.
 */
public static VariantEffect determineVariantTranscriptEffect(
    long variantStart, String allele, Annotation transcript, String transcriptBases) {
  long txLen = transcript.getEnd() - transcript.getStart();
  Preconditions.checkArgument(transcriptBases.length() == txLen,
      "transcriptBases must have equal length to the transcript; got " +
          transcriptBases.length() + " and " + txLen + ", respectively");
  if (allele.length() != 1) {
    LOG.fine("determineVariantTranscriptEffects() only supports SNPs, ignoring " + allele);
    return null;
  }
  if (transcript.getTranscript().getCodingSequence() == null) {
    LOG.fine("determineVariantTranscriptEffects() only supports intersection with coding " +
        "transcript, ignoring ");
    return null;
  }

  long variantEnd = variantStart + 1;
  Range<Long> variantRange = Range.closedOpen(variantStart, variantEnd);
  Range<Long> codingRange = Range.closedOpen(
      transcript.getTranscript().getCodingSequence().getStart(),
      transcript.getTranscript().getCodingSequence().getEnd());
  if (Boolean.TRUE.equals(transcript.getReverseStrand())) {
    allele = SequenceUtil.reverseComplement(allele);
  }
  for (Exon exon : transcript.getTranscript().getExons()) {
    // For now, only compute effects on variants within the coding region of an exon.
    Range<Long> exonRange = Range.closedOpen(exon.getStart(), exon.getEnd());
    if (exonRange.isConnected(codingRange) &&
        exonRange.intersection(codingRange).isConnected(variantRange) &&
        !exonRange.intersection(codingRange).intersection(variantRange).isEmpty()) {
      // Get the bases which correspond to this exon.
      int txOffset = transcript.getStart().intValue();
      String exonBases = transcriptBases.substring(
          exon.getStart().intValue() - txOffset, exon.getEnd().intValue() - txOffset);
      int variantExonOffset = (int) (variantStart - exon.getStart());

      if (Boolean.TRUE.equals(transcript.getReverseStrand())) {
        // Normalize the offset and bases to 5' -> 3'.
        exonBases = SequenceUtil.reverseComplement(exonBases);
        variantExonOffset = (int) (exon.getEnd() - variantEnd);
      }

      // Determine the indices for the codon which contains this variant.
      if (exon.getFrame() == null) {
        LOG.fine("exon lacks frame data, cannot determine effect");
        return null;
      }
      int offsetWithinCodon = (variantExonOffset + exon.getFrame()) % 3;
      int codonExonOffset = variantExonOffset - offsetWithinCodon;
      if (codonExonOffset < 0 || exonBases.length() <= codonExonOffset+3) {
        LOG.fine("variant codon spans multiple exons, this case is not yet handled");
        return null;
      }
      String fromCodon = exonBases.substring(codonExonOffset, codonExonOffset+3);
      String toCodon =
          fromCodon.substring(0, offsetWithinCodon) + allele +
          fromCodon.substring(offsetWithinCodon + 1);
      return codonChangeToEffect(fromCodon, toCodon);
    }
  }
  return null;
}