Example usage for java.util PriorityQueue add

List of usage examples for java.util PriorityQueue add

Introduction

In this page you can find the example usage for java.util PriorityQueue add.

Prototype

public boolean add(E e) 

Source Link

Document

Inserts the specified element into this priority queue.

Usage

From source file:main.java.RMDupper.java

public static void checkForDuplication(DupStats dupStats, OccurenceCounterMerged occurenceCounterMerged,
        SAMFileWriter outputSam, Boolean allReadsAsMerged,
        PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>> recordBuffer,
        PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>> duplicateBuffer, Set<String> discardSet) {
    // At this point recordBuffer contains all alignments that overlap with its first entry
    // Therefore the task here is to de-duplicate for the first entry in recordBuffer
    duplicateBuffer.clear();/*w w  w.j av a2  s. c  o m*/

    Iterator<ImmutableTriple<Integer, Integer, SAMRecord>> it = recordBuffer.iterator();
    while (it.hasNext()) {
        ImmutableTriple<Integer, Integer, SAMRecord> maybeDuplicate = it.next();

        if (allReadsAsMerged) {
            if (recordBuffer.peek().left.equals(maybeDuplicate.left)
                    && recordBuffer.peek().middle.equals(maybeDuplicate.middle)) {
                duplicateBuffer.add(maybeDuplicate);
            }
        } else {
            // We build a logic table
            EnumSet<DL> testConditon = EnumSet.noneOf(DL.class);
            if (recordBuffer.peek().right.getReadName().startsWith("M_")) {
                testConditon.add(DL.buffer_read_merged);
            } else if (recordBuffer.peek().right.getReadName().startsWith("F_")) {
                testConditon.add(DL.buffer_read_one);
            } else if (recordBuffer.peek().right.getReadName().startsWith("R_")) {
                testConditon.add(DL.buffer_read_two);
            } else {
                throw new RuntimeException("Unlabelled read '" + recordBuffer.peek().right.getReadName()
                        + "' read name must start with one of M_,F_,R when not treating all reads as merged");
            }

            if (maybeDuplicate.right.getReadName().startsWith("M_")) {
                testConditon.add(DL.maybed_read_merged);
            } else if (maybeDuplicate.right.getReadName().startsWith("F_")) {
                testConditon.add(DL.maybed_read_one);
            } else if (maybeDuplicate.right.getReadName().startsWith("R_")) {
                testConditon.add(DL.maybed_read_two);
            } else {
                System.err.println("Unlabelled read '" + maybeDuplicate.right.getReadName()
                        + "' read name must start with one of M_,F_,R when not treating all reads as merged");
            }

            if (recordBuffer.peek().left.equals(maybeDuplicate.left)) {
                testConditon.add(DL.equal_alignment_start);
            }
            if (recordBuffer.peek().middle.equals(maybeDuplicate.middle)) {
                testConditon.add(DL.equal_alignment_end);
            }

            boolean duplicateIsShorterOrEqual = maybeDuplicate.middle
                    - maybeDuplicate.left <= recordBuffer.peek().middle - recordBuffer.peek().left;
            boolean duplicateIsLongerOrEqual = recordBuffer.peek().middle
                    - recordBuffer.peek().left <= maybeDuplicate.middle - maybeDuplicate.left;

            if (duplicateIsShorterOrEqual) {
                testConditon.add(DL.maybed_shorter_or_equal);
            }
            if (duplicateIsLongerOrEqual) {
                testConditon.add(DL.maybed_longer_or_equal);
            }

            if (recordBuffer.peek().right.getReadNegativeStrandFlag()) {
                testConditon.add(DL.buffer_reverse_strand);
            } else {
                testConditon.add(DL.buffer_forward_strand);
            }
            if (maybeDuplicate.right.getReadNegativeStrandFlag()) {
                testConditon.add(DL.maybed_reverse_strand);
            } else {
                testConditon.add(DL.maybed_forward_strand);
            }

            //System.out.println("Testing for duplication: "+testConditon);
            //System.out.println(recordBuffer.peek().right.getReadName()+"\t"+recordBuffer.peek().right.getAlignmentStart()+"\t"+recordBuffer.peek().right.getAlignmentEnd());
            //System.out.println(maybeDuplicate.right.getReadName()+"\t"+maybeDuplicate.right.getAlignmentStart()+"\t"+maybeDuplicate.right.getAlignmentEnd());

            //for ( EnumSet<DL> match : duplicateConditionSet.stream().filter(dc -> testConditon.containsAll(dc) ).collect(Collectors.toList()) ) {
            //  System.out.println("Match to: "+match);
            //}
            //for ( EnumSet<DL> match : duplicateConditionSet.stream().collect(Collectors.toList()) ) {
            //  System.out.println("Try to match: "+match);
            //  if ( match.containsAll(testConditon) )
            //  {
            //    System.out.println("success");
            //  }
            //}

            // Test for Duplication
            if (duplicateConditionSet.stream().anyMatch(dc -> testConditon.containsAll(dc))) {
                duplicateBuffer.add(maybeDuplicate);
            }
        }
    }
    //START DEBUG
    /*
    System.out.println ("recordBuffer");
            
    Comparator<SAMRecord> samRecordComparatorForRecordBuffer = new SAMRecordPositionAndQualityComparator();
    ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>> sortedRecordBuffer = new ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>>(recordBuffer.size());
    Iterator<ImmutableTriple<Integer, Integer, SAMRecord>> rit = recordBuffer.iterator();
            
    while (rit.hasNext()) {
    sortedRecordBuffer.add(rit.next());
    }
    sortedRecordBuffer.sort(Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getRight, samRecordComparatorForRecordBuffer));
            
    for ( ImmutableTriple<Integer, Integer, SAMRecord> currTriple : sortedRecordBuffer ) {
    System.out.println(" srb: "+(currTriple.right.getReadNegativeStrandFlag()?"-":"+")+" "+currTriple+" "+SAMRecordQualityComparator.getQualityScore(currTriple.right.getBaseQualityString()));
    }
            
    System.out.println ("duplicateBuffer");
    ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>> sortedDuplicateBuffer = new ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>>(duplicateBuffer.size());
    Iterator<ImmutableTriple<Integer, Integer, SAMRecord>> dit = duplicateBuffer.iterator();
    while (dit.hasNext()) {
    sortedDuplicateBuffer.add(dit.next());
    }
    sortedDuplicateBuffer.sort(Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getMiddle));
            
    for ( ImmutableTriple<Integer, Integer, SAMRecord> currTriple : sortedDuplicateBuffer ) {
    System.out.println(" dbe: "+(currTriple.right.getReadNegativeStrandFlag()?"-":"+")+" "+currTriple+" "+SAMRecordQualityComparator.getQualityScore(currTriple.right.getBaseQualityString()));
    }
            
    // Sort again with priority queue order
    sortedDuplicateBuffer.sort(Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getRight, samRecordComparator.reversed()));
    for ( ImmutableTriple<Integer, Integer, SAMRecord> currTriple : sortedDuplicateBuffer ) {
    System.out.println("sdbe: "+(currTriple.right.getReadNegativeStrandFlag()?"-":"+")+" "+currTriple+" "+SAMRecordQualityComparator.getQualityScore(currTriple.right.getBaseQualityString()));
    }
    */
    //END DEBUG
    if (!duplicateBuffer.isEmpty() && !discardSet.contains(duplicateBuffer.peek().right.getReadName())) {
        //System.out.println("WRITE "+duplicateBuffer.peek());
        decrementDuplicateStats(dupStats, allReadsAsMerged, duplicateBuffer.peek().right.getReadName());
        occurenceCounterMerged.putValue(Long
                .valueOf(duplicateBuffer.stream()
                        .filter(d -> allReadsAsMerged || d.right.getReadName().startsWith("M_")).count())
                .intValue() - 1);
        outputSam.addAlignment(duplicateBuffer.peek().right);
    }
    while (!duplicateBuffer.isEmpty()) {
        discardSet.add(duplicateBuffer.poll().right.getReadName());
    }
    // Maintain the invariant that the first item in recordBuffer may have duplicates
    while (!recordBuffer.isEmpty() && discardSet.contains(recordBuffer.peek().right.getReadName())) {
        String duplicateReadName = recordBuffer.poll().right.getReadName();
        incrementDuplicateStats(dupStats, allReadsAsMerged, duplicateReadName);
        discardSet.remove(duplicateReadName);
    }
}

