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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.google.cloud.genomics.dataflow.pipelines.AnnotateVariants.java

private String getCachedTranscriptBases(Genomics genomics, Annotation transcript) throws IOException {
    Range<Long> rng = Range.closedOpen(transcript.getStart(), transcript.getEnd());
    if (!refBaseCache.containsKey(rng)) {
        refBaseCache.put(rng, retrieveReferenceBases(genomics, transcript));
    }//  w  w w.  j  a v  a  2 s  . co  m
    return refBaseCache.get(rng);
}

From source file:com.google.cloud.genomics.cba.GGAnnotateVariants.java

@org.apache.beam.sdk.transforms.DoFn.ProcessElement
public void processElement(DoFn<StreamVariantsRequest, KV<String, String>>.ProcessContext c) throws Exception {

    Genomics genomics = GenomicsFactory.builder().build().fromOfflineAuth(auth);

    StreamVariantsRequest request = StreamVariantsRequest.newBuilder(c.element()).addAllCallSetIds(callSetIds)
            .build();//from   w w  w .  j  av a2  s  .  co  m

    if (canonicalizeRefName(request.getReferenceName()).equals("M") && supportChrM == false) {
        LOG.info("There is no information about Chr M in the provided AnnotationSet!");
        return;
    }

    Iterator<StreamVariantsResponse> streamVariantIter = VariantStreamIterator.enforceShardBoundary(auth,
            request, ShardBoundary.Requirement.STRICT, VARIANT_FIELDS);

    if (!streamVariantIter.hasNext()) {
        LOG.info("region has no variants, skipping");
        return;
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    int varCount = 0;

    ListMultimap<Range<Long>, Annotation> variantAnnotationSetList = null;
    if (this.variantAnnotationSetIds != null)
        variantAnnotationSetList = retrieveVariantAnnotations(genomics, request);

    IntervalTree<Annotation> transcripts = null;
    if (this.transcriptSetIds != null)
        transcripts = retrieveTranscripts(genomics, request);

    while (streamVariantIter.hasNext()) {
        Iterable<Variant> varIter;
        if (onlySNP)
            varIter = FluentIterable.from(streamVariantIter.next().getVariantsList())
                    .filter(VariantUtils.IS_SNP);
        else
            varIter = FluentIterable.from(streamVariantIter.next().getVariantsList());

        for (Variant variant : varIter) {
            Range<Long> pos = Range.closedOpen(variant.getStart(), variant.getEnd());

            // This variable helps to keep track of alignment
            String VCFOutput = "";

            // Keep track of Empty VCF records
            boolean EmptyVCF = false;

            // Variant Annotation Section
            if (variantAnnotationSetList != null) {

                // Sort the list of matched annotations
                SortedSet<String> VariantAnnotationKeys = new TreeSet<String>(VariantColInfo.keySet());

                // Retrieve a list of matched variant annotations
                List<Annotation> listMatchedAnnotations = variantAnnotationSetList.get(pos);

                // Visit overlapped annotations in order, and the matches in
                // order (First convert to VCF format, and then add it to
                // VCFOutput);
                int index = 0;
                for (String key : VariantAnnotationKeys) {
                    // The following variables help to put a semicolon
                    // between multiple matches from the same annotationSet
                    // e.g., allele_freq1;allele_freq2;...;allele_freqn;
                    boolean SemiColon = false;

                    for (Annotation match : listMatchedAnnotations) {
                        if (match.getAnnotationSetId().compareTo(key) == 0) {
                            // if (match.getVariant().getAlternateBases() !=
                            // null
                            // && variant.getAlternateBasesList() != null)
                            {
                                // check if Variant's alternate bases are
                                // the same as the matched annotation's
                                // alternate bases

                                if (compareAlternateBases(match.getVariant().getAlternateBases(),
                                        variant.getAlternateBasesList(), variant.getReferenceBases())) {

                                    EmptyVCF = true;

                                    if (DEBUG)
                                        LOG.info("MATCHED: variant: (" + variant.getStart() + ", Annotation: "
                                                + match.getStart() + ") ");

                                    if (!SemiColon) {
                                        VCFOutput += createVCFFormat(variant, match);
                                        SemiColon = true;
                                        // Activate it for the next matched
                                        // element

                                        // TESTING
                                        VCFOutput += "ALT:" + match.getVariant().getAlternateBases() + "\t";
                                    } else {
                                        VCFOutput += ";" + createVCFFormat(variant, match);

                                        // TESTING
                                        VCFOutput += "ALT:" + match.getVariant().getAlternateBases() + "\t";
                                    }
                                }
                            }
                        }
                    }
                    index++;
                    /*
                     * formatTabs function helps to keep track of alignment
                     * in the VCF format (e.g., if there is no match for
                     * Variant X in AnnotationSet Y then add spaces equals
                     * to the number of AnnotationSet Y's columns in the VCF
                     * file)
                     */
                    if (VCFOutput.isEmpty()
                            && (VariantAnnotationKeys.size() > index || TranscriptColInfo.size() > 0)) {
                        VCFOutput += formatTabs(VariantColInfo.get(key));
                    }
                } // end of keys
                if (!EmptyVCF)
                    VCFOutput = "";
            } // End of Variant Annotation

            // Transcript Annotation Section
            if (transcripts != null) {

                // Find all the overlapped matches and create an interval
                // tree
                Iterator<Node<Annotation>> transcriptIter = transcripts
                        .overlappers(pos.lowerEndpoint().intValue(), pos.upperEndpoint().intValue() - 1); // Inclusive.

                Iterator<Node<Annotation>> StartPoint = transcriptIter;
                if (transcriptIter != null) {
                    // Sort the list of matched annotations
                    SortedSet<String> transcriptKeys = new TreeSet<String>(TranscriptColInfo.keySet());
                    int index = 0;
                    // Check annotations in order, and in the case of match
                    // convert the matches to VCF format
                    for (String key : transcriptKeys) {
                        transcriptIter = StartPoint;
                        boolean SemiColon = false;
                        while (transcriptIter.hasNext()) {
                            Annotation transcript = transcriptIter.next().getValue();
                            if (transcript.getAnnotationSetId().compareTo(key) == 0) {
                                if (!SemiColon) {
                                    VCFOutput += createVCFFormat(variant, transcript);
                                    SemiColon = true;
                                } else
                                    VCFOutput += ";" + createVCFFormat(variant, transcript);
                            }
                        }
                        index++;

                        if (VCFOutput.isEmpty() && transcriptKeys.size() > index) {
                            VCFOutput += formatTabs(TranscriptColInfo.get(key));
                        }
                    }
                }
            } // End of Transcripts

            String varintALTs = "";
            for (int index = 0; index < variant.getAlternateBasesCount(); index++) {
                if (index > 0)
                    varintALTs += ",";
                varintALTs += variant.getAlternateBases(index);
            }

            // The following section helps to add genotypes
            /*
             * String VariantGenotype=""; List<VariantCall> Genotypes =
             * variant.getCallsList();
             * 
             * for(String CId: callSetIds){ for(VariantCall VC:Genotypes){
             * if(VC.getCallSetId().equals(CId)){
             * 
             * List<Integer> GentotypeList = VC.getGenotypeList(); for(int
             * index=0; index < GentotypeList.size(); index++){ int Genotype
             * = GentotypeList.get(index);
             * 
             * if(index>0) VariantGenotype += "/";
             * 
             * VariantGenotype += Genotype; } } } VariantGenotype += "\t"; }
             */
            // Map<String, ListValue> VariantInfoMap = variant.getInfo();
            /*
             * String VariantInfo=""; List<VariantCall> VariantCall =
             * variant.getCallsList(); for (Iterator<VariantCall> iter =
             * VariantCall.iterator(); iter.hasNext(); ) { VariantCall
             * element = iter.next(); Map<String, ListValue> VariantCallInfo
             * = element.getInfo(); for (Map.Entry<String, ListValue> entry
             * : VariantCallInfo.entrySet()) { VariantInfo +=entry.getKey()
             * + ":" +
             * entry.getValue().getValuesList().get(0).getStringValue() +
             * ";"; } }
             * 
             * 
             * 
             * /* for (Map.Entry<String, ListValue> entry :
             * VariantInfoMap.entrySet()) { //System.out.println("Key = " +
             * entry.getKey() + ", Value = " + entry.getValue());
             * VariantInfo += entry.getKey() + ":" + entry.getValue() + ";";
             * }
             */

            /*
             * Emit the information in the form of <Key, Value> Print out
             * the variant w/ or w/o any matched annotations Key: (ChromId,
             * Start, End) Value:(variant's <referenceName start end
             * referenceBases alternateBases quality>, + The content of
             * "VCFOutput" OR Annotation's fields
             */
            if (this.BigQuery) {
                if (!VCFOutput.isEmpty()) {
                    c.output(KV.of(
                            variant.getReferenceName() + ";" + Long.toString(variant.getStart()) + ";"
                                    + Long.toString(variant.getEnd()),
                            // Value
                            VCFOutput));
                }
            } else {
                if (!VCFOutput.isEmpty()) {
                    c.output(KV.of(
                            variant.getReferenceName() + ";" + Long.toString(variant.getStart()) + ";"
                                    + Long.toString(variant.getEnd()),
                            // Value
                            variant.getReferenceName()
                                    // <-- increment by 1 => convert to 1-based
                                    // -->
                                    + "\t" + (variant.getStart() + 1) + "\t" + variant.getEnd() + "\t"
                                    + variant.getReferenceBases() + "\t" + varintALTs
                                    // + "\t" + VariantInfo
                                    // + "\t" + variant.getQuality()
                                    // + "\t" + VariantGenotype
                                    + "\t" + VCFOutput));
                }
            }

            varCount++;
            if (varCount % 1e3 == 0) {
                LOG.info(String.format("read %d variants (%.2f / s)", varCount,
                        (double) varCount / stopwatch.elapsed(TimeUnit.SECONDS)));
            }
        }

    }

    LOG.info("finished reading " + varCount + " variants in " + stopwatch);
}

From source file:com.google.googlejavaformat.java.JavaOutput.java

/**
 * Expand a token range to start and end on acceptable boundaries for re-formatting.
 *
 * @param iRange the {@link Range} of tokens
 * @return the expanded token range/*from   w w  w . j  av  a 2 s.co  m*/
 */
private Range<Integer> expandToBreakableRegions(Range<Integer> iRange) {
    // The original line range.
    int loTok = iRange.lowerEndpoint();
    int hiTok = iRange.upperEndpoint() - 1;

    // Expand the token indices to formattable boundaries (e.g. edges of statements).
    if (!partialFormatRanges.contains(loTok) || !partialFormatRanges.contains(hiTok)) {
        return EMPTY_RANGE;
    }
    loTok = partialFormatRanges.rangeContaining(loTok).lowerEndpoint();
    hiTok = partialFormatRanges.rangeContaining(hiTok).upperEndpoint();
    return Range.closedOpen(loTok, hiTok + 1);
}

From source file:com.google.googlejavaformat.java.RemoveUnusedImports.java

/** Applies the replacements to the given source, and re-format any edited javadoc. */
private static String applyReplacements(String source, RangeMap<Integer, String> replacements) {
    // save non-empty fixed ranges for reformatting after fixes are applied
    RangeSet<Integer> fixedRanges = TreeRangeSet.create();

    // Apply the fixes in increasing order, adjusting ranges to account for
    // earlier fixes that change the length of the source. The output ranges are
    // needed so we can reformat fixed regions, otherwise the fixes could just
    // be applied in descending order without adjusting offsets.
    StringBuilder sb = new StringBuilder(source);
    int offset = 0;
    for (Map.Entry<Range<Integer>, String> replacement : replacements.asMapOfRanges().entrySet()) {
        Range<Integer> range = replacement.getKey();
        String replaceWith = replacement.getValue();
        int start = offset + range.lowerEndpoint();
        int end = offset + range.upperEndpoint();
        sb.replace(start, end, replaceWith);
        if (!replaceWith.isEmpty()) {
            fixedRanges.add(Range.closedOpen(start, end));
        }/*from w  ww  . j  a v a2  s.co m*/
        offset += replaceWith.length() - (range.upperEndpoint() - range.lowerEndpoint());
    }
    String result = sb.toString();

    // If there were any non-empty replaced ranges (e.g. javadoc), reformat the fixed regions.
    // We could avoid formatting twice in --fix-imports=also mode, but that is not the default
    // and removing imports won't usually affect javadoc.
    if (!fixedRanges.isEmpty()) {
        try {
            result = new Formatter().formatSource(result, fixedRanges.asRanges());
        } catch (FormatterException e) {
            // javadoc reformatting is best-effort
        }
    }
    return result;
}

From source file:edu.mit.streamjit.impl.compiler2.Storage.java

/**
 * Returns a range spanning the indices written in this storage during an
 * execution of the given schedule. (Note that, as a span, not every
 * contained index will be written.) The returned range will be
 * {@link Range#canonical(com.google.common.collect.DiscreteDomain) canonical}.
 * The range is not cached so as to be responsive to changes in output index
 * functions./*from   w w  w .j av  a  2 s .c o  m*/
 * @param externalSchedule the schedule
 * @return a range spanning the indices written during the given schedule
 * under the current index functions
 * @see #writeIndices(java.util.Map)
 */
public Range<Integer> writeIndexSpan(Map<ActorGroup, Integer> externalSchedule) {
    Range<Integer> range = null;
    for (Actor a : upstream()) {
        //just the first and last iteration
        int maxIteration = a.group().schedule().get(a) * externalSchedule.get(a.group()) - 1;
        if (maxIteration >= 0)
            for (int iteration : new int[] { 0, maxIteration }) {
                ImmutableSortedSet<Integer> writes = a.writes(this, iteration);
                Range<Integer> writeRange = writes.isEmpty() ? range
                        : Range.closed(writes.first(), writes.last());
                range = range == null ? writeRange : range.span(writeRange);
            }
    }
    range = (range != null ? range : Range.closedOpen(0, 0));
    return range.canonical(DiscreteDomain.integers());
}

From source file:com.addthis.hydra.query.MeshQueryMaster.java

/** Returns the specified requested tasks as is if not empty, or expands to all known tasks if it is empty. */
private Set<Integer> expandRequestedTasks(Set<Integer> tasks, int canonicalTaskCount) {
    if (tasks.isEmpty()) {
        return ContiguousSet.create(Range.closedOpen(0, canonicalTaskCount), DiscreteDomain.integers());
    } else {//from w  w  w .j a va  2  s .  co m
        return tasks;
    }
}

From source file:org.dishevelled.variation.cytoscape3.internal.VariationModel.java

/**
 * Rebuild range trees./*from  ww w . ja  v a  2s.co  m*/
 */
void rebuildTrees() {
    rangeTrees.clear();
    ListMultimap<String, Feature> featuresByRegion = ArrayListMultimap.create();
    for (Feature feature : features) {
        featuresByRegion.put(feature.getRegion(), feature);
    }
    for (String region : featuresByRegion.keySet()) {
        List<Feature> regionFeatures = featuresByRegion.get(region);
        List<Range<Long>> ranges = Lists.newArrayListWithCapacity(regionFeatures.size());
        for (Feature feature : regionFeatures) {
            Range<Long> range = Range.closedOpen(feature.getStart(), feature.getEnd());
            ranges.add(range);
            featuresToRanges.put(feature, range);
        }
        rangeTrees.put(region, CenteredRangeTree.create(ranges));
    }
}

From source file:org.dishevelled.variation.cytoscape3.internal.VariationModel.java

/**
 * Return zero or more features that overlap with the specified variation.
 *
 * @param variation variation, must not be null
 * @return zero or more features that overlap with the specified variation
 */// w  w  w  .  jav a 2 s  . c  om
Iterable<Feature> hit(final Variation variation) {
    checkNotNull(variation);
    List<Feature> hits = Lists.newArrayList();
    RangeTree<Long> rangeTree = rangeTrees.get(variation.getRegion());

    Range<Long> query;
    if (variation.getStart() == variation.getEnd()) {
        query = Range.singleton(variation.getStart());
    }
    // todo: Ensembl REST client variation query returns end < start for deletions, e.g ref - alt [AAA]
    else if (variation.getEnd() < variation.getStart()) {
        query = Range.closedOpen(variation.getEnd(), variation.getStart());
    } else {
        query = Range.closedOpen(variation.getStart(), variation.getEnd());
    }

    for (Range<Long> range : rangeTree.intersect(query)) {
        hits.add(featuresToRanges.inverse().get(range));
    }
    return hits;
}

From source file:com.github.rinde.rinsim.central.arrays.ArraysSolverValidator.java

/**
 * Validates the {@link SolutionObject} that is produced by a
 * {@link SingleVehicleArraysSolver} . If the {@link SolutionObject} is
 * infeasible, an {@link IllegalArgumentException} is thrown.
 * @param sol The {@link SolutionObject} that is validated.
 * @param travelTime Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          ./* w ww.ja  v a2  s.  c o  m*/
 * @param releaseDates Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param dueDates Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param servicePairs Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param serviceTimes Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param currentSolution Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @return The solution as is supplied, used for method chaining.
 */
public static SolutionObject validateOutputs(SolutionObject sol, int[][] travelTime, int[] releaseDates,
        int[] dueDates, int[][] servicePairs, int[] serviceTimes, @Nullable SolutionObject currentSolution) {
    // convert single vehicle version to multi vehicle version for checking
    // of inputs
    final int n = travelTime.length;
    final int[][] vehicleTravelTimes = new int[1][n];
    // copy first row
    for (int i = 0; i < n; i++) {
        vehicleTravelTimes[0][i] = travelTime[0][i];
    }
    final Set<Integer> locationSet = newHashSet(
            ContiguousSet.create(Range.closedOpen(1, n - 1), DiscreteDomain.integers()));
    for (int i = 0; i < servicePairs.length; i++) {
        locationSet.remove(servicePairs[i][0]);
        locationSet.remove(servicePairs[i][1]);
    }

    final int[][] inventories = new int[locationSet.size()][2];
    final Iterator<Integer> locationSetIterator = locationSet.iterator();
    for (int i = 0; i < locationSet.size(); i++) {
        inventories[i][0] = 0;
        inventories[i][1] = locationSetIterator.next();
    }

    final int[] remainingServiceTimes = new int[] { 0 };
    final int[] currentDestinations = new int[] { 0 };

    @Nullable
    final SolutionObject[] currentSolutions = currentSolution == null ? null
            : new SolutionObject[] { currentSolution };

    // check inputs again since we just modified them
    validateInputs(travelTime, releaseDates, dueDates, servicePairs, serviceTimes, vehicleTravelTimes,
            inventories, remainingServiceTimes, currentDestinations, currentSolutions);

    final SolutionObject[] sols = new SolutionObject[] { sol };
    validateOutputs(sols, travelTime, releaseDates, dueDates, servicePairs, serviceTimes, vehicleTravelTimes,
            inventories, remainingServiceTimes, currentDestinations);
    return sol;
}

From source file:google.registry.model.registry.Registry.java

/**
 * Returns the EAP fee for the registry at the given time.
 *//*w  w w. j a  v  a2s . c  o  m*/
public Fee getEapFeeFor(DateTime now) {
    ImmutableSortedMap<DateTime, Money> valueMap = eapFeeSchedule.toValueMap();
    DateTime periodStart = valueMap.floorKey(now);
    DateTime periodEnd = valueMap.ceilingKey(now);
    // NOTE: assuming END_OF_TIME would never be reached...
    Range<DateTime> validPeriod = Range.closedOpen(periodStart != null ? periodStart : START_OF_TIME,
            periodEnd != null ? periodEnd : END_OF_TIME);
    return Fee.create(eapFeeSchedule.getValueAtTime(now).getAmount(), FeeType.EAP, validPeriod,
            validPeriod.upperEndpoint());
}