cube.c 23.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/******************************************************************************
  This file contains routines that can be bound to a Postgres backend and
  called by the backend in the process of processing queries.  The calling
  format for these routines is dictated by Postgres architecture.
******************************************************************************/

#include "postgres.h"

#include <math.h>

#include "access/gist.h"
#include "access/rtree.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "utils/builtins.h"

#include "cubedata.h"

B
Bruce Momjian 已提交
19 20 21
#define max(a,b)		((a) >	(b) ? (a) : (b))
#define min(a,b)		((a) <= (b) ? (a) : (b))
#define abs(a)			((a) <	(0) ? (-a) : (a))
22

B
Bruce Momjian 已提交
23 24
extern void set_parse_buffer(char *str);
extern int	cube_yyparse();
25 26 27 28

/*
** Input/Output routines
*/
B
Bruce Momjian 已提交
29 30
NDBOX	   *cube_in(char *str);
char	   *cube_out(NDBOX * cube);
31 32


B
Bruce Momjian 已提交
33
/*
34 35
** GiST support methods
*/
B
Bruce Momjian 已提交
36 37 38 39 40 41 42 43 44 45
bool		g_cube_consistent(GISTENTRY *entry, NDBOX * query, StrategyNumber strategy);
GISTENTRY  *g_cube_compress(GISTENTRY *entry);
GISTENTRY  *g_cube_decompress(GISTENTRY *entry);
float	   *g_cube_penalty(GISTENTRY *origentry, GISTENTRY *newentry, float *result);
GIST_SPLITVEC *g_cube_picksplit(bytea *entryvec, GIST_SPLITVEC *v);
bool		g_cube_leaf_consistent(NDBOX * key, NDBOX * query, StrategyNumber strategy);
bool		g_cube_internal_consistent(NDBOX * key, NDBOX * query, StrategyNumber strategy);
NDBOX	   *g_cube_union(bytea *entryvec, int *sizep);
NDBOX	   *g_cube_binary_union(NDBOX * r1, NDBOX * r2, int *sizep);
bool	   *g_cube_same(NDBOX * b1, NDBOX * b2, bool *result);
46 47 48 49

/*
** R-tree suport functions
*/
B
Bruce Momjian 已提交
50 51 52 53 54 55 56 57 58
bool		cube_same(NDBOX * a, NDBOX * b);
bool		cube_different(NDBOX * a, NDBOX * b);
bool		cube_contains(NDBOX * a, NDBOX * b);
bool		cube_contained(NDBOX * a, NDBOX * b);
bool		cube_overlap(NDBOX * a, NDBOX * b);
NDBOX	   *cube_union(NDBOX * a, NDBOX * b);
NDBOX	   *cube_inter(NDBOX * a, NDBOX * b);
float	   *cube_size(NDBOX * a);
void		rt_cube_size(NDBOX * a, float *sz);
59 60 61 62

/*
** These make no sense for this type, but R-tree wants them
*/
B
Bruce Momjian 已提交
63 64 65 66
bool		cube_over_left(NDBOX * a, NDBOX * b);
bool		cube_over_right(NDBOX * a, NDBOX * b);
bool		cube_left(NDBOX * a, NDBOX * b);
bool		cube_right(NDBOX * a, NDBOX * b);
67 68 69 70

/*
** miscellaneous
*/
B
Bruce Momjian 已提交
71 72 73
bool		cube_lt(NDBOX * a, NDBOX * b);
bool		cube_gt(NDBOX * a, NDBOX * b);
float	   *cube_distance(NDBOX * a, NDBOX * b);
74

B
Bruce Momjian 已提交
75
/*
76 77
** Auxiliary funxtions
*/
B
Bruce Momjian 已提交
78 79
static float distance_1D(float a1, float a2, float b1, float b2);
static NDBOX *swap_corners(NDBOX * a);
80 81 82 83 84 85 86 87 88 89 90


/*****************************************************************************
 * Input/Output functions
 *****************************************************************************/

/* NdBox = [(lowerleft),(upperright)] */
/* [(xLL(1)...xLL(N)),(xUR(1)...xUR(n))] */
NDBOX *
cube_in(char *str)
{
B
Bruce Momjian 已提交
91
	void	   *result;
92

B
Bruce Momjian 已提交
93
	set_parse_buffer(str);
94

B
Bruce Momjian 已提交
95 96
	if (cube_yyparse(&result) != 0)
		return NULL;
97

B
Bruce Momjian 已提交
98
	return ((NDBOX *) result);
99 100 101 102 103
}