From source file:com.datatorrent.lib.multiwindow.SortedMovingWindow.java

@Override
protected void processDataTuple(T tuple) {
    tuplesInCurrentStreamWindow.add(tuple);
    K key = function.apply(tuple);/*from  w ww  . ja v  a  2s .c o  m*/
    PriorityQueue<T> sortedList = sortedListInSlidingWin.get(key);
    if (sortedList == null) {
        sortedList = new PriorityQueue<T>(10, comparator);
        sortedListInSlidingWin.put(key, sortedList);
    }
    sortedList.add(tuple);
}

From source file:org.eclipse.recommenders.jayes.transformation.LatentDeterministicDecomposition.java

private List<double[]> getBest(final Map<double[], Integer> counts, int basisSize, int minTotalCounts) {
    PriorityQueue<double[]> q = new PriorityQueue<double[]>(basisSize,
            Ordering.natural().onResultOf(Functions.forMap(counts)));

    for (Entry<double[], Integer> e : counts.entrySet()) {
        if (q.isEmpty() || q.size() < basisSize) {
            q.add(e.getKey());
        } else {//from  ww  w.ja v  a 2  s.  c o m
            double[] head = q.peek();
            if (counts.get(head) < counts.get(e.getKey())) {
                q.remove();
                q.add(e.getKey());
            }
        }
    }

    int totalcounts = 0;
    for (double[] v : q) {
        totalcounts += counts.get(v);
    }
    if (totalcounts < minTotalCounts)
        return null;

    return new ArrayList<double[]>(q);
}

