java.util.PriorityQueue Java Examples

The following examples show how to use java.util.PriorityQueue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NearestNeighborClassifier.java    From AILibs with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * Determine the k nearest neighbors for a test instance.
 *
 * @param testInstance
 *            The time series to determine the k nearest neighbors for.
 * @return Queue of the k nearest neighbors as pairs (class, distance).
 */
protected PriorityQueue<Pair<Integer, Double>> calculateNearestNeigbors(final double[] testInstance) {
	int numberOfTrainInstances = this.values.length;
	// Priority queue of (class, distance)-pairs for nearest neigbors, sorted by
	// distance ascending.
	PriorityQueue<Pair<Integer, Double>> nearestNeighbors = new PriorityQueue<>(nearestNeighborComparator);

	// Calculate the k nearest neighbors.
	for (int i = 0; i < numberOfTrainInstances; i++) {
		double d = this.distanceMeasure.distance(testInstance, this.values[i]);

		Pair<Integer, Double> neighbor = new Pair<>(this.targets[i], d);
		nearestNeighbors.add(neighbor);
		if (nearestNeighbors.size() > this.k) {
			nearestNeighbors.poll();
		}
	}
	return nearestNeighbors;
}
 
Example #2
Source File: CardinalityNodePruning.java    From JedAIToolkit with Apache License 2.0 6 votes vote down vote up
@Override
protected List<AbstractBlock> pruneEdges() {
    nearestEntities = new HashSet[noOfEntities];
    topKEdges = new PriorityQueue<>((int) (2 * threshold), new IncComparisonWeightComparator());
    if (weightingScheme.equals(WeightingScheme.ARCS)) {
        for (int i = 0; i < noOfEntities; i++) {
            processArcsEntity(i);
            verifyValidEntities(i);
        }
    } else {
        for (int i = 0; i < noOfEntities; i++) {
            processEntity(i);
            verifyValidEntities(i);
        }
    }

    return retainValidComparisons();
}
 
Example #3
Source File: Topn.java    From streamline with Apache License 2.0 6 votes vote down vote up
@Override
public PriorityQueue<T> add(PriorityQueue<T> aggregate, Integer n, T val) {
    if (n <= 0) {
        return aggregate;
    }
    if (aggregate.size() >= n) {
        if (val.compareTo(aggregate.peek()) > 0) {
            aggregate.remove();
            aggregate.add(val);
        }
    } else {
        aggregate.add(val);
    }
    return aggregate;

}
 
Example #4
Source File: FindTheRunningMedian.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	PriorityQueue<Integer> highers = new PriorityQueue<Integer>();
	PriorityQueue<Integer> lowers = new PriorityQueue<Integer>(new Comparator<Integer>() {
		public int compare(Integer i1, Integer i2) {
			return i2.compareTo(i1);
		}
	});
	int N = sc.nextInt();
	double meadian = 0;
	for (int i = 1; i <= N; i++) {
		int number = sc.nextInt();
		addNumber(number, lowers, highers);
		rebalance(lowers, highers);
		meadian = getMedian(lowers, highers);
		System.out.println(meadian);
	}
	sc.close();
}
 
Example #5
Source File: YOLO.java    From cineast with MIT License 6 votes vote down vote up
/**
 * It classifies the object/objects on the image
 *
 * @param tensorFlowOutput output from the TensorFlow, it is a 13x13x((num_class +1) * 5) tensor
 * 125 = (numClass +  Tx, Ty, Tw, Th, To) * 5 - cause we have 5 boxes per each cell
 * @param labels a string vector with the labels
 * @return a list of recognition objects
 */
private List<Recognition> classifyImage(final float[] tensorFlowOutput, final String[] labels) {
  int numClass = (int) (tensorFlowOutput.length / (Math.pow(SIZE, 2) * NUMBER_OF_BOUNDING_BOX)
      - 5);
  BoundingBox[][][] boundingBoxPerCell = new BoundingBox[SIZE][SIZE][NUMBER_OF_BOUNDING_BOX];
  PriorityQueue<Recognition> priorityQueue = new PriorityQueue<>(
      MAX_RECOGNIZED_CLASSES,
      new RecognitionComparator());

  int offset = 0;
  for (int cy = 0; cy < SIZE; cy++) {        // SIZE * SIZE cells
    for (int cx = 0; cx < SIZE; cx++) {
      for (int b = 0; b < NUMBER_OF_BOUNDING_BOX; b++) {   // 5 bounding boxes per each cell
        boundingBoxPerCell[cx][cy][b] = getModel(tensorFlowOutput, cx, cy, b, numClass, offset);
        calculateTopPredictions(boundingBoxPerCell[cx][cy][b], priorityQueue, labels);
        offset = offset + numClass + 5;
      }
    }
  }

  return getRecognition(priorityQueue);
}
 
