Example usage for java.util PriorityQueue PriorityQueue

List of usage examples for java.util PriorityQueue PriorityQueue

Introduction

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

Prototype

public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) 

Source Link

Document

Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.

Usage

From source file:org.hbasene.index.search.HBaseTopFieldCollector.java

public HBaseTopFieldCollector(final HTablePool tablePool, final String indexName, final int nDocs,
        final Sort sort) {
    this.tablePool = tablePool;
    this.indexName = indexName;
    this.nDocs = nDocs;
    this.fields = sort.getSort();
    this.pendingDocs = 0;
    this.totalHits = 0;
    this.pq = new PriorityQueue<SortFieldDoc>(nDocs,
            this.fields[0].getReverse() ? DESCENDING_COMPARATOR : ASCENDING_COMPARATOR);

    if (fields.length > 1) {
        throw new IllegalArgumentException("Multiple fields not supported yet ");
    }//  w w w . j  av a  2  s  . co m
}

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

@Override
protected void processDataTuple(T tuple) {
    tuplesInCurrentStreamWindow.add(tuple);
    K key = function.apply(tuple);//  ww  w .j ava  2  s .c  om
    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());/*from www .j  a v a 2  s  .co 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:org.matsim.contrib.dvrp.data.VehicleGenerator.java

private void initQueue(double[] vehicleCounts) {
    int queueCapacity = (int) new Max().evaluate(vehicleCounts) + 1;
    activeVehicles = new PriorityQueue<>(queueCapacity, Vehicles.T1_COMPARATOR);
}

From source file:org.caleydo.neo4j.plugins.kshortestpaths.KShortestPathsAlgo.java

public List<WeightedPath> run(Node sourceNode, Node targetNode, int k, IPathReadyListener onPathReady) {
    StopWatch w = new StopWatch();
    w.start();/*from  w ww .j a  v a2 s  .co m*/

    // Calculate shortest path first
    List<WeightedPath> paths = new ArrayList<>(k);
    profile("start", w);
    WeightedPath shortestPath = shortestPathFinder.findSinglePath(sourceNode, targetNode);
    if (shortestPath == null)
        return paths;
    profile("initial disjkra", w);
    PriorityQueue<WeightedPath> pathCandidates = new PriorityQueue<WeightedPath>(20,
            new Comparator<WeightedPath>() {
                @Override
                public int compare(WeightedPath o1, WeightedPath o2) {
                    return Double.compare(o1.weight(), o2.weight());
                }
            });

    Set<Integer> pathCandidateHashes = new HashSet<>();

    if (onPathReady != null) {
        onPathReady.onPathReady(shortestPath);
    }
    paths.add(shortestPath);

    pathCandidateHashes.add(generatePathHash(shortestPath));

    for (int i = 1; i < k; i++) {

        WeightedPath prevPath = paths.get(i - 1);

        for (Node spurNode : prevPath.nodes()) {
            if (spurNode.getId() == prevPath.endNode().getId())
                break;

            WeightedPath rootPath = getSubPathTo(prevPath, spurNode);

            for (Path path : paths) {
                Iterator<Relationship> pathIterator = path.relationships().iterator();
                boolean containsRootPath = true;

                // Test if the existing shortest path starts with the root path
                for (Relationship relationship : rootPath.relationships()) {
                    if (!pathIterator.hasNext()) {
                        containsRootPath = false;
                        break;
                    }

                    Relationship pathRelationship = pathIterator.next();
                    if (relationship.getId() != pathRelationship.getId()) {
                        containsRootPath = false;
                        break;
                    }
                }

                // If so, set edge weight of following edge in that path to infinity
                if (containsRootPath) {
                    if (pathIterator.hasNext()) {
                        Relationship r = pathIterator.next();
                        costEvaluator.addInvalidRelationship(r);
                        //profile("invalid: "+r,w);
                    }
                }
            }

            // Simulate removal of root path nodes (except spur node) by setting all their edge weights to
            // infinity
            Set<Long> badIds = new HashSet<Long>();
            for (Node rootPathNode : rootPath.nodes()) {
                if (rootPathNode.getId() != spurNode.getId()) {
                    badIds.add(rootPathNode.getId());
                    //for (Relationship relationship : getRelationships(rootPathNode)) {
                    //   costEvaluator.addInvalidRelationship(relationship);
                    //}
                    //profile("invalids: "+rootPathNode.getRelationships(),w);
                }
            }
            expander.setExtraIgnoreNodes(badIds);

            profile("Find next path", w);
            WeightedPath spurPath = shortestPathFinder.findSinglePath(spurNode, targetNode);
            profile("Found next path", w);
            if (spurPath != null && !Double.isInfinite(spurPath.weight())) {
                WeightedPath pathCandidate = concatenate(rootPath, spurPath);
                Integer pathHash = generatePathHash(pathCandidate);
                if (!pathCandidateHashes.contains(pathHash)) {
                    pathCandidates.add(pathCandidate);
                    pathCandidateHashes.add(pathHash);
                }
            }

            // Restore edges
            costEvaluator.clearInvalidRelationships();
            expander.setExtraIgnoreNodes(null);

        }

        if (pathCandidates.isEmpty())
            break;

        WeightedPath nextBest = pathCandidates.poll();
        profile("flush path", w);
        if (onPathReady != null) {
            onPathReady.onPathReady(nextBest);
        }
        paths.add(nextBest);

    }
    profile("done", w);
    return paths;
}

