_reg_blockMatching.cpp 37.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 *  _reg_blockMatching.cpp
 *  
 *
 *  Created by Marc Modat and Pankaj Daga on 24/03/2009.
 *  Copyright (c) 2009, University College London. All rights reserved.
 *  Centre for Medical Image Computing (CMIC)
 *  See the LICENSE.txt file in the nifty_reg root folder
 *
 */

#include "_reg_blockMatching.h"
#include "_reg_affineTransformation.h"
#include <queue>
#include <iostream>

// Helper function: Get the square of the Euclidean distance
double get_square_distance(float * first_point3D, float * second_point3D)
{
20
	return 	sqrt((first_point3D[0]-second_point3D[0])*(first_point3D[0]-second_point3D[0]) +
21
		(first_point3D[1]-second_point3D[1])*(first_point3D[1]-second_point3D[1]) +
22
		(first_point3D[2]-second_point3D[2])*(first_point3D[2]-second_point3D[2]));
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
}

// Heap sort
void reg_heapSort(float *array_tmp, int *index_tmp, int blockNum)
{
	float *array = &array_tmp[-1];
	int *index = &index_tmp[-1];
	int l=(blockNum >> 1)+1;
	int ir=blockNum;
	float val;
	int iVal;
	for(;;){
		if(l>1){
			val=array[--l];
			iVal=index[l];
		}
		else{
			val=array[ir];
			iVal=index[ir];
			array[ir]=array[1];
			index[ir]=index[1];
			if(--ir == 1){
				array[1]=val;
				index[1]=iVal;
				break;
			}
		}
		int i=l;
		int j=l+l;
		while(j<=ir){
			if(j<ir && array[j]<array[j+1]) j++;
			if(val<array[j]){
				array[i]=array[j];
				index[i]=index[j];
				i=j;
				j<<=1;
			}
			else break;
		}
		array[i]=val;
		index[i]=iVal;
	}
}

template <class DTYPE>
68
void _reg_set_active_blocks(nifti_image *targetImage, _reg_blockMatchingParam *params, int *mask, bool runningOnGPU)
69 70 71
{
	const int totalBlockNumber = params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2];
	float *varianceArray=(float *)malloc(totalBlockNumber*sizeof(float));
72 73 74
    int *indexArray=(int *)malloc(totalBlockNumber*sizeof(int));

    int *maskPtr=&mask[0];
75 76

	int unusableBlock=0;
77
    int index;
78

79
    DTYPE *targetValues = (DTYPE *)malloc(BLOCK_SIZE * sizeof(DTYPE));
80
	DTYPE *targetPtr = static_cast<DTYPE *>(targetImage->data);
81
	int blockIndex=0;
82 83 84 85
	for(int k=0; k<params->blockNumber[2]; k++){
		for(int j=0; j<params->blockNumber[1]; j++){
			for(int i=0; i<params->blockNumber[0]; i++){

86
                memset(targetValues, 0, BLOCK_SIZE * sizeof(DTYPE));
87 88
				float mean=0.0f;
				float voxelNumber=0.0f;
89
                int coord=0;
90 91
				for(int z=k*BLOCK_WIDTH; z<(k+1)*BLOCK_WIDTH; z++){
					if(z<targetImage->nz){
92 93 94
                        index =z*targetImage->nx*targetImage->ny;
                        DTYPE *targetPtrZ=&targetPtr[index];
                        int *maskPtrZ=&maskPtr[index];
95 96
						for(int y=j*BLOCK_WIDTH; y<(j+1)*BLOCK_WIDTH; y++){
							if(y<targetImage->ny){
97 98 99
                                index = y*targetImage->nx+i*BLOCK_WIDTH;
                                DTYPE *targetPtrXYZ=&targetPtrZ[index];
                                int *maskPtrXYZ=&maskPtrZ[index];
100
								for(int x=i*BLOCK_WIDTH; x<(i+1)*BLOCK_WIDTH; x++){
101 102 103 104
									if(x<targetImage->nx){
										targetValues[coord] = *targetPtrXYZ;
										if(targetValues[coord]>0.0 && *maskPtrXYZ>-1){
											mean += (float)targetValues[coord];
105 106 107
											voxelNumber++;
										}
									}
108 109 110
                                    targetPtrXYZ++;
                                    maskPtrXYZ++;
                                    coord++;
111 112 113 114 115 116
								}
							}
						}
					}
				}
				if(voxelNumber>BLOCK_SIZE/2){
117 118 119 120 121 122 123
                    float variance=0.0f;
                    for(int i=0; i<BLOCK_SIZE; i++){
						if(targetValues[coord]>0.0)
							variance += (mean - (float)targetValues[i])
                                * (mean - (float)targetValues[i]);
                    }

124 125 126 127 128 129 130 131 132 133 134 135
					variance /= voxelNumber;
					varianceArray[blockIndex]=variance;
				}
				else{
					varianceArray[blockIndex]=-1;
					unusableBlock++;
				}
				indexArray[blockIndex]=blockIndex;
				blockIndex++;
			}
		}
	}
136
    free(targetValues);
137 138 139 140 141 142 143 144 145 146 147 148 149

	params->activeBlockNumber=params->activeBlockNumber<(totalBlockNumber-unusableBlock)?params->activeBlockNumber:(totalBlockNumber-unusableBlock);

	reg_heapSort(varianceArray, indexArray, totalBlockNumber);

	memset(params->activeBlock, 0, totalBlockNumber * sizeof(int));
	int *indexArrayPtr = &indexArray[totalBlockNumber-1];
	int count = 0;
	for(int i=0; i<params->activeBlockNumber; i++){
		params->activeBlock[*indexArrayPtr--] = count++;
	}
	for (int i = params->activeBlockNumber; i < totalBlockNumber; ++i){
		params->activeBlock[*indexArrayPtr--] = -1;
150
	}    
151

152
    count = 0;
153 154 155 156 157 158 159
    if (runningOnGPU) {
        for(int i = 0; i < totalBlockNumber; ++i){
            if(params->activeBlock[i] != -1){            
                params->activeBlock[i] = -1;
                params->activeBlock[count] = i;            
                ++count;
            }
160
        }
161
    }