Example #6
Source File: ProportionalCapacityPreemptionPolicy.java    From big-c with Apache License 2.0 6 votes vote down vote up
protected Collection<TempQueue> getMostUnderservedQueues(
    PriorityQueue<TempQueue> orderedByNeed, TQComparator tqComparator) {
  ArrayList<TempQueue> underserved = new ArrayList<TempQueue>();
  while (!orderedByNeed.isEmpty()) {
    TempQueue q1 = orderedByNeed.remove();
    underserved.add(q1);
    TempQueue q2 = orderedByNeed.peek();
    // q1's pct of guaranteed won't be larger than q2's. If it's less, then
    // return what has already been collected. Otherwise, q1's pct of
    // guaranteed == that of q2, so add q2 to underserved list during the
    // next pass.
    if (q2 == null || tqComparator.compare(q1,q2) < 0) {
      return underserved;
    }
  }
  return underserved;
}
 
Example #7
Source File: LastPointReader.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
/**
 * find the last TimeseriesMetadata in unseq files and unpack all overlapped unseq files
 */
private void UnpackOverlappedUnseqFiles(long lBoundTime) throws IOException {
  PriorityQueue<TsFileResource> unseqFileResource =
      sortUnSeqFileResourcesInDecendingOrder(dataSource.getUnseqResources());

  while (!unseqFileResource.isEmpty()
      && (lBoundTime <= unseqFileResource.peek().getEndTime(seriesPath.getDevice()))) {
    TimeseriesMetadata timeseriesMetadata =
        FileLoaderUtils.loadTimeSeriesMetadata(
            unseqFileResource.poll(), seriesPath, context, timeFilter, deviceMeasurements);

    if (timeseriesMetadata == null || (!timeseriesMetadata.isModified()
        && timeseriesMetadata.getStatistics().getEndTime() < lBoundTime)) {
      continue;
    }
    unseqTimeseriesMetadataList.add(timeseriesMetadata);
    if (!timeseriesMetadata.isModified()) {
      if (endtimeContainedByTimeFilter(timeseriesMetadata.getStatistics())) {
        lBoundTime = Math.max(lBoundTime, timeseriesMetadata.getStatistics().getEndTime());
      } else {
        lBoundTime = Math.max(lBoundTime, timeseriesMetadata.getStatistics().getStartTime());
      }
    }
  }
}
 
Example #8
Source File: PrimeFactorization.java    From Algorithms with MIT License 6 votes vote down vote up
public static ArrayList<Long> primeFactorization(long n) {
  ArrayList<Long> factors = new ArrayList<>();
  if (n <= 0) throw new IllegalArgumentException();
  else if (n == 1) return factors;
  PriorityQueue<Long> divisorQueue = new PriorityQueue<>();
  divisorQueue.add(n);
  while (!divisorQueue.isEmpty()) {
    long divisor = divisorQueue.remove();
    if (isPrime(divisor)) {
      factors.add(divisor);
      continue;
    }
    long next_divisor = pollardRho(divisor);
    if (next_divisor == divisor) {
      divisorQueue.add(divisor);
    } else {
      divisorQueue.add(next_divisor);
      divisorQueue.add(divisor / next_divisor);
    }
  }
  return factors;
}
 
Example #9
Source File: BusinessService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
public static List<Integer> mergekSortedArrays(List<List<Integer>> arrays) {
    ArrayList<Integer> list = new ArrayList<>();
    if (arrays == null || arrays.size() == 0 || arrays.get(0).size() == 0) {
        return list;
    }
    PriorityQueue<NewInteger> pq = new PriorityQueue<>(arrays.size(), (x, y) -> x.value > y.value ? -1 : 1);
    for (int i = 0; i < arrays.size(); i++) {
        pq.offer(new NewInteger(arrays.get(i).get(0), i, 0));
    }
    while (list.size() < 3000 && !pq.isEmpty()) {
        NewInteger min = pq.poll();
        if (min.col + 1 < arrays.get(min.row).size()) {
            pq.offer(new NewInteger(arrays.get(min.row).get(min.col + 1), min.row, min.col + 1));
        }
        list.add(min.value);
    }
    return list;
}
 