/*
 * You might have noticed a slight inconsistency between the following
 * declaration and the SQL definition:
B
Bruce Momjian 已提交
104
 *	   CREATE FUNCTION cube_out(opaque) RETURNS opaque ...
105 106
 * The reason is that the argument pass into cube_out is really just a
 * pointer. POSTGRES thinks all output functions are:
B
Bruce Momjian 已提交
107
 *	   char *out_func(char *);
108 109
 */
char *
B
Bruce Momjian 已提交
110
cube_out(NDBOX * cube)
111
{
B
Bruce Momjian 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	char	   *result;
	char	   *p;
	int			equal = 1;
	int			dim = cube->dim;
	int			i;

	if (cube == NULL)
		return (NULL);

	p = result = (char *) palloc(100);

	/*
	 * while printing the first (LL) corner, check if it is equal to the
	 * scond one
	 */
	p += sprintf(p, "(");
	for (i = 0; i < dim; i++)
	{
		p += sprintf(p, "%g", cube->x[i]);
		p += sprintf(p, ", ");
		if (cube->x[i] != cube->x[i + dim])
			equal = 0;
	}
	p -= 2;						/* get rid of the last ", " */
	p += sprintf(p, ")");

	if (!equal)
	{
		p += sprintf(p, ",(");
		for (i = dim; i < dim * 2; i++)
		{
			p += sprintf(p, "%g", cube->x[i]);
			p += sprintf(p, ", ");
		}
		p -= 2;
		p += sprintf(p, ")");
	}

	return (result);
151 152 153 154
}


/*****************************************************************************
B
Bruce Momjian 已提交
155
 *						   GiST functions
156 157 158 159 160 161 162 163
 *****************************************************************************/

/*
** The GiST Consistent method for boxes
** Should return false if for all data items x below entry,
** the predicate x op query == FALSE, where op is the oper
** corresponding to strategy in the pg_amop table.
*/
B
Bruce Momjian 已提交
164
bool
165
g_cube_consistent(GISTENTRY *entry,
B
Bruce Momjian 已提交
166 167
				  NDBOX * query,
				  StrategyNumber strategy)
168
{
B
Bruce Momjian 已提交
169 170 171 172 173 174 175 176 177

	/*
	 * * if entry is not leaf, use g_cube_internal_consistent, * else use
	 * g_cube_leaf_consistent
	 */
	if (GIST_LEAF(entry))
		return (g_cube_leaf_consistent((NDBOX *) (entry->pred), query, strategy));
	else
		return (g_cube_internal_consistent((NDBOX *) (entry->pred), query, strategy));
178 179 180 181 182 183 184 185 186 187
}


/*
** The GiST Union method for boxes
** returns the minimal bounding box that encloses all the entries in entryvec
*/
NDBOX *
g_cube_union(bytea *entryvec, int *sizep)
{
B
Bruce Momjian 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
	int			numranges,
				i;
	NDBOX	   *out = (NDBOX *) NULL;
	NDBOX	   *tmp;

	/*
	 * fprintf(stderr, "union\n");
	 */
	numranges = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
	tmp = (NDBOX *) (((GISTENTRY *) (VARDATA(entryvec)))[0]).pred;

	/*
	 * sizep = sizeof(NDBOX); -- NDBOX has variable size
	 */
	*sizep = tmp->size;

	for (i = 1; i < numranges; i++)
	{
		out = g_cube_binary_union(tmp, (NDBOX *)
						   (((GISTENTRY *) (VARDATA(entryvec)))[i]).pred,
								  sizep);

		/*
		 * fprintf(stderr, "\t%s ^ %s -> %s\n", cube_out(tmp),
		 * cube_out((NDBOX *)(((GISTENTRY
		 * *)(VARDATA(entryvec)))[i]).pred), cube_out(out));
		 */
		if (i > 1)
			pfree(tmp);
		tmp = out;
	}

	return (out);
221 222 223 224 225 226
}

/*
** GiST Compress and Decompress methods for boxes
** do not do anything.
*/
B
Bruce Momjian 已提交
227
GISTENTRY  *
228 229
g_cube_compress(GISTENTRY *entry)
{
B
Bruce Momjian 已提交
230
	return (entry);
231 232
}

B
Bruce Momjian 已提交
233
GISTENTRY  *
234 235
g_cube_decompress(GISTENTRY *entry)
{
B
Bruce Momjian 已提交
236
	return (entry);
237 238 239 240 241 242 243 244 245
}