162

163 164
    free(varianceArray);
    free(indexArray);
165 166
}

167 168 169 170
void initialise_block_matching_method(  nifti_image * target,
                                        _reg_blockMatchingParam *params,
                                        int percentToKeep_block,
                                        int percentToKeep_opt,
171 172
                                        int *mask,
                                        bool runningOnGPU)
173 174 175 176 177 178 179 180 181 182 183
{
	params->blockNumber[0]=(int)ceil((float)target->nx / (float)BLOCK_WIDTH);
	params->blockNumber[1]=(int)ceil((float)target->ny / (float)BLOCK_WIDTH);
	params->blockNumber[2]=(int)ceil((float)target->nz / (float)BLOCK_WIDTH);

	params->percent_to_keep=percentToKeep_opt;
	params->activeBlockNumber=params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2] * percentToKeep_block / 100;

	params->activeBlock = (int *)malloc(params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2] * sizeof(int));
	switch(target->datatype){
		case NIFTI_TYPE_UINT8:
184
			_reg_set_active_blocks<unsigned char>(target, params, mask, runningOnGPU);break;
185
		case NIFTI_TYPE_INT8:
186
			_reg_set_active_blocks<char>(target, params, mask, runningOnGPU);break;
187
		case NIFTI_TYPE_UINT16:
188
			_reg_set_active_blocks<unsigned short>(target, params, mask, runningOnGPU);break;
189
		case NIFTI_TYPE_INT16:
190
			_reg_set_active_blocks<short>(target, params, mask, runningOnGPU);break;
191
		case NIFTI_TYPE_UINT32:
192
			_reg_set_active_blocks<unsigned int>(target, params, mask, runningOnGPU);break;
193
		case NIFTI_TYPE_INT32:
194
			_reg_set_active_blocks<int>(target, params, mask, runningOnGPU);break;
195
		case NIFTI_TYPE_FLOAT32:
196
			_reg_set_active_blocks<float>(target, params, mask, runningOnGPU);break;
197
		case NIFTI_TYPE_FLOAT64:
198
			_reg_set_active_blocks<double>(target, params, mask, runningOnGPU);break;
199 200 201 202
		default:
			fprintf(stderr,"ERROR\tinitialise_block_matching_method\tThe target image data type is not supported\n");
			return;
	}
203 204
#ifdef _VERBOSE
	printf("[VERBOSE]: There are %i active block(s) out of %i.\n", params->activeBlockNumber, params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2]);
205 206 207
#endif
	params->targetPosition = (float *)malloc(params->activeBlockNumber*3*sizeof(float));
	params->resultPosition = (float *)malloc(params->activeBlockNumber*3*sizeof(float));
208 209
#ifdef _VERBOSE
	printf("[VERBOSE]: block matching initialisation done.\n");