Example #10
Source File: PriorityQueueSerializer.java    From flink with Apache License 2.0 6 votes vote down vote up
public PriorityQueue<?> read(Kryo k, Input i, Class<PriorityQueue<?>> c) {
	Comparator<Object> comp = (Comparator<Object>) k.readClassAndObject(i);
	int sz = i.readInt(true);
	// can't create with size 0:
	PriorityQueue<Object> result;
	if (sz == 0) {
		result = new PriorityQueue<Object>(1, comp);
	}
	else {
		result = new PriorityQueue<Object>(sz, comp);
	}
	int idx = 0;
	while (idx < sz) {
		result.add(k.readClassAndObject(i));
		idx += 1;
	}
	return result;
}
 
Example #11
Source File: RocksStatesPerKeyGroupMergeIterator.java    From flink with Apache License 2.0 6 votes vote down vote up
private PriorityQueue<RocksSingleStateIterator> buildIteratorHeap(
	List<Tuple2<RocksIteratorWrapper, Integer>> kvStateIterators) {

	Comparator<RocksSingleStateIterator> iteratorComparator = COMPARATORS.get(keyGroupPrefixByteCount - 1);

	PriorityQueue<RocksSingleStateIterator> iteratorPriorityQueue =
		new PriorityQueue<>(kvStateIterators.size(), iteratorComparator);

	for (Tuple2<RocksIteratorWrapper, Integer> rocksIteratorWithKVStateId : kvStateIterators) {
		final RocksIteratorWrapper rocksIterator = rocksIteratorWithKVStateId.f0;
		rocksIterator.seekToFirst();
		if (rocksIterator.isValid()) {
			iteratorPriorityQueue.offer(
				new RocksSingleStateIterator(rocksIterator, rocksIteratorWithKVStateId.f1));
		} else {
			IOUtils.closeQuietly(rocksIterator);
		}
	}
	return iteratorPriorityQueue;
}
 
Example #12
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public boolean isPossibleDivide(int[] nums, int k) {
    int len = nums.length;
    if (len % k != 0) {
        return false;
    }

    PriorityQueue<Integer> minHeap = new PriorityQueue<>(len);
    for (int num : nums) {
        minHeap.offer(num);
    }

    while (!minHeap.isEmpty()) {
        Integer top = minHeap.poll();

        for (int i = 1; i < k; i++) {
            // 从 1 开始,正好需要移除 k - 1 个元素
            // i 正好就是相对于 top 的偏移
            if (!minHeap.remove(top + i)) {
                // 如果移除失败,说明划分不存在,直接返回 false 即可
                return false;
            }
        }
    }
    return true;
}
 
Example #13
Source File: PriorityQueueTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_spliterator() throws Exception {
    ArrayList<Integer> testElements = new ArrayList<>(
            Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));
    PriorityQueue<Integer> list = new PriorityQueue<>();
    list.addAll(testElements);

    SpliteratorTester.runBasicIterationTests(list.spliterator(), testElements);
    SpliteratorTester.runBasicSplitTests(list, testElements);
    SpliteratorTester.testSpliteratorNPE(list.spliterator());

    assertTrue(list.spliterator().hasCharacteristics(
            Spliterator.SIZED | Spliterator.SUBSIZED));

    SpliteratorTester.runSizedTests(list, 16 /* expected size */);
    SpliteratorTester.runSubSizedTests(list, 16 /* expected size */);
    SpliteratorTester.assertSupportsTrySplit(list);
}
 