/*
** The GiST Penalty method for boxes
** As in the R-tree paper, we use change in area as our penalty metric
*/
float *
g_cube_penalty(GISTENTRY *origentry, GISTENTRY *newentry, float *result)
{
B
Bruce Momjian 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259
	Datum		ud;
	float		tmp1,
				tmp2;

	ud = (Datum) cube_union((NDBOX *) (origentry->pred), (NDBOX *) (newentry->pred));
	rt_cube_size((NDBOX *) ud, &tmp1);
	rt_cube_size((NDBOX *) (origentry->pred), &tmp2);
	*result = tmp1 - tmp2;
	pfree((char *) ud);

	/*
	 * fprintf(stderr, "penalty\n"); fprintf(stderr, "\t%g\n", *result);
	 */
	return (result);
260 261 262 263 264 265
}



/*
** The GiST PickSplit method for boxes
B
Bruce Momjian 已提交
266
** We use Guttman's poly time split algorithm
267 268 269
*/
GIST_SPLITVEC *
g_cube_picksplit(bytea *entryvec,
B
Bruce Momjian 已提交
270
				 GIST_SPLITVEC *v)
271
{
B
Bruce Momjian 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
	OffsetNumber i,
				j;
	NDBOX	   *datum_alpha,
			   *datum_beta;
	NDBOX	   *datum_l,
			   *datum_r;
	NDBOX	   *union_d,
			   *union_dl,
			   *union_dr;
	NDBOX	   *inter_d;
	bool		firsttime;
	float		size_alpha,
				size_beta,
				size_union,
				size_inter;
	float		size_waste,
				waste;
	float		size_l,
				size_r;
	int			nbytes;
	OffsetNumber seed_1 = 0,
				seed_2 = 0;
	OffsetNumber *left,
			   *right;
	OffsetNumber maxoff;

298
	/*
B
Bruce Momjian 已提交
299
	 * fprintf(stderr, "picksplit\n");
300
	 */
B
Bruce Momjian 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
	maxoff = ((VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY)) - 2;
	nbytes = (maxoff + 2) * sizeof(OffsetNumber);
	v->spl_left = (OffsetNumber *) palloc(nbytes);
	v->spl_right = (OffsetNumber *) palloc(nbytes);

	firsttime = true;
	waste = 0.0;

	for (i = FirstOffsetNumber; i < maxoff; i = OffsetNumberNext(i))
	{
		datum_alpha = (NDBOX *) (((GISTENTRY *) (VARDATA(entryvec)))[i].pred);
		for (j = OffsetNumberNext(i); j <= maxoff; j = OffsetNumberNext(j))
		{
			datum_beta = (NDBOX *) (((GISTENTRY *) (VARDATA(entryvec)))[j].pred);

			/* compute the wasted space by unioning these guys */
			/* size_waste = size_union - size_inter; */
			union_d = (NDBOX *) cube_union(datum_alpha, datum_beta);
			rt_cube_size(union_d, &size_union);
			inter_d = (NDBOX *) cube_inter(datum_alpha, datum_beta);
			rt_cube_size(inter_d, &size_inter);
			size_waste = size_union - size_inter;

			pfree(union_d);

			if (inter_d != (NDBOX *) NULL)
				pfree(inter_d);

			/*
			 * are these a more promising split than what we've already
			 * seen?
			 */

			if (size_waste > waste || firsttime)
			{
				waste = size_waste;
				seed_1 = i;
				seed_2 = j;
				firsttime = false;
			}
		}
342
	}
B
Bruce Momjian 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

	left = v->spl_left;
	v->spl_nleft = 0;
	right = v->spl_right;
	v->spl_nright = 0;

	datum_alpha = (NDBOX *) (((GISTENTRY *) (VARDATA(entryvec)))[seed_1].pred);
	datum_l = (NDBOX *) cube_union(datum_alpha, datum_alpha);
	rt_cube_size((NDBOX *) datum_l, &size_l);
	datum_beta = (NDBOX *) (((GISTENTRY *) (VARDATA(entryvec)))[seed_2].pred);;
	datum_r = (NDBOX *) cube_union(datum_beta, datum_beta);
	rt_cube_size((NDBOX *) datum_r, &size_r);

	/*
	 * Now split up the regions between the two seeds.	An important
	 * property of this split algorithm is that the split vector v has the
	 * indices of items to be split in order in its left and right
	 * vectors.  We exploit this property by doing a merge in the code
	 * that actually splits the page.
	 *
	 * For efficiency, we also place the new index tuple in this loop. This
	 * is handled at the very end, when we have placed all the existing
	 * tuples and i == maxoff + 1.
	 */

	maxoff = OffsetNumberNext(maxoff);
	for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
	{

		/*
		 * If we've already decided where to place this item, just put it
		 * on the right list.  Otherwise, we need to figure out which page
		 * needs the least enlargement in order to store the item.
		 */

		if (i == seed_1)
		{
			*left++ = i;
			v->spl_nleft++;
			continue;
		}
		else if (i == seed_2)
		{
			*right++ = i;
			v->spl_nright++;
			continue;
		}

		/* okay, which page needs least enlargement? */
		datum_alpha = (NDBOX *) (((GISTENTRY *) (VARDATA(entryvec)))[i].pred);
		union_dl = (NDBOX *) cube_union(datum_l, datum_alpha);
		union_dr = (NDBOX *) cube_union(datum_r, datum_alpha);
		rt_cube_size((NDBOX *) union_dl, &size_alpha);
		rt_cube_size((NDBOX *) union_dr, &size_beta);

		/* pick which page to add it to */
		if (size_alpha - size_l < size_beta - size_r)
		{
			pfree(datum_l);
			pfree(union_dr);
			datum_l = union_dl;
			size_l = size_alpha;
			*left++ = i;
			v->spl_nleft++;
		}
		else
		{
			pfree(datum_r);
			pfree(union_dl);
			datum_r = union_dr;
			size_r = size_alpha;
			*right++ = i;
			v->spl_nright++;
		}
417
	}
B
Bruce Momjian 已提交
418
	*left = *right = FirstOffsetNumber; /* sentinel value, see dosplit() */
419

B
Bruce Momjian 已提交
420 421 422 423
	v->spl_ldatum = (char *) datum_l;
	v->spl_rdatum = (char *) datum_r;

	return v;
424 425 426 427 428 429
}

