package org.apache.lucene.spatial.prefix.tree;
import java.text.ParseException;
import org.locationtech.spatial4j.context.SpatialContext;
import org.locationtech.spatial4j.context.SpatialContextFactory;
import org.locationtech.spatial4j.shape.Point;
import org.locationtech.spatial4j.shape.Rectangle;
import org.locationtech.spatial4j.shape.Shape;
import org.locationtech.spatial4j.shape.SpatialRelation;
import org.locationtech.spatial4j.shape.impl.RectangleImpl;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.StringHelper;
public abstract class NumberRangePrefixTree extends SpatialPrefixTree {
private static final SpatialContext DUMMY_CTX;
static {
SpatialContextFactory factory = new SpatialContextFactory();
factory.geo = false;
factory.worldBounds = new RectangleImpl(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 0L, 0L, null);
DUMMY_CTX = factory.newSpatialContext();
}
public static interface NRShape extends Shape, Cloneable {
abstract String toString();
public NRShape roundToLevel(int targetLevel);
}
public abstract UnitNRShape toUnitShape(Object value);
public NRShape toRangeShape(UnitNRShape startUnit, UnitNRShape endUnit) {
startUnit = startUnit.getShapeAtLevel(truncateStartVals(startUnit, 0));
endUnit = endUnit.getShapeAtLevel(truncateEndVals(endUnit, 0));
int cmp = comparePrefix(startUnit, endUnit);
if (cmp > 0) {
throw new IllegalArgumentException("Wrong order: "+ startUnit +" TO "+ endUnit);
}
if (cmp == 0) {
if (startUnit.getLevel() == endUnit.getLevel()) {
return startUnit;
} else if (endUnit.getLevel() > startUnit.getLevel()) {
if (truncateStartVals(endUnit, startUnit.getLevel()) == startUnit.getLevel()) {
return endUnit;
}
} else {
if (truncateEndVals(startUnit, endUnit.getLevel()) == endUnit.getLevel()) {
return startUnit;
}
}
}
return new SpanUnitsNRShape(startUnit, endUnit);
}
private int truncateStartVals(UnitNRShape lv, int endLevel) {
for (int level = lv.getLevel(); level > endLevel; level--) {
if (lv.getValAtLevel(level) != 0)
return level;
}
return endLevel;
}
private int truncateEndVals(UnitNRShape lv, int endLevel) {
for (int level = lv.getLevel(); level > endLevel; level--) {
int max = getNumSubCells(lv.getShapeAtLevel(level - 1)) - 1;
if (lv.getValAtLevel(level) != max)
return level;
}
return endLevel;
}
public abstract Object toObject(UnitNRShape shape);
protected abstract String toString(UnitNRShape lv);
protected static String toStringUnitRaw(UnitNRShape lv) {
StringBuilder buf = new StringBuilder(100);
buf.append('[');
for (int level = 1; level <= lv.getLevel(); level++) {
buf.append(lv.getValAtLevel(level)).append(',');
}
buf.setLength(buf.length()-1);
buf.append(']');
return buf.toString();
}
public NRShape parseShape(String str) throws ParseException {
if (str == null || str.isEmpty())
throw new IllegalArgumentException("str is null or blank");
if (str.charAt(0) == '[') {
if (str.charAt(str.length()-1) != ']')
throw new ParseException("If starts with [ must end with ]; got "+str, str.length()-1);
int middle = str.indexOf(" TO ");
if (middle < 0)
throw new ParseException("If starts with [ must contain ' TO '; got "+str, -1);
String leftStr = str.substring(1, middle);
String rightStr = str.substring(middle + " TO ".length(), str.length()-1);
return toRangeShape(parseUnitShape(leftStr), parseUnitShape(rightStr));
} else if (str.charAt(0) == '{') {
throw new ParseException("Exclusive ranges not supported; got "+str, 0);
} else {
return parseUnitShape(str);
}
}
protected abstract UnitNRShape parseUnitShape(String str) throws ParseException;
public static interface UnitNRShape extends NRShape, Comparable<UnitNRShape> {
int getLevel();
int getValAtLevel(int level);
UnitNRShape getShapeAtLevel(int level);
@Override
UnitNRShape roundToLevel(int targetLevel);
UnitNRShape clone();
}
protected static int comparePrefix(UnitNRShape a, UnitNRShape b) {
int minLevel = Math.min(a.getLevel(), b.getLevel());
for (int level = 1; level <= minLevel; level++) {
int diff = a.getValAtLevel(level) - b.getValAtLevel(level);
if (diff != 0)
return diff;
}
return 0;
}
public class SpanUnitsNRShape implements NRShape {
private final UnitNRShape minLV, maxLV;
private final int lastLevelInCommon;
private SpanUnitsNRShape(UnitNRShape minLV, UnitNRShape maxLV) {
this.minLV = minLV;
this.maxLV = maxLV;
int level = 1;
for (; level <= minLV.getLevel() && level <= maxLV.getLevel(); level++) {
if (minLV.getValAtLevel(level) != maxLV.getValAtLevel(level))
break;
}
lastLevelInCommon = level - 1;
}
@Override
public SpatialContext getContext() {
return DUMMY_CTX;
}
public UnitNRShape getMinUnit() { return minLV; }
public UnitNRShape getMaxUnit() { return maxLV; }
private int getLevelsInCommon() { return lastLevelInCommon; }
@Override
public NRShape roundToLevel(int targetLevel) {
return toRangeShape(minLV.roundToLevel(targetLevel), maxLV.roundToLevel(targetLevel));
}
@Override
public SpatialRelation relate(Shape shape) {
if (shape instanceof SpanUnitsNRShape)
return relate((SpanUnitsNRShape) shape);
return shape.relate(this).transpose();
}
public SpatialRelation relate(SpanUnitsNRShape ext) {
int extMin_intMax = comparePrefix(ext.getMinUnit(), getMaxUnit());
if (extMin_intMax > 0)
return SpatialRelation.DISJOINT;
int extMax_intMin = comparePrefix(ext.getMaxUnit(), getMinUnit());
if (extMax_intMin < 0)
return SpatialRelation.DISJOINT;
int extMin_intMin = comparePrefix(ext.getMinUnit(), getMinUnit());
int extMax_intMax = comparePrefix(ext.getMaxUnit(), getMaxUnit());
if ((extMin_intMin > 0 || extMin_intMin == 0 && ext.getMinUnit().getLevel() >= getMinUnit().getLevel())
&& (extMax_intMax < 0 || extMax_intMax == 0 && ext.getMaxUnit().getLevel() >= getMaxUnit().getLevel()))
return SpatialRelation.CONTAINS;
if ((extMin_intMin < 0 || extMin_intMin == 0 && ext.getMinUnit().getLevel() <= getMinUnit().getLevel())
&& (extMax_intMax > 0 || extMax_intMax == 0 && ext.getMaxUnit().getLevel() <= getMaxUnit().getLevel()))
return SpatialRelation.WITHIN;
return SpatialRelation.INTERSECTS;
}
@Override
public Rectangle getBoundingBox() { throw new UnsupportedOperationException(); }
@Override
public boolean hasArea() { return true; }
@Override
public double getArea(SpatialContext spatialContext) { throw new UnsupportedOperationException(); }
@Override
public Point getCenter() { throw new UnsupportedOperationException(); }
@Override
public Shape getBuffered(double v, SpatialContext spatialContext) { throw new UnsupportedOperationException(); }
@Override
public boolean isEmpty() { return false; }
@Override
public SpanUnitsNRShape clone() {
return new SpanUnitsNRShape(minLV.clone(), maxLV.clone());
}
@Override
public String toString() {
return "[" + NumberRangePrefixTree.this.toString(minLV) + " TO "
+ NumberRangePrefixTree.this.toString(maxLV) + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpanUnitsNRShape spanShape = (SpanUnitsNRShape) o;
if (!maxLV.equals(spanShape.maxLV)) return false;
if (!minLV.equals(spanShape.minLV)) return false;
return true;
}
@Override
public int hashCode() {
int result = minLV.hashCode();
result = 31 * result + maxLV.hashCode();
return result;
}
}
protected final int[] maxSubCellsByLevel;
protected final int[] termLenByLevel;
protected final int[] levelByTermLen;
protected final int maxTermLen;
protected NumberRangePrefixTree(int[] maxSubCellsByLevel) {
super(DUMMY_CTX, maxSubCellsByLevel.length);
this.maxSubCellsByLevel = maxSubCellsByLevel;
this.termLenByLevel = new int[maxLevels + 1];
termLenByLevel[0] = 0;
final int MAX_STATES = 1 << 15;
for (int level = 1; level <= maxLevels; level++) {
final int states = maxSubCellsByLevel[level - 1];
if (states >= MAX_STATES || states <= 1) {
throw new IllegalArgumentException("Max states is "+MAX_STATES+", given "+states+" at level "+level);
}
boolean twoBytes = states >= 256;
termLenByLevel[level] = termLenByLevel[level-1] + (twoBytes ? 2 : 1);
}
maxTermLen = termLenByLevel[maxLevels] + 1;
levelByTermLen = new int[maxTermLen];
levelByTermLen[0] = 0;
for (int level = 1; level < termLenByLevel.length; level++) {
int termLen = termLenByLevel[level];
int prevTermLen = termLenByLevel[level-1];
if (termLen - prevTermLen == 2) {
levelByTermLen[termLen-1] = -1;
levelByTermLen[termLen] = level;
} else {
assert termLen - prevTermLen == 1;
levelByTermLen[termLen] = level;
}
}
}
@Override
public String toString() {
return getClass().getSimpleName();
}
@Override
public int getLevelForDistance(double dist) {
return maxLevels;
}
@Override
public double getDistanceForLevel(int level) {
throw new UnsupportedOperationException("Not applicable.");
}
protected UnitNRShape toShape(int[] valStack, int len) {
final NRCell[] cellStack = newCellStack(len);
for (int i = 0; i < len; i++) {
cellStack[i+1].resetCellWithCellNum(valStack[i]);
}
return cellStack[len];
}
@Override
public Cell getWorldCell() {
return newCellStack(maxLevels)[0];
}
protected NRCell[] newCellStack(int levels) {
final NRCell[] cellsByLevel = new NRCell[levels + 1];
final BytesRef term = new BytesRef(maxTermLen);
for (int level = 0; level <= levels; level++) {
cellsByLevel[level] = new NRCell(cellsByLevel,term,level);
}
return cellsByLevel;
}
@Override
public Cell readCell(BytesRef term, Cell scratch) {
if (scratch == null)
scratch = getWorldCell();
NRCell[] cellsByLevel = ((NRCell) scratch).cellsByLevel;
boolean isLeaf = term.bytes[term.offset + term.length - 1] == 0;
int lenNoLeaf = isLeaf ? term.length - 1 : term.length;
NRCell result = cellsByLevel[levelByTermLen[lenNoLeaf]];
if (cellsByLevel[0].termBuf == null)
cellsByLevel[0].termBuf = result.term.bytes;
result.term.bytes = term.bytes;
result.term.offset = term.offset;
result.term.length = lenNoLeaf;
result.reset();
if (isLeaf)
result.setLeaf();
result.cellNumber = -1;
return result;
}
public int getNumSubCells(UnitNRShape lv) {
return maxSubCellsByLevel[lv.getLevel()];
}
protected class NRCell extends CellIterator implements Cell, UnitNRShape {
final NRCell[] cellsByLevel;
final BytesRef term;
byte[] termBuf;
final int cellLevel;
int cellNumber;
SpatialRelation cellShapeRel;
boolean cellIsLeaf;
NRCell(NRCell[] cellsByLevel, BytesRef term, int cellLevel) {
this.cellsByLevel = cellsByLevel;
this.term = term;
this.cellLevel = cellLevel;
this.cellNumber = cellLevel == 0 ? 0 : -1;
this.cellIsLeaf = false;
assert cellsByLevel[cellLevel] == null;
}
void ensureOwnTermBytes() {
NRCell cell0 = cellsByLevel[0];
if (cell0.termBuf == null)
return;
System.arraycopy(term.bytes, term.offset, cell0.termBuf, 0, term.length);
term.bytes = cell0.termBuf;
term.offset = 0;
cell0.termBuf = null;
}
private void reset() {
this.cellIsLeaf = false;
this.cellShapeRel = null;
}
private void resetCellWithCellNum(int cellNumber) {
reset();
if (cellNumber >= 0) {
ensureOwnTermBytes();
int termLen = termLenByLevel[getLevel()];
boolean twoBytes = (termLen - termLenByLevel[getLevel()-1]) > 1;
if (twoBytes) {
term.bytes[termLen-2] = (byte) (cellNumber >> 7);
term.bytes[termLen-1] = (byte) ((cellNumber & 0x7F) + 1);
} else {
term.bytes[termLen-1] = (byte) (cellNumber+1);
}
assert term.bytes[termLen-1] != 0;
term.length = termLen;
}
this.cellNumber = cellNumber;
}
private void ensureDecoded() {
if (cellNumber >= 0)
return;
for (int level = 1; level <= getLevel(); level++) {
NRCell cell = cellsByLevel[level];
int termLen = termLenByLevel[level];
boolean twoBytes = (termLen - termLenByLevel[level-1]) > 1;
if (twoBytes) {
int byteH = (term.bytes[term.offset + termLen - 2] & 0xFF);
int byteL = (term.bytes[term.offset + termLen - 1] & 0xFF);
assert byteL - 1 < (1<<7);
cell.cellNumber = (byteH << 7) + (byteL-1);
assert cell.cellNumber < 1<<15;
} else {
cell.cellNumber = (term.bytes[term.offset + termLen - 1] & 0xFF) - 1;
assert cell.cellNumber < 255;
}
cell.assertDecoded();
}
}
private void assertDecoded() {
assert cellNumber >= 0 : "Illegal state; ensureDecoded() wasn't called";
}
@Override
public int getLevel() {
return cellLevel;
}
@Override
public SpatialRelation getShapeRel() {
return cellShapeRel;
}
@Override
public void setShapeRel(SpatialRelation rel) {
cellShapeRel = rel;
}
@Override
public boolean isLeaf() {
return cellIsLeaf;
}
@Override
public void setLeaf() {
cellIsLeaf = true;
}
@Override
public UnitNRShape getShape() {
ensureDecoded();
return this;
}
@Override
public BytesRef getTokenBytesNoLeaf(BytesRef result) {
if (result == null)
result = new BytesRef();
result.bytes = term.bytes;
result.offset = term.offset;
result.length = termLenByLevel[cellLevel];
assert result.length <= term.length;
return result;
}
@Override
public BytesRef getTokenBytesWithLeaf(BytesRef result) {
ensureOwnTermBytes();
result = getTokenBytesNoLeaf(result);
if (isLeaf()) {
result.bytes[result.length++] = 0;
}
return result;
}
@Override
public boolean isPrefixOf(Cell c) {
NRCell otherCell = (NRCell) c;
assert term != otherCell.term;
int myLastLen = term.length;
term.length = termLenByLevel[getLevel()];
int otherLastLen = otherCell.term.length;
otherCell.term.length = termLenByLevel[otherCell.getLevel()];
boolean answer = StringHelper.startsWith(otherCell.term, term);
term.length = myLastLen;
otherCell.term.length = otherLastLen;
return answer;
}
@Override
public int compareToNoLeaf(Cell fromCell) {
final NRCell nrCell = (NRCell) fromCell;
assert term != nrCell.term;
int myLastLen = term.length;
int otherLastLen = nrCell.term.length;
term.length = termLenByLevel[getLevel()];
nrCell.term.length = termLenByLevel[nrCell.getLevel()];
int answer = term.compareTo(nrCell.term);
term.length = myLastLen;
nrCell.term.length = otherLastLen;
return answer;
}
@Override
public CellIterator getNextLevelCells(Shape shapeFilter) {
ensureDecoded();
NRCell subCell = cellsByLevel[cellLevel + 1];
subCell.initIter(shapeFilter);
return subCell;
}
Shape iterFilter;
boolean iterFirstIsIntersects;
boolean iterLastIsIntersects;
int iterFirstCellNumber;
int iterLastCellNumber;
private void initIter(Shape filter) {
cellNumber = -1;
if (filter instanceof UnitNRShape && ((UnitNRShape) filter).getLevel() == 0)
filter = null;
iterFilter = filter;
NRCell parent = getShapeAtLevel(getLevel() - 1);
if (filter == null) {
iterFirstCellNumber = 0;
iterFirstIsIntersects = false;
iterLastCellNumber = getNumSubCells(parent) - 1;
iterLastIsIntersects = false;
return;
}
final UnitNRShape minLV;
final UnitNRShape maxLV;
final int lastLevelInCommon;
if (filter instanceof SpanUnitsNRShape) {
SpanUnitsNRShape spanShape = (SpanUnitsNRShape) iterFilter;
minLV = spanShape.getMinUnit();
maxLV = spanShape.getMaxUnit();
lastLevelInCommon = spanShape.getLevelsInCommon();
} else {
minLV = (UnitNRShape) iterFilter;
maxLV = minLV;
lastLevelInCommon = minLV.getLevel();
}
if (iterFilter == parent.iterFilter &&
(getLevel() <= lastLevelInCommon || parent.iterFirstCellNumber != parent.iterLastCellNumber)) {
if (parent.iterFirstIsIntersects && parent.cellNumber == parent.iterFirstCellNumber
&& minLV.getLevel() >= getLevel()) {
iterFirstCellNumber = minLV.getValAtLevel(getLevel());
iterFirstIsIntersects = (minLV.getLevel() > getLevel());
} else {
iterFirstCellNumber = 0;
iterFirstIsIntersects = false;
}
if (parent.iterLastIsIntersects && parent.cellNumber == parent.iterLastCellNumber
&& maxLV.getLevel() >= getLevel()) {
iterLastCellNumber = maxLV.getValAtLevel(getLevel());
iterLastIsIntersects = (maxLV.getLevel() > getLevel());
} else {
iterLastCellNumber = getNumSubCells(parent) - 1;
iterLastIsIntersects = false;
}
if (iterFirstCellNumber == iterLastCellNumber) {
if (iterLastIsIntersects)
iterFirstIsIntersects = true;
else if (iterFirstIsIntersects)
iterLastIsIntersects = true;
}
return;
}
int startCmp = comparePrefix(minLV, parent);
if (startCmp > 0) {
iterFirstCellNumber = 0;
iterFirstIsIntersects = false;
iterLastCellNumber = -1;
iterLastIsIntersects = false;
return;
}
int endCmp = comparePrefix(maxLV, parent);
if (endCmp < 0) {
iterFirstCellNumber = 0;
iterFirstIsIntersects = false;
iterLastCellNumber = -1;
iterLastIsIntersects = false;
return;
}
if (startCmp < 0 || minLV.getLevel() < getLevel()) {
iterFirstCellNumber = 0;
iterFirstIsIntersects = false;
} else {
iterFirstCellNumber = minLV.getValAtLevel(getLevel());
iterFirstIsIntersects = (minLV.getLevel() > getLevel());
}
if (endCmp > 0 || maxLV.getLevel() < getLevel()) {
iterLastCellNumber = getNumSubCells(parent) - 1;
iterLastIsIntersects = false;
} else {
iterLastCellNumber = maxLV.getValAtLevel(getLevel());
iterLastIsIntersects = (maxLV.getLevel() > getLevel());
}
if (iterFirstCellNumber == iterLastCellNumber) {
if (iterLastIsIntersects)
iterFirstIsIntersects = true;
else if (iterFirstIsIntersects)
iterLastIsIntersects = true;
}
}
@Override
public boolean hasNext() {
thisCell = null;
if (nextCell != null)
return true;
if (cellNumber >= iterLastCellNumber)
return false;
resetCellWithCellNum(cellNumber < iterFirstCellNumber ? iterFirstCellNumber : cellNumber + 1);
boolean hasChildren =
(cellNumber == iterFirstCellNumber && iterFirstIsIntersects)
|| (cellNumber == iterLastCellNumber && iterLastIsIntersects);
if (!hasChildren) {
setLeaf();
setShapeRel(SpatialRelation.WITHIN);
} else if (iterFirstCellNumber == iterLastCellNumber) {
setShapeRel(SpatialRelation.CONTAINS);
} else {
setShapeRel(SpatialRelation.INTERSECTS);
}
nextCell = this;
return true;
}
@Override
public int getValAtLevel(int level) {
final int result = cellsByLevel[level].cellNumber;
assert result >= 0;
return result;
}
@Override
public NRCell getShapeAtLevel(int level) {
assert level <= cellLevel;
return cellsByLevel[level];
}
@Override
public UnitNRShape roundToLevel(int targetLevel) {
if (getLevel() <= targetLevel) {
return this;
} else {
return getShapeAtLevel(targetLevel);
}
}
@Override
public SpatialRelation relate(Shape shape) {
assertDecoded();
if (shape == iterFilter && cellShapeRel != null)
return cellShapeRel;
if (shape instanceof UnitNRShape)
return relate((UnitNRShape)shape);
if (shape instanceof SpanUnitsNRShape)
return relate((SpanUnitsNRShape)shape);
return shape.relate(this).transpose();
}
public SpatialRelation relate(UnitNRShape lv) {
assertDecoded();
int cmp = comparePrefix(this, lv);
if (cmp != 0)
return SpatialRelation.DISJOINT;
if (getLevel() > lv.getLevel())
return SpatialRelation.WITHIN;
return SpatialRelation.CONTAINS;
}
public SpatialRelation relate(SpanUnitsNRShape spanShape) {
assertDecoded();
int startCmp = comparePrefix(spanShape.getMinUnit(), this);
if (startCmp > 0) {
return SpatialRelation.DISJOINT;
}
int endCmp = comparePrefix(spanShape.getMaxUnit(), this);
if (endCmp < 0) {
return SpatialRelation.DISJOINT;
}
int nrMinLevel = spanShape.getMinUnit().getLevel();
int nrMaxLevel = spanShape.getMaxUnit().getLevel();
if ((startCmp < 0 || startCmp == 0 && nrMinLevel <= getLevel())
&& (endCmp > 0 || endCmp == 0 && nrMaxLevel <= getLevel()))
return SpatialRelation.WITHIN;
if (startCmp != 0 || endCmp != 0)
return SpatialRelation.INTERSECTS;
for (;nrMinLevel < getLevel(); nrMinLevel++) {
if (getValAtLevel(nrMinLevel + 1) != 0)
return SpatialRelation.INTERSECTS;
}
for (;nrMaxLevel < getLevel(); nrMaxLevel++) {
if (getValAtLevel(nrMaxLevel + 1) != getNumSubCells(getShapeAtLevel(nrMaxLevel)) - 1)
return SpatialRelation.INTERSECTS;
}
return SpatialRelation.CONTAINS;
}
@Override
public UnitNRShape clone() {
NRCell cell = (NRCell) readCell(getTokenBytesNoLeaf(null), null);
cell.ensureOwnTermBytes();
return cell.getShape();
}
@Override
public int compareTo(UnitNRShape o) {
assertDecoded();
int cmp = comparePrefix(this, o);
if (cmp != 0) {
return cmp;
} else {
return getLevel() - o.getLevel();
}
}
@Override
public Rectangle getBoundingBox() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasArea() {
return true;
}
@Override
public double getArea(SpatialContext ctx) {
throw new UnsupportedOperationException();
}
@Override
public Point getCenter() {
throw new UnsupportedOperationException();
}
@Override
public Shape getBuffered(double distance, SpatialContext ctx) { throw new UnsupportedOperationException(); }
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof NRCell)) {
return false;
}
if (this == obj)
return true;
NRCell nrCell = (NRCell) obj;
assert term != nrCell.term;
if (getLevel() != nrCell.getLevel())
return false;
int myLastLen = term.length;
int otherLastLen = nrCell.term.length;
boolean answer = getTokenBytesNoLeaf(term).equals(nrCell.getTokenBytesNoLeaf(nrCell.term));
term.length = myLastLen;
nrCell.term.length = otherLastLen;
return answer;
}
@Override
public SpatialContext getContext() {
return DUMMY_CTX;
}
@Override
public int hashCode() {
int myLastLen = term.length;
int result = getTokenBytesNoLeaf(term).hashCode();
term.length = myLastLen;
return result;
}
@Override
public String toString() {
return NumberRangePrefixTree.this.toString(getShape());
}
public String toStringDebug() {
String pretty = toString();
if (getLevel() == 0)
return pretty;
return toStringUnitRaw(this) + (isLeaf() ? "•" : "") + " " + pretty;
}
}
}