Example #14
Source File: YOLO.java    From cineast with MIT License 6 votes vote down vote up
private List<Recognition> getRecognition(final PriorityQueue<Recognition> priorityQueue) {
  ArrayList<Recognition> recognitions = new ArrayList<>();

  if (priorityQueue.size() > 0) {
    // Best recognition
    Recognition bestRecognition = priorityQueue.poll();
    recognitions.add(bestRecognition);

    for (int i = 0; i < Math.min(priorityQueue.size(), MAX_RESULTS); ++i) {
      Recognition recognition = priorityQueue.poll();
      boolean overlaps = false;
      for (Recognition previousRecognition : recognitions) {
        overlaps = overlaps || (getIntersectionProportion(previousRecognition.getLocation(),
            recognition.getLocation()) > OVERLAP_THRESHOLD);
      }

      if (!overlaps) {
        recognitions.add(recognition);
      }
    }
  }

  return recognitions;
}
 
Example #15
Source File: CommonsBeanutilsCollectionsLogging1.java    From JavaSerialKiller with MIT License 6 votes vote down vote up
public Object getObject(final String command) throws Exception {
	final TemplatesImpl templates = Gadgets.createTemplatesImpl(command);
	// mock method name until armed
	final BeanComparator comparator = new BeanComparator("lowestSetBit");

	// create queue with numbers and basic comparator
	final PriorityQueue<Object> queue = new PriorityQueue<Object>(2, comparator);
	// stub data for replacement later
	queue.add(new BigInteger("1"));
	queue.add(new BigInteger("1"));

	// switch method called by comparator
	Reflections.setFieldValue(comparator, "property", "outputProperties");

	// switch contents of queue
	final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
	queueArray[0] = templates;
	queueArray[1] = templates;

	return queue;
}
 
Example #16
Source File: TestAdminHelper.java    From uReplicator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetControllerAutobalancing() throws Exception {
    ControllerHelixManager mockHelixManager = EasyMock.createMock(ControllerHelixManager.class);
    AdminHelper helper = new AdminHelper(mockHelixManager);
    Map<String, PriorityQueue<InstanceTopicPartitionHolder>> instanceMap = new HashMap<>();
    PriorityQueue<InstanceTopicPartitionHolder> sjc1aTosjc1Agg1 = new PriorityQueue<>();
    String pipeline = ControllerUtils.getPipelineName("sjc1a", "sjc1-agg1");
    InstanceTopicPartitionHolder ith = new InstanceTopicPartitionHolder("compute9527-sjc1",
        new TopicPartition(pipeline, 0));
    sjc1aTosjc1Agg1.add(ith);
    instanceMap.put(pipeline, sjc1aTosjc1Agg1);
    EasyMock.expect(mockHelixManager.getPipelineToInstanceMap()).andReturn(instanceMap).atLeastOnce();
    EasyMock.expect(mockHelixManager.getControllerAutobalancingStatus("compute9527-sjc1"))
        .andReturn(false);
    EasyMock.replay(mockHelixManager);
    JSONObject status = helper.getControllerAutobalancingStatus();
    Assert.assertEquals(status.size(), 1);
    JSONObject detail = (JSONObject) status.get("compute9527-sjc1");
    Assert.assertEquals(detail.get("autoBalance"), false);
    EasyMock.verify(mockHelixManager);
}
 
Example #17
Source File: GTAggregateScanner.java    From kylin with Apache License 2.0 6 votes vote down vote up
public DumpMerger(List<Dump> dumps) {
    minHeap = new PriorityQueue<>(dumps.size(), new Comparator<Entry<byte[], Integer>>() {
        @Override
        public int compare(Entry<byte[], Integer> o1, Entry<byte[], Integer> o2) {
            return bytesComparator.compare(o1.getKey(), o2.getKey());
        }
    });
    dumpIterators = Lists.newArrayListWithCapacity(dumps.size());
    dumpCurrentValues = Lists.newArrayListWithCapacity(dumps.size());

    Iterator<Pair<byte[], byte[]>> it;
    for (int i = 0; i < dumps.size(); i++) {
        it = dumps.get(i).iterator();
        dumpCurrentValues.add(i, null);
        if (it.hasNext()) {
            dumpIterators.add(i, it);
            enqueueFromDump(i);
        } else {
            dumpIterators.add(i, null);
        }
    }
}
 