210 211 212 213
#endif
}
template<typename PrecisionTYPE, typename TargetImageType, typename ResultImageType>
void real_block_matching_method(nifti_image * target,
214
                                nifti_image * result,
215 216
                                _reg_blockMatchingParam *params,
                                int *mask)
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
{
	TargetImageType *targetPtr=static_cast<TargetImageType *>(target->data);
	ResultImageType *resultPtr=static_cast<ResultImageType *>(result->data);

	TargetImageType *targetValues=(TargetImageType *)malloc(BLOCK_SIZE*sizeof(TargetImageType));
	bool *targetOverlap=(bool *)malloc(BLOCK_SIZE*sizeof(bool));
	ResultImageType *resultValues=(ResultImageType *)malloc(BLOCK_SIZE*sizeof(ResultImageType));
	bool *resultOverlap=(bool *)malloc(BLOCK_SIZE*sizeof(bool));

	mat44 *targetMatrix_xyz;
	if(target->sform_code >0)
		targetMatrix_xyz = &(target->sto_xyz);
	else targetMatrix_xyz = &(target->qto_xyz);

	int targetIndex_start_x;
	int targetIndex_start_y;
	int targetIndex_start_z;
	int targetIndex_end_x;
	int targetIndex_end_y;
	int targetIndex_end_z;
	int resultIndex_start_x;
	int resultIndex_start_y;
	int resultIndex_start_z;
	int resultIndex_end_x;
	int resultIndex_end_y;
	int resultIndex_end_z;

	unsigned int targetIndex;
	unsigned int resultIndex;

	unsigned int blockIndex=0;
	unsigned int activeBlockIndex=0;
249 250
    int index;

251 252 253 254 255 256 257 258 259 260 261 262
	for(int k=0; k<params->blockNumber[2]; k++){
		targetIndex_start_z=k*BLOCK_WIDTH;
		targetIndex_end_z=targetIndex_start_z+BLOCK_WIDTH;

		for(int j=0; j<params->blockNumber[1]; j++){
			targetIndex_start_y=j*BLOCK_WIDTH;
			targetIndex_end_y=targetIndex_start_y+BLOCK_WIDTH;

			for(int i=0; i<params->blockNumber[0]; i++){
				targetIndex_start_x=i*BLOCK_WIDTH;
				targetIndex_end_x=targetIndex_start_x+BLOCK_WIDTH;

263
				if(params->activeBlock[blockIndex] > -1){
264 265 266 267
					targetIndex=0;
					memset(targetOverlap, 0, BLOCK_SIZE*sizeof(bool));
					for(int z=targetIndex_start_z; z<targetIndex_end_z; z++){
						if(-1<z && z<target->nz){
268 269 270
                            index = z*target->nx*target->ny;
							TargetImageType *targetPtr_Z = &targetPtr[index];
                            int *maskPtr_Z=&mask[index];
271 272
							for(int y=targetIndex_start_y; y<targetIndex_end_y; y++){
								if(-1<y && y<target->ny){
273 274 275
                                    index = y*target->nx+targetIndex_start_x;
									TargetImageType *targetPtr_XYZ = &targetPtr_Z[index];
                                    int *maskPtr_XYZ=&maskPtr_Z[index];
276 277 278
									for(int x=targetIndex_start_x; x<targetIndex_end_x; x++){
										if(-1<x && x<target->nx){
											TargetImageType value = *targetPtr_XYZ;
279
											if(value>0.0 && *maskPtr_XYZ>-1){
280 281 282 283 284
												targetValues[targetIndex]=value;
												targetOverlap[targetIndex]=1;
											}
										}
										targetPtr_XYZ++;
285
                                        maskPtr_XYZ++;
286 287 288 289 290 291 292 293 294
										targetIndex++;
									}
								}
								else targetIndex+=BLOCK_WIDTH;
							}
						}
						else targetIndex+=BLOCK_WIDTH*BLOCK_WIDTH;
					}
					PrecisionTYPE bestCC=0.0;
295
					float bestDisplacement[3] = {0.0f, 0.0f, 0.0f};
296 297
	
					// iteration over the result blocks
298
					for(int n=-OVERLAP_SIZE; n<=OVERLAP_SIZE; n+=STEP_SIZE){
299 300
						resultIndex_start_z=targetIndex_start_z+n;
						resultIndex_end_z=resultIndex_start_z+BLOCK_WIDTH;
301
						for(int m=-OVERLAP_SIZE; m<=OVERLAP_SIZE; m+=STEP_SIZE){
302 303
							resultIndex_start_y=targetIndex_start_y+m;
							resultIndex_end_y=resultIndex_start_y+BLOCK_WIDTH;
304
							for(int l=-OVERLAP_SIZE; l<=OVERLAP_SIZE; l+=STEP_SIZE){
305 306
								resultIndex_start_x=targetIndex_start_x+l;
								resultIndex_end_x=resultIndex_start_x+BLOCK_WIDTH;
307

308 309
								resultIndex=0;
								memset(resultOverlap, 0, BLOCK_SIZE*sizeof(bool));
310

311 312
								for(int z=resultIndex_start_z; z<resultIndex_end_z; z++){
									if(-1<z && z<result->nz){
313 314 315
                                        index = z*result->nx*result->ny;
                                        ResultImageType *resultPtr_Z = &resultPtr[index];
                                        int *maskPtr_Z = &mask[index];
316 317
										for(int y=resultIndex_start_y; y<resultIndex_end_y; y++){
											if(-1<y && y<result->ny){
318 319 320
                                                index=y*result->nx+resultIndex_start_x;
												ResultImageType *resultPtr_XYZ = &resultPtr_Z[index];
                                                int *maskPtr_XYZ=&maskPtr_Z[index];
321 322 323
												for(int x=resultIndex_start_x; x<resultIndex_end_x; x++){
													if(-1<x && x<result->nx){
														ResultImageType value = *resultPtr_XYZ;
324
														if(value>0.0 && *maskPtr_XYZ>-1){
325 326 327 328 329
															resultValues[resultIndex]=value;
															resultOverlap[resultIndex]=1;
														}
													}
													resultPtr_XYZ++;
330 331
                                                    resultIndex++;
                                                    maskPtr_XYZ++;
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
												}
											}
											else resultIndex+=BLOCK_WIDTH;
										}
									}
									else resultIndex+=BLOCK_WIDTH*BLOCK_WIDTH;
								}
								PrecisionTYPE targetMean=0.0;
								PrecisionTYPE resultMean=0.0;
								PrecisionTYPE voxelNumber=0.0;
								for(int a=0; a<BLOCK_SIZE; a++){
									if(targetOverlap[a] && resultOverlap[a]){
										targetMean += (PrecisionTYPE)targetValues[a];
										resultMean += (PrecisionTYPE)resultValues[a];
										voxelNumber++;
									}
								}
	
350
                                if(voxelNumber>BLOCK_SIZE/2){
351 352 353
									targetMean /= voxelNumber;
									resultMean /= voxelNumber;
	
354 355 356 357
                                    PrecisionTYPE targetVar=0.0;
                                    PrecisionTYPE resultVar=0.0;
                                    PrecisionTYPE localCC=0.0;

358 359
									for(int a=0; a<BLOCK_SIZE; a++){
										if(targetOverlap[a] && resultOverlap[a]){
360 361
											PrecisionTYPE targetTemp=(PrecisionTYPE)(targetValues[a]-targetMean);
											PrecisionTYPE resultTemp=(PrecisionTYPE)(resultValues[a]-resultMean);
362 363 364 365 366 367
											targetVar += (targetTemp)*(targetTemp);
											resultVar += (resultTemp)*(resultTemp);
											localCC += (targetTemp)*(resultTemp);
										}
									}
	
368
                                    localCC = fabs(localCC/sqrt(targetVar*resultVar));
369
	
370
									if(localCC>bestCC){                                        
371
										bestCC=localCC;
372 373 374
										bestDisplacement[0] = (float)l;
										bestDisplacement[1] = (float)m;
										bestDisplacement[2] = (float)n;
375 376 377 378 379 380 381
									}
								} 
							}
						}
					}
					
					float targetPosition_temp[3];
382 383 384
					targetPosition_temp[0] = (float)(i*BLOCK_WIDTH);
					targetPosition_temp[1] = (float)(j*BLOCK_WIDTH);
					targetPosition_temp[2] = (float)(k*BLOCK_WIDTH);
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

					bestDisplacement[0] += targetPosition_temp[0];
					bestDisplacement[1] += targetPosition_temp[1];
					bestDisplacement[2] += targetPosition_temp[2];

					float tempPosition[3];
					apply_affine(targetMatrix_xyz, targetPosition_temp, tempPosition);
					params->targetPosition[activeBlockIndex] = tempPosition[0];
					params->targetPosition[activeBlockIndex+1] = tempPosition[1];
					params->targetPosition[activeBlockIndex+2] = tempPosition[2];
					apply_affine(targetMatrix_xyz, bestDisplacement, tempPosition);
					params->resultPosition[activeBlockIndex] = tempPosition[0];
					params->resultPosition[activeBlockIndex+1] = tempPosition[1];
					params->resultPosition[activeBlockIndex+2] = tempPosition[2];
					activeBlockIndex += 3;
				}
				blockIndex++;
			}
		}
	}
	free(resultValues);
	free(targetValues);
	free(targetOverlap);
408
	free(resultOverlap);    
409 410
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
// Called internally to determine the parameter type
template<typename PrecisionTYPE, typename TargetImageType> 
void block_matching_method_2(   nifti_image * target,
                                nifti_image * result,
                                _reg_blockMatchingParam *params,
                                int *mask)
{
    switch(result->datatype){
        case NIFTI_TYPE_UINT8:
            real_block_matching_method<PrecisionTYPE, TargetImageType, unsigned char>
                    (target, result, params, mask);
                    break;
        case NIFTI_TYPE_INT8:
            real_block_matching_method<PrecisionTYPE, TargetImageType, char>
                    (target, result, params, mask);
                    break;
        case NIFTI_TYPE_UINT16:
            real_block_matching_method<PrecisionTYPE, TargetImageType, unsigned short>
                    (target, result, params, mask);
                    break;
        case NIFTI_TYPE_INT16:
            real_block_matching_method<PrecisionTYPE, TargetImageType, short>
                    (target, result, params, mask);
                    break;
        case NIFTI_TYPE_UINT32:
            real_block_matching_method<PrecisionTYPE, TargetImageType, unsigned int>
                    (target, result, params, mask);
                    break;
        case NIFTI_TYPE_INT32:
            real_block_matching_method<PrecisionTYPE, TargetImageType, int>
                    (target, result, params, mask);
                    break;
        case NIFTI_TYPE_FLOAT32:
            real_block_matching_method<PrecisionTYPE, TargetImageType, float>
                    (target, result, params, mask);
                    break;
        case NIFTI_TYPE_FLOAT64:
            real_block_matching_method<PrecisionTYPE, TargetImageType, double>
                    (target, result, params, mask);
                    break;
        default:
            printf("err\tblock_match\tThe target image data type is not "
                    "supported\n");
            return;
    }
}

458 459
// Block matching interface function
template<typename PrecisionTYPE>
460 461 462 463
void block_matching_method(	nifti_image * target,
							nifti_image * result,
							_reg_blockMatchingParam *params,
                            int *mask)
464 465 466 467
{
	switch(target->datatype){
		case NIFTI_TYPE_UINT8:
			block_matching_method_2<PrecisionTYPE, unsigned char>
468
					(target, result, params, mask);
469 470 471
					break;
		case NIFTI_TYPE_INT8:
			block_matching_method_2<PrecisionTYPE, char>
472
					(target, result, params, mask);
473 474 475
					break;
		case NIFTI_TYPE_UINT16:
			block_matching_method_2<PrecisionTYPE, unsigned short>
476
					(target, result, params, mask);
477 478 479
					break;
		case NIFTI_TYPE_INT16:
			block_matching_method_2<PrecisionTYPE, short>
480
					(target, result, params, mask);
481 482 483
					break;
		case NIFTI_TYPE_UINT32:
			block_matching_method_2<PrecisionTYPE, unsigned int>
484
					(target, result, params, mask);
485 486 487
					break;
		case NIFTI_TYPE_INT32:
			block_matching_method_2<PrecisionTYPE, int>
488
					(target, result, params, mask);
489 490 491
					break;
		case NIFTI_TYPE_FLOAT32:
			block_matching_method_2<PrecisionTYPE, float>
492
					(target, result, params, mask);
493 494 495
					break;
		case NIFTI_TYPE_FLOAT64:
			block_matching_method_2<PrecisionTYPE, double>
496
					(target, result, params, mask);
497 498 499 500 501 502 503
					break;
		default:
			printf("err\tblock_match\tThe target image data type is not"
					"supported\n");
			return;
	}
}
504 505
template void block_matching_method<float>(nifti_image *, nifti_image *, _reg_blockMatchingParam *, int *);
template void block_matching_method<double>(nifti_image *, nifti_image *, _reg_blockMatchingParam *, int *);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 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 592 593 594 595 596 597 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


// Apply the suppled affine transformation to a 3D point
void apply_affine(mat44 * mat, float *pt, float *result)
{	
	result[0] = (mat->m[0][0] * pt[0]) + (mat->m[0][1]*pt[1]) + (mat->m[0][2]*pt[2]) + (mat->m[0][3]);
	result[1] = (mat->m[1][0] * pt[0]) + (mat->m[1][1]*pt[1]) + (mat->m[1][2]*pt[2]) + (mat->m[1][3]);
	result[2] = (mat->m[2][0] * pt[0]) + (mat->m[2][1]*pt[1]) + (mat->m[2][2]*pt[2]) + (mat->m[2][3]);
}



struct _reg_sorted_point
{
	float target[3];
	float result[3];
	
	double distance;
	
	_reg_sorted_point(float * t, float * r, double d)
		:distance(d)
	{
		target[0] = t[0];
		target[1] = t[1];
		target[2] = t[2];
		
		result[0] = r[0];
		result[1] = r[1];
		result[2] = r[2];
	}
	 
	const bool operator <(const _reg_sorted_point & sp) const
	{
		return (sp.distance < distance);
	}
};

// Multiply matrices A and B together and store the result in r.
// We assume that the input pointers are valid and can store the result.
// A = ar * ac
// B = ac * bc
// r = ar * bc

// We can specify if we want to multiply A with the transpose of B

void mul_matrices(float ** a, float ** b, int ar, int ac, int bc, float ** r, bool transposeB)
{
	if (transposeB){
		for (int i = 0; i < ar; ++i){
			for (int j = 0; j < bc; ++j){
				r[i][j] = 0.0f;
				for (int k = 0; k < ac; ++k){
					r[i][j] += a[i][k] * b[j][k];
				}
			}
		}
	}
	else{		
		for (int i = 0; i < ar; ++i){
			for (int j = 0; j < bc; ++j){
				r[i][j] = 0.0f;
				for (int k = 0; k < ac; ++k){
					r[i][j] += a[i][k] * b[k][j];
				}
			}
		}
	}
}

// Multiply a matrix with a vctor
void mul_matvec(float ** a, int ar, int ac, float * b, float * r)
{
	for (int i = 0; i < ar; ++i){
		r[i] = 0;
		for (int k = 0; k < ac; ++k){
			r[i] += a[i][k] * b[k];
		}
	}
}

// Compute determinant of a 3x3 matrix
float compute_determinant3x3(float ** mat)
{
	return 	(mat[0][0]*(mat[1][1]*mat[2][2]-mat[1][2]*mat[2][1]))-
			(mat[0][1]*(mat[1][0]*mat[2][2]-mat[1][2]*mat[2][0]))+
			(mat[0][2]*(mat[1][0]*mat[2][1]-mat[1][1]*mat[2][0]));
}

// estimate an affine transformation using least square
void estimate_affine_transformation(std::vector<_reg_sorted_point> & points,
									mat44 * transformation,
									float ** A,
									float *  w,
									float ** v,
									float ** r,
									float *  b)
{	
	// Create our A matrix
	// Each point will give us 3 linearly independent equations, so
	// we need at least 4 points. Assuming we have that here.
	int num_equations = points.size() * 3;
	unsigned c = 0;
	for (unsigned k = 0; k < points.size(); ++k)
	{
		c = k * 3;
		A[c][0] = points[k].target[0];
		A[c][1] = points[k].target[1];
		A[c][2] = points[k].target[2];
		A[c][3] = A[c][4] = A[c][5] = A[c][6] = A[c][7] = A[c][8] = A[c][10] = A[c][11] = 0.0f;
		A[c][9] = 1.0;
			
		A[c+1][3] = points[k].target[0];
		A[c+1][4] = points[k].target[1];
		A[c+1][5] = points[k].target[2];
		A[c+1][0] = A[c+1][1] = A[c+1][2] = A[c+1][6] = A[c+1][7] = A[c+1][8] = A[c+1][9] = A[c+1][11] = 0.0f;
		A[c+1][10] = 1.0;
			
		A[c+2][6] = points[k].target[0];
		A[c+2][7] = points[k].target[1];
		A[c+2][8] = points[k].target[2];
		A[c+2][0] = A[c+2][1] = A[c+2][2] = A[c+2][3] = A[c+2][4] = A[c+2][5] = A[c+2][9] = A[c+2][10] = 0.0f;
		A[c+2][11] = 1.0;
	}	
	
	for (unsigned k = 0; k < 12; ++k)
	{
		w[k] = 0.0f;
	}	
634
	// Now we can compute our svd
635 636
	svd(A, num_equations, 12, w, v);
		
637 638 639
	// First we make sure that the really small singular values
	// are set to 0. and compute the inverse by taking the reciprocal
	// of the entries
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 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
	for (unsigned k = 0; k < 12; ++k)
	{
		if (w[k] < 0.0001)
		{
			w[k] = 0.0f;
		}
		else
		{
			w[k] = 1.0f/w[k];
		}
	}
		
	// Now we can compute the pseudoinverse which is given by
	// V*inv(W)*U'
	// First compute the V * inv(w) in place.
	// Simply scale each column by the corresponding singular value 
	for (unsigned k = 0; k < 12; ++k)
	{
		for (unsigned j = 0; j < 12; ++j)
		{
			v[j][k] *=w[k];
		}
	}
		
	// Now multiply the matrices together
	// Pseudoinverse = v * e * A(transpose)
	mul_matrices(v, A, 12, 12, num_equations, r, true);		
	// Now r contains the pseudoinverse
	// Create vector b and then multiple rb to get the affine paramsA
	for (unsigned k = 0; k < points.size(); ++k)
	{
		c = k * 3;			 
		b[c] = 		points[k].result[0];
		b[c+1] = 	points[k].result[1];
		b[c+2] = 	points[k].result[2];
	}
		
	float * transform = new float[12];
	mul_matvec(r, 12, num_equations, b, transform);
	
	transformation->m[0][0] = transform[0];
	transformation->m[0][1] = transform[1];
	transformation->m[0][2] = transform[2];
	transformation->m[0][3] = transform[9];
		
	transformation->m[1][0] = transform[3];
	transformation->m[1][1] = transform[4];
	transformation->m[1][2] = transform[5];
	transformation->m[1][3] = transform[10];
		
	transformation->m[2][0] = transform[6];
	transformation->m[2][1] = transform[7];
	transformation->m[2][2] = transform[8];
	transformation->m[2][3] = transform[11];
		
	transformation->m[3][0] = 0.0f;
	transformation->m[3][1] = 0.0f;
	transformation->m[3][2] = 0.0f;
	transformation->m[3][3] = 1.0f;

	delete[] transform;
}

void optimize_affine(	_reg_blockMatchingParam *params,
						mat44 * final)
{
	// Set the current transformation to identity
	final->m[0][0] = final->m[1][1] = final->m[2][2] = final->m[3][3] = 1.0f;
	final->m[0][1] = final->m[0][2] = final->m[0][3] = 0.0f;
	final->m[1][0] = final->m[1][2] = final->m[1][3] = 0.0f;
	final->m[2][0] = final->m[2][1] = final->m[2][3] = 0.0f;
	final->m[3][0] = final->m[3][1] = final->m[3][2] = 0.0f;

	const unsigned num_points = params->activeBlockNumber;
	unsigned long num_equations = num_points * 3;
	std::priority_queue<_reg_sorted_point> queue;
	std::vector<_reg_sorted_point> top_points;
	double distance = 0.0;
	double lastDistance = 0.0;
	unsigned long i;

	// massive left hand side matrix
	float ** a = new float *[num_equations];
	for (unsigned k = 0; k < num_equations; ++k)
	{			
		a[k] = new float[12]; // full affine
	}
	
	// The array of singular values returned by svd
	float *w = new float[12];
		
	// v will be n x n
	float **v = new float *[12];
	for (unsigned k = 0; k < 12; ++k)
	{
		v[k] = new float[12];
	}
	
	// Allocate memory for pseudoinverse		
	float **r = new float *[12];
	for (unsigned k = 0; k < 12; ++k)
	{
		r[k] = new float[num_equations];
	}
	
	// Allocate memory for RHS vector
	float *b = new float[num_equations];
	
	// The initial vector with all the input points
	for (unsigned j = 0; j < num_points*3; j+=3)
	{
		top_points.push_back(_reg_sorted_point(&(params->targetPosition[j]), 
							 &(params->resultPosition[j]),0.0f));
	}
	
	// estimate the optimal transformation while considering all the points
	estimate_affine_transformation(top_points, final, a, w, v, r, b);

	// Delete a, b and r. w and v will not change size in subsequent svd operations.
	for (unsigned int k = 0; k < num_equations; ++k)
	{
		delete[] a[k];
	}
	delete[] a;
	delete[] b;
	
	for (unsigned k = 0; k < 12; ++k)
	{
		delete[] r[k];
	}
	delete [] r;


	// The LS in the iterations is done on subsample of the input data	
	float * newResultPosition = new float[num_points*3];
	const unsigned long num_to_keep = (unsigned long)(num_points * (params->percent_to_keep/100.0f));
	num_equations = num_to_keep*3;

	// The LHS matrix
	a = new float *[num_equations];
	for (unsigned k = 0; k < num_equations; ++k)
	{			
		a[k] = new float[12]; // full affine
	}
	
	// Allocate memory for pseudoinverse		
	r = new float *[12];
	for (unsigned k = 0; k < 12; ++k)
	{
		r[k] = new float[num_equations];
	}
	
	// Allocate memory for RHS vector
	b = new float[num_equations];
	
	for (unsigned count = 0; count < MAX_ITERATIONS; ++count)
	{
		// Transform the points in the target
		for (unsigned j = 0; j < num_points * 3; j+=3)		
		{				
			apply_affine(final, &(params->targetPosition[j]), &newResultPosition[j]);
		}

		queue = std::priority_queue<_reg_sorted_point> ();
		for (unsigned j = 0; j < num_points * 3; j+=3)
		{
			distance = get_square_distance(&newResultPosition[j], &(params->resultPosition[j]));
			queue.push(_reg_sorted_point(&(params->targetPosition[j]), 
					   &(params->resultPosition[j]), distance));
		}
						
		distance = 0.0;	
		i = 0;
		top_points.clear();
		while (i < num_to_keep && i < queue.size())
		{
			top_points.push_back(queue.top());
			distance += queue.top().distance;
			queue.pop();
			++i;
		}
				
822
		// If the change is not substantial, we return 
823
		if (fabs(distance - lastDistance) < TOLERANCE)
824 825
		{
			return;
826
		}
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 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 930 931 932 933 934 935 936 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
		
		lastDistance = distance;
		estimate_affine_transformation(top_points, final, a, w, v, r, b);	
	}
	
	delete[] newResultPosition;
	delete[] b;
	for (unsigned k = 0; k < 12; ++k)
	{
		delete[] r[k];
	}
	delete [] r;
				
	// free the memory
	for (unsigned int k = 0; k < num_equations; ++k)
	{
		delete[] a[k];
	}
	delete[] a;
		
	delete[] w;
	for (int k = 0; k < 12; ++k)
	{
		delete[] v[k];
	}
	delete [] v;	
}

void estimate_rigid_transformation(std::vector<_reg_sorted_point> & points,
								   mat44 * transformation)
{	
	float centroid_target[3] = {0.0f};
	float centroid_result[3] = {0.0f};
	
	
	for (unsigned j = 0; j < points.size(); ++j)
	{
		centroid_target[0] += points[j].target[0];
		centroid_target[1] += points[j].target[1];
		centroid_target[2] += points[j].target[2];
			
		centroid_result[0] += points[j].result[0];
		centroid_result[1] += points[j].result[1];
		centroid_result[2] += points[j].result[2];
	}
		
	centroid_target[0] /= (float)(points.size());
	centroid_target[1] /= (float)(points.size());
	centroid_target[2] /= (float)(points.size());
	
	centroid_result[0] /= (float)(points.size());
	centroid_result[1] /= (float)(points.size());
	centroid_result[2] /= (float)(points.size());
	
	float ** u = new float*[3];
	float * w = new float[3];
	float ** v = new float*[3];
	float ** ut = new float*[3];
	float ** r = new float*[3];

	for (unsigned i = 0; i < 3; ++i)
	{
		u[i] = new float[3];
		v[i] = new float[3];
		ut[i] = new float[3];
		r[i] = new float[3];
		
		w[i] = 0.0f;
	
		
		for (unsigned j = 0; j < 3; ++j)
		{
			u[i][j] = v[i][j] = ut[i][j] = r[i][j] = 0.0f;			
		}
	}
	
	// Demean the input points
	for (unsigned j = 0; j < points.size(); ++j)
	{
		points[j].target[0] -= centroid_target[0];
		points[j].target[1] -= centroid_target[1];
		points[j].target[2] -= centroid_target[2];
			
		points[j].result[0] -= centroid_result[0];
		points[j].result[1] -= centroid_result[1];
		points[j].result[2] -= centroid_result[2];
			
		u[0][0] += points[j].target[0] * points[j].result[0];
		u[0][1] += points[j].target[0] * points[j].result[1];
		u[0][2] += points[j].target[0] * points[j].result[2];
			
		u[1][0] += points[j].target[1] * points[j].result[0];
		u[1][1] += points[j].target[1] * points[j].result[1];
		u[1][2] += points[j].target[1] * points[j].result[2];
			
		u[2][0] += points[j].target[2] * points[j].result[0];
		u[2][1] += points[j].target[2] * points[j].result[1];
		u[2][2] += points[j].target[2] * points[j].result[2];
		
	}
	
	svd(u, 3, 3, w, v);	
	
	// Calculate transpose	
	ut[0][0] = u[0][0];	
	ut[1][0] = u[0][1];
	ut[2][0] = u[0][2];
	
	ut[0][1] = u[1][0];
	ut[1][1] = u[1][1];
	ut[2][1] = u[1][2];
	
	ut[0][2] = u[2][0];
	ut[1][2] = u[2][1];
	ut[2][2] = u[2][2];
	
	// Calculate the rotation matrix
	mul_matrices(v, ut, 3, 3, 3, r, false);
	
	float det = compute_determinant3x3(r);
	
	// Take care of possible reflection 
	if (det < 0.0f)
	{
		v[0][2] = -v[0][2];
		v[1][2] = -v[1][2];
		v[2][2] = -v[2][2];
		
	}
		// Calculate the rotation matrix
	mul_matrices(v, ut, 3, 3, 3, r, false);
	
	// Calculate the translation
	float t[3];
	t[0] = centroid_result[0] - (r[0][0] * centroid_target[0] +
	r[0][1] * centroid_target[1] +
	r[0][2] * centroid_target[2]);
	
	t[1] = centroid_result[1] - (r[1][0] * centroid_target[0] +
	r[1][1] * centroid_target[1] +
	r[1][2] * centroid_target[2]);
	
	t[2] = centroid_result[2] - (r[2][0] * centroid_target[0] +
	r[2][1] * centroid_target[1] +
971
	r[2][2] * centroid_target[2]);	
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 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 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
		
	transformation->m[0][0] = r[0][0];
	transformation->m[0][1] = r[0][1];
	transformation->m[0][2] = r[0][2];
	transformation->m[0][3] = t[0];	
		
	transformation->m[1][0] = r[1][0];
	transformation->m[1][1] = r[1][1];
	transformation->m[1][2] = r[1][2];
	transformation->m[1][3] = t[1];
		
	transformation->m[2][0] = r[2][0];
	transformation->m[2][1] = r[2][1];
	transformation->m[2][2] = r[2][2];
	transformation->m[2][3] = t[2];
		
	transformation->m[3][0] = 0.0f;
	transformation->m[3][1] = 0.0f;
	transformation->m[3][2] = 0.0f;
	transformation->m[3][3] = 1.0f;
	
	// Do the deletion here
	for (int i = 0; i < 3; ++i)
	{
		delete [] u[i];
		delete [] v[i];
		delete [] ut[i];
		delete [] r[i];
	}
	delete [] u;
	delete [] v;
	delete [] ut;	
	delete [] r;
	delete [] w;
}


// Find the optimal rigid transformation that will
// bring the point clouds into alignment.
void optimize_rigid(_reg_blockMatchingParam *params,
					mat44 * final)
{	
	unsigned num_points = params->activeBlockNumber;	
	// Keep a sorted list of the distance measure
	std::priority_queue<_reg_sorted_point> queue;
	std::vector<_reg_sorted_point> top_points;
	double distance = 0.0;
	double lastDistance = 0.0;	
	unsigned long i;
	
	// Set the current transformation to identity
	final->m[0][0] = final->m[1][1] = final->m[2][2] = final->m[3][3] = 1.0f;
	final->m[0][1] = final->m[0][2] = final->m[0][3] = 0.0f;
	final->m[1][0] = final->m[1][2] = final->m[1][3] = 0.0f;
	final->m[2][0] = final->m[2][1] = final->m[2][3] = 0.0f;	
	final->m[3][0] = final->m[3][1] = final->m[3][2] = 0.0f;
	
	for (unsigned j = 0; j < num_points * 3; j+= 3)	
	{	
		top_points.push_back(_reg_sorted_point(&(params->targetPosition[j]), 
		&(params->resultPosition[j]), 0.0f));
	}
		
	estimate_rigid_transformation(top_points, final);
	unsigned long num_to_keep = (unsigned long)(num_points * (params->percent_to_keep/100.0f));
	float * newResultPosition = new float[num_points*3];
	
	for (unsigned count = 0; count < MAX_ITERATIONS; ++count)
	{	
		// Transform the points in the target
		for (unsigned j = 0; j < num_points * 3; j+=3)		
		{				
			apply_affine(final, &(params->targetPosition[j]), &newResultPosition[j]);
		}	
		
		queue = std::priority_queue<_reg_sorted_point> ();
		for (unsigned j = 0; j < num_points * 3; j+= 3)
		{			
			distance = get_square_distance(&newResultPosition[j], &(params->resultPosition[j]));
			queue.push(_reg_sorted_point(&(params->targetPosition[j]), 
				&(params->resultPosition[j]), distance));			
		}
						
		distance = 0.0;	
		i = 0;		
		top_points.clear();		
		while (i < num_to_keep && i < queue.size())
		{			
1060
			top_points.push_back(queue.top());
1061 1062 1063 1064
			distance += queue.top().distance;
			queue.pop();
			++i;
		}
1065 1066

		// If the change is not substantial, we return 		
1067
 		if (fabs(distance - lastDistance) < TOLERANCE)
1068 1069
 		{
 			return;
1070 1071
        }
        lastDistance = distance;		
1072
		estimate_rigid_transformation(top_points, final);
1073
	}	
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
	delete [] newResultPosition;
}


// Find the optimal affine transformation
void optimize(	_reg_blockMatchingParam *params,
		mat44 * final,
		bool affine)
{	

	if (affine){
		optimize_affine(params, final);
	}
	else{
		optimize_rigid(params, final);
	}	
}

// Routines for alculating Singular Value Decomposition follows.
// Adopted from Numerical Recipes in C.

#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))

static float maxarg1,maxarg2;
#define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\
        (maxarg1) : (maxarg2))