From source file:org.apache.omid.tso.ReplyProcessorImpl.java

@Inject
ReplyProcessorImpl(MetricsRegistry metrics, Panicker panicker, ObjectPool<Batch> batchPool) {

    // ------------------------------------------------------------------------------------------------------------
    // Disruptor initialization
    // ------------------------------------------------------------------------------------------------------------

    ThreadFactoryBuilder threadFactory = new ThreadFactoryBuilder().setNameFormat("reply-%d");
    this.disruptorExec = Executors.newSingleThreadExecutor(threadFactory.build());

    this.disruptor = new Disruptor<>(EVENT_FACTORY, 1 << 12, disruptorExec, MULTI, new BusySpinWaitStrategy());
    disruptor.handleExceptionsWith(new FatalExceptionHandler(panicker));
    disruptor.handleEventsWith(this);
    this.replyRing = disruptor.start();

    // ------------------------------------------------------------------------------------------------------------
    // Attribute initialization
    // ------------------------------------------------------------------------------------------------------------

    this.batchPool = batchPool;
    this.nextIDToHandle.set(0);
    this.futureEvents = new PriorityQueue<>(10, new Comparator<ReplyBatchEvent>() {
        public int compare(ReplyBatchEvent replyBatchEvent1, ReplyBatchEvent replyBatchEvent2) {
            return Long.compare(replyBatchEvent1.getBatchSequence(), replyBatchEvent2.getBatchSequence());
        }//ww  w  .  j av a  2 s.c o m
    });

    // Metrics config
    this.abortMeter = metrics.meter(name("tso", "aborts"));
    this.commitMeter = metrics.meter(name("tso", "commits"));
    this.timestampMeter = metrics.meter(name("tso", "timestampAllocation"));

    LOG.info("ReplyProcessor initialized");

}

From source file:com.aliyun.odps.mapred.local.MapOutputBuffer.java

public MapOutputBuffer(JobConf conf, Pipeline pipeline, String taskId, int reduceNum) {
    int pipeIndex = Integer.parseInt(taskId.split("_")[0].substring(1)) - 1;
    TransformNode pipeNode = pipeline.getNode(pipeIndex);
    Column[] key = pipeNode.getOutputKeySchema();
    if (key != null) {
        String[] partCols = pipeNode.getPartitionColumns();
        this.partColIdxs = new int[partCols.length];
        Map<String, Integer> reverseLookupMap = new HashMap<String, Integer>();
        int i = 0;
        for (Column c : key) {
            reverseLookupMap.put(c.getName(), i);
            i++;//from  ww w.j a va 2 s. c  o  m
        }
        i = 0;
        for (String col : partCols) {
            partColIdxs[i] = reverseLookupMap.get(col);
        }

        // reduce copy count
        numReduce = reduceNum;
        String[] sortColumns = pipeNode.getOutputKeySortColumns();
        SortOrder[] sortOrders = pipeNode.getOutputKeySortOrder();
        comparator = new LocalColumnBasedRecordComparator(sortColumns, key, sortOrders);
        buffers = new ArrayList<PriorityQueue<Object[]>>(numReduce);
        for (i = 0; i < numReduce; i++) {
            buffers.add(new PriorityQueue<Object[]>(16, comparator));
        }
    }

}

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();
    }// www . 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:org.apache.hadoop.hbase.regionserver.KeyValueHeap.java

/**
 * Constructor./*from  ww  w . j av  a 2 s.c  o  m*/
 * @param scanners
 * @param comparator
 * @throws IOException
 */
KeyValueHeap(List<? extends KeyValueScanner> scanners, KVScannerComparator comparator) throws IOException {
    this.comparator = comparator;
    this.scannersForDelayedClose = new ArrayList<KeyValueScanner>(scanners.size());
    if (!scanners.isEmpty()) {
        this.heap = new PriorityQueue<KeyValueScanner>(scanners.size(), this.comparator);
        for (KeyValueScanner scanner : scanners) {
            if (scanner.peek() != null) {
                this.heap.add(scanner);
            } else {
                this.scannersForDelayedClose.add(scanner);
            }
        }
        this.current = pollRealKV();
    }
}

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  a2 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;
}