Example #18
Source File: BinaryTreeTest.java    From JImageHash with MIT License 6 votes vote down vote up
@Test
public void searchItemMultipleValues2() {
	Hash hash = TestResources.createHash("101010100011", 0);
	Hash hash1 = TestResources.createHash("101010100010", 0);

	binTree.addHash(hash, 1);
	binTree.addHash(hash, 2);
	binTree.addHash(hash, 3);
	binTree.addHash(hash1, 3);
	binTree.addHash(hash1, 3);
	binTree.addHash(hash1, 3);

	PriorityQueue<Result> results = binTree.getElementsWithinHammingDistance(hash, 2);

	assertEquals(6, results.size());
}
 
Example #19
Source File: SessionReconstructionFilter.java    From kieker with Apache License 2.0 6 votes vote down vote up
private <T extends AbstractSession<?>> void processTimeouts(final long currentTime, final String outputPortName, final PriorityQueue<T> timeoutQueue,
		final Map<String, T> openSessions) {
	while (!timeoutQueue.isEmpty()) {
		final T session = timeoutQueue.peek();
		final long currentThinkTime = (currentTime - session.getEndTimestamp());

		// The current session timed out
		if (currentThinkTime > this.maxThinkTime) {
			timeoutQueue.remove();
			openSessions.remove(session.getSessionId());
			this.dispatchCompletedSession(session, outputPortName);
		} else { // If the current session has not timed out, we are done due to the ordering of the queue
			break;
		}
	}
}
 
Example #20
Source File: PriorityBlockingQueue.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Saves this queue to a stream (that is, serializes it).
 *
 * For compatibility with previous version of this class, elements
 * are first copied to a java.util.PriorityQueue, which is then
 * serialized.
 *
 * @param s the stream
 * @throws java.io.IOException if an I/O error occurs
 */
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    lock.lock();
    try {
        // avoid zero capacity argument
        q = new PriorityQueue<E>(Math.max(size, 1), comparator);
        q.addAll(this);
        s.defaultWriteObject();
    } finally {
        q = null;
        lock.unlock();
    }
}
 
Example #21
Source File: DatabaseExample.java    From JImageHash with MIT License 5 votes vote down vote up
private static void createDatabaseViaCredentials() throws Exception {
	String dbName = "imageHashDB";
	String userName = "root";
	String password = "";

	// Wrap in try with block or call close at the end!
	try (H2DatabaseImageMatcher db = new H2DatabaseImageMatcher(dbName, userName, password)) {
		// Proceed as normal
		db.addHashingAlgorithm(new DifferenceHash(32, Precision.Double), .4);
		db.addHashingAlgorithm(new PerceptiveHash(32), .2);

		// Image files
		File ballon = new File("src/test/resources/ballon.jpg");
		File copyright = new File("src/test/resources/copyright.jpg");
		File highQuality = new File("src/test/resources/highQuality.jpg");

		db.addImages(ballon, copyright, highQuality);

		PriorityQueue<Result<String>> results = db.getMatchingImages(copyright);
		results.forEach(System.out::println);

		// Find all images which are similar to any image in the database
		System.out.println(db.getAllMatchingImages());
	}

	/*
	 * finally { //Not necessary since we use a try with otherwise db.close(); }
	 */

}
 
Example #22
Source File: ConsecutiveMatcher.java    From JImageHash with MIT License 5 votes vote down vote up
protected PriorityQueue<Result<String>> getMatchingImagesInternal(BufferedImage image, String uniqueId) {

		if (steps.isEmpty())
			throw new IllegalStateException(
					"Please supply at least one hashing algorithm prior to invoking the match method");

		PriorityQueue<Result<String>> returnValues = null;

		for (Entry<HashingAlgorithm, AlgoSettings> entry : steps.entrySet()) {
			HashingAlgorithm algo = entry.getKey();

			BinaryTree<String> binTree = binTreeMap.get(algo);
			AlgoSettings settings = entry.getValue();

			Hash needleHash = getHash(algo, uniqueId, image);

			int threshold = 0;
			if (settings.isNormalized()) {
				int hashLength = needleHash.getBitResolution();
				threshold = (int) Math.round(settings.getThreshold() * hashLength);
			} else {
				threshold = (int) settings.getThreshold();
			}

			PriorityQueue<Result<String>> temp = binTree.getElementsWithinHammingDistance(needleHash, threshold);

			if (returnValues == null) {
				returnValues = temp;
			} else {
				temp.retainAll(returnValues);
				returnValues = temp;
			}
		}
		return returnValues;
	}
 