/*
** Equality method
*/
bool *
B
Bruce Momjian 已提交
430
g_cube_same(NDBOX * b1, NDBOX * b2, bool *result)
431
{
B
Bruce Momjian 已提交
432 433 434 435 436 437 438 439 440
	if (cube_same(b1, b2))
		*result = TRUE;
	else
		*result = FALSE;

	/*
	 * fprintf(stderr, "same: %s\n", (*result ? "TRUE" : "FALSE" ));
	 */
	return (result);
441 442
}

B
Bruce Momjian 已提交
443
/*
444 445
** SUPPORT ROUTINES
*/
B
Bruce Momjian 已提交
446 447 448 449
bool
g_cube_leaf_consistent(NDBOX * key,
					   NDBOX * query,
					   StrategyNumber strategy)
450
{
B
Bruce Momjian 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
	bool		retval;

	/*
	 * fprintf(stderr, "leaf_consistent, %d\n", strategy);
	 */
	switch (strategy)
	{
		case RTLeftStrategyNumber:
			retval = (bool) cube_left(key, query);
			break;
		case RTOverLeftStrategyNumber:
			retval = (bool) cube_over_left(key, query);
			break;
		case RTOverlapStrategyNumber:
			retval = (bool) cube_overlap(key, query);
			break;
		case RTOverRightStrategyNumber:
			retval = (bool) cube_over_right(key, query);
			break;
		case RTRightStrategyNumber:
			retval = (bool) cube_right(key, query);
			break;
		case RTSameStrategyNumber:
			retval = (bool) cube_same(key, query);
			break;
		case RTContainsStrategyNumber:
			retval = (bool) cube_contains(key, query);
			break;
		case RTContainedByStrategyNumber:
			retval = (bool) cube_contained(key, query);
			break;
		default:
			retval = FALSE;
	}
	return (retval);
486 487
}

B
Bruce Momjian 已提交
488 489 490 491
bool
g_cube_internal_consistent(NDBOX * key,
						   NDBOX * query,
						   StrategyNumber strategy)
492
{
B
Bruce Momjian 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
	bool		retval;

	/*
	 * fprintf(stderr, "internal_consistent, %d\n", strategy);
	 */
	switch (strategy)
	{
		case RTLeftStrategyNumber:
		case RTOverLeftStrategyNumber:
			retval = (bool) cube_over_left(key, query);
			break;
		case RTOverlapStrategyNumber:
			retval = (bool) cube_overlap(key, query);
			break;
		case RTOverRightStrategyNumber:
		case RTRightStrategyNumber:
			retval = (bool) cube_right(key, query);
			break;
		case RTSameStrategyNumber:
		case RTContainsStrategyNumber:
			retval = (bool) cube_contains(key, query);
			break;
		case RTContainedByStrategyNumber:
			retval = (bool) cube_overlap(key, query);
			break;
		default:
			retval = FALSE;
	}
	return (retval);
522 523 524
}

NDBOX *
B
Bruce Momjian 已提交
525
g_cube_binary_union(NDBOX * r1, NDBOX * r2, int *sizep)
526
{
B
Bruce Momjian 已提交
527
	NDBOX	   *retval;
528

B
Bruce Momjian 已提交
529 530
	retval = cube_union(r1, r2);
	*sizep = retval->size;
531

B
Bruce Momjian 已提交
532
	return (retval);
533 534 535 536
}


