/******************************************************************** * * Function : jacobi * Goal : * * * input parameters : mat : original Matrix * * output parameters : d : contains the eigenvalues * eig_v : contains the eigenvectors as columna * * returnted Value : success or error messages * ********************************************************************/ extern int jacobi( Matrix* mat, Vector *d, Matrix *eig_v ) { int j, iq, ip, i, n, nrot; double tresh, theta, tau, t, sm, s, h, g, c; Vector *b, *z; /* this vector accumulate terms */ double **mval, **vval, **bval, **dval, **zval; Matrix *msave; if( (mat == NULL) || (d == NULL) || (eig_v == NULL) ) { printf(" jacobi: you gave me a NULL-pointer\n"); return( MATH_FATAL_ERROR ); } if( (MDim1(mat) != MDim2(mat)) || (VDim(d) != MDim1(mat)) || (MDim1(eig_v) != MDim2(eig_v)) || (MDim1(mat) != MDim1(eig_v)) ) { printf(" jacobi: wrong dimensions of the matrices or the vector\n"); return( MATH_WARNING ); } msave = matrix_alloc( MDim1(mat), MDim2(mat) ); matrix_copy( mat, msave ); n = MDim1(msave); mval = msave->val; vval = eig_v->val; dval = d->val; b = vector_alloc( n ); bval = b->val; z = vector_alloc( n ); zval = z->val; /* Initialize */ for( ip = 0; ip < n; ip++ ) /* initialize to the identiy matrix */ { for( iq = 0; iq < n; iq ++ ) MVal(vval,ip,iq) = 0.0; MVal(vval,ip,ip) = 1.0; } for( ip = 0; ip < n; ip++ ) /* initialize b and d to the */ { VVal(bval,ip) = VVal(dval,ip) = MVal(mval,ip,ip) ; /* diagonal of msave */ VVal(zval,ip) = 0.0; } nrot = 0; for( i = 0; i < 50; i++ ) { sm = 0.0; for( ip = 0; ip < n-1; ip++) for( iq = ip+1; iq < n; iq++) sm += SYS_FABS(MVal(mval,ip,iq)); if( sm == 0.0) { vector_free( b ); vector_free( z ); matrix_free( msave ); eigsort( eig_v, d ); return( MATH_SUCCESS ); } if (i < 4) tresh = 0.2 * sm / (n * n); else tresh = 0.0; for( ip = 0; ip < n-1;ip++) for( iq = ip+1; iq < n; iq++) { g = 100.0 * SYS_FABS( MVal(mval,ip,iq) ); if ( (i > 4) && ((double) SYS_FABS(VVal(dval,ip))+g)==(double) SYS_FABS(VVal(dval,ip)) && ((double) SYS_FABS(VVal(dval,iq))+g)==(double) SYS_FABS(VVal(dval,iq)) ) { MVal(mval,ip,iq) = 0.0; } else if( SYS_FABS( MVal(mval,ip,iq) ) > tresh ) { h = VVal(dval,iq) - VVal(dval,ip); if( (double) (SYS_FABS(h) + g) == (double)SYS_FABS(h)) { t = ( MVal(mval,ip,iq) ) / h; } else { theta = 0.5 * h / ( MVal(mval,ip,iq) ); t = 1.0 / (SYS_FABS(theta) + sqrt(1.0 + theta*theta)); if( theta < 0.0 ) t = -t; } c = 1.0 / sqrt( 1 + t*t); s = t * c; tau = s / (1.0 + c); h = t * MVal(mval,ip,iq); VVal(zval,ip) -= h; VVal(zval,iq) += h; VVal(dval,ip) -= h; VVal(dval,iq) += h; MVal( mval,ip,iq) = 0.0; for (j = 0; j < ip; j++) ROTATE( mval,j, ip,j, iq); for (j = ip+1; j < iq; j++) ROTATE( mval,ip,j, j, iq); for (j = iq+1; j < n; j++) ROTATE( mval,ip,j, iq,j); for (j = 0; j < n; j++) ROTATE( vval,j, ip,j, iq); ++nrot; } } for( ip = 0; ip < n; ip++ ) { VVal(bval,ip) += VVal(zval,ip); VVal(dval,ip) = VVal(bval,ip); VVal(zval,ip) = 0.0; } } printf(" jacobi: to many iterations in routine\n"); return( MATH_WARNING ); }
matrix_type * matrix_fread_alloc(FILE * stream) { matrix_type * matrix = matrix_alloc(1,1); matrix_fread(matrix , stream); return matrix; }
matrix_type * matrix_alloc_transpose( const matrix_type * A) { matrix_type * B = matrix_alloc( matrix_get_columns( A ) , matrix_get_rows( A )); matrix_transpose( A , B ); return B; }
static double stepwise_test_var( stepwise_type * stepwise , int test_var , int blocks) { double prediction_error = 0; bool_vector_iset( stepwise->active_set , test_var , true ); // Temporarily activate this variable { int nvar = matrix_get_columns( stepwise->X0 ); int nsample = matrix_get_rows( stepwise->X0 ); int block_size = nsample / blocks; bool_vector_type * active_rows = bool_vector_alloc( nsample, true ); /*True Cross-Validation: */ int * randperms = util_calloc( nsample , sizeof * randperms ); for (int i=0; i < nsample; i++) randperms[i] = i; /* Randomly perturb ensemble indices */ rng_shuffle_int( stepwise->rng , randperms , nsample ); for (int iblock = 0; iblock < blocks; iblock++) { int validation_start = iblock * block_size; int validation_end = validation_start + block_size - 1; if (iblock == (blocks - 1)) validation_end = nsample - 1; /* Ensure that the active_rows vector has a block consisting of the interval [validation_start : validation_end] which is set to false, and the remaining part of the vector is set to true. */ { bool_vector_set_all(active_rows, true); /* If blocks == 1 that means all datapoint are used in the regression, and then subsequently reused in the R2 calculation. */ if (blocks > 1) { for (int i = validation_start; i <= validation_end; i++) { bool_vector_iset( active_rows , randperms[i] , false ); } } } /* Evaluate the prediction error on the validation part of the dataset. */ { stepwise_estimate__( stepwise , active_rows ); { int irow; matrix_type * x_vector = matrix_alloc( 1 , nvar ); //matrix_type * e_vector = matrix_alloc( 1 , nvar ); for (irow=validation_start; irow <= validation_end; irow++) { matrix_copy_row( x_vector , stepwise->X0 , 0 , randperms[irow]); //matrix_copy_row( e_vector , stepwise->E0 , 0 , randperms[irow]); { double true_value = matrix_iget( stepwise->Y0 , randperms[irow] , 0 ); double estimated_value = stepwise_eval__( stepwise , x_vector ); prediction_error += (true_value - estimated_value) * (true_value - estimated_value); //double e_estimated_value = stepwise_eval__( stepwise , e_vector ); //prediction_error += e_estimated_value*e_estimated_value; } } matrix_free( x_vector ); } } } free( randperms ); bool_vector_free( active_rows ); } /*inactivate the test_var-variable after completion*/ bool_vector_iset( stepwise->active_set , test_var , false ); return prediction_error; }
static double stepwise_estimate__( stepwise_type * stepwise , bool_vector_type * active_rows) { matrix_type * X; matrix_type * E; matrix_type * Y; double y_mean = 0; int nvar = matrix_get_columns( stepwise->X0 ); int nsample = matrix_get_rows( stepwise->X0 ); nsample = bool_vector_count_equal( active_rows , true ); nvar = bool_vector_count_equal( stepwise->active_set , true ); matrix_set( stepwise->beta , 0 ); // It is essential to make sure that old finite values in the beta0 vector do not hang around. /* Extracting the data used for regression, and storing them in the temporary local matrices X and Y. Selecting data is based both on which varibles are active (stepwise->active_set) and which rows should be used for regression, versus which should be used for validation (@active_rows). */ if ((nsample < matrix_get_rows( stepwise->X0 )) || (nvar < matrix_get_columns( stepwise->X0 ))) { X = matrix_alloc( nsample , nvar ); E = matrix_alloc( nsample , nvar ); Y = matrix_alloc( nsample , 1); { int icol,irow; // Running over all values. int arow,acol; // Running over active values. arow = 0; for (irow = 0; irow < matrix_get_rows( stepwise->X0 ); irow++) { if (bool_vector_iget( active_rows , irow )) { acol = 0; for (icol = 0; icol < matrix_get_columns( stepwise->X0 ); icol++) { if (bool_vector_iget( stepwise->active_set , icol )) { matrix_iset( X , arow , acol , matrix_iget( stepwise->X0 , irow , icol )); matrix_iset( E , arow , acol , matrix_iget( stepwise->E0 , irow , icol )); acol++; } } matrix_iset( Y , arow , 0 , matrix_iget( stepwise->Y0 , irow , 0 )); arow++; } } } } else { X = matrix_alloc_copy( stepwise->X0 ); E = matrix_alloc_copy( stepwise->E0 ); Y = matrix_alloc_copy( stepwise->Y0 ); } { if (stepwise->X_mean != NULL) matrix_free( stepwise->X_mean); stepwise->X_mean = matrix_alloc( 1 , nvar ); if (stepwise->X_norm != NULL) matrix_free( stepwise->X_norm); stepwise->X_norm = matrix_alloc( 1 , nvar ); matrix_type * beta = matrix_alloc( nvar , 1); /* This is the beta vector as estimated from the OLS estimator. */ regression_augmented_OLS( X , Y , E, beta ); /* In this code block the beta/tmp_beta vector which is dense with fewer elements than the full model is scattered into the beta0 vector which has full size and @nvar elements. */ { int ivar,avar; avar = 0; for (ivar = 0; ivar < matrix_get_columns( stepwise->X0 ); ivar++) { if (bool_vector_iget( stepwise->active_set , ivar )) { matrix_iset( stepwise->beta , ivar , 0 , matrix_iget( beta , avar , 0)); avar++; } } } matrix_free( beta ); } matrix_free( X ); matrix_free( E ); matrix_free( Y ); return y_mean; }
static void poly_projectforget_array(bool project, bool lazy, ap_manager_t* man, pk_t* po, pk_t* pa, ap_dim_t* tdim, size_t size) { bool res; matrix_t* mat; size_t i,j; pk_internal_t* pk = (pk_internal_t*)man->internal; pk_internal_realloc_lazy(pk,pa->intdim+pa->realdim); res = false; /* Get the generator systems, and possibly minimize */ if (lazy) poly_obtain_F(man,pa,"of the argument"); else poly_chernikova(man,pa,"of the argument"); if (pk->exn){ pk->exn = AP_EXC_NONE; if (!pa->F){ man->result.flag_best = man->result.flag_exact = false; poly_set_top(pk,po); return; } } /* if empty, return empty */ if (!pa->F){ man->result.flag_best = man->result.flag_exact = true; poly_set_bottom(pk,po); return; } if (project){ /* Project: assign the dimension to zero */ if (po==pa){ /* Forget the other matrices */ if (po->C){ matrix_free(po->C); po->C = NULL; } if (po->satC){ satmat_free(po->satC); po->satC = NULL; } if (po->satF){ satmat_free(po->satF); po->satF = NULL; } } else { /* Copy the old one */ po->F = matrix_copy(pa->F); } mat = po->F; for (i=0; i<mat->nbrows; i++){ for (j=0; j<size; j++){ numint_set_int(mat->p[i][pk->dec+tdim[j]],0); } matrix_normalize_row(pk,mat,(size_t)i); } po->status = 0; if (!lazy){ poly_chernikova(man,po,"of the result"); } } else { /* Forget */ mat = matrix_alloc(size,pa->F->nbcolumns,false); for (i=0; i<size; i++){ numint_set_int(mat->p[i][pk->dec+tdim[i]],1); } matrix_sort_rows(pk,mat); poly_dual(pa); if (po!=pa) poly_dual(po); if (!lazy) poly_obtain_satC(pa); res = poly_meet_matrix(false,lazy,man,po,pa,mat); poly_dual(pa); if (po!=pa) poly_dual(po); matrix_free(mat); } if (res || pk->exn){ pk->exn = AP_EXC_NONE; if (!po->F){ man->result.flag_best = man->result.flag_exact = false; poly_set_top(pk,po); return; } } if (pk->funopt->flag_best_wanted || pk->funopt->flag_exact_wanted){ bool real = true; if (pa->intdim>0){ for (i=0; i<size; i++){ if (tdim[i]<pa->intdim){ real = false; break; } } } man->result.flag_best = man->result.flag_exact = real; } else { man->result.flag_best = man->result.flag_exact = pa->intdim==0; } }
/*-------------------------------------------------------------*/ int main(int argc, char *argv[]) { /* check for and handle version tag */ int nargs = handle_version_option (argc, argv, "$Id: mri_gcut.cpp,v 1.14 2011/03/02 00:04:16 nicks Exp $", "$Name: stable5 $"); if (nargs && argc - nargs == 1) { exit (0); } argc -= nargs; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; parse_commandline(argc, argv); MRI *mri, *mri2, *mri3, *mri_mask=NULL; mri3 = MRIread(in_filename); if ( mri3 == NULL ) { printf("can't read file %s\nexit!\n", in_filename); exit(0); } mri = MRISeqchangeType(mri3, MRI_UCHAR, 0.0, 0.999, FALSE); mri2 = MRISeqchangeType(mri3, MRI_UCHAR, 0.0, 0.999, FALSE); //MRI* mri4 = MRIread("gcutted.mgz"); if (bNeedMasking == 1) { printf("reading mask...\n"); mri_mask = MRIread(mask_filename); if ( mri_mask == NULL ) { printf("can't read %s, omit -mult option!\n", mask_filename); print_help(); exit(1); } else { if ( mri_mask->width != mri->width || mri_mask->height != mri->height || mri_mask->depth != mri->depth ) { printf("Two masks are of different size, omit -mult option!\n"); print_help(); exit(1); } } } int w = mri->width; int h = mri->height; int d = mri->depth; // -- copy of mri matrix unsigned char ***label; label = new unsigned char**[d]; for (int i = 0; i < d; i++) { label[i] = new unsigned char*[h]; for (int j = 0; j < h; j++) { label[i][j] = new unsigned char[w]; for (int k = 0; k < w; k++) { label[i][j][k] = 0; } } } // -- gcut image int ***im_gcut; im_gcut = new int**[d]; for (int i = 0; i < d; i++) { im_gcut[i] = new int*[h]; for (int j = 0; j < h; j++) { im_gcut[i][j] = new int[w]; for (int k = 0; k < w; k++) { im_gcut[i][j][k] = 0; } } } // -- diluted int ***im_diluteerode; im_diluteerode = new int**[d]; for (int i = 0; i < d; i++) { im_diluteerode[i] = new int*[h]; for (int j = 0; j < h; j++) { im_diluteerode[i][j] = new int[w]; for (int k = 0; k < w; k++) { im_diluteerode[i][j][k] = 0; } } } //int w, h, d; //int x, y, z; double whitemean; if (bNeedPreprocessing == 0) { // pre-processed: 110 intensity voxels are the WM if (LCC_function(mri ->slices, label, mri->width, mri->height, mri->depth, whitemean) == 1) { if ( whitemean < 0 ) { printf("whitemean < 0 error!\n"); exit(0); } } else { whitemean = 110; printf("use voxels with intensity 110 as WM mask\n"); } } else { printf("estimating WM mask\n"); whitemean = pre_processing(mri ->slices, label, mri->width, mri->height, mri->depth); if ( whitemean < 0 ) { printf("whitemean < 0 error!\n"); exit(0); } } double threshold = whitemean * _t; printf("threshold set to: %f*%f=%f\n", whitemean, _t, threshold); for (int z = 0 ; z < mri->depth ; z++) { for (int y = 0 ; y < mri->height ; y++) { for (int x = 0 ; x < mri->width ; x++) { if ( mri->slices[z][y][x] < threshold + 1 ) { mri->slices[z][y][x] = 0; } } }//end of for } //new code int ***foregroundseedwt; int ***backgroundseedwt; matrix_alloc(&foregroundseedwt, d, h, w); matrix_alloc(&backgroundseedwt, d, h, w); double kval = 2.3; graphcut(mri->slices, label, im_gcut, foregroundseedwt, backgroundseedwt, w, h, d, kval, threshold, whitemean); printf("g-cut done!\npost-processing...\n"); //printf("_test: %f\n", _test); post_processing(mri2->slices, mri->slices, threshold, im_gcut, im_diluteerode, w, h, d); printf("post-processing done!\n"); if (bNeedMasking == 1)//masking { printf("masking...\n"); for (int z = 0 ; z < mri_mask->depth ; z++) { for (int y = 0 ; y < mri_mask->height ; y++) { for (int x = 0 ; x < mri_mask->width ; x++) { if ( mri_mask->slices[z][y][x] == 0 ) { im_diluteerode[z][y][x] = 0; } } } } } //if the output might have some problem int numGcut = 0, numMask = 0; double _ratio = 0; int error_Hurestic = 0; if (bNeedMasking == 1)//-110 and masking are both set { for (int z = 0 ; z < mri_mask->depth ; z++) { for (int y = 0 ; y < mri_mask->height ; y++) { for (int x = 0 ; x < mri_mask->width ; x++) { if ( im_diluteerode[z][y][x] != 0 ) { numGcut++; } if ( mri_mask->slices[z][y][x] != 0 ) { numMask++; } } } } _ratio = (double)numGcut / numMask; if (_ratio <= 0.85) { error_Hurestic = 1; } } if (error_Hurestic == 1) { printf("** Gcutted brain is much smaller than the mask!\n"); printf("** Using the mask as the output instead!\n"); //printf("** Gcutted output is written as: 'error_gcutted_sample'\n"); } for (int z = 0 ; z < mri->depth ; z++) { for (int y = 0 ; y < mri->height ; y++) { for (int x = 0 ; x < mri->width ; x++) { if (error_Hurestic == 0) { if ( im_diluteerode[z][y][x] == 0 ) { mri2 ->slices[z][y][x] = 0; } } else { if ( mri_mask->slices[z][y][x] == 0 ) { mri2 ->slices[z][y][x] = 0; } //if( im_diluteerode[z][y][x] == 0 ) //mri ->slices[z][y][x] = 0; } } }//end of for 2 }//end of for 1 MRIwrite(mri2, out_filename); // if user supplied a filename to which to write diffs, then write-out // volume file containing where cuts were made (for debug) if (diff_filename[0] && (error_Hurestic != 1)) { MRI *mri_diff = MRISeqchangeType(mri3, MRI_UCHAR, 0.0, 0.999, FALSE); for (int z = 0 ; z < mri3->depth ; z++) { for (int y = 0 ; y < mri3->height ; y++) { for (int x = 0 ; x < mri3->width ; x++) { if (mri_mask) { mri_diff->slices[z][y][x] = mri2->slices[z][y][x] - mri_mask->slices[z][y][x]; } else { mri_diff->slices[z][y][x] = mri2->slices[z][y][x] - mri3->slices[z][y][x]; } } }//end of for 2 }//end of for 1 MRIwrite(mri_diff, diff_filename); MRIfree(&mri_diff); } if (mri) { MRIfree(&mri); } if (mri2) { MRIfree(&mri2); } if (mri3) { MRIfree(&mri3); } if (mri_mask) { MRIfree(&mri_mask); } for (int i = 0; i < d; i++) { for (int j = 0; j < h; j++) { delete[] im_diluteerode[i][j]; delete[] im_gcut[i][j]; delete[] label[i][j]; } delete[] im_diluteerode[i]; delete[] im_gcut[i]; delete[] label[i]; } delete[] im_diluteerode; delete[] im_gcut; delete[] label; return 0; }
double graphcut(unsigned char ***image, unsigned char ***label, int ***im_gcut, int ***foreSW, int ***backSW, int xVol, int yVol, int zVol, double kval, double threshold, double whitemean) { //city block matrix int ***cityblock; matrix_alloc(&cityblock, zVol, yVol, xVol); //fore groud seed & back ground seed for (int z = 0; z < zVol; z++) { for (int y = 0; y < yVol; y++) { for (int x = 0; x < xVol; x++) { if ( label[z][y][x] == 1 ) { foreSW[z][y][x] = 4000; } if ( image[z][y][x] <= 0 ) { backSW[z][y][x] = 4000; } if ( image[z][y][x] > 0 ) { cityblock[z][y][x] = -1; } } } } do_cityblock(cityblock, zVol, yVol, xVol); int x_start, x_end, y_start, y_end, z_start, z_end; decide_bound(image, threshold, xVol, yVol, zVol, x_start, x_end, y_start, y_end, z_start, z_end); //new range int xVol_new = x_end - x_start + 1; int yVol_new = y_end - y_start + 1; int zVol_new = z_end - z_start + 1; //printf("x_new=%d, y_new=%d, z_new=%d", xVol_new, yVol_new, zVol_new); double k = kval / (whitemean - threshold); //assign memory int length_h = (xVol_new-1)*yVol_new*zVol_new; int length_v = xVol_new*(yVol_new-1)*zVol_new; int length_t = xVol_new*yVol_new*(zVol_new-1); edgeW *hor = new edgeW[length_h]; edgeW *ver = new edgeW[length_v]; edgeW *tra = new edgeW[length_t]; memset(hor,0,sizeof(edgeW[length_h])); memset(ver,0,sizeof(edgeW[length_v])); memset(tra,0,sizeof(edgeW[length_t])); int i, j; int x, y, z; printf("calculating weights...\n"); //hor for (i = 0, j = 0; i < length_h; j++) { map(j, &x, &y, &z, xVol_new, yVol_new, zVol_new); if ( x+1 == xVol_new ) continue; hor[i].edge1 = j + 1; hor[i].edge2 = j + 1 + 1; //weight //map(hor[i].edge1-1, &x, &y, &z, xVol_new, yVol_new, zVol_new); x += x_start; y += y_start; z += z_start; hor[i].weight = cityblock[z][y][x] > cityblock[z][y][x+1] ? cityblock[z][y][x] : cityblock[z][y][x+1]; hor[i].weight = hor[i].weight * hor[i].weight; if (hor[i].weight > 1 && hor[i].weight < 6) hor[i].weight = 6; if (hor[i].weight != 1 && hor[i].weight != 6 && hor[i].weight != 0) { unsigned char value = image[z][y][x] > image[z][y][x+1] ? image[z][y][x+1] : image[z][y][x]; hor[i].weight = (int)fabs(hor[i].weight * (exp(k * (value - threshold)) - 1)); } if (hor[i].weight > 1 && hor[i].weight < 6) hor[i].weight = 6; if (hor[i].weight > 0 && hor[i].weight < 1) hor[i].weight = 1; if (hor[i].weight == 0) hor[i].weight = 1000; //foreground seed and background seed hor[i].fsw = foreSW[z][y][x+1]; hor[i].bsw = backSW[z][y][x+1]; i++; } //ver for (i = 0, j = 0; i < length_v; j++) { map(j, &x, &y, &z, xVol_new, yVol_new, zVol_new); if ( y+1 == yVol_new ) continue; ver[i].edge1 = j + 1; ver[i].edge2 = j + 1 + xVol_new; //weight //map(ver[i].edge1-1, &x, &y, &z, xVol_new, yVol_new, zVol_new); x += x_start; y += y_start; z += z_start; ver[i].weight = cityblock[z][y][x] > cityblock[z][y+1][x] ? cityblock[z][y][x] : cityblock[z][y+1][x]; ver[i].weight = ver[i].weight * ver[i].weight; if (ver[i].weight > 1 && ver[i].weight < 6) ver[i].weight = 6; if (ver[i].weight != 1 && ver[i].weight != 6 && ver[i].weight != 0) { unsigned char value = image[z][y][x] > image[z][y+1][x] ? image[z][y+1][x] : image[z][y][x]; ver[i].weight = (int)fabs(ver[i].weight * (exp(k * (value - threshold)) - 1)); } if (ver[i].weight > 1 && ver[i].weight < 6) ver[i].weight = 6; if (ver[i].weight > 0 && ver[i].weight < 1) ver[i].weight = 1; if (ver[i].weight == 0) ver[i].weight = 1000; //foreground seed and background seed ver[i].fsw = foreSW[z][y+1][x]; ver[i].bsw = backSW[z][y+1][x]; i++; } //tra for (i = 0, j = 0; i < length_t; j++) { map(j, &x, &y, &z, xVol_new, yVol_new, zVol_new); if ( z+1 == zVol_new ) continue; tra[i].edge1 = j + 1; tra[i].edge2 = j + 1 + xVol_new * yVol_new; //weight //map(tra[i].edge1-1, &x, &y, &z, xVol_new, yVol_new, zVol_new); x += x_start; y += y_start; z += z_start; tra[i].weight = cityblock[z][y][x] > cityblock[z+1][y][x] ? cityblock[z][y][x] : cityblock[z+1][y][x]; tra[i].weight = tra[i].weight * tra[i].weight; if (tra[i].weight > 1 && tra[i].weight < 6) tra[i].weight = 6; if (tra[i].weight != 1 && tra[i].weight != 6 && tra[i].weight != 0) { unsigned char value = image[z][y][x] > image[z+1][y][x] ? image[z+1][y][x] : image[z][y][x]; tra[i].weight = (int)fabs(tra[i].weight * (exp(k * (value - threshold)) - 1)); } if (tra[i].weight > 1 && tra[i].weight < 6) tra[i].weight = 6; if (tra[i].weight > 0 && tra[i].weight < 1) tra[i].weight = 1; if (tra[i].weight == 0) tra[i].weight = 1000; //foreground seed and background seed tra[i].fsw = foreSW[z+1][y][x]; tra[i].bsw = backSW[z+1][y][x]; i++; } // -- free memory matrix_free(cityblock, zVol, yVol, xVol); matrix_free(backSW, zVol, yVol, xVol); matrix_free(foreSW, zVol, yVol, xVol); //mincut printf("doing mincut...\n"); mincut(im_gcut, hor, ver, tra, length_h, length_v, length_t, x_start, y_start, z_start, x_end, y_end, z_end); delete[] hor; delete[] ver; delete[] tra; return 0; }
void lars_estimate(lars_type * lars , int max_vars , double max_beta , bool verbose) { int nvars = matrix_get_columns( lars->X ); int nsample = matrix_get_rows( lars->X ); matrix_type * X = matrix_alloc( nsample, nvars ); // Allocate local X and Y variables matrix_type * Y = matrix_alloc( nsample, 1 ); // which will hold the normalized data lars_estimate_init( lars , X , Y); // during the estimation process. { matrix_type * G = matrix_alloc_gram( X , true ); matrix_type * mu = matrix_alloc( nsample , 1 ); matrix_type * C = matrix_alloc( nvars , 1 ); matrix_type * Y_mu = matrix_alloc_copy( Y ); int_vector_type * active_set = int_vector_alloc(0,0); int_vector_type * inactive_set = int_vector_alloc(0,0); int active_size; if ((max_vars <= 0) || (max_vars > nvars)) max_vars = nvars; { int i; for (i=0; i < nvars; i++) int_vector_iset( inactive_set , i , i ); } matrix_set( mu , 0 ); while (true) { double maxC = 0; /* The first step is to calculate the correlations between the covariates, and the current residual. All the currently inactive covariates are searched; the covariate with the greatest correlation with (Y - mu) is selected and added to the active set. */ matrix_sub( Y_mu , Y , mu ); // Y_mu = Y - mu matrix_dgemm( C , X , Y_mu , true , false , 1.0 , 0); // C = X' * Y_mu { int i; int max_set_index = 0; for (i=0; i < int_vector_size( inactive_set ); i++) { int set_index = i; int var_index = int_vector_iget( inactive_set , set_index ); double value = fabs( matrix_iget(C , var_index , 0) ); if (value > maxC) { maxC = value; max_set_index = set_index; } } /* Remove element corresponding to max_set_index from the inactive set and add it to the active set: */ int_vector_append( active_set , int_vector_idel( inactive_set , max_set_index )); } active_size = int_vector_size( active_set ); /* Now we have calculated the correlations between all the covariates and the current residual @Y_mu. The correlations are stored in the matrix @C. The value of the maximum correlation is stored in @maxC. Based on the value of @maxC we have added one new covariate to the model, technically by moving the index from @inactive_set to @active_set. */ /*****************************************************************/ { matrix_type * weights = matrix_alloc( active_size , 1); double scale; /*****************************************************************/ /* This scope should compute and initialize the variables @weights and @scale. */ { matrix_type * subG = matrix_alloc( active_size , active_size ); matrix_type * STS = matrix_alloc( active_size , active_size ); matrix_type * sign_vector = matrix_alloc( active_size , 1); int i , j; /* STS = S' o S where 'o' is the Schur product and S is given by: [ s1 s2 s3 s4 ] S = [ s1 s2 s3 s4 ] [ s1 s2 s3 s4 ] [ s1 s2 s3 s4 ] Where si is the sign of the correlation between (active) variable 'i' and Y_mu. */ for (i=0; i < active_size ; i++) { int vari = int_vector_iget( active_set , i ); double signi = sgn( matrix_iget( C , vari , 0)); matrix_iset( sign_vector , i , 0 , signi ); for (j=0; j < active_size; j++) { int varj = int_vector_iget( active_set , j ); double signj = sgn( matrix_iget( C , varj , 0)); matrix_iset( STS , i , j , signi * signj ); } } // Extract the elements from G corresponding to active indices and // copy to the matrix subG: for (i=0; i < active_size ; i++) { int ii = int_vector_iget( active_set , i ); for (j=0; j < active_size; j++) { int jj = int_vector_iget( active_set , j ); matrix_iset( subG , i , j , matrix_iget(G , ii , jj)); } } // Weights matrix_inplace_mul( subG , STS ); matrix_inv( subG ); { matrix_type * ones = matrix_alloc( active_size , 1 ); matrix_type * GA1 = matrix_alloc( active_size , 1 ); matrix_set( ones , 1.0 ); matrix_matmul( GA1 , subG , ones ); scale = 1.0 / sqrt( matrix_get_column_sum( GA1 , 0 )); matrix_mul( weights , GA1 , sign_vector ); matrix_scale( weights , scale ); matrix_free( GA1 ); matrix_free( ones ); } matrix_free( sign_vector ); matrix_free( subG ); matrix_free( STS ); } /******************************************************************/ /* The variables weight and scale have been calculated, proceed to calculate the step length @gamma. */ { int i; double gamma; { matrix_type * u = matrix_alloc( nsample , 1 ); int j; for (i=0; i < nsample; i++) { double row_sum = 0; for (j =0; j < active_size; j++) row_sum += matrix_iget( X , i , int_vector_iget( active_set , j)) * matrix_iget(weights , j , 0 ); matrix_iset( u , i , 0 , row_sum ); } gamma = maxC / scale; if (active_size < matrix_get_columns( X )) { matrix_type * equi_corr = matrix_alloc( nvars , 1 ); matrix_dgemm( equi_corr , X , u , true , false , 1.0 , 0); // equi_corr = X'·u for (i=0; i < (nvars - active_size); i++) { int var_index = int_vector_iget( inactive_set , i ); double gamma1 = (maxC - matrix_iget(C , var_index , 0 )) / ( scale - matrix_iget( equi_corr , var_index , 0)); double gamma2 = (maxC + matrix_iget(C , var_index , 0 )) / ( scale + matrix_iget( equi_corr , var_index , 0)); if ((gamma1 > 0) && (gamma1 < gamma)) gamma = gamma1; if ((gamma2 > 0) && (gamma2 < gamma)) gamma = gamma2; } matrix_free( equi_corr ); } /* Update the current estimated 'location' mu. */ matrix_scale( u , gamma ); matrix_inplace_add( mu , u ); matrix_free( u ); } /* We have calculated the step length @gamma, and the @weights. Update the @beta matrix. */ for (i=0; i < active_size; i++) matrix_iset( lars->beta , int_vector_iget( active_set , i ) , active_size - 1 , gamma * matrix_iget( weights , i , 0)); if (active_size > 1) for (i=0; i < nvars; i++) matrix_iadd( lars->beta , i , active_size - 1 , matrix_iget( lars->beta , i , active_size - 2)); matrix_free( weights ); } } if (active_size == max_vars) break; if (max_beta > 0) { double beta_norm2 = matrix_get_column_abssum( lars->beta , active_size - 1 ); if (beta_norm2 > max_beta) { // We stop - we will use an interpolation between this beta estimate and // the previous, to ensure that the |beta| = max_beta criteria is satisfied. if (active_size >= 2) { double beta_norm1 = matrix_get_column_abssum( lars->beta , active_size - 2 ); double s = (max_beta - beta_norm1)/(beta_norm2 - beta_norm1); { int j; for (j=0; j < nvars; j++) { double beta1 = matrix_iget( lars->beta , j , active_size - 2 ); double beta2 = matrix_iget( lars->beta , j , active_size - 1 ); matrix_iset( lars->beta , j , active_size - 1 , beta1 + s*(beta2 - beta1)); } } } break; } } } matrix_free( G ); matrix_free( mu ); matrix_free( C ); matrix_free( Y_mu ); int_vector_free( active_set ); int_vector_free( inactive_set ); matrix_resize( lars->beta , nvars , active_size , true ); if (verbose) matrix_pretty_fprint( lars->beta , "beta" , "%12.5f" , stdout ); lars_select_beta( lars , active_size - 1); } matrix_free( X ); matrix_free( Y ); }
void airsar_to_latlon(meta_parameters *meta, double xSample, double yLine, double height, double *lat, double *lon) { if (!meta->airsar) asfPrintError("airsar_to_latlon() called with no airsar block!\n"); const double a = 6378137.0; // semi-major axis const double b = 6356752.3412; // semi-minor axis const double e2 = 0.00669437999014; // ellipticity const double e12 = 0.00673949674228; // second eccentricity // we try to cache the matrices needed for the computation // this makes sure we don't reuse the cache incorrectly (i.e., on // data (=> an airsar block) which doesn't match what we cached for) static meta_airsar *cached_airsar_block = NULL; // these are the cached transformation parameters static matrix *m = NULL; static double ra=-999, o1=-999, o2=-999, o3=-999; if (!m) m = matrix_alloc(3,3); // only needs to be done once // if we aren't calculating with the exact same airsar block, we // need to recalculate the transformation block int recalc = !cached_airsar_block || cached_airsar_block->lat_peg_point != meta->airsar->lat_peg_point || cached_airsar_block->lon_peg_point != meta->airsar->lon_peg_point || cached_airsar_block->head_peg_point != meta->airsar->head_peg_point; if (recalc) { // cache airsar block, so we can be sure we're not reusing // the stored data incorrectly if (cached_airsar_block) free(cached_airsar_block); cached_airsar_block = meta_airsar_init(); *cached_airsar_block = *(meta->airsar); asfPrintStatus("Calculating airsar transformation parameters...\n"); // now precalculate data double lat_peg = meta->airsar->lat_peg_point*D2R; double lon_peg = meta->airsar->lon_peg_point*D2R; double head_peg = meta->airsar->head_peg_point*D2R; double re = a / sqrt(1-e2*sin(lat_peg)*sin(lat_peg)); double rn = (a*(1-e2)) / pow(1-e2*sin(lat_peg)*sin(lat_peg), 1.5); ra = (re*rn) / (re*cos(head_peg)*cos(head_peg)+rn*sin(head_peg)*sin(head_peg)); matrix *m1, *m2; m1 = matrix_alloc(3,3); m2 = matrix_alloc(3,3); m1->coeff[0][0] = -sin(lon_peg); m1->coeff[0][1] = -sin(lat_peg)*cos(lon_peg); m1->coeff[0][2] = cos(lat_peg)*cos(lon_peg); m1->coeff[1][0] = cos(lon_peg); m1->coeff[1][1] = -sin(lat_peg)*sin(lon_peg); m1->coeff[1][2] = cos(lat_peg)*sin(lon_peg); m1->coeff[2][0] = 0.0; m1->coeff[2][1] = cos(lat_peg); m1->coeff[2][2] = sin(lat_peg); m2->coeff[0][0] = 0.0; m2->coeff[0][1] = sin(head_peg); m2->coeff[0][2] = -cos(head_peg); m2->coeff[1][0] = 0.0; m2->coeff[1][1] = cos(head_peg); m2->coeff[1][2] = sin(head_peg); m2->coeff[2][0] = 1.0; m2->coeff[2][1] = 0.0; m2->coeff[2][2] = 0.0; o1 = re*cos(lat_peg)*cos(lon_peg)-ra*cos(lat_peg)*cos(lon_peg); o2 = re*cos(lat_peg)*sin(lon_peg)-ra*cos(lat_peg)*sin(lon_peg); o3 = re*(1-e2)*sin(lat_peg)-ra*sin(lat_peg); matrix_mult(m,m1,m2); matrix_free(m1); matrix_free(m2); } // Make sure we didn't miss anything assert(ra != -999 && o1 != -999 && o2 != -999 && o3 != -999); //------------------------------------------------------------------ // Now the actual computation, using the cached matrix etc // convenience aliases double c0 = meta->airsar->cross_track_offset; double s0 = meta->airsar->along_track_offset; double ypix = meta->general->y_pixel_size; double xpix = meta->general->x_pixel_size; // radar coordinates double c_lat = (xSample*xpix+c0)/ra; double s_lon = (yLine*ypix+s0)/ra; //height += meta->airsar->gps_altitude; // radar coordinates in WGS84 double t1 = (ra+height)*cos(c_lat)*cos(s_lon); double t2 = (ra+height)*cos(c_lat)*sin(s_lon); double t3 = (ra+height)*sin(c_lat); double c1 = m->coeff[0][0]*t1 + m->coeff[0][1]*t2 + m->coeff[0][2]*t3; double c2 = m->coeff[1][0]*t1 + m->coeff[1][1]*t2 + m->coeff[1][2]*t3; double c3 = m->coeff[2][0]*t1 + m->coeff[2][1]*t2 + m->coeff[2][2]*t3; // shift into local Cartesian coordinates double x = c1 + o1;// + 9.0; double y = c2 + o2;// - 161.0; double z = c3 + o3;// - 179.0; // local Cartesian coordinates into geographic coordinates double d = sqrt(x*x+y*y); double theta = atan2(z*a, d*b); *lat = R2D*atan2(z+e12*b*sin(theta)*sin(theta)*sin(theta), d-e2*a*cos(theta)*cos(theta)*cos(theta)); *lon = R2D*atan2(y, x); }
void test_create_invalid() { test_assert_NULL( matrix_alloc(0, 100)); test_assert_NULL( matrix_alloc(100, 0)); test_assert_NULL( matrix_alloc(0, 0)); test_assert_NULL( matrix_alloc(-1, -1)); }
int main(int argc, char *argv[]){ /* Declare vars that hold numRow and numCols values scanned from txt file */ int numRows, numCols; /* Declare pointer to matrix */ MatElement **matrix, **perm; /* Declare pointer to vector */ VectorElement *solution, *right; /* Declare row and column values to loop over rows / cols */ int rowCounter, colCounter; /* Check to make sure there are the correct number of cmdline args */ if(argc==2){ /* Declare FILE variable */ FILE* inputFile; /* Attempt to open file provided in cmdline arg */ inputFile=fopen(argv[1],"r"); /* Check to make sure file was opened properly */ if(inputFile==NULL){ /* Alert user file was not opened properly */ fprintf(stdout,"\nFile was not opened properly\n"); return 2; }else{ /* Scan numRows and numCols from file */ fscanf(inputFile, "%d %d", &numRows, &numCols); /* Check that numRows and numCols are equal */ if(numRows!=numCols){ /* numRows and numCols dont match, alert and exit */ fprintf(stdout, "Matrix has %d rows and %d columns, not a square matrix.\nExiting...\n", numRows, numCols); return 0; } /* Call matrix_alloc to allocate memory for matrix */ matrix=matrix_alloc(numRows,numCols); perm=matrix_identity(numRows); /* Call vector_alloc to allocate memory for vector */ right=vector_alloc(numRows); solution=vector_alloc(numRows); /* For each row, read in value for each column, in * addition to permutation value at end of row */ for(rowCounter=0;rowCounter<numRows;rowCounter++){ /* Declare variable for right hand side */ double rightValue; /* Loop over cols of each row */ for(colCounter=0;colCounter<numCols;colCounter++){ /* Declare variable for value stored in amtrix */ double matValue; /* Grab value for matrix at A[rowCounter][colCounter] */ fscanf(inputFile, "%lf", &matValue); /* Set matrix value at [rowCount][colCount] */ matrix[rowCounter][colCounter]=matValue; } /* End for over cols */ /* Grab the value for matrix at right[rowCounter] */ fscanf(inputFile, "%lf", &rightValue); /* Set right value at right[rowCounter] */ right[rowCounter]=rightValue; } /* End for over rows */ fprintf(stdout, "Original Matrix: \n"); matrix_print(matrix, " %g ", numRows, numCols); fprintf(stdout, "\nRight hand side vector:\n"); vector_print(right, " %g ", numRows); fprintf(stdout, "\nPermutation Matrix: \n"); matrix_print(perm, " %g ", numRows, numCols); /* make call to decomp */ linalg_LU_decomp(matrix,perm,numRows); print_plu(matrix, perm, numRows); fprintf(stdout, "Matrix after decomposition \n"); matrix_print(matrix, " %g ", numRows, numCols); fprintf(stdout, "\nPermuation after decomposition \n"); matrix_print(perm, " %g ", numRows, numCols); /* make call to solve */ linalg_LU_solve(matrix,perm,right,solution, numRows); vector_print(solution, " %g ", numRows); fprintf(stdout,"Freeing matrices\n"); matrix_free(matrix); matrix_free(perm); fprintf(stdout,"Freeing vectors\n"); vector_free(solution); } /* End check for valid input file */ }else{ /* Alert user to proper usage */ fprintf(stdout,"Usage: ./linalg <xxxx.txt>\n"); return 1; } /* End check for cmdline args */ /* Program completed successfully, return 0 to user */ return 0; }