From source file:org.apache.mahout.classifier.bayes.algorithm.BayesAlgorithm.java

@Override
public ClassifierResult[] classifyDocument(String[] document, Datastore datastore, String defaultCategory,
        int numResults) throws InvalidDatastoreException {
    Collection<String> categories = datastore.getKeys("labelWeight");
    PriorityQueue<ClassifierResult> pq = new PriorityQueue<ClassifierResult>(numResults,
            new ByScoreLabelResultComparator());
    for (String category : categories) {
        double prob = documentWeight(datastore, category, document);
        if (prob > 0.0) {
            pq.add(new ClassifierResult(category, prob));
            if (pq.size() > numResults) {
                pq.remove();//from   w ww  . jav  a2s. c  o  m
            }
        }
    }

    if (pq.isEmpty()) {
        return new ClassifierResult[] { new ClassifierResult(defaultCategory, 0.0) };
    } else {
        List<ClassifierResult> result = new ArrayList<ClassifierResult>(pq.size());
        while (pq.isEmpty() == false) {
            result.add(pq.remove());
        }
        Collections.reverse(result);
        return result.toArray(new ClassifierResult[pq.size()]);
    }
}

From source file:org.petalslink.dsb.federation.core.server.ServiceManagerImpl.java

/**
 * {@inheritDoc}/*from   w  w  w  . ja v a2  s  . c  o m*/
 */
public void start() {

    // first start the internal services...
    if (logger.isDebugEnabled()) {
        logger.debug("Starting internal services");
    }
    PriorityQueue<Service> queue = new PriorityQueue<Service>(this.services.size(), new Comparator());
    for (String name : this.services.keySet()) {
        if ((this.services.get(name) != null) && (this.services.get(name).getType() == Service.TYPE.INTERNAL)) {
            queue.add(this.services.get(name));
        }
    }
    Service s = null;
    while ((s = queue.poll()) != null) {
        this.start(s.getName());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Starting *bound services");
    }
    queue = new PriorityQueue<Service>(this.services.size(), new Comparator());
    for (String name : this.services.keySet()) {
        if ((this.services.get(name) != null) && (this.services.get(name).getType() != Service.TYPE.INTERNAL)) {
            queue.add(this.services.get(name));
        }
    }
    while ((s = queue.poll()) != null) {
        this.start(s.getName());
    }
}

From source file:com.android.switchaccess.HuffmanTreeBuilder.java