/* cube_union */
B
Bruce Momjian 已提交
537 538
NDBOX *
cube_union(NDBOX * box_a, NDBOX * box_b)
539
{
B
Bruce Momjian 已提交
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
	int			i;
	NDBOX	   *result;
	NDBOX	   *a = swap_corners(box_a);
	NDBOX	   *b = swap_corners(box_b);

	if (a->dim >= b->dim)
	{
		result = palloc(a->size);
		result->size = a->size;
		result->dim = a->dim;
	}
	else
	{
		result = palloc(b->size);
		result->size = b->size;
		result->dim = b->dim;
	}

	/* swap the box pointers if needed */
	if (a->dim < b->dim)
	{
		NDBOX	   *tmp = b;

		b = a;
		a = tmp;
	}

	/*
	 * use the potentially smaller of the two boxes (b) to fill in the
	 * result, padding absent dimensions with zeroes
	 */
	for (i = 0; i < b->dim; i++)
	{
		result->x[i] = b->x[i];
		result->x[i + a->dim] = b->x[i + b->dim];
	}
	for (i = b->dim; i < a->dim; i++)
	{
		result->x[i] = 0;
		result->x[i + a->dim] = 0;
	}

	/* compute the union */
	for (i = 0; i < a->dim; i++)
		result->x[i] = min(a->x[i], result->x[i]);
	for (i = a->dim; i < a->dim * 2; i++)
		result->x[i] = max(a->x[i], result->x[i]);

	pfree(a);
	pfree(b);

	return (result);
592 593 594
}

/* cube_inter */
B
Bruce Momjian 已提交
595 596
NDBOX *
cube_inter(NDBOX * box_a, NDBOX * box_b)
597
{
B
Bruce Momjian 已提交
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
	int			i;
	NDBOX	   *result;
	NDBOX	   *a = swap_corners(box_a);
	NDBOX	   *b = swap_corners(box_b);

	if (a->dim >= b->dim)
	{
		result = palloc(a->size);
		result->size = a->size;
		result->dim = a->dim;
	}
	else
	{
		result = palloc(b->size);
		result->size = b->size;
		result->dim = b->dim;
	}

	/* swap the box pointers if needed */
	if (a->dim < b->dim)
	{
		NDBOX	   *tmp = b;

		b = a;
		a = tmp;
	}

	/*
	 * use the potentially	smaller of the two boxes (b) to fill in the
	 * result, padding absent dimensions with zeroes
	 */
	for (i = 0; i < b->dim; i++)
	{
		result->x[i] = b->x[i];
		result->x[i + a->dim] = b->x[i + b->dim];
	}
	for (i = b->dim; i < a->dim; i++)
	{
		result->x[i] = 0;
		result->x[i + a->dim] = 0;
	}

	/* compute the intersection */
	for (i = 0; i < a->dim; i++)
		result->x[i] = max(a->x[i], result->x[i]);
	for (i = a->dim; i < a->dim * 2; i++)
		result->x[i] = min(a->x[i], result->x[i]);

	pfree(a);
	pfree(b);

	/*
	 * Is it OK to return a non-null intersection for non-overlapping
	 * boxes?
	 */
	return (result);
654 655 656
}

/* cube_size */
B
Bruce Momjian 已提交
657 658
float *
cube_size(NDBOX * a)
659
{
B
Bruce Momjian 已提交
660 661 662 663 664 665 666 667 668 669 670
	int			i,
				j;
	float	   *result;

	result = (float *) palloc(sizeof(float));

	*result = 1.0;
	for (i = 0, j = a->dim; i < a->dim; i++, j++)
		*result = (*result) * abs((a->x[j] - a->x[i]));

	return (result);
671 672 673
}

void
B
Bruce Momjian 已提交
674
rt_cube_size(NDBOX * a, float *size)
675
{
B
Bruce Momjian 已提交
676 677 678 679 680 681 682 683 684 685 686 687
	int			i,
				j;

	if (a == (NDBOX *) NULL)
		*size = 0.0;
	else
	{
		*size = 1.0;
		for (i = 0, j = a->dim; i < a->dim; i++, j++)
			*size = (*size) * abs((a->x[j] - a->x[i]));
	}
	return;
688 689 690 691 692 693 694
}

/* The following four methods compare the projections of the boxes
   onto the 0-th coordinate axis. These methods are useless for dimensions
   larger than 2, but it seems that R-tree requires all its strategies
   map to real functions that return something */

