gnu.trove.set.TLongSet Java Examples

The following examples show how to use gnu.trove.set.TLongSet. 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: MappedArrayWithLongCoding.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public Array<T> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<T> builder = ArrayBuilder.of(capacity, type());
    for (int i=0; i<length(); ++i) {
        final long code = getLong(i);
        if (set.add(code)) {
            final T value = getValue(i);
            builder.add(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #2
Source File: DenseArrayWithLongCoding.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public Array<T> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<T> builder = ArrayBuilder.of(capacity, type());
    for (int i=0; i<length(); ++i) {
        final long code = getLong(i);
        if (set.add(code)) {
            final T value = getValue(i);
            builder.add(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #3
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static TLongSet affectedBlocks(final RandomAccessibleInterval<?> input, final CellGrid grid, final Interval
		interval)
{
	if (input instanceof AccessedBlocksRandomAccessible<?>)
	{
		final AccessedBlocksRandomAccessible<?> tracker = (net.imglib2.util.AccessedBlocksRandomAccessible<?>)
				input;
		if (grid.equals(tracker.getGrid()))
		{
			final long[] blocks = tracker.listBlocks();
			LOG.debug("Got these blocks from tracker: {}", blocks);
			return new TLongHashSet(blocks);
		}
	}
	return affectedBlocks(grid, interval);
}
 
Example #4
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static TLongSet affectedBlocks(final long[] gridDimensions, final int[] blockSize, final Interval...
		intervals)
{
	final TLongHashSet blocks              = new TLongHashSet();
	final int[]        ones                = IntStream.generate(() -> 1).limit(blockSize.length).toArray();
	final long[]       relevantIntervalMin = new long[blockSize.length];
	final long[]       relevantIntervalMax = new long[blockSize.length];
	for (final Interval interval : intervals)
	{
		Arrays.setAll(relevantIntervalMin, d -> (interval.min(d) / blockSize[d]));
		Arrays.setAll(relevantIntervalMax, d -> (interval.max(d) / blockSize[d]));
		Grids.forEachOffset(
				relevantIntervalMin,
				relevantIntervalMax,
				ones,
				offset -> blocks.add(IntervalIndexer.positionToIndex(offset, gridDimensions))
		                   );
	}

	return blocks;
}
 
Example #5
Source File: DenseArrayOfLongs.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public final Array<Long> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<Long> builder = ArrayBuilder.of(capacity, Long.class);
    for (int i=0; i<length(); ++i) {
        final long value = getLong(i);
        if (set.add(value)) {
            builder.addLong(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #6
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public static TLongSet affectedBlocks(final long[] gridDimensions, final int[] blockSize, final Interval interval)
{
	final TLongHashSet blocks              = new TLongHashSet();
	final int[]        ones                = IntStream.generate(() -> 1).limit(blockSize.length).toArray();
	final long[]       relevantIntervalMin = new long[blockSize.length];
	final long[]       relevantIntervalMax = new long[blockSize.length];
	Arrays.setAll(relevantIntervalMin, d -> (interval.min(d) / blockSize[d]));
	Arrays.setAll(relevantIntervalMax, d -> (interval.max(d) / blockSize[d]));
	Grids.forEachOffset(
			relevantIntervalMin,
			relevantIntervalMax,
			ones,
			offset -> blocks.add(IntervalIndexer.positionToIndex(offset, gridDimensions))
	                   );

	return blocks;
}
 
Example #7
Source File: MappedArrayOfLongs.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public final Array<Long> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<Long> builder = ArrayBuilder.of(capacity, Long.class);
    for (int i=0; i<length(); ++i) {
        final long value = getLong(i);
        if (set.add(value)) {
            builder.addLong(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #8
Source File: IdSelector.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void selectAllInCurrentViewLabelMultisetType(final ViewerPanelFX viewer, final TLongSet idsInCurrentView)
{
	VisitEveryDisplayPixel.visitEveryDisplayPixel(
			(DataSource<LabelMultisetType, ?>) source,
			viewer,
			lmt -> {
				for (final Entry<Label> entry : lmt.entrySet())
				{
					final long id = entry.getElement().id();
					if (foregroundCheck.test(id))
						idsInCurrentView.add(id);
				}
			}
		);
}
 
Example #9
Source File: FallingBlocksMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Return the number of unsupported blocks connected to any blocks neighboring the given location,
 * which is assumed to contain an air block. The search may bail out early when the count is greater
 * or equal to the given limit, though this cannot be guaranteed.
 */
private int countUnsupportedNeighbors(long pos, int limit) {
    TLongSet supported = new TLongHashSet();
    TLongSet unsupported = new TLongHashSet();

    try {
        for(BlockFace face : NEIGHBORS) {
            if(!this.isSupported(neighborPos(pos, face), supported, unsupported)) {
                if(unsupported.size() >= limit) break;
            }
        }
    }
    catch(MaxSearchVisitsExceeded ex) {
        this.logError(ex);
    }

    return unsupported.size();
}
 
Example #10
Source File: IdSelector.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private void selectAllLabelMultisetType(final TLongSet allIds)
{
	@SuppressWarnings("unchecked")
	final RandomAccessibleInterval<LabelMultisetType> data = (RandomAccessibleInterval<LabelMultisetType>)
			source.getDataSource(0, source.getNumMipmapLevels() - 1);

	final Cursor<LabelMultisetType> cursor = Views.iterable(data).cursor();
	while (cursor.hasNext())
	{
		final LabelMultisetType lmt = cursor.next();
		for (final Entry<Label> entry : lmt.entrySet())
		{
			final long id = entry.getElement().id();
			if (foregroundCheck.test(id))
				allIds.add(id);
		}
	}
}
 
Example #11
Source File: FallingBlocksMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Make any unsupported blocks fall that are disturbed for the current tick
 */
private void fallCheck() {
    this.visitsWorstTick = Math.max(this.visitsWorstTick, this.visitsThisTick);
    this.visitsThisTick = 0;

    World world = this.getMatch().getWorld();
    TLongObjectMap<ParticipantState> blockDisturbers = this.blockDisturbersByTick.remove(this.getMatch().getClock().now().tick);
    if(blockDisturbers == null) return;

    TLongSet supported = new TLongHashSet();
    TLongSet unsupported = new TLongHashSet();
    TLongObjectMap<ParticipantState> fallsByBreaker = new TLongObjectHashMap<>();

    try {
        while(!blockDisturbers.isEmpty()) {
            long pos = blockDisturbers.keySet().iterator().next();
            ParticipantState breaker = blockDisturbers.remove(pos);

            // Search down for the first block that can actually fall
            for(;;) {
                long below = neighborPos(pos, BlockFace.DOWN);
                if(!Materials.isColliding(blockAt(world, below).getType())) break;
                blockDisturbers.remove(pos); // Remove all the blocks we find along the way
                pos = below;
            }

            // Check if the block needs to fall, if it isn't already falling
            if(!fallsByBreaker.containsKey(pos) && !this.isSupported(pos, supported, unsupported)) {
                fallsByBreaker.put(pos, breaker);
            }
        }
    } catch(MaxSearchVisitsExceeded ex) {
        this.logError(ex);
    }

    for(TLongObjectIterator<ParticipantState> iter = fallsByBreaker.iterator(); iter.hasNext();) {
        iter.advance();
        this.fall(iter.key(), iter.value());
    }
}
 
Example #12
Source File: SparseArrayOfLongs.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public final Array<Long> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<Long> builder = ArrayBuilder.of(capacity, Long.class);
    for (int i=0; i<length(); ++i) {
        final long value = getLong(i);
        if (set.add(value)) {
            builder.addLong(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #13
Source File: SparseArrayWithLongCoding.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Override
public Array<T> distinct(int limit) {
    final int capacity = limit < Integer.MAX_VALUE ? limit : 100;
    final TLongSet set = new TLongHashSet(capacity);
    final ArrayBuilder<T> builder = ArrayBuilder.of(capacity, type());
    for (int i=0; i<length(); ++i) {
        final long code = getLong(i);
        if (set.add(code)) {
            final T value = getValue(i);
            builder.add(value);
            if (set.size() >= limit) {
                break;
            }
        }
    }
    return builder.toArray();
}
 
Example #14
Source File: ReceivedMessage.java    From JDA with Apache License 2.0 6 votes vote down vote up
public ReceivedMessage(
    long id, MessageChannel channel, MessageType type,
    boolean fromWebhook, boolean mentionsEveryone, TLongSet mentionedUsers, TLongSet mentionedRoles, boolean tts, boolean pinned,
    String content, String nonce, User author, Member member, MessageActivity activity, OffsetDateTime editTime,
    List<MessageReaction> reactions, List<Attachment> attachments, List<MessageEmbed> embeds, int flags)
{
    super(content, nonce, tts);
    this.id = id;
    this.channel = channel;
    this.type = type;
    this.api = (channel != null) ? (JDAImpl) channel.getJDA() : null;
    this.fromWebhook = fromWebhook;
    this.mentionsEveryone = mentionsEveryone;
    this.pinned = pinned;
    this.author = author;
    this.member = member;
    this.activity = activity;
    this.editedTime = editTime;
    this.reactions = Collections.unmodifiableList(reactions);
    this.attachments = Collections.unmodifiableList(attachments);
    this.embeds = Collections.unmodifiableList(embeds);
    this.mentionedUsers = mentionedUsers;
    this.mentionedRoles = mentionedRoles;
    this.flags = flags;
}
 
Example #15
Source File: FallingBlocksMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Return the number of unsupported blocks connected to any blocks neighboring the given location,
 * which is assumed to contain an air block. The search may bail out early when the count is
 * greater or equal to the given limit, though this cannot be guaranteed.
 */
private int countUnsupportedNeighbors(long pos, int limit) {
  TLongSet supported = new TLongHashSet();
  TLongSet unsupported = new TLongHashSet();

  try {
    for (BlockFace face : NEIGHBORS) {
      if (!this.isSupported(neighborPos(pos, face), supported, unsupported)) {
        if (unsupported.size() >= limit) break;
      }
    }
  } catch (MaxSearchVisitsExceeded ex) {
    this.logError(ex);
  }

  return unsupported.size();
}
 
Example #16
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Downsample affected blocks of img.
 * @param source
 * @param img
 * @param affectedBlocks
 * @param steps
 * @param interval
 */
public static void downsampleBlocks(
		final RandomAccessible<UnsignedLongType> source,
		final CachedCellImg<UnsignedLongType, LongAccess> img,
		final TLongSet affectedBlocks,
		final int[] steps,
		final Interval interval)
{
	final BlockSpec blockSpec = new BlockSpec(img.getCellGrid());

	final long[] intersectedCellMin = new long[blockSpec.grid.numDimensions()];
	final long[] intersectedCellMax = new long[blockSpec.grid.numDimensions()];

	LOG.debug("Initializing affected blocks: {}", affectedBlocks);
	for (final TLongIterator it = affectedBlocks.iterator(); it.hasNext(); )
	{
		final long blockId = it.next();
		blockSpec.fromLinearIndex(blockId);

		Arrays.setAll(intersectedCellMin, d -> blockSpec.min[d]);
		Arrays.setAll(intersectedCellMax, d -> blockSpec.max[d]);

		intersect(intersectedCellMin, intersectedCellMax, interval);

		if (isNonEmpty(intersectedCellMin, intersectedCellMax))
		{
			LOG.trace("Downsampling for intersected min/max: {} {}", intersectedCellMin, intersectedCellMax);
			downsample(source, Views.interval(img, intersectedCellMin, intersectedCellMax), steps);
		}
	}
}
 
Example #17
Source File: BlockUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static TLongSet encodePosSet(Collection<?> vectors) {
    TLongSet encoded = new TLongHashSet(vectors.size());
    for(Object o : vectors) {
        if(o instanceof BlockVector) {
            encoded.add(encodePos((BlockVector) o));
        }
    }
    return encoded;
}
 
Example #18
Source File: Grids.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param sourceBlocks linear index representation of blocks in source grid space
 * @param sourceGrid grid of source
 * @param targetGrid grid of target
 * @param scaleSourceToWorld scale source coordinate to world
 * @param scaleTargetToWorld scale target coordinate to world
 * @return Linear index representation for all blocks in {@code targetGrid} that intersect with {@code sourceBlocks}
 * in {@code sourcegrid}
 */
public static TLongSet getRelevantBlocksInTargetGrid(
		final long[] sourceBlocks,
		final CellGrid sourceGrid,
		final CellGrid targetGrid,
		final double[] scaleSourceToWorld,
		final double[] scaleTargetToWorld)
{

	assert DoubleStream.of(scaleSourceToWorld).filter(d -> d <= 0).count() == 0;
	assert DoubleStream.of(scaleTargetToWorld).filter(d -> d <= 0).count() == 0;

	final long[]   blockPos     = new long[sourceGrid.numDimensions()];
	final int[]    blockSize    = new int[sourceGrid.numDimensions()];
	final double[] blockMin     = new double[sourceGrid.numDimensions()];
	final double[] blockMax     = new double[sourceGrid.numDimensions()];
	sourceGrid.cellDimensions(blockSize);

	final TLongSet targetBlocks = new TLongHashSet();
	for (final long blockId : sourceBlocks)
	{
		sourceGrid.getCellGridPositionFlat(blockId, blockPos);
		Arrays.setAll(blockMin, d -> blockPos[d] * blockSize[d]);
		Arrays.setAll(blockMax, d -> Math.min(blockMin[d] + blockSize[d], sourceGrid.imgDimension(d)) - 1);
		scaleBoundingBox(blockMin, blockMax, blockMin, blockMax, scaleSourceToWorld, scaleTargetToWorld);
		targetBlocks.addAll(getIntersectingBlocks(blockMin, blockMax, targetGrid));
	}

	return targetBlocks;
}
 
Example #19
Source File: Grids.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param sourceBlocks linear index representation of blocks in source grid space
 * @param sourceGrid grid of source
 * @param targetGrid grid of target
 * @param relativeScale relative scale from source to target coordinates
 * @return Linear index representation for all blocks in {@code targetGrid} that intersect with {@code sourceBlocks}
 * in {@code sourcegrid}
 */
public static TLongSet getRelevantBlocksInTargetGrid(
		final long[] sourceBlocks,
		final CellGrid sourceGrid,
		final CellGrid targetGrid,
		final double[] relativeScale)
{
	return getRelevantBlocksInTargetGrid(
			sourceBlocks,
			sourceGrid,
			targetGrid,
			DoubleStream.generate(() -> 1.0).limit(relativeScale.length).toArray(),
			relativeScale
	);
}
 
Example #20
Source File: SegmentMaskGenerators.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public LabelMultisetTypeMaskWithMinLabelRatio(final TLongSet validLabels, final double minLabelRatio, final long numFullResPixels)
{
	assert numFullResPixels > 0;
	LOG.debug(
			"Creating {} with min label ratio: {}, numFullResPixels: {}, valid labels: {}",
			this.getClass().getSimpleName(),
			validLabels,
			minLabelRatio,
			numFullResPixels);
	this.validLabels = validLabels;
	this.minNumRequiredPixels = (long) Math.ceil(numFullResPixels * minLabelRatio);
}
 
Example #21
Source File: BlockVectors.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
static TLongSet encodePosSet(Collection<?> vectors) {
  TLongSet encoded = new TLongHashSet(vectors.size());
  for (Object o : vectors) {
    if (o instanceof BlockVector) {
      encoded.add(encodePos((BlockVector) o));
    }
  }
  return encoded;
}
 
Example #22
Source File: VertexSerializer.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, TLongSet> getEdgeIds(Vertex vertex, Direction direction) {
  Map<String, TLongSet> edgeIdsByLabel = new THashMap<>();
  vertex.edges(direction).forEachRemaining(edge -> {
    edgeIdsByLabel.computeIfAbsent(edge.label(), label -> new TLongHashSet());
    edgeIdsByLabel.get(edge.label()).add((long) edge.id());
  });
  return edgeIdsByLabel;
}
 
Example #23
Source File: Serializer.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
/**
 * format: two `Map<Label, Array<EdgeId>>`, i.e. one Map for `IN` and one for `OUT` edges
 */
private void packEdgeIds(final MessageBufferPacker packer,
                         final Map<String, TLongSet> edgeIdsByLabel) throws IOException {
  packer.packMapHeader(edgeIdsByLabel.size());
  for (Map.Entry<String, TLongSet> entry : edgeIdsByLabel.entrySet()) {
    final String label = entry.getKey();
    packer.packString(label);
    final TLongSet edgeIds = entry.getValue();
    packer.packArrayHeader(edgeIds.size());
    final TLongIterator edgeIdIter = edgeIds.iterator();
    while (edgeIdIter.hasNext()) {
      packer.packLong(edgeIdIter.next());
    }
  }
}
 
Example #24
Source File: EdgeSerializer.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
/** using same format to store edgeIds as for vertices */
protected Map<String, TLongSet> getEdgeIds(Edge edge, Direction direction) {
  final Map<String, TLongSet> edgeIds = new THashMap<>();
  switch (direction) {
    case IN:
      edgeIds.put(Direction.IN.name(), new TLongHashSet(Arrays.asList((long) edge.inVertex().id())));
      break;
    case OUT:
      edgeIds.put(Direction.OUT.name(), new TLongHashSet(Arrays.asList((long) edge.outVertex().id())));
      break;
    default: throw new NotImplementedException();
  }
  return edgeIds;
}
 
Example #25
Source File: MaskedSource.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private TLongSet scaleBlocksToLevel(final TLongSet blocks, final int blocksLevel, final int targetLevel)
{
	if (blocksLevel == targetLevel) { return blocks; }

	final CellGrid grid          = this.dataCanvases[blocksLevel].getCellGrid();
	final CellGrid targetGrid    = this.dataCanvases[targetLevel].getCellGrid();
	final double[] toTargetScale = DataSource.getRelativeScales(this, 0, blocksLevel, targetLevel);
	return org.janelia.saalfeldlab.util.grids.Grids.getRelevantBlocksInTargetGrid(
			blocks.toArray(),
			grid,
			targetGrid,
			toTargetScale
	);
}
 
Example #26
Source File: JDAImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Set<String> getUnavailableGuilds()
{
    TLongSet unavailableGuilds = guildSetupController.getUnavailableGuilds();
    Set<String> copy = new HashSet<>();
    unavailableGuilds.forEach(id -> copy.add(Long.toUnsignedString(id)));
    return copy;
}
 
Example #27
Source File: IdSelector.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private void selectAllInCurrentViewPrimitiveType(final ViewerPanelFX viewer, final TLongSet idsInCurrentView)
{
	VisitEveryDisplayPixel.visitEveryDisplayPixel(
			source,
			viewer,
			val -> {
				final long id = val.getIntegerLong();
				if (foregroundCheck.test(id))
					idsInCurrentView.add(id);
			}
		);
}
 
Example #28
Source File: IdSelector.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public void selectAllInCurrentView(final ViewerPanelFX viewer)
{
	final TLongSet idsInCurrentView = new TLongHashSet();
	if (source.getDataType() instanceof LabelMultisetType)
		selectAllInCurrentViewLabelMultisetType(viewer, idsInCurrentView);
	else
		selectAllInCurrentViewPrimitiveType(viewer, idsInCurrentView);
	LOG.debug("Collected {} ids in current view", idsInCurrentView.size());
	selectedIds.activate(idsInCurrentView.toArray());
}
 
Example #29
Source File: IdSelector.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private void selectAllPrimitiveType(final TLongSet allIds)
{
	// TODO: run the operation in separate thread and allow to cancel it
	LOG.warn("Label data is stored as primitive type, looping over full resolution data to collect all ids -- SLOW");
	final RandomAccessibleInterval<? extends IntegerType<?>> data = source.getDataSource(0, 0);
	final Cursor<? extends IntegerType<?>> cursor = Views.iterable(data).cursor();
	while (cursor.hasNext())
	{
		final long id = cursor.next().getIntegerLong();
		if (foregroundCheck.test(id))
			allIds.add(id);
	}
}
 
Example #30
Source File: IdSelector.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public void selectAll()
{
	final TLongSet allIds = new TLongHashSet();
	if (source.getDataType() instanceof LabelMultisetType)
		selectAllLabelMultisetType(allIds);
	else
		selectAllPrimitiveType(allIds);
	LOG.debug("Collected {} ids", allIds.size());
	selectedIds.activate(allIds.toArray());
}