/**
 * Builds a Huffman tree with all the clickable nodes in the tree anchored at
 * {@code windowRoot}. The context provides information about actions the user has taken so far
 * and allows the probabilities for the views in a window to be adjusted based on that.
 *
 * @param windowRoot The root of the tree of SwitchAccessNodeCompat
 * @param treeToBuildOn A tree of OptionScanNodes that should be included as part of the
 *        Huffman tree.//from ww  w  . ja  v  a  2 s. co m
 * @param context The actions the user has taken so far. In case of an IME, this would be what
 *        the user has typed so far.
 * @return A Huffman tree of OptionScanNodes including the tree {@code treeToBuildOn} and all
 *        clickable nodes from the {@code windowRoot} tree. If there are no clickable nodes in
 *        {@code windowRoot and the treeToBuildOn is {@code null}, a {@code ClearFocusNode} is
 *        returned.
 */
/* TODO(rmorina) It will probably not be possible to capture context using a string only.
 * Once we understand how to capture context better we need to change this. */
public OptionScanNode buildTreeFromNodeTree(SwitchAccessNodeCompat windowRoot, OptionScanNode treeToBuildOn,
        String context) {
    PriorityQueue<HuffmanNode> optionScanNodeProbabilities = getOptionScanNodeProbabilities(context,
            windowRoot);
    ClearFocusNode clearFocusNode = new ClearFocusNode();
    if (treeToBuildOn != null) {
        optionScanNodeProbabilities.add(new HuffmanNode(treeToBuildOn, DEFAULT_PROBABILITY));
    } else if (optionScanNodeProbabilities.isEmpty()) {
        return clearFocusNode;
    }
    optionScanNodeProbabilities.add(createParentNode(optionScanNodeProbabilities,
            getNodesPerParent(optionScanNodeProbabilities.size()), clearFocusNode));
    while (optionScanNodeProbabilities.size() > 1) {
        optionScanNodeProbabilities.add(createParentNode(optionScanNodeProbabilities, mDegree, clearFocusNode));
    }
    return optionScanNodeProbabilities.peek().getOptionScanNode();
}

From source file:com.jxt.web.service.AgentEventServiceImpl.java

private List<AgentEvent> createAgentEvents(List<AgentEventBo> agentEventBos, boolean includeEventMessage) {
    if (CollectionUtils.isEmpty(agentEventBos)) {
        return Collections.emptyList();
    }/*from w w  w  .j  a  v a  2 s .c  o m*/
    List<AgentEvent> agentEvents = new ArrayList<>(agentEventBos.size());
    PriorityQueue<DurationalAgentEvent> durationalAgentEvents = new PriorityQueue<>(agentEventBos.size(),
            AgentEvent.EVENT_TIMESTAMP_ASC_COMPARATOR);
    for (AgentEventBo agentEventBo : agentEventBos) {
        if (agentEventBo.getEventType().isCategorizedAs(AgentEventTypeCategory.DURATIONAL)) {
            durationalAgentEvents.add(createDurationalAgentEvent(agentEventBo, includeEventMessage));
        } else {
            agentEvents.add(createAgentEvent(agentEventBo, includeEventMessage));
        }
    }
    long durationStartTimestamp = DurationalAgentEvent.UNKNOWN_TIMESTAMP;
    while (!durationalAgentEvents.isEmpty()) {
        DurationalAgentEvent currentEvent = durationalAgentEvents.remove();
        if (durationStartTimestamp == DurationalAgentEvent.UNKNOWN_TIMESTAMP) {
            durationStartTimestamp = currentEvent.getEventTimestamp();
        }
        currentEvent.setDurationStartTimestamp(durationStartTimestamp);
        DurationalAgentEvent nextEvent = durationalAgentEvents.peek();
        if (nextEvent != null) {
            long nextEventTimestamp = nextEvent.getEventTimestamp();
            currentEvent.setDurationEndTimestamp(nextEventTimestamp);
            durationStartTimestamp = nextEventTimestamp;
        }
        agentEvents.add(currentEvent);
    }
    return agentEvents;
}

From source file:com.navercorp.pinpoint.web.service.AgentEventServiceImpl.java

