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

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

Introduction

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

Prototype

public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) 

Source Link

Document

Returns a range that contains all values greater than or equal to lower and less than or equal to upper .

Usage

From source file:org.nmdp.ngs.tools.EvaluateScaffolds.java

@Override
public Integer call() throws Exception {
    PrintWriter writer = null;//  ww w  .j a v  a 2  s . c  o m
    try {
        writer = writer(evalFile);

        Sequence reference = readReference();
        List<Sequence> scaffolds = readScaffolds();

        writer.println("#reference length = " + reference.length());
        writer.println("#scaffold count = " + scaffolds.size());
        writer.println("#scaffold lengths = " + dumpLengths(scaffolds));

        RangeSet<Long> ranges = TreeRangeSet.create();
        for (HighScoringPair hsp : blastn(referenceFastaFile, scaffoldsFastaFile)) {
            if (reference.getName().equals(hsp.target())) {
                writer.println("#" + hsp.toString());
                if (hsp.targetStart() <= hsp.targetEnd()) { // strands match
                    ranges.add(Range.closed(hsp.targetStart(), hsp.targetEnd()));
                } else {
                    ranges.add(Range.closed(hsp.targetEnd(), hsp.targetStart()));
                }
            }
        }

        writer.println("#coalesced intervals = " + ranges);

        long breadthOfCoverage = 0;
        for (Range<Long> range : ranges.asRanges()) {
            breadthOfCoverage += ContiguousSet.create(range, DiscreteDomain.longs()).size();
        }
        double normalizedBreadthOfCoverage = (double) breadthOfCoverage / (double) reference.length();
        writer.println("#breadth-of-coverage = " + breadthOfCoverage);
        writer.println("#normalized breadth-of-coverage = " + normalizedBreadthOfCoverage);

        StringBuilder sb = new StringBuilder();
        sb.append(referenceFastaFile.getName());
        sb.append("\t");
        sb.append(scaffoldsFastaFile.getName());
        sb.append("\t");
        sb.append(reference.length());
        sb.append("\t");
        sb.append(scaffolds.size());
        sb.append("\t");
        sb.append(ranges.asRanges().size());
        sb.append("\t");
        sb.append(breadthOfCoverage);
        sb.append("\t");
        sb.append(normalizedBreadthOfCoverage);
        sb.append("\t");
        writer.println(sb.toString());

        return 0;
    } finally {
        try {
            writer.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:org.jpmml.evaluator.DiscretizationUtil.java

static public Range<Double> toRange(Interval interval) {
    Double leftMargin = interval.getLeftMargin();
    Double rightMargin = interval.getRightMargin();

    // "The attributes leftMargin and rightMargin are optional but at least one value must be defined"
    if (leftMargin == null && rightMargin == null) {
        throw new InvalidFeatureException(interval);
    } // End if//  w  w  w  . j  a  v  a 2 s.  c  o  m

    if (leftMargin != null && rightMargin != null && (leftMargin).compareTo(rightMargin) > 0) {
        throw new InvalidFeatureException(interval);
    }

    Interval.Closure closure = interval.getClosure();
    switch (closure) {
    case OPEN_OPEN: {
        if (leftMargin == null) {
            return Range.lessThan(rightMargin);
        } else

        if (rightMargin == null) {
            return Range.greaterThan(leftMargin);
        }

        return Range.open(leftMargin, rightMargin);
    }
    case OPEN_CLOSED: {
        if (leftMargin == null) {
            return Range.atMost(rightMargin);
        } else

        if (rightMargin == null) {
            return Range.greaterThan(leftMargin);
        }

        return Range.openClosed(leftMargin, rightMargin);
    }
    case CLOSED_OPEN: {
        if (leftMargin == null) {
            return Range.lessThan(rightMargin);
        } else

        if (rightMargin == null) {
            return Range.atLeast(leftMargin);
        }

        return Range.closedOpen(leftMargin, rightMargin);
    }
    case CLOSED_CLOSED: {
        if (leftMargin == null) {
            return Range.atMost(rightMargin);
        } else

        if (rightMargin == null) {
            return Range.atLeast(leftMargin);
        }

        return Range.closed(leftMargin, rightMargin);
    }
    default:
        throw new UnsupportedFeatureException(interval, closure);
    }
}

From source file:io.horizondb.model.core.predicates.BetweenPredicate.java

/**    
 * {@inheritDoc}//from w  w w  . ja  v a2s  .com
 */
@Override
public Filter<Record> toFilter(TimeSeriesDefinition definition) {

    Range<Field> range = Range.closed(this.min, this.max);
    Filter<Field> fieldFilter = range(range, isTimestamp());

    if (this.notBetween) {
        fieldFilter = not(fieldFilter);
    }

    return toRecordFilter(definition, getFieldName(), fieldFilter);
}

From source file:org.robotframework.ide.eclipse.main.plugin.project.build.validation.RobotResourceFileValidator.java

private void reportProblem(final String declarationName, final AModelElement<?> element) {
    final RobotProblem problem = RobotProblem.causedBy(GeneralSettingsProblem.UNSUPPORTED_SETTING)
            .formatMessageWith(declarationName, "resource");
    final ProblemPosition position = new ProblemPosition(element.getBeginPosition().getLine(),
            Range.closed(element.getBeginPosition().getOffset(), element.getEndPosition().getOffset()));
    reporter.handleProblem(problem, file, position);
}

From source file:com.wealdtech.jackson.modules.DateTimeRangeDeserializer.java

public static Range<DateTime> deserialize(final String txt) throws IOException {
      final int txtLen = txt.length();

      final int firstDateChar;
      boolean lowerClosed;
      if (txt.charAt(0) == '[') {
          firstDateChar = 1;//  w ww.j  a  va2s .c  o  m
          lowerClosed = true;
      } else if (txt.charAt(0) == '(') {
          firstDateChar = 1;
          lowerClosed = false;
      } else if (txt.charAt(0) >= '0' && txt.charAt(0) <= '9') {
          // Lazy version
          firstDateChar = 0;
          lowerClosed = true;
      } else {
          throw new DataError.Bad("Unexpected first character in range \"" + txt + "\"");
      }

      boolean upperClosed;
      if (txt.charAt(txtLen - 1) == ']') {
          upperClosed = true;
      } else if (txt.charAt(txtLen - 1) == ')') {
          upperClosed = false;
      } else if (firstDateChar == 0) {
          upperClosed = false;
      } else {
          throw new DataError.Bad("Unexpected last character in range \"" + txt + "\"");
      }

      final Iterator<String> dateTimes;
      if (txt.indexOf(WEALD_SPLITTER_CHAR) != -1) {
          dateTimes = WEALD_SPLITTER.split(txt.substring(firstDateChar, txtLen - firstDateChar)).iterator();
      } else if (txt.indexOf(GUAVA_SPLITTER_CHAR) != -1) {
          dateTimes = GUAVA_SPLITTER.split(txt.substring(firstDateChar, txtLen - firstDateChar)).iterator();
      } else {
          throw new DataError.Bad("Cannot find a range separator in range \"" + txt + "\"");
      }
      String start = dateTimes.next();
      String end = dateTimes.next();

      boolean lowerBound;
      final DateTime lowerPoint;
      if (start.equals(NEGATIVE_INFINITY)) {
          lowerBound = false;
          lowerPoint = null;
      } else {
          lowerBound = true;
          lowerPoint = DateTimeDeserializer.deserialize(start);
      }

      boolean upperBound;
      final DateTime upperPoint;
      if (end.equals(POSITIVE_INFINITY)) {
          upperBound = false;
          upperPoint = null;
      } else {
          upperBound = true;
          upperPoint = DateTimeDeserializer.deserialize(end);
      }

      if (lowerBound == false && upperBound == false) {
          return Range.all();
      } else if (lowerBound == false) {
          // Upper present
          if (upperClosed == true) {
              return Range.lessThan(upperPoint);
          } else {
              return Range.atMost(upperPoint);
          }
      } else if (upperBound == false) {
          // Lower present
          if (lowerClosed == true) {
              return Range.atLeast(lowerPoint);
          } else {
              return Range.greaterThan(lowerPoint);
          }
      } else {
          // Both present
          if (lowerClosed == true) {
              if (upperClosed == true) {
                  return Range.closed(lowerPoint, upperPoint);
              } else {
                  return Range.closedOpen(lowerPoint, upperPoint);
              }
          } else {
              if (upperClosed == true) {
                  return Range.openClosed(lowerPoint, upperPoint);
              } else {
                  return Range.open(lowerPoint, upperPoint);
              }
          }
      }
  }

From source file:org.mskcc.shenkers.control.track.gene.GTFGeneModelProvider.java

@Override
public Iterable<GeneModel> query(String chr, int start, int end) {
    CloseableTribbleIterator<GTFContext> query = null;
    try {//from   w w w .j  a v  a2  s. com
        query = features.query(chr, start, end);

        Stream<GTFContext> filter = StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(query, Spliterator.CONCURRENT), true)
                .filter(c -> c.getTranscriptId() != null);

        ImmutableListMultimap<String, GTFContext> transcript_id_multimap = Multimaps.index(filter.iterator(),
                GTFContext::getTranscriptId);

        Stream<GeneModel> map = transcript_id_multimap.keySet().stream().map(key -> {
            System.out.println(key);
            ImmutableListMultimap<String, GTFContext> transcript_features = Multimaps
                    .index(transcript_id_multimap.get(key), GTFContext::getFeature);
            Map<String, RangeSet<Integer>> collect = transcript_features.keySet().stream()
                    .collect(Collectors.toMap(s -> s, feature -> {
                        return transcript_features.get(feature).stream()
                                .map(c -> Range.closed(c.getStart(), c.getEnd()))
                                .collect(new RangeSetCollector());
                    }));

            GeneModel model = new GeneModel(collect.get("transcript").span(),
                    Optional.ofNullable(collect.get("exon")),
                    Optional.ofNullable(collect.get("CDS")).map(c -> c.span()));
            return model;
        });

        return map::iterator;
    } catch (IOException ex) {
        logger.error("exception reading gene models ", ex);
        throw new RuntimeException(ex);
    } finally {
        query.close();
    }
}

From source file:es.upv.grycap.coreutils.fiber.http.HttpDataFetcher.java

/**
 * Convenient constructor that allows creating a new instance of this class setting the value of the concurrency level.
 * Values above this {@link HttpDataFetcher#MAX_CONCURRENCY limit} will be trimmed.
 * @param concurrencyLevel - desired concurrency level
 *///from  w  w  w . ja v a 2  s  . com
public HttpDataFetcher(final int concurrencyLevel) {
    this.concurrencyLevel = Range.closed(1, MAX_CONCURRENCY).contains(concurrencyLevel) ? concurrencyLevel
            : MAX_CONCURRENCY;
    LOGGER.info(new StringBuilder("Concurrency level: ").append(this.concurrencyLevel).toString());
}

From source file:org.eclipse.m2m.internal.qvt.oml.tools.coverage.ui.TransformationCoverageModel.java

public RangeSet<Integer> getTouchedRanges() {
    if (touchedRanges == null) {
        touchedRanges = TreeRangeSet.create();
        for (NodeCoverageModel nodeModel : getTouchedExpressionNodes()) {
            touchedRanges.add(Range.closed(nodeModel.getStart(), nodeModel.getEnd() + 1));
        }//  w w  w.j a va2  s  .c om
        // Now remove untouched ranges
        for (Range<Integer> untouchedRange : getUntouchedRanges().asRanges()) {
            touchedRanges.remove(untouchedRange);
        }
    }
    return touchedRanges;
}

From source file:com.basistech.tclre.ColorMap.java

ColorMap(Compiler compiler) {
    map = TreeRangeMap.create();/*from  w  ww .j  a  va2  s.  c o m*/
    // the color map starts by assigning all characters to WHITE
    map.put(Range.closed(0, Character.MAX_CODE_POINT), Constants.WHITE);
    this.compiler = compiler;

    colorDescs = Lists.newArrayList();

    ColorDesc white = new ColorDesc(); // [WHITE]
    colorDescs.add(white);
    assert colorDescs.size() == 1;
    white.sub = Constants.NOSUB;
    white.setNChars(65536);
}

From source file:net.sf.mzmine.modules.visualization.twod.TwoDXYPlot.java

public boolean render(final Graphics2D g2, final Rectangle2D dataArea, int index, PlotRenderingInfo info,
        CrosshairState crosshairState) {

    // if this is not TwoDDataSet
    if (index != 0)
        return super.render(g2, dataArea, index, info, crosshairState);

    // prepare some necessary constants
    final int x = (int) dataArea.getX();
    final int y = (int) dataArea.getY();
    final int width = (int) dataArea.getWidth();
    final int height = (int) dataArea.getHeight();

    final double imageRTMin = (double) getDomainAxis().getRange().getLowerBound();
    final double imageRTMax = (double) getDomainAxis().getRange().getUpperBound();
    final double imageRTStep = (imageRTMax - imageRTMin) / width;
    final double imageMZMin = (double) getRangeAxis().getRange().getLowerBound();
    final double imageMZMax = (double) getRangeAxis().getRange().getUpperBound();
    final double imageMZStep = (imageMZMax - imageMZMin) / height;

    if ((zoomOutBitmap != null) && (imageRTMin == totalRTRange.lowerEndpoint())
            && (imageRTMax == totalRTRange.upperEndpoint()) && (imageMZMin == totalMZRange.lowerEndpoint())
            && (imageMZMax == totalMZRange.upperEndpoint()) && (zoomOutBitmap.getWidth() == width)
            && (zoomOutBitmap.getHeight() == height)) {
        g2.drawImage(zoomOutBitmap, x, y, null);
        return true;
    }/*w  w w.ja  v a 2 s  . c  o  m*/

    // Save current time
    Date renderStartTime = new Date();

    // prepare a double array of summed intensities
    double values[][] = new double[width][height];
    maxValue = 0; // now this is an instance variable

    for (int i = 0; i < width; i++)
        for (int j = 0; j < height; j++) {

            double pointRTMin = imageRTMin + (i * imageRTStep);
            double pointRTMax = pointRTMin + imageRTStep;
            double pointMZMin = imageMZMin + (j * imageMZStep);
            double pointMZMax = pointMZMin + imageMZStep;

            double lv = dataset.upperEndpointIntensity(Range.closed(pointRTMin, pointRTMax),
                    Range.closed(pointMZMin, pointMZMax), plotMode);

            if (logScale) {
                lv = Math.log10(lv);
                if (lv < 0 || Double.isInfinite(lv))
                    lv = 0;
                values[i][j] = lv;
                // values[r.nextInt(width)][r.nextInt(height)] = lv;
            } else {
                values[i][j] = lv;
            }

            if (lv > maxValue)
                maxValue = lv;

        }

    // This should never happen, but just for correctness
    if (maxValue == 0)
        return false;

    // Normalize all values
    for (int i = 0; i < width; i++)
        for (int j = 0; j < height; j++) {
            values[i][j] /= maxValue;
        }

    // prepare a bitmap of required size
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    // draw image points
    for (int i = 0; i < width; i++)
        for (int j = 0; j < height; j++) {
            Color pointColor = paletteType.getColor(values[i][j]);
            image.setRGB(i, height - j - 1, pointColor.getRGB());
        }

    // if we are zoomed out, save the values
    if ((imageRTMin == totalRTRange.lowerEndpoint()) && (imageRTMax == totalRTRange.upperEndpoint())
            && (imageMZMin == totalMZRange.lowerEndpoint()) && (imageMZMax == totalMZRange.upperEndpoint())) {
        zoomOutBitmap = image;
    }

    // Paint image
    g2.drawImage(image, x, y, null);

    Date renderFinishTime = new Date();

    logger.finest("Finished rendering 2D visualizer, "
            + (renderFinishTime.getTime() - renderStartTime.getTime()) + " ms");

    return true;

}