B
Bruce Momjian 已提交
695 696 697 698
/*	is the right edge of (a) located to the left of
	the right edge of (b)? */
bool
cube_over_left(NDBOX * box_a, NDBOX * box_b)
699
{
B
Bruce Momjian 已提交
700 701 702 703 704
	NDBOX	   *a;
	NDBOX	   *b;

	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);
705

B
Bruce Momjian 已提交
706 707
	a = swap_corners(box_a);
	b = swap_corners(box_b);
708

B
Bruce Momjian 已提交
709
	return (a->x[a->dim - 1] <= b->x[b->dim - 1] && !cube_left(a, b) && !cube_right(a, b));
710 711
}

B
Bruce Momjian 已提交
712 713 714 715
/*	is the left edge of (a) located to the right of
	the left edge of (b)? */
bool
cube_over_right(NDBOX * box_a, NDBOX * box_b)
716
{
B
Bruce Momjian 已提交
717 718
	NDBOX	   *a;
	NDBOX	   *b;
719

B
Bruce Momjian 已提交
720 721
	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);
722

B
Bruce Momjian 已提交
723 724 725 726
	a = swap_corners(box_a);
	b = swap_corners(box_b);

	return (a->x[a->dim - 1] >= b->x[b->dim - 1] && !cube_left(a, b) && !cube_right(a, b));
727 728 729 730 731
}


/* return 'true' if the projection of 'a' is
   entirely on the left of the projection of 'b' */
B
Bruce Momjian 已提交
732 733
bool
cube_left(NDBOX * box_a, NDBOX * box_b)
734
{
B
Bruce Momjian 已提交
735 736 737 738 739
	NDBOX	   *a;
	NDBOX	   *b;

	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);
740

B
Bruce Momjian 已提交
741 742
	a = swap_corners(box_a);
	b = swap_corners(box_b);
743

B
Bruce Momjian 已提交
744
	return (a->x[a->dim - 1] < b->x[0]);
745 746 747 748
}

/* return 'true' if the projection of 'a' is
   entirely on the right  of the projection of 'b' */
B
Bruce Momjian 已提交
749 750
bool
cube_right(NDBOX * box_a, NDBOX * box_b)
751
{
B
Bruce Momjian 已提交
752 753
	NDBOX	   *a;
	NDBOX	   *b;
754

B
Bruce Momjian 已提交
755 756
	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);
757

B
Bruce Momjian 已提交
758 759 760 761
	a = swap_corners(box_a);
	b = swap_corners(box_b);

	return (a->x[0] > b->x[b->dim - 1]);
762 763 764 765
}

/* make up a metric in which one box will be 'lower' than the other
   -- this can be useful for srting and to determine uniqueness */
B
Bruce Momjian 已提交
766 767
bool
cube_lt(NDBOX * box_a, NDBOX * box_b)
768
{
B
Bruce Momjian 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
	int			i;
	int			dim;
	NDBOX	   *a;
	NDBOX	   *b;

	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);

	a = swap_corners(box_a);
	b = swap_corners(box_b);
	dim = min(a->dim, b->dim);

	/*
	 * if all common dimensions are equal, the cube with more dimensions
	 * wins
	 */
	if (cube_same(a, b))
	{
		if (a->dim < b->dim)
			return (TRUE);
		else
			return (FALSE);
	}

	/* compare the common dimensions */
	for (i = 0; i < dim; i++)
	{
		if (a->x[i] > b->x[i])
			return (FALSE);
		if (a->x[i] < b->x[i])
			return (TRUE);
	}
	for (i = 0; i < dim; i++)
	{
		if (a->x[i + a->dim] > b->x[i + b->dim])
			return (FALSE);
		if (a->x[i + a->dim] < b->x[i + b->dim])
			return (TRUE);
	}

	/* compare extra dimensions to zero */
	if (a->dim > b->dim)
	{
		for (i = dim; i < a->dim; i++)
		{
			if (a->x[i] > 0)
				return (FALSE);
			if (a->x[i] < 0)
				return (TRUE);
		}
		for (i = 0; i < dim; i++)
		{
			if (a->x[i + a->dim] > 0)
				return (FALSE);
			if (a->x[i + a->dim] < 0)
				return (TRUE);
		}
	}
	if (a->dim < b->dim)
	{
		for (i = dim; i < b->dim; i++)
		{
			if (b->x[i] > 0)
				return (TRUE);
			if (b->x[i] < 0)
				return (FALSE);
		}
		for (i = 0; i < dim; i++)
		{
			if (b->x[i + b->dim] > 0)
				return (TRUE);
			if (b->x[i + b->dim] < 0)
				return (FALSE);
		}
	}

	return (FALSE);
