Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small Refactoring #194

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/main/java/com/github/davidmoten/rtree/Backpressure.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,19 @@ private static <T, S extends Geometry> StackAndRequest<NodePosition<T, S>> searc
final Func1<? super Geometry, Boolean> condition,
final Subscriber<? super Entry<T, S>> subscriber,
StackAndRequest<NodePosition<T, S>> state, NodePosition<T, S> np) {
final long nextRequest=getNextRequest(condition, subscriber, state, np);
return StackAndRequest.create(state.stack.pop().push(np.nextPosition()), nextRequest);
}

private static <T, S extends Geometry> long getNextRequest(Func1<? super Geometry, Boolean> condition, Subscriber<? super Entry<T, S>> subscriber, StackAndRequest<NodePosition<T, S>> state, NodePosition<T, S> np) {
final long nextRequest;
Entry<T, S> entry = ((Leaf<T, S>) np.node()).entry(np.position());
if (condition.call(entry.geometry())) {
subscriber.onNext(entry);
nextRequest = state.request - 1;
} else
nextRequest = state.request;
return StackAndRequest.create(state.stack.pop().push(np.nextPosition()), nextRequest);
return nextRequest;
}

private static <S extends Geometry, T> ImmutableStack<NodePosition<T, S>> searchNonLeaf(
Expand Down
36 changes: 23 additions & 13 deletions src/main/java/com/github/davidmoten/rtree/RTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -378,12 +378,7 @@ private <T, S extends Geometry> RTree<T, S> packingSTR(List<? extends HasGeometr
if (nodeCount == 0) {
return create();
} else if (nodeCount == 1) {
Node<T, S> root;
if (isLeaf) {
root = context.factory().createLeaf((List<Entry<T, S>>) objects, context);
} else {
root = context.factory().createNonLeaf((List<Node<T, S>>) objects, context);
}
Node<T, S> root=getTsNode(objects, isLeaf, context);
return new RTree<T, S>(of(root), size, context);
}

Expand Down Expand Up @@ -416,6 +411,16 @@ private <T, S extends Geometry> RTree<T, S> packingSTR(List<? extends HasGeometr
return packingSTR(nodes, false, size, context);
}

private <T, S extends Geometry> Node<T, S> getTsNode(List<? extends HasGeometry> objects, boolean isLeaf, Context<T, S> context) {
Node<T, S> root;
if (isLeaf) {
root = context.factory().createLeaf((List<Entry<T, S>>) objects, context);
} else {
root = context.factory().createNonLeaf((List<Node<T, S>>) objects, context);
}
return root;
}

private static final class MidComparator implements Comparator<HasGeometry> {
private final short dimension; // leave space for multiple dimensions, 0 for x, 1 for y,
// ...
Expand Down Expand Up @@ -450,13 +455,7 @@ private double mid(HasGeometry o) {
@SuppressWarnings("unchecked")
public RTree<T, S> add(Entry<? extends T, ? extends S> entry) {
if (root.isPresent()) {
List<Node<T, S>> nodes = root.get().add(entry);
Node<T, S> node;
if (nodes.size() == 1)
node = nodes.get(0);
else {
node = context.factory().createNonLeaf(nodes, context);
}
Node<T, S> node=getTsNode(entry);
return new RTree<T, S>(node, size + 1, context);
} else {
Leaf<T, S> node = context.factory().createLeaf(Lists.newArrayList((Entry<T, S>) entry),
Expand All @@ -465,6 +464,17 @@ public RTree<T, S> add(Entry<? extends T, ? extends S> entry) {
}
}

private Node<T, S> getTsNode(Entry<? extends T, ? extends S> entry) {
List<Node<T, S>> nodes = root.get().add(entry);
Node<T, S> node;
if (nodes.size() == 1)
node = nodes.get(0);
else {
node = context.factory().createNonLeaf(nodes, context);
}
return node;
}

/**
* Returns an immutable copy of the RTree with the addition of an entry
* comprised of the given value and Geometry.
Expand Down
16 changes: 3 additions & 13 deletions src/main/java/com/github/davidmoten/rtree/Serializers.java
Original file line number Diff line number Diff line change
Expand Up @@ -163,22 +163,14 @@ private static Func1<Serializable, byte[]> javaIoSerializer() {
@Override
public byte[] call(Serializable o) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(bytes);
try (ObjectOutputStream oos=new ObjectOutputStream(bytes)) {
oos.writeObject(o);
oos.close();
return bytes.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
// ignore
}
}
// ignore
}
};
}
Expand All @@ -192,9 +184,7 @@ public Serializable call(byte[] bytes) {
try {
ois = new ObjectInputStream(is);
return (Serializable) ois.readObject();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (ois != null)
Expand Down
14 changes: 12 additions & 2 deletions src/main/java/com/github/davidmoten/rtree/SplitterRStar.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,24 @@ public <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize) {
// compute S the sum of all margin-values of the lists above
// the list with the least S is then used to find minimum overlap

List<ListPair<T>> pairs=getListPairs(items, minSize);
return Collections.min(pairs, comparator);
}

private <T extends HasGeometry> List<ListPair<T>> getListPairs(List<T> items, int minSize) {
List<ListPair<T>> pairs = null;
double lowestMarginSum = Double.POSITIVE_INFINITY;
List<T> list = null;
pairs=getListPairs(items, minSize, pairs, lowestMarginSum, list);
return pairs;
}

private <T extends HasGeometry> List<ListPair<T>> getListPairs(List<T> items, int minSize, List<ListPair<T>> pairs, double lowestMarginSum, List<T> list) {
for (SortType sortType : SortType.values()) {
if (list == null) {
list = new ArrayList<T>(items);
}
Collections.sort(list, comparator(sortType));
list.sort(comparator(sortType));
List<ListPair<T>> p = getPairs(minSize, list);
double marginSum = marginValueSum(p);
if (marginSum <= lowestMarginSum) {
Expand All @@ -57,7 +67,7 @@ public <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize) {
list = null;
}
}
return Collections.min(pairs, comparator);
return pairs;
}

private static Comparator<HasGeometry> comparator(SortType sortType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,7 @@ private static <T, S extends Geometry> void searchWithoutBackpressure(Node_ node
{
// write bounds from node to bounds variable
node.mbb(bounds);
final Rectangle rect;
if (bounds.type() == BoundsType_.BoundsDouble) {
BoxDouble_ b = bounds.boxDouble();
rect = Geometries.rectangle(b.minX(), b.minY(), b.maxX(), b.maxY());
} else {
BoxFloat_ b = bounds.boxFloat();
rect = Geometries.rectangle(b.minX(), b.minY(), b.maxX(), b.maxY());
}
final Rectangle rect=getRectangle(bounds);
if (!criterion.call(rect)) {
return;
}
Expand Down Expand Up @@ -117,6 +110,18 @@ private static <T, S extends Geometry> void searchWithoutBackpressure(Node_ node

}

private static Rectangle getRectangle(Bounds_ bounds) {
final Rectangle rect;
if (bounds.type() == BoundsType_.BoundsDouble) {
BoxDouble_ b = bounds.boxDouble();
rect = Geometries.rectangle(b.minX(), b.minY(), b.maxX(), b.maxY());
} else {
BoxFloat_ b = bounds.boxFloat();
rect = Geometries.rectangle(b.minX(), b.minY(), b.maxX(), b.maxY());
}
return rect;
}

private List<Node<T, S>> createChildren() {

// reduce allocations by resusing objects
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,7 @@ public static <T, S extends Geometry> Serializer<T, S> create(
@Override
public void write(RTree<T, S> tree, OutputStream os) throws IOException {
FlatBufferBuilder builder = new FlatBufferBuilder();
final Rectangle mbb;
if (tree.root().isPresent()) {
mbb = tree.root().get().geometry().mbr();
} else {
mbb = Geometries.rectangle(0, 0, 0, 0);
}
final Rectangle mbb=getRectangle(tree);
int b = toBounds(builder, mbb);
Context_.startContext_(builder);
Context_.addBounds(builder, b);
Expand Down Expand Up @@ -86,6 +81,16 @@ public void write(RTree<T, S> tree, OutputStream os) throws IOException {
os.write(bb.array(), bb.position(), bb.remaining());
}

private Rectangle getRectangle(RTree<T, S> tree) {
final Rectangle mbb;
if (tree.root().isPresent()) {
mbb = tree.root().get().geometry().mbr();
} else {
mbb = Geometries.rectangle(0, 0, 0, 0);
}
return mbb;
}

private static int toBounds(FlatBufferBuilder builder, final Rectangle r) {
Bounds_.startBounds_(builder);
if (r.isDoublePrecision()) {
Expand Down Expand Up @@ -134,18 +139,23 @@ public RTree<T, S> read(InputStream is, long sizeBytes, InternalStructure struct
if (node == null) {
return SerializerHelper.create(Optional.empty(), 0, context);
} else {
final Node<T, S> root;
if (structure == InternalStructure.SINGLE_ARRAY) {
if (node.childrenLength() > 0) {
root = new NonLeafFlatBuffers<T, S>(node, context, factory.deserializer());
} else {
root = new LeafFlatBuffers<T, S>(node, context, factory.deserializer());
}
final Node<T, S> root=getTsNode(structure, context, node);
return SerializerHelper.create(Optional.of(root), (int) t.size(), context);
}
}

private Node<T, S> getTsNode(InternalStructure structure, Context<T, S> context, Node_ node) {
final Node<T, S> root;
if (structure == InternalStructure.SINGLE_ARRAY) {
if (node.childrenLength() > 0) {
root = new NonLeafFlatBuffers<T, S>(node, context, factory.deserializer());
} else {
root = toNodeDefault(node, context, factory.deserializer());
root = new LeafFlatBuffers<T, S>(node, context, factory.deserializer());
}
return SerializerHelper.create(Optional.of(root), (int) t.size(), context);
} else {
root = toNodeDefault(node, context, factory.deserializer());
}
return root;
}

private static <T, S extends Geometry> Node<T, S> toNodeDefault(Node_ node,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,23 @@ public static <T, S extends Geometry> NodeAndEntries<T, S> delete(
List<Node<T, S>> addTheseNodes = new ArrayList<Node<T, S>>();
int countDeleted = 0;
List<? extends Node<T, S>> children = node.children();
countDeleted=getCountDeleted(entry, all, addTheseEntries, removeTheseNodes, addTheseNodes, countDeleted, children);
if (removeTheseNodes.isEmpty())
return new NodeAndEntries<>(of(node), Collections.emptyList(), 0);
else {
List<Node<T, S>> nodes = Util.remove(children, removeTheseNodes);
nodes.addAll(addTheseNodes);
if (nodes.isEmpty())
return new NodeAndEntries<>(Optional.empty(), addTheseEntries,
countDeleted);
else {
NonLeaf<T, S> nd = node.context().factory().createNonLeaf(nodes, node.context());
return new NodeAndEntries<>(of(nd), addTheseEntries, countDeleted);
}
}
}

private static <T, S extends Geometry> int getCountDeleted(Entry<? extends T, ? extends S> entry, boolean all, List<Entry<T, S>> addTheseEntries, List<Node<T, S>> removeTheseNodes, List<Node<T, S>> addTheseNodes, int countDeleted, List<? extends Node<T, S>> children) {
for (final Node<T, S> child : children) {
if (entry.geometry().intersects(child.geometry().mbr())) {
final NodeAndEntries<T, S> result = child.delete(entry, all);
Expand All @@ -105,19 +122,7 @@ public static <T, S extends Geometry> NodeAndEntries<T, S> delete(
}
}
}
if (removeTheseNodes.isEmpty())
return new NodeAndEntries<>(of(node), Collections.emptyList(), 0);
else {
List<Node<T, S>> nodes = Util.remove(children, removeTheseNodes);
nodes.addAll(addTheseNodes);
if (nodes.isEmpty())
return new NodeAndEntries<>(Optional.empty(), addTheseEntries,
countDeleted);
else {
NonLeaf<T, S> nd = node.context().factory().createNonLeaf(nodes, node.context());
return new NodeAndEntries<>(of(nd), addTheseEntries, countDeleted);
}
}
return countDeleted;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -60,24 +60,26 @@ private static boolean _rectangleIntersectsLine(double rectX, double rectY, doub
return false;
}
if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
double x = rectX;
if ((out1 & OUT_RIGHT) != 0) {
x += rectWidth;
}
double x=getX(rectX, rectWidth, out1, OUT_RIGHT);
y1 = y1 + (x - x1) * (y2 - y1) / (x2 - x1);
x1 = x;
} else {
double y = rectY;
if ((out1 & OUT_BOTTOM) != 0) {
y += rectHeight;
}
double y=getX(rectY, rectHeight, out1, OUT_BOTTOM);
x1 = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
y1 = y;
}
}
return true;
}

private static double getX(double rectX, double rectWidth, int out1, int outRight) {
double x=rectX;
if ((out1 & outRight) != 0) {
x+=rectWidth;
}
return x;
}

private static boolean rectangleCornerOnSegment(double rectX, double rectY, double rectWidth,
double rectHeight, double x1, double y1, double x2, double y2) {
if (pointOnSegment(rectX, rectY, x1, y1, x2, y2)) {
Expand Down