Example #23
Source File: Top.java    From spork with Apache License 2.0 5 votes vote down vote up
protected static void updateTop(PriorityQueue<Tuple> store, int limit, DataBag inputBag) {
    Iterator<Tuple> itr = inputBag.iterator();
    while (itr.hasNext()) {
        Tuple t = itr.next();
        store.add(t);
        if (store.size() > limit)
            store.poll();
    }
}
 
Example #24
Source File: 10147 Highways.java    From UVA with GNU General Public License v3.0 5 votes vote down vote up
private static ArrayList<Edge> mst(int [] parent, PriorityQueue<Edge> edges) {
	ArrayList<Edge> list=new ArrayList<>();
	while (!edges.isEmpty()) {
		Edge e=edges.poll();
		int px=getParent(parent, e.x);
		int py=getParent(parent, e.y);
		if (px!=py) {
			if (px>py) parent[px]=py;
			else parent[py]=px;
			list.add(e);
		}
	}
	return list;
}
 
Example #25
Source File: PriorityQueueTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * poll succeeds unless empty
 */
public void testPoll() {
    PriorityQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.poll());
    }
    assertNull(q.poll());
}
 
Example #26
Source File: PriorityQueueSerializer.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public void write(Kryo k, Output o, PriorityQueue<?> q) {
	k.writeClassAndObject(o, getComparator(q));
	o.writeInt(q.size(), true);
	for (Object a : q) {
		k.writeClassAndObject(o, a);
		o.flush();
	}
}
 
Example #27
Source File: UnicastProcessorTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void bufferSizeOtherQueue() {
	UnicastProcessor processor = UnicastProcessor.create(
			new PriorityQueue<>(10));

	assertThat(processor.getBufferSize())
			.isEqualTo(Integer.MIN_VALUE)
            .isEqualTo(Queues.CAPACITY_UNSURE);
}
 
Example #28
Source File: MagicPermanentTriggerMap.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
public MagicPermanentTrigger remove(final MagicPermanent permanent, final MagicTrigger<?> trigger) {
    for (final Map.Entry<MagicTriggerType, PriorityQueue<MagicPermanentTrigger>> type : effects.entrySet()) {
        final Collection<MagicPermanentTrigger> triggers = type.getValue();
        for (final Iterator<MagicPermanentTrigger> iterator = triggers.iterator();iterator.hasNext();) {
            final MagicPermanentTrigger permanentTrigger = iterator.next();
            if (permanentTrigger.getPermanent() == permanent &&
                permanentTrigger.getTrigger() == trigger) {
                iterator.remove();
                return permanentTrigger;
            }
        }
    }
    throw new GameException("Could not remove " + permanent + "'s trigger " + trigger, permanent.getGame());
}
 
Example #29
Source File: PriorityBlockingQueue.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Saves this queue to a stream (that is, serializes it).
 *
 * For compatibility with previous version of this class, elements
 * are first copied to a java.util.PriorityQueue, which is then
 * serialized.
 *
 * @param s the stream
 * @throws java.io.IOException if an I/O error occurs
 */
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    lock.lock();
    try {
        // avoid zero capacity argument
        q = new PriorityQueue<E>(Math.max(size, 1), comparator);
        q.addAll(this);
        s.defaultWriteObject();
    } finally {
        q = null;
        lock.unlock();
    }
}
 
Example #30
Source File: GraphVectorsImpl.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Override
public int[] verticesNearest(int vertexIdx, int top) {

    INDArray vec = lookupTable.getVector(vertexIdx).dup();
    double norm2 = vec.norm2Number().doubleValue();


    PriorityQueue<Pair<Double, Integer>> pq =
                    new PriorityQueue<>(lookupTable.getNumVertices(), new PairComparator());

    Level1 l1 = Nd4j.getBlasWrapper().level1();
    for (int i = 0; i < numVertices(); i++) {
        if (i == vertexIdx)
            continue;

        INDArray other = lookupTable.getVector(i);
        double cosineSim = l1.dot(vec.length(), 1.0, vec, other) / (norm2 * other.norm2Number().doubleValue());

        pq.add(new Pair<>(cosineSim, i));
    }

    int[] out = new int[top];
    for (int i = 0; i < top; i++) {
        out[i] = pq.remove().getSecond();
    }

    return out;
}