private List<AgentEvent> createAgentEvents(List<AgentEventBo> agentEventBos) {
    if (CollectionUtils.isEmpty(agentEventBos)) {
        return Collections.emptyList();
    }/*from   ww w.  jav a 2  s .  com*/
    List<AgentEvent> agentEvents = new ArrayList<>(agentEventBos.size());
    PriorityQueue<DurationalAgentEvent> durationalAgentEvents = new PriorityQueue<>(agentEventBos.size(),
            AgentEvent.EVENT_TIMESTAMP_ASC_COMPARATOR);
    for (AgentEventBo agentEventBo : agentEventBos) {
        if (agentEventBo.getEventType().isCategorizedAs(AgentEventTypeCategory.DURATIONAL)) {
            durationalAgentEvents.add(createDurationalAgentEvent(agentEventBo, false));
        } else {
            boolean hasMessage = !ArrayUtils.isEmpty(agentEventBo.getEventBody());
            agentEvents.add(createAgentEvent(agentEventBo, hasMessage));
        }
    }
    long durationStartTimestamp = DurationalAgentEvent.UNKNOWN_TIMESTAMP;
    while (!durationalAgentEvents.isEmpty()) {
        DurationalAgentEvent currentEvent = durationalAgentEvents.remove();
        if (durationStartTimestamp == DurationalAgentEvent.UNKNOWN_TIMESTAMP) {
            durationStartTimestamp = currentEvent.getEventTimestamp();
        }
        currentEvent.setDurationStartTimestamp(durationStartTimestamp);
        DurationalAgentEvent nextEvent = durationalAgentEvents.peek();
        if (nextEvent != null) {
            long nextEventTimestamp = nextEvent.getEventTimestamp();
            currentEvent.setDurationEndTimestamp(nextEventTimestamp);
            durationStartTimestamp = nextEventTimestamp;
        }
        agentEvents.add(currentEvent);
    }
    return agentEvents;
}

From source file:MSUmpire.PSMDataStructure.ProtID.java

public float GetAbundanceByTopPepFrag(int toppep, int topfrag, float pepweight) {
    if (PeptideID.isEmpty()) {
        return 0;
    }//from ww w.j  av a 2  s  .c o m
    PriorityQueue<Float> TopQueue = new PriorityQueue<>(PeptideID.size(), Collections.reverseOrder());
    for (PepIonID peptide : PeptideID.values()) {
        if (peptide.FilteringWeight > pepweight) {
            TopQueue.add(peptide.GetPepAbundanceByTopFragments(topfrag));
        }
    }
    float totalabundance = 0f;
    int num = Math.min(toppep, TopQueue.size());

    for (int i = 0; i < num; i++) {
        totalabundance += TopQueue.poll();
    }
    return totalabundance / num;
}

From source file:mulavito.algorithms.shortestpath.ksp.Eppstein.java

@Override
protected List<List<E>> getShortestPathsIntern(V source, V target, int k) {
    PriorityQueue<WeightedPath> prioQ = new PriorityQueue<WeightedPath>();
    List<List<E>> found_paths = new LinkedList<List<E>>();

    Transformer<E, Double> delta = prepareTransformations(target);

    // Initialize with start vertex.
    prioQ.add(new WeightedPath(source));

    while (!prioQ.isEmpty() && found_paths.size() < k) {
        WeightedPath curPath = prioQ.poll(); // get & remove next shortest
        V curV = curPath.getLast();/* w ww  . jav a2  s. c  om*/

        if (curV.equals(target)) {
            found_paths.add(curPath.getPath());
            continue;
        }

        // Create new paths for every expanded vertex ...
        for (V nextV : graph.getSuccessors(curV)) {
            if (curPath.contains(nextV))
                continue; // Prevent looping!

            // ... and every possible edge.
            for (E e : graph.findEdgeSet(curV, nextV)) {
                if (Double.isInfinite(delta.transform(e)))
                    continue; // Skip unreachable vertices.

                WeightedPath tmpPath = new WeightedPath(curPath); // clone
                tmpPath.addHop(e, delta.transform(e), nextV);

                prioQ.add(tmpPath);
            }
        }
    }

    return found_paths;
}