846 847 848
}


B
Bruce Momjian 已提交
849 850
bool
cube_gt(NDBOX * box_a, NDBOX * box_b)
851
{
B
Bruce Momjian 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
	int			i;
	int			dim;
	NDBOX	   *a;
	NDBOX	   *b;

	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);

	a = swap_corners(box_a);
	b = swap_corners(box_b);
	dim = min(a->dim, b->dim);

	/*
	 * if all common dimensions are equal, the cube with more dimensions
	 * wins
	 */
	if (cube_same(a, b))
	{
		if (a->dim > b->dim)
			return (TRUE);
		else
			return (FALSE);
	}

	/* compare the common dimensions */
	for (i = 0; i < dim; i++)
	{
		if (a->x[i] < b->x[i])
			return (FALSE);
		if (a->x[i] > b->x[i])
			return (TRUE);
	}
	for (i = 0; i < dim; i++)
	{
		if (a->x[i + a->dim] < b->x[i + b->dim])
			return (FALSE);
		if (a->x[i + a->dim] > b->x[i + b->dim])
			return (TRUE);
	}


	/* compare extra dimensions to zero */
	if (a->dim > b->dim)
	{
		for (i = dim; i < a->dim; i++)
		{
			if (a->x[i] < 0)
				return (FALSE);
			if (a->x[i] > 0)
				return (TRUE);
		}
		for (i = 0; i < dim; i++)
		{
			if (a->x[i + a->dim] < 0)
				return (FALSE);
			if (a->x[i + a->dim] > 0)
				return (TRUE);
		}
	}
	if (a->dim < b->dim)
	{
		for (i = dim; i < b->dim; i++)
		{
			if (b->x[i] < 0)
				return (TRUE);
			if (b->x[i] > 0)
				return (FALSE);
		}
		for (i = 0; i < dim; i++)
		{
			if (b->x[i + b->dim] < 0)
				return (TRUE);
			if (b->x[i + b->dim] > 0)
				return (FALSE);
		}
	}

	return (FALSE);
930 931 932 933
}


/* Equal */
B
Bruce Momjian 已提交
934 935
bool
cube_same(NDBOX * box_a, NDBOX * box_b)
936
{
B
Bruce Momjian 已提交
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
	int			i;
	NDBOX	   *a;
	NDBOX	   *b;

	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);

	a = swap_corners(box_a);
	b = swap_corners(box_b);

	/* swap the box pointers if necessary */
	if (a->dim < b->dim)
	{
		NDBOX	   *tmp = b;

		b = a;
		a = tmp;
	}

	for (i = 0; i < b->dim; i++)
	{
		if (a->x[i] != b->x[i])
			return (FALSE);
		if (a->x[i + a->dim] != b->x[i + b->dim])
			return (FALSE);
	}

	/*
	 * all dimensions of (b) are compared to those of (a); instead of
	 * those in (a) absent in (b), compare (a) to zero
	 */
	for (i = b->dim; i < a->dim; i++)
	{
		if (a->x[i] != 0)
			return (FALSE);
		if (a->x[i + a->dim] != 0)
			return (FALSE);
	}

	pfree(a);
	pfree(b);

	return (TRUE);
980 981 982
}

/* Different */
B
Bruce Momjian 已提交
983 984
bool
cube_different(NDBOX * box_a, NDBOX * box_b)
985
{
B
Bruce Momjian 已提交
986
	return (!cube_same(box_a, box_b));
987 988 989 990 991
}


/* Contains */
/* Box(A) CONTAINS Box(B) IFF pt(A) < pt(B) */
B
Bruce Momjian 已提交
992 993
bool
cube_contains(NDBOX * box_a, NDBOX * box_b)
994
{
B
Bruce Momjian 已提交
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	int			i;
	NDBOX	   *a;
	NDBOX	   *b;

	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);

	a = swap_corners(box_a);
	b = swap_corners(box_b);

	if (a->dim < b->dim)
	{

		/*
		 * the further comparisons will make sense if the excess
		 * dimensions of (b) were zeroes
		 */
		for (i = a->dim; i < b->dim; i++)
		{
			if (b->x[i] != 0)
				return (FALSE);
			if (b->x[i + b->dim] != 0)
				return (FALSE);
		}
	}

	/* Can't care less about the excess dimensions of (a), if any */
	for (i = 0; i < min(a->dim, b->dim); i++)
	{
		if (a->x[i] > b->x[i])
			return (FALSE);
		if (a->x[i + a->dim] < b->x[i + b->dim])
			return (FALSE);
	}

	pfree(a);
	pfree(b);

	return (TRUE);
1034 1035 1036 1037
}

