List of usage examples for java.util PriorityQueue size
int size
To view the source code for java.util PriorityQueue size.
Click Source Link
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());//from w w w.j a v a2 s. c o m } else { 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:com.android.switchaccess.HuffmanTreeBuilder.java
/** * Given a priority queue of HuffmanNodes and the number of nodes per parent, a new * parent HuffmanNode is constructed. The probability of the parent HuffmanNode is the sum of * the probabilities of all its children. If none of the children branches have a * {@code ClearFocusNode}, one is included when the parent node is created. * * @param nodes The total nodes that will be included in the Huffman tree. * @param nodesPerParent The number of children the parent node will have. * @param clearFocusNode The clear focus node to be included if none of the children branches * have a {@code ClearFocusNode} included. * @return The parent HuffmanNode created. *//* ww w . ja v a 2 s . c o m*/ private HuffmanNode createParentNode(PriorityQueue<HuffmanNode> nodes, int nodesPerParent, ClearFocusNode clearFocusNode) throws IllegalArgumentException { if (nodesPerParent < 2 || nodes.size() < nodesPerParent) { throw new IllegalArgumentException(); } Double childrenProbability = 0.0; List<OptionScanNode> children = new ArrayList<>(nodesPerParent); Boolean clearFocusNodePresence = false; for (int i = 0; i < nodesPerParent; i++) { HuffmanNode huffmanNode = nodes.poll(); childrenProbability += huffmanNode.getProbability(); children.add(huffmanNode.getOptionScanNode()); if ((i == nodesPerParent - 1) && huffmanNode.hasClearFocusNode()) { clearFocusNodePresence = true; } } if (!clearFocusNodePresence) { addClearFocusNodeToBranch(children, clearFocusNode); } List<OptionScanNode> otherChildren = children.subList(2, children.size()); OptionScanNode parent = new OptionScanSelectionNode(children.get(0), children.get(1), otherChildren.toArray(new OptionScanNode[otherChildren.size()])); HuffmanNode parentHuffmanNode = new HuffmanNode(parent, childrenProbability); parentHuffmanNode.setClearFocusNodePresence(); return parentHuffmanNode; }
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();// ww w .ja v a 2s. c om } } } 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:android.support.v7.graphics.ColorCutQuantizer.java
/** * Iterate through the {@link java.util.Queue}, popping * {@link ColorCutQuantizer.Vbox} objects from the queue * and splitting them. Once split, the new box and the remaining box are offered back to the * queue.//from www. j a va 2s. c o m * * @param queue {@link java.util.PriorityQueue} to poll for boxes * @param maxSize Maximum amount of boxes to split */ private void splitBoxes(final PriorityQueue<Vbox> queue, final int maxSize) { while (queue.size() < maxSize) { final Vbox vbox = queue.poll(); if (vbox != null && vbox.canSplit()) { // First split the box, and offer the result queue.offer(vbox.splitBox()); if (LOG_TIMINGS) { mTimingLogger.addSplit("Box split"); } // Then offer the box back queue.offer(vbox); } else { if (LOG_TIMINGS) { mTimingLogger.addSplit("All boxes split"); } // If we get here then there are no more boxes to split, so return return; } } }
From source file:MSUmpire.PSMDataStructure.ProtID.java
public float GetAbundanceByTopPepFrag(int toppep, int topfrag, float pepweight) { if (PeptideID.isEmpty()) { return 0; }/*from w w w . ja v 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:MSUmpire.PSMDataStructure.ProtID.java
public float GetAbundanceByMS1_TopN(int topN, float pepweight) { if (PeptideID.isEmpty()) { return 0; }//ww w . ja v a 2 s . com PriorityQueue<Float> TopQueue = new PriorityQueue<>(PeptideID.size(), Collections.reverseOrder()); for (PepIonID peptide : PeptideID.values()) { if (peptide.PeakHeight != null && peptide.FilteringWeight > pepweight) { TopQueue.add(peptide.PeakHeight[0]); } } float totalabundance = 0f; int num = Math.min(topN, TopQueue.size()); for (int i = 0; i < num; i++) { totalabundance += TopQueue.poll(); } return totalabundance / num; }
From source file:com.net2plan.gui.utils.onlineSimulationPane.OnlineSimulationPane.java
/** * Shows the future event list./*w w w . j a v a 2 s . c om*/ * * @since 0.3.0 */ public void viewFutureEventList() { final JDialog dialog = new JDialog(); dialog.setTitle("Future event list"); SwingUtils.configureCloseDialogOnEscape(dialog); dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); dialog.setSize(new Dimension(500, 300)); dialog.setLocationRelativeTo(null); dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); dialog.setLayout(new MigLayout("fill, insets 0 0 0 0")); final String[] tableHeader = StringUtils.arrayOf("Id", "Time", "Priority", "Type", "To module", "Custom object"); Object[][] data = new Object[1][tableHeader.length]; DefaultTableModel model = new ClassAwareTableModel(); model.setDataVector(new Object[1][tableHeader.length], tableHeader); JTable table = new AdvancedJTable(model); RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model); table.setRowSorter(sorter); JScrollPane scrollPane = new JScrollPane(table); dialog.add(scrollPane, "grow"); PriorityQueue<SimEvent> futureEventList = simKernel.getSimCore().getFutureEventList().getPendingEvents(); if (!futureEventList.isEmpty()) { int numEvents = futureEventList.size(); SimEvent[] futureEventList_array = futureEventList.toArray(new SimEvent[numEvents]); Arrays.sort(futureEventList_array, futureEventList.comparator()); data = new Object[numEvents][tableHeader.length]; for (int eventId = 0; eventId < numEvents; eventId++) { // List<SimAction> actions = futureEventList_array[eventId].getEventActionList(); Object customObject = futureEventList_array[eventId].getEventObject(); data[eventId][0] = eventId; data[eventId][1] = StringUtils .secondsToYearsDaysHoursMinutesSeconds(futureEventList_array[eventId].getEventTime()); data[eventId][2] = futureEventList_array[eventId].getEventPriority(); data[eventId][3] = futureEventList_array[eventId].getEventType(); data[eventId][4] = futureEventList_array[eventId].getEventDestinationModule().toString(); data[eventId][5] = customObject == null ? "none" : customObject; } } model.setDataVector(data, tableHeader); table.getTableHeader().addMouseListener(new ColumnFitAdapter()); table.setDefaultRenderer(Double.class, new CellRenderers.NumberCellRenderer()); dialog.setVisible(true); }
From source file:io.anserini.rerank.lib.AxiomReranker.java
/** * Calculate the scores (weights) of each term that occured in the reranking pool. * The Process:/* w ww .ja v a2 s .c o m*/ * 1. For each query term, calculate its score for each term in the reranking pool. the score * is calcuated as * <pre> * P(both occurs)*log{P(both occurs)/P(t1 occurs)/P(t2 occurs)} * + P(both not occurs)*log{P(both not occurs)/P(t1 not occurs)/P(t2 not occurs)} * + P(t1 occurs t2 not occurs)*log{P(t1 occurs t2 not occurs)/P(t1 occurs)/P(t2 not occurs)} * + P(t1 not occurs t2 occurs)*log{P(t1 not occurs t2 occurs)/P(t1 not occurs)/P(t2 occurs)} * </pre> * 2. For each query term the scores of every other term in the reranking pool are stored in a * PriorityQueue, only the top {@code K} are kept. * 3. Add the scores of the same term together and pick the top {@code M} ones. * * @param termInvertedList A Map of <term -> Set<docId>> where the Set of docIds is where the term occurs * @param context An instance of RerankerContext * @return Map<String, Double> Top terms and their weight scores in a HashMap */ private Map<String, Double> computeTermScore(Map<String, Set<Integer>> termInvertedList, RerankerContext<T> context) throws IOException { class ScoreComparator implements Comparator<Pair<String, Double>> { public int compare(Pair<String, Double> a, Pair<String, Double> b) { int cmp = Double.compare(b.getRight(), a.getRight()); if (cmp == 0) { return a.getLeft().compareToIgnoreCase(b.getLeft()); } else { return cmp; } } } // get collection statistics so that we can get idf later on. IndexReader reader; if (this.externalIndexPath != null) { Path indexPath = Paths.get(this.externalIndexPath); if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) { throw new IllegalArgumentException( this.externalIndexPath + " does not exist or is not a directory."); } reader = DirectoryReader.open(FSDirectory.open(indexPath)); } else { IndexSearcher searcher = context.getIndexSearcher(); reader = searcher.getIndexReader(); } final long docCount = reader.numDocs() == -1 ? reader.maxDoc() : reader.numDocs(); //calculate the Mutual Information between term with each query term List<String> queryTerms = context.getQueryTokens(); Map<String, Integer> queryTermsCounts = new HashMap<>(); for (String qt : queryTerms) { queryTermsCounts.put(qt, queryTermsCounts.getOrDefault(qt, 0) + 1); } Set<Integer> allDocIds = new HashSet<>(); for (Set<Integer> s : termInvertedList.values()) { allDocIds.addAll(s); } int docIdsCount = allDocIds.size(); // Each priority queue corresponds to a query term: The p-queue itself stores all terms // in the reranking pool and their reranking scores to the query term. List<PriorityQueue<Pair<String, Double>>> allTermScoresPQ = new ArrayList<>(); for (Map.Entry<String, Integer> q : queryTermsCounts.entrySet()) { String queryTerm = q.getKey(); long df = reader.docFreq(new Term(LuceneDocumentGenerator.FIELD_BODY, queryTerm)); if (df == 0L) { continue; } float idf = (float) Math.log((1 + docCount) / df); int qtf = q.getValue(); if (termInvertedList.containsKey(queryTerm)) { PriorityQueue<Pair<String, Double>> termScorePQ = new PriorityQueue<>(new ScoreComparator()); double selfMI = computeMutualInformation(termInvertedList.get(queryTerm), termInvertedList.get(queryTerm), docIdsCount); for (Map.Entry<String, Set<Integer>> termEntry : termInvertedList.entrySet()) { double score; if (termEntry.getKey().equals(queryTerm)) { // The mutual information to itself will always be 1 score = idf * qtf; } else { double crossMI = computeMutualInformation(termInvertedList.get(queryTerm), termEntry.getValue(), docIdsCount); score = idf * beta * qtf * crossMI / selfMI; } termScorePQ.add(Pair.of(termEntry.getKey(), score)); } allTermScoresPQ.add(termScorePQ); } } Map<String, Double> aggTermScores = new HashMap<>(); for (PriorityQueue<Pair<String, Double>> termScores : allTermScoresPQ) { for (int i = 0; i < Math.min(termScores.size(), this.K); i++) { Pair<String, Double> termScore = termScores.poll(); String term = termScore.getLeft(); Double score = termScore.getRight(); if (score - 0.0 > 1e-8) { aggTermScores.put(term, aggTermScores.getOrDefault(term, 0.0) + score); } } } PriorityQueue<Pair<String, Double>> termScoresPQ = new PriorityQueue<>(new ScoreComparator()); for (Map.Entry<String, Double> termScore : aggTermScores.entrySet()) { termScoresPQ.add(Pair.of(termScore.getKey(), termScore.getValue() / queryTerms.size())); } Map<String, Double> resultTermScores = new HashMap<>(); for (int i = 0; i < Math.min(termScoresPQ.size(), this.M); i++) { Pair<String, Double> termScore = termScoresPQ.poll(); String term = termScore.getKey(); double score = termScore.getValue(); resultTermScores.put(term, score); } return resultTermScores; }
From source file:com.joliciel.jochre.analyser.BeamSearchImageAnalyser.java
public void analyseInternal(JochreImage image) { LOG.debug("Analysing image " + image.getId()); if (currentMonitor != null) { currentMonitor.setCurrentAction("imageMonitor.analysingImage", new Object[] { image.getPage().getIndex() }); }/* www. j av a2 s.c om*/ for (LetterGuessObserver observer : observers) { observer.onImageStart(image); } if (totalShapeCount < 0) totalShapeCount = image.getShapeCount(); for (Paragraph paragraph : image.getParagraphs()) { LOG.debug("Analysing paragraph " + paragraph.getIndex() + " (id=" + paragraph.getId() + ")"); List<LetterSequence> holdoverSequences = null; for (RowOfShapes row : paragraph.getRows()) { LOG.debug("Analysing row " + row.getIndex() + " (id=" + row.getId() + ")"); for (GroupOfShapes group : row.getGroups()) { if (group.isSkip()) { LOG.debug("Skipping group " + group.getIndex() + " (id=" + group.getId() + ")"); continue; } LOG.debug("Analysing group " + group.getIndex() + " (id=" + group.getId() + ")"); int width = group.getRight() - group.getLeft() + 1; List<ShapeSequence> shapeSequences = null; if (boundaryDetector != null) { shapeSequences = boundaryDetector.findBoundaries(group); } else { // simply add this groups shape's shapeSequences = new ArrayList<ShapeSequence>(); ShapeSequence shapeSequence = boundaryService.getEmptyShapeSequence(); for (Shape shape : group.getShapes()) shapeSequence.addShape(shape); shapeSequences.add(shapeSequence); } // Perform a beam search to guess the most likely sequence for this word TreeMap<Integer, PriorityQueue<LetterSequence>> heaps = new TreeMap<Integer, PriorityQueue<LetterSequence>>(); // prime a starter heap with the n best shape boundary analyses for this group PriorityQueue<LetterSequence> starterHeap = new PriorityQueue<LetterSequence>(1); for (ShapeSequence shapeSequence : shapeSequences) { LetterSequence emptySequence = this.getLetterGuesserService() .getEmptyLetterSequence(shapeSequence); starterHeap.add(emptySequence); } heaps.put(0, starterHeap); PriorityQueue<LetterSequence> finalHeap = null; while (heaps.size() > 0) { Entry<Integer, PriorityQueue<LetterSequence>> heapEntry = heaps.pollFirstEntry(); if (LOG.isTraceEnabled()) LOG.trace("heap for index: " + heapEntry.getKey().intValue() + ", width: " + width); if (heapEntry.getKey().intValue() == width) { finalHeap = heapEntry.getValue(); break; } PriorityQueue<LetterSequence> previousHeap = heapEntry.getValue(); // limit the breadth to K int maxSequences = previousHeap.size() > this.beamWidth ? this.beamWidth : previousHeap.size(); for (int j = 0; j < maxSequences; j++) { LetterSequence history = previousHeap.poll(); ShapeInSequence shapeInSequence = history.getNextShape(); Shape shape = shapeInSequence.getShape(); if (LOG.isTraceEnabled()) { LOG.trace("Sequence " + history + ", shape: " + shape); } LogUtils.logMemory(LOG); int position = 0; if (Linguistics.getInstance(image.getPage().getDocument().getLocale()) .isLeftToRight()) { position = shape.getRight() - group.getLeft() + 1; } else { position = group.getRight() - shape.getLeft() + 1; } PriorityQueue<LetterSequence> heap = heaps.get(position); if (heap == null) { heap = new PriorityQueue<LetterSequence>(); heaps.put(position, heap); } MONITOR.startTask("guess letter"); try { letterGuesser.guessLetter(shapeInSequence, history); } finally { MONITOR.endTask(); } MONITOR.startTask("heap sort"); try { for (Decision<Letter> letterGuess : shape.getLetterGuesses()) { // leave out very low probability outcomes if (letterGuess.getProbability() > this.minOutcomeWeight) { LetterSequence sequence = this.getLetterGuesserService() .getLetterSequencePlusOne(history); sequence.add(letterGuess.getOutcome()); sequence.addDecision(letterGuess); heap.add(sequence); } // weight big enough to include } // next letter guess for this shape } finally { MONITOR.endTask(); } } // next history in heap } // any more heaps? LetterSequence bestSequence = null; boolean shouldCombineWithHoldover = false; boolean isHoldover = false; MONITOR.startTask("best sequence"); try { List<LetterSequence> finalSequences = new ArrayList<LetterSequence>(); for (int i = 0; i < this.beamWidth; i++) { if (finalHeap.isEmpty()) break; finalSequences.add(finalHeap.poll()); } if (this.getMostLikelyWordChooser() == null) { // most likely sequence is on top of the last heap bestSequence = finalSequences.get(0); } else { // get most likely sequence using lexicon if (holdoverSequences != null) { // we have a holdover from the previous row ending with a dash bestSequence = this.getMostLikelyWordChooser().chooseMostLikelyWord(finalSequences, holdoverSequences, this.beamWidth); shouldCombineWithHoldover = true; } else { // check if this is the last group on the row and could end with a dash boolean shouldBeHeldOver = false; if (group.getIndex() == row.getGroups().size() - 1 && row.getIndex() < paragraph.getRows().size() - 1) { for (LetterSequence letterSequence : finalSequences) { if (letterSequence.toString().endsWith("-")) { shouldBeHeldOver = true; break; } } } if (shouldBeHeldOver) { holdoverSequences = finalSequences; isHoldover = true; } else { // simplest case: no holdover bestSequence = this.getMostLikelyWordChooser() .chooseMostLikelyWord(finalSequences, this.beamWidth); } } // have we holdover sequences? } // have we a most likely word chooser? if (!isHoldover) { for (LetterGuessObserver observer : observers) { observer.onBeamSearchEnd(bestSequence, finalSequences, holdoverSequences); } } } finally { MONITOR.endTask(); } MONITOR.startTask("assign letter"); try { if (shouldCombineWithHoldover) { holdoverSequences = null; } if (!isHoldover) { for (LetterGuessObserver observer : observers) { observer.onStartSequence(bestSequence); } group.setBestLetterSequence(bestSequence); int i = 0; for (ShapeInSequence shapeInSequence : bestSequence.getUnderlyingShapeSequence()) { String bestOutcome = bestSequence.get(i).getString(); this.assignLetter(shapeInSequence, bestOutcome); i++; } // next shape for (LetterGuessObserver observer : observers) { observer.onGuessSequence(bestSequence); } } this.shapeCount += group.getShapes().size(); if (this.currentMonitor != null) { double progress = (double) shapeCount / (double) totalShapeCount; LOG.debug("progress: " + progress); currentMonitor.setPercentComplete(progress); } } finally { MONITOR.endTask(); } } // next group } // next row } // next paragraph for (LetterGuessObserver observer : observers) { observer.onImageEnd(); } }
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 w w w . j a v a 2 s. c o 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(); }