static int iminarg1,iminarg2;
#define IMIN(a,b) (iminarg1=(a),iminarg2=(b),(iminarg1) < (iminarg2) ?\
        (iminarg1) : (iminarg2))

static float sqrarg;
#define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg)

// Calculate pythagorean distance
float pythag(float a, float b)
{
	float absa, absb;
	absa = fabs(a);
	absb = fabs(b);

1115 1116
	if (absa > absb) return (float)(absa * sqrt(1.0f+SQR(absb/absa)));
	else return (absb == 0.0f ? 0.0f : (float)(absb * sqrt(1.0f+SQR(absa/absb))));
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 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
}

void svd(float ** in, int m, int n, float * w, float ** v)
{
	float * rv1 = (float *)malloc(sizeof(float) * n);
	float anorm, c, f, g, h, s, scale, x, y, z; 
	int flag,i,its,j,jj,k,l,nm;

	g = scale = anorm = 0.0f;
	for (i = 1; i <= n; ++i)
	{
		l = i + 1;
		rv1[i-1] = scale * g;
		g = s = scale = 0.0f;

		if ( i <= m)
		{
			for (k = i; k <= m; ++k)
			{
				scale += fabs(in[k-1][i-1]);
			}
			if (scale)
			{   
				for (k = i; k <= m; ++k)
				{
					in[k-1][i-1] /= scale;
					s += in[k-1][i-1] * in[k-1][i-1];
				}
				f = in[i-1][i-1];
				g = -SIGN(sqrt(s), f);
				h = f * g - s;
				in[i-1][i-1] = f - g;

				for (j = l; j <= n; ++j)
				{
					for (s = 0.0, k=i; k<=m; ++k) s += in[k-1][i-1]*in[k-1][j-1];				
					f = s/h;
					for (k = i; k <= m; ++k) in[k-1][j-1] += f * in[k-1][i-1];
				}
				for (k = i; k <= m; ++k)
				{
					in[k-1][i-1] *= scale;
				}
			}
		}
		w[i-1] = scale * g;
		g = s = scale = 0.0;
		if ((i <= m) && (i != n))
		{
			for (k = l; k <= n; ++k)
			{
				scale += fabs(in[i-1][k-1]);
			}
			if (scale)
			{
				for (k = l; k <= n; ++k)
				{
					in[i-1][k-1] /= scale;
					s += in[i-1][k-1] * in[i-1][k-1];
				}
				f = in[i-1][l-1];
				g = -SIGN(sqrt(s), f);
				h = f*g-s;
				in[i-1][l-1] = f - g;

				for (k = l; k <= n; ++k) rv1[k-1] = in[i-1][k-1]/h;
				for (j = l; j <= m; ++j)
				{
					for (s = 0.0, k = l; k <= n; ++k)
					{
						s += in[j-1][k-1] * in[i-1][k-1];
					}
					for (k = l; k <= n; ++k)
					{
						in[j-1][k-1] += s * rv1[k-1];
					}
				}

				for (k=l;k<=n;++k) in[i-1][k-1] *= scale;
			}
		}
		anorm = FMAX(anorm, (fabs(w[i-1])+fabs(rv1[i-1])));
	}
    
	for (i = n; i >= 1; --i)
	{
		if (i < n)
		{
			if (g)
			{
				for (j = l; j <= n; ++j)
				{
					v[j-1][i-1] = (in[i-1][j-1]/in[i-1][l-1])/g;
				}
				for (j = l; j <= n; ++j)
				{
					for (s = 0.0, k = l; k <= n; ++k) s += in[i-1][k-1] * v[k-1][j-1];
					for (k=l;k<=n;++k) v[k-1][j-1] += s * v[k-1][i-1];
				}
			}
			for (j = l; j <= n; ++j) v[i-1][j-1] = v[j-1][i-1] = 0.0;
		}
		v[i-1][i-1] = 1.0f;
		g = rv1[i-1];
		l = i;
	}

	for (i = IMIN(m, n); i >= 1; --i)
	{
		l = i+1;
		g = w[i-1];
		for (j = l; j <= n; ++j) in[i-1][j-1] = 0.0f;
		if (g)
		{
			g = 1.0f/g;
			for (j = l; j <= n; ++j)
			{
				for (s = 0.0, k = l; k <= m; ++k) s += in[k-1][i-1] * in[k-1][j-1];
				f = (s/in[i-1][i-1])*g;
				for (k=i; k <=m; ++k) in[k-1][j-1] += f * in[k-1][i-1];
			}
			for (j=i; j <= m; ++j) in[j-1][i-1] *= g;
		}
		else for (j = i; j <= m; ++j) in[j-1][i-1] = 0.0;
		++in[i-1][i-1];
	}

	for (k = n; k >= 1; --k)
	{
		for (its = 0; its < 30; ++its)
		{
			flag = 1;
			for (l=k; l >= 1; --l)
			{
				nm = l - 1;
				if ((float)(fabs(rv1[l-1])+anorm) == anorm)
				{
					flag = 0;
					break;
				}
				if ((float)(fabs(w[nm-1])+anorm) == anorm) break;
			}

			if (flag)
			{
				c = 0.0f;
				s = 1.0f;
				for (i=l; i<=k; ++i) // changed
				{
					f = s * rv1[i-1];
					rv1[i-1] = c * rv1[i-1];
					if ((float)(fabs(f)+anorm) == anorm) break;
					g=w[i-1];
					h=pythag(f,g);
					w[i-1]=h;
					h=1.0f/h;
					c=g*h;
					s = -f*h;

					for (j = 1; j <= m; ++j)
					{
						y=in[j-1][nm-1];
						z=in[j-1][i-1];
						in[j-1][nm-1]=y*c+z*s;
						in[j-1][i-1]=z*c-y*s;
					}
				}
			}
			z = w[k-1];
			if (l == k)
			{
				if (z < 0.0f)
				{
					w[k-1] = -z;
					for (j = 1; j <= n; ++j) v[j-1][k-1] = -v[j-1][k-1];
				}
				break;
			}

			x = w[l-1];
			nm = k - 1;
			y = w[nm-1];
			g = rv1[nm-1];
			h = rv1[k-1];

1302
			f = ((y-z)*(y+z)+(g-h)*(g+h))/(2.0f*h*y);
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
			g = pythag(f, 1.0f);
			f = ((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x;
			c = s = 1.0f;
			for (j = l; j <= nm; ++j)
			{
				i = j + 1;
				g = rv1[i-1];
				y = w[i-1];
				h = s * g;
				g = c * g;
				z = pythag(f, h);
				rv1[j-1] = z;
				c = f/z;
				s = h/z;
				f = x*c+g*s;
				g = g*c-x*s;
				h = y*s;
				y *= c;

				for (jj = 1; jj <= n; ++jj)
				{
					x = v[jj-1][j-1];
					z = v[jj-1][i-1];
					v[jj-1][j-1] = x*c+z*s;
					v[jj-1][i-1] = z*c-x*s;
				}
				z = pythag(f, h);
				w[j-1] = z;
				if (z)
				{
					z = 1.0f/z;
					c = f * z;
					s = h * z;
				}
				f = c*g+s*y;
				x = c*y-s*g;

				for (jj = 1; jj <= m; ++jj)
				{
					y = in[jj-1][j-1];
					z = in[jj-1][i-1];
					in[jj-1][j-1] = y*c+z*s;
					in[jj-1][i-1] = z*c-y*s;
				}
			}
			rv1[l-1] = 0.0f;
			rv1[k-1] = f;
			w[k-1] = x;
		}
	}
1353
	free (rv1);    
1354
}