/* Contained */
/* Box(A) Contained by Box(B) IFF Box(B) Contains Box(A) */
B
Bruce Momjian 已提交
1038 1039
bool
cube_contained(NDBOX * a, NDBOX * b)
1040
{
B
Bruce Momjian 已提交
1041 1042 1043 1044
	if (cube_contains(b, a) == TRUE)
		return (TRUE);
	else
		return (FALSE);
1045 1046 1047 1048
}

/* Overlap */
/* Box(A) Overlap Box(B) IFF (pt(a)LL < pt(B)UR) && (pt(b)LL < pt(a)UR) */
B
Bruce Momjian 已提交
1049 1050
bool
cube_overlap(NDBOX * box_a, NDBOX * box_b)
1051
{
B
Bruce Momjian 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
	int			i;
	NDBOX	   *a;
	NDBOX	   *b;

	/*
	 * This *very bad* error was found in the source: if ( (a==NULL) ||
	 * (b=NULL) ) return(FALSE);
	 */
	if ((box_a == NULL) || (box_b == NULL))
		return (FALSE);

	a = swap_corners(box_a);
	b = swap_corners(box_b);

	/* swap the box pointers if needed */
	if (a->dim < b->dim)
	{
		NDBOX	   *tmp = b;

		b = a;
		a = tmp;
	}

	/* compare within the dimensions of (b) */
	for (i = 0; i < b->dim; i++)
	{
		if (a->x[i] > b->x[i + b->dim])
			return (FALSE);
		if (a->x[i + a->dim] < b->x[i])
			return (FALSE);
	}

	/* compare to zero those dimensions in (a) absent in (b) */
	for (i = b->dim; i < a->dim; i++)
	{
		if (a->x[i] > 0)
			return (FALSE);
		if (a->x[i + a->dim] < 0)
			return (FALSE);
	}

	pfree(a);
	pfree(b);

	return (TRUE);
1097 1098 1099 1100 1101
}


/* Distance */
/* The distance is computed as a per axis sum of the squared distances
B
Bruce Momjian 已提交
1102 1103
   between 1D projections of the boxes onto Cartesian axes. Assuming zero
   distance between overlapping projections, this metric coincides with the
1104
   "common sense" geometric distance */
B
Bruce Momjian 已提交
1105 1106
float *
cube_distance(NDBOX * a, NDBOX * b)
1107
{
B
Bruce Momjian 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
	int			i;
	double		d,
				distance;
	float	   *result;

	result = (float *) palloc(sizeof(float));

	/* swap the box pointers if needed */
	if (a->dim < b->dim)
	{
		NDBOX	   *tmp = b;

		b = a;
		a = tmp;
	}

	distance = 0.0;
	/* compute within the dimensions of (b) */
	for (i = 0; i < b->dim; i++)
	{
		d = distance_1D(a->x[i], a->x[i + a->dim], b->x[i], b->x[i + b->dim]);
		distance += d * d;
	}

	/* compute distance to zero for those dimensions in (a) absent in (b) */
	for (i = b->dim; i < a->dim; i++)
	{
		d = distance_1D(a->x[i], a->x[i + a->dim], 0.0, 0.0);
		distance += d * d;
	}

	*result = (float) sqrt(distance);

	return (result);
1142 1143
}

B
Bruce Momjian 已提交
1144 1145
static float
distance_1D(float a1, float a2, float b1, float b2)
1146
{
B
Bruce Momjian 已提交
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
	/* interval (a) is entirely on the left of (b) */
	if ((a1 <= b1) && (a2 <= b1) && (a1 <= b2) && (a2 <= b2))
		return (min(b1, b2) - max(a1, a2));

	/* interval (a) is entirely on the right of (b) */
	if ((a1 > b1) && (a2 > b1) && (a1 > b2) && (a2 > b2))
		return (min(a1, a2) - max(b1, b2));

	/* the rest are all sorts of intersections */
	return (0.0);
1157 1158 1159
}

/* normalize the box's co-ordinates by placing min(xLL,xUR) to LL
B
Bruce Momjian 已提交
1160
   and max(xLL,xUR) to UR
1161
*/
B
Bruce Momjian 已提交
1162 1163
static NDBOX *
swap_corners(NDBOX * a)
1164
{
B
Bruce Momjian 已提交
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
	int			i,
				j;
	NDBOX	   *result;

	result = palloc(a->size);
	result->size = a->size;
	result->dim = a->dim;

	for (i = 0, j = a->dim; i < a->dim; i++, j++)
	{
		result->x[i] = min(a->x[i], a->x[j]);
		result->x[j] = max(a->x[i], a->x[j]);
	}

	return (result);
1180
}