int main(){ uint64_t nodes = pow(2,SCALE); uint64_t edges = nodes*EDGEFACTOR; uint64_t *startVertex = malloc(edges*I64_BYTES); uint64_t *endVertex = malloc(edges*I64_BYTES); float initiator[] = {0.57,0.19,0.19,0.05}; generate_graph(SCALE, EDGEFACTOR, startVertex, endVertex,initiator); char matrix[NODES][NODES] = {{0,1,0,0,0,0,0}, {0,0,1,0,0,0,0}, {0,0,0,1,0,0,0}, {0,0,0,0,1,0,0}, {0,0,0,0,0,1,0}, {0,0,0,0,0,0,1}, {0,0,0,0,0,0,0}}; char parents[] = {0,0,0,0,0,0,0}; char level[] = {0,0,0,0,0,0,0}; double time = mytime(); transpose_matrix(matrix); bfs_2d(matrix, level, parents); time = mytime() - time; printf("Time: %f\n", time/1000000); return 0; }
int main(void) { int** m; int num_cols, num_rows; srand (time(NULL)); printf("How many columns?: "); scanf("%d", &num_cols); printf("How many rows?: "); scanf("%d", &num_rows); m = create_matrix(num_cols, num_rows); if (NULL == m) { exit(-1); } random_int_matrix(m, num_cols, num_rows); print_matrix(m, num_cols, num_rows); int **transpose = create_matrix(num_rows, num_cols); if (NULL == transpose) { exit(-1); } transpose_matrix(m, transpose, num_cols, num_rows); print_matrix(transpose, num_rows, num_cols); destroy_matrix(m, num_rows); destroy_matrix(transpose, num_cols); return 0; }
static void whittle2 (Array acf, Array Aold, Array Bold, int lag, char *direction, Array A, Array K, Array E) { int d, i, nser=DIM(acf)[1]; const void *vmax; Array beta, tmp, id; d = strcmp(direction, "forward") == 0; vmax = vmaxget(); beta = make_zero_matrix(nser,nser); tmp = make_zero_matrix(nser, nser); id = make_identity_matrix(nser); set_array_to_zero(E); copy_array(id, subarray(A,0)); for(i = 0; i < lag; i++) { matrix_prod(subarray(acf,lag - i), subarray(Aold,i), d, 1, tmp); array_op(beta, tmp, '+', beta); matrix_prod(subarray(acf,i), subarray(Bold,i), d, 1, tmp); array_op(E, tmp, '+', E); } qr_solve(E, beta, K); transpose_matrix(K,K); for (i = 1; i <= lag; i++) { matrix_prod(K, subarray(Bold,lag - i), 0, 0, tmp); array_op(subarray(Aold,i), tmp, '-', subarray(A,i)); } vmaxset(vmax); }
/* Função main. * A função espera um único argumento. * O argumento deve ser o nome de um arquivo no seguinte formato: num_linhas num_colunas a11 a12 a13 ... a1n a21 a22 a23 ... a2n . . . . . . . . . . . . . . . am1 am2 am3 ... amn * Os termos são separados por espaços. * num_linhas e num_colunas DEVEM ser inteiros. * Os termos podem ser em ponto flutuante. */ int main(int argc, char *argv[]){ if (argc != 2){ printf("Número inválido de argumentos!\n"); return 0; } int lines,columns; int index_i,index_j; float value; FILE *archive; archive=fopen(argv[1],"r"); fscanf(archive,"%d %d",&lines,&columns); matrix *pointer_matrix,*transposed_matrix; pointer_matrix = create(lines,columns); // Atribui valores na matriz. for(index_i=0;index_i<lines;index_i++){ for(index_j=0;index_j<columns;index_j++){ fscanf(archive,"%f ",&value); assign(pointer_matrix,index_i,index_j,value); } } printf("A matriz possui %d linhas e %d colunas.\nElementos:\n\n",lines,columns); //Imprime a matriz original, antes de realizar a transposição. print_matrix(pointer_matrix); transposed_matrix=transpose_matrix(pointer_matrix); lines=size_lines(transposed_matrix); columns=size_columns(transposed_matrix); printf("A matriz transposta possui %d linhas e %d colunas.\nElementos:\n\n",lines,columns); // Imprime a matriz transposta. print_matrix(transposed_matrix); release(transposed_matrix); release(pointer_matrix); return 0; }
static void qr_solve(Array x, Array y, Array coef) /* Translation of the R function qr.solve into pure C NB We have to transpose the matrices since the ordering of an array is different in Fortran NB2 We have to copy x to avoid it being overwritten. */ { int i, info = 0, rank, *pivot, n, p; const void *vmax; double tol = 1.0E-7, *qraux, *work; Array xt, yt, coeft; assert(NROW(x) == NROW(y)); assert(NCOL(coef) == NCOL(y)); assert(NCOL(x) == NROW(coef)); vmax = vmaxget(); qraux = (double *) R_alloc(NCOL(x), sizeof(double)); pivot = (int *) R_alloc(NCOL(x), sizeof(int)); work = (double *) R_alloc(2*NCOL(x), sizeof(double)); for(i = 0; i < NCOL(x); i++) pivot[i] = i+1; xt = make_zero_matrix(NCOL(x), NROW(x)); transpose_matrix(x,xt); n = NROW(x); p = NCOL(x); F77_CALL(dqrdc2)(VECTOR(xt), &n, &n, &p, &tol, &rank, qraux, pivot, work); if (rank != p) error(_("Singular matrix in qr_solve")); yt = make_zero_matrix(NCOL(y), NROW(y)); coeft = make_zero_matrix(NCOL(coef), NROW(coef)); transpose_matrix(y, yt); F77_CALL(dqrcf)(VECTOR(xt), &NROW(x), &rank, qraux, yt.vec, &NCOL(y), coeft.vec, &info); transpose_matrix(coeft,coef); vmaxset(vmax); }
void setup_view_matrix( player_data_t *plyr ) { vector_t view_x, view_y, view_z; matrixgl_t view_mat; point_t viewpt_in_view_frame; view_z = scale_vector( -1, plyr->view.dir ); view_x = cross_product( plyr->view.up, view_z ); view_y = cross_product( view_z, view_x ); normalize_vector( &view_z ); normalize_vector( &view_x ); normalize_vector( &view_y ); make_identity_matrix( plyr->view.inv_view_mat ); plyr->view.inv_view_mat[0][0] = view_x.x; plyr->view.inv_view_mat[0][1] = view_x.y; plyr->view.inv_view_mat[0][2] = view_x.z; plyr->view.inv_view_mat[1][0] = view_y.x; plyr->view.inv_view_mat[1][1] = view_y.y; plyr->view.inv_view_mat[1][2] = view_y.z; plyr->view.inv_view_mat[2][0] = view_z.x; plyr->view.inv_view_mat[2][1] = view_z.y; plyr->view.inv_view_mat[2][2] = view_z.z; plyr->view.inv_view_mat[3][0] = plyr->view.pos.x; plyr->view.inv_view_mat[3][1] = plyr->view.pos.y; plyr->view.inv_view_mat[3][2] = plyr->view.pos.z; plyr->view.inv_view_mat[3][3] = 1; transpose_matrix( plyr->view.inv_view_mat, view_mat ); view_mat[0][3] = 0; view_mat[1][3] = 0; view_mat[2][3] = 0; viewpt_in_view_frame = transform_point( view_mat, plyr->view.pos ); view_mat[3][0] = -viewpt_in_view_frame.x; view_mat[3][1] = -viewpt_in_view_frame.y; view_mat[3][2] = -viewpt_in_view_frame.z; glLoadIdentity(); #ifdef __APPLE__DISABLED__ GLfloat matrix[3][3]; int i,j; for( i = 0; i < 3; i++ ) { for( j = 0; j < 3; j++ ) matrix[i][j] = view_mat[i][j]; } glMultMatrixf( (GLfloat *) matrix ); #else glMultMatrixd( (scalar_t *) view_mat ); #endif }
enum efp_result efp_compute_id_direct(struct efp *efp) { double *c; size_t n; fortranint_t *ipiv; enum efp_result res; n = 3 * efp->n_polarizable_pts; c = (double *)calloc(n * n, sizeof *c); ipiv = (fortranint_t *)calloc(n, sizeof *ipiv); if (c == NULL || ipiv == NULL) { res = EFP_RESULT_NO_MEMORY; goto error; } /* induced dipoles */ compute_lhs(efp, c, 0); compute_rhs(efp, efp->indip, 0); transpose_matrix(c, n); if (efp_dgesv((fortranint_t)n, 1, c, (fortranint_t)n, ipiv, (double *)efp->indip, (fortranint_t)n) != 0) { efp_log("dgesv: error solving for induced dipoles"); res = EFP_RESULT_FATAL; goto error; } /* conjugate induced dipoles */ compute_lhs(efp, c, 1); compute_rhs(efp, efp->indipconj, 1); transpose_matrix(c, n); if (efp_dgesv((fortranint_t)n, 1, c, (fortranint_t)n, ipiv, (double *)efp->indipconj, (fortranint_t)n) != 0) { efp_log("dgesv: error solving for conjugate induced dipoles"); res = EFP_RESULT_FATAL; goto error; } res = EFP_RESULT_SUCCESS; error: free(c); free(ipiv); return res; }
void apply_rot_norm(double *m, t_coord *move) { double *tmp; tmp = (double *)j_malloc(sizeof(double) * 16); transpose_matrix(tmp, m); apply_matrix(tmp, move); free(tmp); }
int main(int argc, char **argv){ int matrix[][3] = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}}; transpose_matrix(3, matrix); getchar(); return 0; }
void matrix_mult_ijk_transposed (float **a, float **b, float **c, int N){ transpose_matrix(b,N); for(unsigned i=0;i<N;i++){ for(unsigned j=0;j<N;j++){ for(unsigned k=0;k<N;k++){ c[i][j] += a[i][k] * b[j][k]; } } } }
void DXShader::SetConstantMatrix(const String& name, int shaderType, const mat4x4& matrix) { ShaderConstant* con = GetConstant(name, shaderType); if(con == nullptr) return; con->type = ShaderConstant::MAT4X4; mat4x4 transMat = transpose_matrix((mat4x4) matrix); for(int i = 0; i < 16; i++) con->constant[i] = transMat[i]; }
void setup_view_matrix( player_data_t *plyr ) { GLfloat matrix[4][4]; int i,j; vector_t view_x, view_y, view_z; matrixgl_t view_mat; point_t viewpt_in_view_frame; view_z = scale_vector( -1, plyr->view.dir ); view_x = cross_product( plyr->view.up, view_z ); view_y = cross_product( view_z, view_x ); normalize_vector( &view_z ); normalize_vector( &view_x ); normalize_vector( &view_y ); make_identity_matrix( plyr->view.inv_view_mat ); plyr->view.inv_view_mat[0][0] = view_x.x; plyr->view.inv_view_mat[0][1] = view_x.y; plyr->view.inv_view_mat[0][2] = view_x.z; plyr->view.inv_view_mat[1][0] = view_y.x; plyr->view.inv_view_mat[1][1] = view_y.y; plyr->view.inv_view_mat[1][2] = view_y.z; plyr->view.inv_view_mat[2][0] = view_z.x; plyr->view.inv_view_mat[2][1] = view_z.y; plyr->view.inv_view_mat[2][2] = view_z.z; plyr->view.inv_view_mat[3][0] = plyr->view.pos.x; plyr->view.inv_view_mat[3][1] = plyr->view.pos.y; plyr->view.inv_view_mat[3][2] = plyr->view.pos.z; plyr->view.inv_view_mat[3][3] = 1; transpose_matrix( plyr->view.inv_view_mat, view_mat ); view_mat[0][3] = 0; view_mat[1][3] = 0; view_mat[2][3] = 0; viewpt_in_view_frame = transform_point( view_mat, plyr->view.pos ); view_mat[3][0] = -viewpt_in_view_frame.x; view_mat[3][1] = -viewpt_in_view_frame.y; view_mat[3][2] = -viewpt_in_view_frame.z; //glLoadIdentity(); for( i = 0; i < 4; i++ ) { for( j = 0; j < 4; j++ ) matrix[i][j] = view_mat[i][j]; } util_set_view(matrix); }
int main(void) { void transpose_matrix(void); transpose_matrix(); for (i = 0; i < 2; ++i) for (j = 0; j < 3; ++j) printf("%i (%i) | ", matrix2[i][j], i); return 0; }
void load_convolutional_weights(layer l, FILE *fp) { if(l.binary){ //load_convolutional_weights_binary(l, fp); //return; } if(l.numload) l.n = l.numload; int num = l.c/l.groups*l.n*l.size*l.size; fread(l.biases, sizeof(float), l.n, fp); if (l.batch_normalize && (!l.dontloadscales)){ fread(l.scales, sizeof(float), l.n, fp); fread(l.rolling_mean, sizeof(float), l.n, fp); fread(l.rolling_variance, sizeof(float), l.n, fp); if(0){ int i; for(i = 0; i < l.n; ++i){ printf("%g, ", l.rolling_mean[i]); } printf("\n"); for(i = 0; i < l.n; ++i){ printf("%g, ", l.rolling_variance[i]); } printf("\n"); } if(0){ fill_cpu(l.n, 0, l.rolling_mean, 1); fill_cpu(l.n, 0, l.rolling_variance, 1); } if(0){ int i; for(i = 0; i < l.n; ++i){ printf("%g, ", l.rolling_mean[i]); } printf("\n"); for(i = 0; i < l.n; ++i){ printf("%g, ", l.rolling_variance[i]); } printf("\n"); } } fread(l.weights, sizeof(float), num, fp); //if(l.c == 3) scal_cpu(num, 1./256, l.weights, 1); if (l.flipped) { transpose_matrix(l.weights, l.c*l.size*l.size, l.n); } //if (l.binary) binarize_weights(l.weights, l.n, l.c*l.size*l.size, l.weights); #ifdef GPU if(gpu_index >= 0){ push_convolutional_layer(l); } #endif }
// Performs matrix multiplication and stores the result in the given // destination matrix (C). void mult_matrix(Matrix *A, Matrix *B, Matrix *C) { // Fill this in // Note that it is asking for matrix multiplication, not // elementwise multiplication if ((A->cols != B->rows) || (A->rows != C->rows) || (B->cols != C->cols)){ printf("%s\n", "DIM Mismatch"); exit(1); } Matrix *BT = transpose_matrix(B); int i, j; for (i = 0; i < A->rows; ++i) { for (j = 0; j < B->cols; ++j) { C->data[i][j] = dot_product(A->data[i], BT->data[j], A->cols); } } destroy_matrix(BT); }
int main(void) { void transpose_matrix(int x, int y, int matrix1[x][y], int matrix2[y][x]); int i, j; int mat1[3][2] = { {1, 2}, {3, 4}, {5, 6}}; int mat2[2][3] = {{}, {}}; transpose_matrix(3, 2, mat1, mat2); for (i = 0; i < 2; ++i) for (j = 0; j < 3; ++j) printf("%i (%i) | ", mat2[i][j], i); return 0; }
/* Aplica transformações geométrica à localização do vértice corrente e ao vetor normal associado a ele. * * Argumentos de entrada: * 'vertex_oc' : Localização do vértice representada no sistema de coordenadas do objeto (object coordinates, OC). * 'normal_oc' : Vetor normal à superfície representada no sistema de coordenadas do objeto (OC). * 'modelview_matrix' : Matriz 4x4 composta pelas transformações de modelo e visualização (view_matrix * model_matrix). * 'projection_matrix': Matriz 4x4 de projeção. * * Argumentos de saída: * 'vertex_ec' : Localização do vértice representada no sistema de coordenadas da câmera (eye coordinates, EC). * 'vertex_cc' : Localização do vértice representada no sistema coordenadas de recorte (clip coordinates, CC). * 'unit_normal_ec' : Vetor normal à superfície representado no sistema de coordenadas da câmera (EC). Assume-se que * a norma deste vetor é igual a 1.0f. */ void vertex_transformation(const location_struct &vertex_oc, const direction_struct &normal_oc, const matrix_struct &modelview_matrix, const matrix_struct &projection_matrix, location_struct &vertex_ec, location_struct &vertex_cc, direction_struct &unit_normal_ec) { //Calcular 'vertex_ec'. //Calcular 'vertex_cc'. //Calcular 'unit_normal_ec'. vertex_ec[0] = vertex_oc[0] * modelview_matrix(0,0) + vertex_oc[1] * modelview_matrix(0,1) + vertex_oc[2] * modelview_matrix(0,2) + vertex_oc[3] * modelview_matrix(0,3); vertex_ec[1] = vertex_oc[0] * modelview_matrix(1,0) + vertex_oc[1] * modelview_matrix(1,1) + vertex_oc[2] * modelview_matrix(1,2) + vertex_oc[3] * modelview_matrix(1,3); vertex_ec[2] = vertex_oc[0] * modelview_matrix(2,0) + vertex_oc[1] * modelview_matrix(2,1) + vertex_oc[2] * modelview_matrix(2,2) + vertex_oc[3] * modelview_matrix(2,3); vertex_ec[3] = vertex_oc[0] * modelview_matrix(3,0) + vertex_oc[1] * modelview_matrix(3,1) + vertex_oc[2] * modelview_matrix(3,2) + vertex_oc[3] * modelview_matrix(3,3); vertex_cc[0] = vertex_ec[0] * projection_matrix(0,0) + vertex_ec[1] * projection_matrix(0,1) + vertex_ec[2] * projection_matrix(0,2) + vertex_ec[3] * projection_matrix(0,3); vertex_cc[1] = vertex_ec[0] * projection_matrix(1,0) + vertex_ec[1] * projection_matrix(1,1) + vertex_ec[2] * projection_matrix(1,2) + vertex_ec[3] * projection_matrix(1,3); vertex_cc[2] = vertex_ec[0] * projection_matrix(2,0) + vertex_ec[1] * projection_matrix(2,1) + vertex_ec[2] * projection_matrix(2,2) + vertex_ec[3] * projection_matrix(2,3); vertex_cc[3] = vertex_ec[0] * projection_matrix(3,0) + vertex_ec[1] * projection_matrix(3,1) + vertex_ec[2] * projection_matrix(3,2) + vertex_ec[3] * projection_matrix(3,3); matrix_struct transposta = matrix_struct(); matrix_struct inverse = matrix_struct(); inverse_matrix(modelview_matrix, inverse); transpose_matrix(inverse, transposta); unit_normal_ec[0] = normal_oc[0] * transposta(0,0) + normal_oc[1] * transposta(0,1) + normal_oc[2] * transposta(0,2); unit_normal_ec[1] = normal_oc[0] * transposta(1,0) + normal_oc[1] * transposta(1,1) + normal_oc[2] * transposta(1,2); unit_normal_ec[2] = normal_oc[0] * transposta(2,0) + normal_oc[1] * transposta(2,1) + normal_oc[2] * transposta(2,2); normalize(unit_normal_ec); }
/** * mash_light_set_direction_uniform: * @light: The #MashLight which is generating the shader * @uniform_location: The location of the uniform * @direction_in: The untransformed direction uniform * * This is a convenience intended to be used within * mash_light_update_uniforms() to help set uniforms. It * should not generally need to be called by an application unless it * is implementing its own lighting algorithms. * * This is intended to help when setting a direction * uniform. @direction_in should be an untransformed array of 3 floats * representing a vector. The vector will be transformed into eye * space according to the inverse transposed matrix of @light so that * it won't change direction for non-uniform scaling transformations. */ void mash_light_set_direction_uniform (MashLight *light, CoglHandle program, int uniform_location, const float *direction_in) { float light_direction[4]; CoglMatrix matrix, inverse_matrix; float magnitude; memcpy (light_direction, direction_in, sizeof (light_direction)); mash_light_get_modelview_matrix (light, &matrix); /* To safely transform the direction when the matrix might not be orthogonal we need the transposed inverse matrix */ cogl_matrix_get_inverse (&matrix, &inverse_matrix); transpose_matrix (&inverse_matrix, &matrix); cogl_matrix_transform_point (&matrix, light_direction + 0, light_direction + 1, light_direction + 2, light_direction + 3); /* Normalize the light direction */ magnitude = sqrtf ((light_direction[0] * light_direction[0]) + (light_direction[1] * light_direction[1]) + (light_direction[2] * light_direction[2])); light_direction[0] /= magnitude; light_direction[1] /= magnitude; light_direction[2] /= magnitude; cogl_program_set_uniform_float (program, uniform_location, 3, 1, light_direction); }
/******************************************************************************* * vector_t lin_system_solve_qr(matrix_t A, vector_t b) * * Gives a least-squares solution to the system AX=b for non-square A using QR. * * Ax=b * QRx=b * Rx=Q'b (because Q'Q=I) * then solve for x with gaussian elimination *******************************************************************************/ vector_t lin_system_solve_qr(matrix_t A, vector_t b){ vector_t xout = create_empty_vector(); vector_t temp; matrix_t Q,R; int i,k; if(!A.initialized || !b.initialized){ printf("ERROR: matrix or vector not initialized yet\n"); return xout; } // do QR decomposition if(QR_decomposition(A,&Q,&R)<0){ printf("failed to perform QR decomposition on A\n"); return xout; } // transpose Q matrix if(transpose_matrix(&Q)<0){ printf("ERROR: failed to transpose Q\n"); return xout; } // multiply through temp = matrix_times_col_vec(Q,b); destroy_matrix(&Q); // solve for x knowing R is upper triangular int nDim = R.cols; xout = create_vector(nDim); for(k=(nDim-1); k>=0; k--){ xout.data[k] = temp.data[k]; for(i=(k+1); i<nDim; i++){ xout.data[k] -= (R.data[k][i]*xout.data[i]); } xout.data[k] = xout.data[k] / R.data[k][k]; } destroy_matrix(&R); destroy_vector(&temp); return xout; }
void load_connected_weights(layer l, FILE *fp, int transpose) { fread(l.biases, sizeof(float), l.outputs, fp); fread(l.weights, sizeof(float), l.outputs*l.inputs, fp); if(transpose){ transpose_matrix(l.weights, l.inputs, l.outputs); } //printf("Biases: %f mean %f variance\n", mean_array(l.biases, l.outputs), variance_array(l.biases, l.outputs)); //printf("Weights: %f mean %f variance\n", mean_array(l.weights, l.outputs*l.inputs), variance_array(l.weights, l.outputs*l.inputs)); if (l.batch_normalize && (!l.dontloadscales)){ fread(l.scales, sizeof(float), l.outputs, fp); fread(l.rolling_mean, sizeof(float), l.outputs, fp); fread(l.rolling_variance, sizeof(float), l.outputs, fp); //printf("Scales: %f mean %f variance\n", mean_array(l.scales, l.outputs), variance_array(l.scales, l.outputs)); //printf("rolling_mean: %f mean %f variance\n", mean_array(l.rolling_mean, l.outputs), variance_array(l.rolling_mean, l.outputs)); //printf("rolling_variance: %f mean %f variance\n", mean_array(l.rolling_variance, l.outputs), variance_array(l.rolling_variance, l.outputs)); } #ifdef GPU if(gpu_index >= 0){ push_connected_layer(l); } #endif }
void least_squares(double *ans,double const*const* R,const int m,const int n,double const*z,const int m1) { if(m1!=m) return; double **temp_m=new double*[n],**temp_m1=new double*[n]; double *r=new double[n]; double **Rt=new double*[n]; for (int j=0;j<n;j++) Rt[j]=new double[m]; for (int i=0;i<n;i++) { temp_m[i]=new double[n]; temp_m1[i]=new double[n]; } transpose_matrix(Rt,R,m,n); multiply(r,Rt,n,m,z,m); multiply(temp_m,Rt,n,m,R,m,n); obratnaya_matrica(temp_m1,temp_m,n,n); multiply(ans,temp_m1,n,n,r,n); for (int j=0;j<n;j++) delete[] Rt[j]; delete[] Rt; for (int i=0;i<n;i++) { delete[] temp_m[i]; delete[] temp_m1[i]; } delete[] temp_m; delete[] temp_m1; delete[] r; }
void load_convolutional_weights(layer l, FILE *fp) { if(l.binary){ //load_convolutional_weights_binary(l, fp); //return; } int num = l.n*l.c*l.size*l.size; fread(l.biases, sizeof(float), l.n, fp); if (l.batch_normalize && (!l.dontloadscales)){ fread(l.scales, sizeof(float), l.n, fp); fread(l.rolling_mean, sizeof(float), l.n, fp); fread(l.rolling_variance, sizeof(float), l.n, fp); } fread(l.filters, sizeof(float), num, fp); if (l.flipped) { transpose_matrix(l.filters, l.c*l.size*l.size, l.n); } if (l.binary) binarize_filters(l.filters, l.n, l.c*l.size*l.size, l.filters); #ifdef GPU if(gpu_index >= 0){ push_convolutional_layer(l); } #endif }
static void burg2(Array ss_ff, Array ss_bb, Array ss_fb, Array E, Array KA, Array KB) /* Estimate partial correlation by minimizing (1/2)*log(det(s)) where "s" is the the sum of the forward and backward prediction errors. In the multivariate case, the forward (KA) and backward (KB) partial correlation coefficients are related by KA = solve(E) %*% t(KB) %*% E where E is the prediction variance. */ { int i, j, k, l, nser = NROW(ss_ff); int iter; Array ss_bf; Array s, tmp, d1; Array D1, D2, THETA, THETAOLD, THETADIFF, TMP; Array obj; Array e, f, g, h, sg, sh; Array theta; ss_bf = make_zero_matrix(nser,nser); transpose_matrix(ss_fb, ss_bf); s = make_zero_matrix(nser, nser); tmp = make_zero_matrix(nser, nser); d1 = make_zero_matrix(nser, nser); e = make_zero_matrix(nser, nser); f = make_zero_matrix(nser, nser); g = make_zero_matrix(nser, nser); h = make_zero_matrix(nser, nser); sg = make_zero_matrix(nser, nser); sh = make_zero_matrix(nser, nser); theta = make_zero_matrix(nser, nser); D1 = make_zero_matrix(nser*nser, 1); D2 = make_zero_matrix(nser*nser, nser*nser); THETA = make_zero_matrix(nser*nser, 1); /* theta in vector form */ THETAOLD = make_zero_matrix(nser*nser, 1); THETADIFF = make_zero_matrix(nser*nser, 1); TMP = make_zero_matrix(nser*nser, 1); obj = make_zero_matrix(1,1); /* utility matrices e,f,g,h */ qr_solve(E, ss_bf, e); qr_solve(E, ss_fb, f); qr_solve(E, ss_bb, tmp); transpose_matrix(tmp, tmp); qr_solve(E, tmp, g); qr_solve(E, ss_ff, tmp); transpose_matrix(tmp, tmp); qr_solve(E, tmp, h); for(iter = 0; iter < BURG_MAX_ITER; iter++) { /* Forward and backward partial correlation coefficients */ transpose_matrix(theta, tmp); qr_solve(E, tmp, tmp); transpose_matrix(tmp, KA); qr_solve(E, theta, tmp); transpose_matrix(tmp, KB); /* Sum of forward and backward prediction errors ... */ set_array_to_zero(s); /* Forward */ array_op(s, ss_ff, '+', s); matrix_prod(KA, ss_bf, 0, 0, tmp); array_op(s, tmp, '-', s); transpose_matrix(tmp, tmp); array_op(s, tmp, '-', s); matrix_prod(ss_bb, KA, 0, 1, tmp); matrix_prod(KA, tmp, 0, 0, tmp); array_op(s, tmp, '+', s); /* Backward */ array_op(s, ss_bb, '+', s); matrix_prod(KB, ss_fb, 0, 0, tmp); array_op(s, tmp, '-', s); transpose_matrix(tmp, tmp); array_op(s, tmp, '-', s); matrix_prod(ss_ff, KB, 0, 1, tmp); matrix_prod(KB, tmp, 0, 0, tmp); array_op(s, tmp, '+', s); matrix_prod(s, f, 0, 0, d1); matrix_prod(e, s, 1, 0, tmp); array_op(d1, tmp, '+', d1); /*matrix_prod(g,s,0,0,sg);*/ matrix_prod(s,g,0,0,sg); matrix_prod(s,h,0,0,sh); for (i = 0; i < nser; i++) { for (j = 0; j < nser; j++) { MATRIX(D1)[nser*i+j][0] = MATRIX(d1)[i][j]; for (k = 0; k < nser; k++) for (l = 0; l < nser; l++) { MATRIX(D2)[nser*i+j][nser*k+l] = (i == k) * MATRIX(sg)[j][l] + MATRIX(sh)[i][k] * (j == l); } } } copy_array(THETA, THETAOLD); qr_solve(D2, D1, THETA); for (i = 0; i < vector_length(theta); i++) VECTOR(theta)[i] = VECTOR(THETA)[i]; matrix_prod(D2, THETA, 0, 0, TMP); array_op(THETAOLD, THETA, '-', THETADIFF); matrix_prod(D2, THETADIFF, 0, 0, TMP); matrix_prod(THETADIFF, TMP, 1, 0, obj); if (VECTOR(obj)[0] < BURG_TOL) break; } if (iter == BURG_MAX_ITER) error(_("Burg's algorithm failed to find partial correlation")); }
static int calccoef(struct Control_Points_3D *cp, double OR[], int ndims) { double **src_mat = NULL; double **src_mat_T = NULL; double **dest_mat = NULL; double **dest_mat_T = NULL; double **src_dest_mat = NULL; double *S_vec = NULL; double **R_mat = NULL; double **R_mat_T = NULL; double **mat_mn1 = NULL; double **mat_mn2 = NULL; double **mat_nm1 = NULL; double **mat_nm2 = NULL; double **mat_nn1 = NULL; double **E_mat = NULL; double **P_mat = NULL; double **Q_mat = NULL; double *D_vec = NULL; double *one_vec = NULL; double trace1 = 0.0; double trace2 = 0.0; int numactive; /* NUMBER OF ACTIVE CONTROL POINTS */ int m, n, i, j; int status; /* CALCULATE THE NUMBER OF VALID CONTROL POINTS */ for (i = numactive = 0; i < cp->count; i++) { if (cp->status[i] > 0) numactive++; } m = numactive; n = ndims; src_mat = G_alloc_matrix(m, n); dest_mat = G_alloc_matrix(m, n); for (i = numactive = 0; i < cp->count; i++) { if (cp->status[i] > 0) { src_mat[numactive][0] = cp->e1[i]; src_mat[numactive][1] = cp->n1[i]; src_mat[numactive][2] = cp->z1[i]; dest_mat[numactive][0] = cp->e2[i]; dest_mat[numactive][1] = cp->n2[i]; dest_mat[numactive][2] = cp->z2[i]; numactive++; } } D_vec = G_alloc_vector(ndims); src_mat_T = G_alloc_matrix(n, m); dest_mat_T = G_alloc_matrix(n, m); src_dest_mat = G_alloc_matrix(n, n); R_mat = G_alloc_matrix(n, n); R_mat_T = G_alloc_matrix(n, n); mat_mn1 = G_alloc_matrix(m, n); mat_mn2 = G_alloc_matrix(m, n); mat_nm1 = G_alloc_matrix(n, m); mat_nm2 = G_alloc_matrix(n, m); mat_nn1 = G_alloc_matrix(n, n); E_mat = G_alloc_matrix(m, m); P_mat = G_alloc_matrix(ndims, ndims); Q_mat = G_alloc_matrix(ndims, ndims); transpose_matrix(m, n, dest_mat, dest_mat_T); for (i = 0; i < m; i++) { for (j = 0; j < m; j++) { if (i != j) { E_mat[i][j] = -1.0 / (double)m; } else{ E_mat[i][j] = 1.0 - 1.0 / (double)m; } } } matmult(n, m, m, dest_mat_T, E_mat, mat_nm1); matmult(n, m, n, mat_nm1, src_mat, src_dest_mat); copy_matrix(n, n, src_dest_mat, P_mat); copy_matrix(n, n, src_dest_mat, mat_nn1); status = G_math_svduv(D_vec, mat_nn1, P_mat, n, Q_mat, n); if (status == 0) status = MSUCCESS; transpose_matrix(n, n, P_mat, mat_nn1); /* rotation matrix */ matmult(n, n, n, Q_mat, mat_nn1, R_mat_T); transpose_matrix(n, n, R_mat_T, R_mat); /* scale */ matmult(n, n, n, src_dest_mat, R_mat_T, mat_nn1); trace1 = trace(n, n, mat_nn1); transpose_matrix(m, n, src_mat, src_mat_T); matmult(n, m, m, src_mat_T, E_mat, mat_nm1); matmult(n, m, n, mat_nm1, src_mat, mat_nn1); trace2 = trace(n, n, mat_nn1); OR[14] = trace1 / trace2; /* shifts */ matmult(m, n, n, src_mat, R_mat_T, mat_mn1); scale_matrix(m, n, OR[14], mat_mn1, mat_mn2); subtract_matrix(m, n, dest_mat, mat_mn2, mat_mn1); scale_matrix(m, n, 1.0 / m, mat_mn1, mat_mn2); transpose_matrix(m, n, mat_mn2, mat_nm1); S_vec = G_alloc_vector(n); one_vec = G_alloc_vector(m); for (i = 0; i < m; i++){ one_vec[i] = 1.0; } matrix_multiply(n, m, mat_nm1, one_vec, S_vec); /* matrix to vector */ for (i = 0; i < ndims; i++) { for (j = 0; j < ndims; j++) { OR[i * ndims + j] = R_mat[i][j]; } } G_free_matrix(src_mat); G_free_matrix(src_mat_T); G_free_matrix(dest_mat); G_free_matrix(dest_mat_T); G_free_matrix(src_dest_mat); G_free_vector(D_vec); G_free_matrix(E_mat); G_free_matrix(P_mat); G_free_matrix(Q_mat); G_free_matrix(R_mat); G_free_matrix(R_mat_T); G_free_matrix(mat_mn1); G_free_matrix(mat_mn2); G_free_matrix(mat_nm1); G_free_matrix(mat_nm2); G_free_matrix(mat_nn1); G_free_vector(S_vec); G_free_vector(one_vec); return status; }
int main(void) { clock_t begin, end; double time_spent; begin = clock(); matrix* a = create_matrix(4, 4); value temp_a[16] = { 18, 60, 57, 96, 41, 24, 99, 58, 14, 30, 97, 66, 51, 13, 19, 85 }; insert_array(temp_a, a); matrix* b = create_matrix(4, 4); assert(insert_array(temp_a, b)); //tests check_boundaries assert(check_boundaries(1,1,a)); assert(check_boundaries(4,4,a)); assert(!check_boundaries(4,5,a)); assert(!check_boundaries(5,4,a)); assert(!check_boundaries(0,1,a)); assert(!check_boundaries(1,0,a)); assert(!check_boundaries(-1,1,a)); assert(!check_boundaries(1,-1,a)); //tests compare_matrices,insert_value and get_value assert(compare_matrices(a,b)); assert(insert_value(10,1,1,b)); assert(!compare_matrices(a,b)); assert(get_value(1,1,b)==10); assert(insert_value(18,1,1,b)); assert(compare_matrices(a,b)); //tests is_matrix matrix* c=a; assert(compare_matrices(a,c)); assert(!is_matrix(a,b)); assert(is_matrix(a,c)); //tests insert_value by trying to go outside the matrix assert(insert_value(1,1,1,c)); assert(insert_value(2,2,2,c)); assert(insert_value(3,3,3,c)); assert(insert_value(4,4,4,c)); assert(!insert_value(5,5,5,c)); assert(!insert_value(-1,-1,-1,c)); assert(!insert_value(-1,-1,1,c)); assert(!insert_value(-1,1,-1,c)); //test get_value assert(get_value(1,1,c)==1); assert(get_value(2,2,c)==2); assert(get_value(3,3,c)==3); assert(get_value(4,4,c)==4); assert(get_value(0,0,c)==0); assert(get_value(1,-1,c)==0); assert(get_value(-1,1,c)==0); assert(get_value(5,5,c)==0); //tests insert and get without boundary checks insert_value_without_check(4,1,1,c); insert_value_without_check(3,2,2,c); insert_value_without_check(2,3,3,c); insert_value_without_check(1,4,4,c); assert(get_value_without_check(1,1,c)==4); assert(get_value_without_check(2,2,c)==3); assert(get_value_without_check(3,3,c)==2); assert(get_value_without_check(4,4,c)==1); //tests add_matrices value temp_b[16]={ 36,120,114,192, 82,48,198,116, 28, 60, 194,132, 102,26,38,170}; assert(insert_array(temp_b,a)); matrix* d = create_matrix(4, 4); assert(add_matrices(b,b,d)); assert(compare_matrices(d,a)); //tests subtract_matrices value temp_c[16]={ 0,0,0,0, 0,0,0,0, 0, 0, 0,0, 0,0,0,0}; assert(insert_array(temp_c,a)); assert(subtract_matrices(b,b,d)); assert(compare_matrices(d,a)); //tests sum_of_row assert(insert_array(temp_a,a)); assert(sum_of_row(1,a)==231); assert(sum_of_row(4,a)==168); assert(sum_of_row(0,a)==0); assert(sum_of_row(5,a)==0); //tests sum_of_column assert(sum_of_column(1,a)==124); assert(sum_of_column(4,a)==305); assert(sum_of_column(0,a)==0); assert(sum_of_column(5,a)==0); //tests get_row_vector matrix* e = create_matrix(1, 4); value temp_d[4] = { 18, 60, 57, 96}; assert(insert_array(temp_d,e)); matrix* f = create_matrix(1, 4); assert(!get_row_vector(0,a,f)); assert(!get_row_vector(5,a,f)); assert(get_row_vector(1,a,f)); assert(compare_matrices(e,f)); //tests get_column_vector matrix* g = create_matrix(4, 1); assert(insert_array(temp_d,e)); matrix* h = create_matrix(1, 4); assert(!get_row_vector(0,a,h)); assert(!get_row_vector(5,a,h)); assert(get_row_vector(1,a,h)); assert(compare_matrices(e,h)); //tests mulitply_matrices assert(multiply_matrices(a,a,b)); value temp_f[16]={8478,5478,14319,17130, 6066,6760,15418,16792, 6206,5328,14431,15096, 6052,5047,7652,14129.00}; assert(insert_array(temp_f,d)); assert(compare_matrices(b,d)); assert(!multiply_matrices(a,h,b)); assert(!multiply_matrices(a,a,h)); //tests transpose_matrix value temp_g[16]={18,41,14,51, 60,24,30,13, 57,99,97,19, 96,58,66,85}; assert(insert_array(temp_g,d)); assert(transpose_matrix(a,b)); assert(compare_matrices(b,d)); assert(!transpose_matrix(e,b)); assert(!transpose_matrix(a,e)); //tests multiply_matrix_with_scalar value temp_h[16] = { 36, 120, 114, 192, 82, 48, 198, 116, 28, 60, 194, 132, 102, 26, 38, 170 }; assert(insert_array(temp_h,b)); multiply_matrix_with_scalar(2,a); assert(compare_matrices(a,b)); //test get_sub_matrix matrix* i=create_matrix(2,2); assert(insert_array(temp_a,a)); assert(get_sub_matrix(1,2,1,2,a,i)); matrix* j=create_matrix(2,2); value temp_i[4] = { 18, 60, 41, 24}; assert(insert_array(temp_i,j)); assert(compare_matrices(j,i)); value temp_j[4] = { 97, 66, 19, 85}; assert(insert_array(temp_j,j)); assert(get_sub_matrix(3,4,3,4,a,i)); assert(compare_matrices(j,i)); assert(!get_sub_matrix(2,4,3,4,a,i)); assert(!get_sub_matrix(3,4,2,4,a,i)); assert(!get_sub_matrix(4,5,4,5,a,i)); assert(!get_sub_matrix(0,1,0,1,a,i)); //test insert_row_vector assert(insert_array(temp_a,a)); value temp_k[16] = { 18, 60, 57, 96, 18, 60, 57, 96, 14, 30, 97, 66, 51, 13, 19, 85 }; assert(insert_array(temp_k,b)); assert(insert_array(temp_d,e)); assert(insert_row_vector(2,e,a)); assert(compare_matrices(a,b)); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("time taken was: %f \n",time_spent); free_matrix(a); free_matrix(b); free_matrix(d); free_matrix(e); free_matrix(f); free_matrix(g); free_matrix(h); free_matrix(i); free_matrix(j); return 0; }
int main() { printf("Task 1. Sort an array:\n"); //define array variables int random_order [ARRAY_LENGHT]; int sorted [ARRAY_LENGHT]; int inversed [ARRAY_LENGHT]; //initialize array variables for (int i = 0; i < ARRAY_LENGHT; ++i) { random_order[i] = rand() % 100; sorted[i] = i; inversed[i] = ARRAY_LENGHT - i; } printf("Before sorting.\n"); printf("Random array:\n"); print_array(random_order, ARRAY_LENGHT); printf("Sorted array:\n"); print_array(sorted, ARRAY_LENGHT); printf("Inversed array:\n"); print_array(inversed, ARRAY_LENGHT); //sorting sort_array(random_order, ARRAY_LENGHT); sort_array(sorted, ARRAY_LENGHT); sort_array(inversed, ARRAY_LENGHT); printf("After sorting.\n"); printf("Random array:\n"); print_array(random_order, ARRAY_LENGHT); printf("Sorted array:\n"); print_array(sorted, ARRAY_LENGHT); printf("Inversed array:\n"); print_array(inversed, ARRAY_LENGHT); printf("\n\n"); printf("Task 2. Binary search:\n"); int niddle = rand() % 100; int position = binary_search_i(random_order, ARRAY_LENGHT, niddle); if (position == NOT_FOUND) { printf("There is no %d in random array.\n", niddle); } else { printf("Position of %d in random array is %d.\n", niddle, position); } printf("\n\n"); printf("Task 3. Transpose matrix:\n"); int matrix [M_WIDTH * M_HEIGHT]; for (int i = 0; i < M_HEIGHT; ++i) { for (int j = 0; j < M_WIDTH; ++j) { matrix[i * M_WIDTH + j] = rand() % 100; } } print_matrix(matrix, M_WIDTH, M_HEIGHT); transpose_matrix(matrix, M_WIDTH, M_HEIGHT); print_matrix(matrix, M_HEIGHT, M_WIDTH); return 0; }
void get_rotation(float angle, float ax, float ay, float az, gtMatrix mat) { gtMatrix r1,r2,r3; float theta; gtVector n; gtVector a,b,c; a[0] = ax; a[1] = ay; a[2] = az; normalize_vector(a); /* create vector not parallel to "a" */ ax = fabs(a[0]); ay = fabs(a[1]); az = fabs(a[2]); n[0] = n[1] = n[2] = 0; if (ax > ay) { if (ay > az) n[2] = 1; /* z is smallest */ else n[1] = 1; /* y is smallest */ } else { if (ax > az) n[2] = 1; /* z is smallest */ else n[0] = 1; /* x is smallest */ } /* create "b" orthogonal to "a" */ cross (b, a, n); normalize_vector(b); /* create "c" orthogonal to "a" and "b" */ cross (c, a, b); /* make matrix that rotates a,b,c into x,y,z axes */ identity_matrix (r1); r1[0][0] = a[0]; r1[1][0] = a[1]; r1[2][0] = a[2]; r1[0][1] = b[0]; r1[1][1] = b[1]; r1[2][1] = b[2]; r1[0][2] = c[0]; r1[1][2] = c[1]; r1[2][2] = c[2]; /* make matrix for rotation by theta degrees around x-axis */ theta = angle * 3.1415926535 / 180.0; identity_matrix (r2); r2[1][1] = cos(theta); r2[2][2] = cos(theta); r2[1][2] = sin(theta); r2[2][1] = -sin(theta); /* make matrix that is inverse of r1 */ copy_matrix (r3, r1); transpose_matrix (r3); /* compose these matrices for final matrix mat = r3 * r2 * r1 */ mult_matrix (mat, r3, r2); mult_matrix (mat, mat, r1); }
FLT_DBL find_ortho (FLT_DBL * cc, FLT_DBL * rmat) { int kk; FLT_DBL ccrot[6 * 6]; FLT_DBL ccortho[6 * 6]; FLT_DBL ccrot2[6 * 6]; FLT_DBL ccti[6 * 6]; FLT_DBL rmat_transp[9]; FLT_DBL rmat_temp[9]; FLT_DBL rmat_temp2[9]; FLT_DBL vec[3]; FLT_DBL vec2[3]; FLT_DBL dist; FLT_DBL dista[3]; FLT_DBL qq[4], qq_best[4]; double center[4]; double range[4]; int count[4]; int qindex[4]; double inc[4]; FLT_DBL phi, theta; FLT_DBL temp; FLT_DBL dist_best; /* * Keep the compiler from complaining that this may be uninitialized. */ dist_best = NO_NORM; /* * Search over all possible orientations. * * Any orientation in 3-space can be specified by a unit vector, * giving an axis to rotate around, and an angle to rotate about * the given axis. The orientation is given with respect to some * fixed reference orientation. * * Since rotating by theta degrees about (A,B,C) produces the same * result as rotating -theta degrees about (-A,-B,-C), we only * need to consider 180 degrees worth of angles, not 360. * * In this application, we are finding the orientation of an orthorhombic * medium. Orthorhombic symmetry has three orthogonal symmetry planes, * so any one octant defines the whole. We thus only need to search * over rotation axes within one octant. * * Following the article in EDN, March 2, 1995, on page 95, author * "Do-While Jones" (a pen name of R. David Pogge), * "Quaternions quickly transform coordinates without error buildup", * we use quaternions to express the rotation. The article can be read * online here: * http://www.reed-electronics.com/ednmag/archives/1995/030295/05df3.htm * * If (A,B,C) is a unit vector to rotate theta degrees about, then: * * q0 = Cos (theta/2) * q1 = A * Sin(theta/2) * q2 = B * Sin(theta/2) * q3 = C * Sin(theta/2) * * so that q0^2 + q1^2 + q2^2 + q3^2 = 1. (A unit magnitude quaternion * represents a pure rotation, with no change in scale). * * For our case, taking advantage of the orthorhombic symmetry to * restrict the search space, we have: * 0 <= A <= 1 * 0 <= B <= 1 * 0 <= C <= 1 * 0 <= theta <= 180 degrees. * The rotation axis direction is limited to within one octant, * and the rotation about that axis is limited to half of the full circle. * * In terms of quaternions, this bounds all four elements between 0 and 1, * inclusive. */ /* * How much to subdivide each quaternion axis in the original scan. These * were somewhat arbitrarily chosen. These choices appear to be overkill, * but that ensures we won't accidentally miss the correct result by * insufficient sampling of the search space. */ /* * We sample the rotation angle more finely than the rotation axis. */ count[0] = SUB_ROT; count[1] = SUB_POS; count[2] = SUB_POS; count[3] = SUB_POS; /* * Between 0. and 1. for all 4 Q's (That is .5 +- .5.) */ for (kk = 0; kk < 4; kk++) { range[kk] = .5; center[kk] = .5; /* * A number meaning "not set yet", to get us through the loop the * first time. Needs to be much bigger than END_RES. */ inc[kk] = NOT_SET_YET; } while (inc[0] > END_RES && inc[1] > END_RES && inc[2] > END_RES && inc[3] > END_RES) { /* * Update inc to reflect the increment for the current search */ for (kk = 0; kk < 4; kk++) { inc[kk] = (2. * range[kk]) / (FLT_DBL) (count[kk] - 1); } /* * Start the 4-dimensional search. Keep track of the best result * found so far. The distance must be non-negative; we use -1 to mean * "not set yet". */ dist_best = NO_NORM; for (qindex[3] = 0; qindex[3] < count[3]; qindex[3]++) for (qindex[2] = 0; qindex[2] < count[2]; qindex[2]++) for (qindex[1] = 0; qindex[1] < count[1]; qindex[1]++) for (qindex[0] = 0; qindex[0] < count[0]; qindex[0]++) { /* * Calculate the quaternion for this search point. */ for (kk = 0; kk < 4; kk++) { /* * The term in parenthesis ranges from -1 to +1, * inclusive, so qq ranges from (-range+center) * to (+range + center). */ qq[kk] = range[kk] * (((FLT_DBL) (2 * qindex[kk] - (count[kk] - 1))) / ((FLT_DBL) (count[kk] - 1))) + center[kk]; } /* * Convert from a quaternion to a rotation matrix. * The subroutine also takes care of normalizing the * quaternion. */ quaternion_to_matrix (qq, rmat); /* * Apply the rotation matrix to the elastic stiffness * matrix. */ rotate_tensor (ccrot, cc, rmat); /* * Find the distance of the rotated medium from * orthorhombic aligned with the coordinate axes. */ dist = ortho_distance (ccortho, ccrot); /* * If it's the best found so far, or the first time * through, remember it. */ if (dist < dist_best || dist_best < 0.) { dist_best = dist; for (kk = 0; kk < 4; kk++) qq_best[kk] = qq[kk]; } } /* * Refine for the next, finer, search. To avoid any possible problem * caused by the optimal solution landing at an edge, we search over * twice the distance between the two search points from the previous * iteration. */ for (kk = 0; kk < 4; kk++) { center[kk] = qq_best[kk]; count[kk] = SUBDIVIDE; range[kk] = inc[kk]; } /* * We keep refining and searching the ever finer grid until we * achieve the required accuracy, at which point we fall out the * bottom of the loop here. */ } /* * We've got the answer to sufficient resolution... clean it up a bit, * then output it. */ /* * Convert the best answer from a Quaternion back to a rotation matrix */ quaternion_to_matrix (qq_best, rmat); /* * To make the order of the axes unique, we sort the principal axes * according to how well they work as a TI symmetry axis. * * Specifically, since after rotation the medium is canonically oriented, * with the X, Y, and Z axes the principal axes, the INVERSE rotation * must take the X, Y, and Z axes to the original arbitrarily oriented * principal axes. So we first inverse-rotate a coordinate axis back to a * principal axis. We then use vector_to_angles to give us the Euler * angles theta and phi for the principal axis. make_rotation_matrix then * constructs a rotation matrix that rotates that principal axis to +Z. * We then use that matrix to rotate the tensor. We then measure its * distance from VTI, and remember that distance. */ /* * First we need to find the inverse (the same as the transpose, because * it's _unitary_) of the rotation matrix rmat. */ transpose_matrix (rmat_transp, rmat); /* Test the X axis */ vec[0] = 1.; vec[1] = 0.; vec[2] = 0.; matrix_times_vector (vec2, rmat_transp, vec); vector_to_angles (vec2, &phi, &theta); make_rotation_matrix (theta, phi, 0., rmat_temp); rotate_tensor (ccrot2, cc, rmat_temp); dista[0] = ti_distance (ccti, ccrot2); /* Test the Y axis */ vec[0] = 0.; vec[1] = 1.; vec[2] = 0.; matrix_times_vector (vec2, rmat_transp, vec); vector_to_angles (vec2, &phi, &theta); make_rotation_matrix (theta, phi, 0., rmat_temp); rotate_tensor (ccrot2, cc, rmat_temp); dista[1] = ti_distance (ccti, ccrot2); /* Test the Z axis */ vec[0] = 0.; vec[1] = 0.; vec[2] = 1.; matrix_times_vector (vec2, rmat_transp, vec); vector_to_angles (vec2, &phi, &theta); make_rotation_matrix (theta, phi, 0., rmat_temp); rotate_tensor (ccrot2, cc, rmat_temp); dista[2] = ti_distance (ccti, ccrot2); /* * See which axis best functions as a TI symmetry axis, and make that one * the Z axis. */ if (dista[2] <= dista[1] && dista[2] <= dista[0]) { /* The Z axis is already the best. No rotation needed. */ make_rotation_matrix (0., 0., 0., rmat_temp); } else if (dista[1] <= dista[2] && dista[1] <= dista[0]) { /* Rotate Y to Z */ make_rotation_matrix (0., 90., 0., rmat_temp); temp = dista[2]; dista[2] = dista[1]; dista[1] = temp; } else { /* Rotate X to Z */ make_rotation_matrix (90., 90., -90., rmat_temp); temp = dista[2]; dista[2] = dista[0]; dista[0] = temp; } /* * Accumulate this axis-relabeling rotation (rmat_temp) onto the original * rotation (rmat). */ matrix_times_matrix (rmat_temp2, rmat_temp, rmat); /* * Now find the next-best TI symmetry axis and make that one the Y axis. */ if (dista[1] <= dista[0]) { /* Already there; do nothing. */ make_rotation_matrix (0., 0., 0., rmat_temp); } else { /* Rotate X to Y */ make_rotation_matrix (90., 0., 0., rmat_temp); temp = dista[1]; dista[1] = dista[0]; dista[0] = temp; } /* * Accumulate the new axis relabeling rotation (rmat_temp) onto the * combined previous rotation matrix (rmat_temp2) to produce the final * desired result, rmat. The axes should now be in sorted order. */ matrix_times_matrix (rmat, rmat_temp, rmat_temp2); return dist_best; }
/******************************************************************************* * int QR_decomposition(matrix_t A, matrix_t* Q, matrix_t* R) * * *******************************************************************************/ int QR_decomposition(matrix_t A, matrix_t* Q, matrix_t* R){ int i, j, k, s; int m = A.rows; int n = A.cols; vector_t xtemp; matrix_t Qt, Rt, Qi, F, temp; if(!A.initialized){ printf("ERROR: matrix not initialized yet\n"); return -1; } destroy_matrix(Q); destroy_matrix(R); Qt = create_matrix(m,m); for(i=0;i<m;i++){ // initialize Qt as I Qt.data[i][i] = 1; } Rt = duplicate_matrix(A); // duplicate A to Rt for(i=0;i<n;i++){ // iterate through columns of A xtemp = create_vector(m-i); // allocate length, decreases with i for(j=i;j<m;j++){ // take col of -R from diag down xtemp.data[j-i] = -Rt.data[j][i]; } if(Rt.data[i][i] > 0) s = -1; // check the sign else s = 1; xtemp.data[0] += s*vector_norm(xtemp); // add norm to 1st element Qi = create_square_matrix(m); // initialize Qi F = create_square_matrix(m-i); // initialize shrinking householder_matrix F = householder_matrix(xtemp); // fill in Househodor for(j=0;j<i;j++){ Qi.data[j][j] = 1; // fill in partial I matrix } for(j=i;j<m;j++){ // fill in remainder (householder_matrix) for(k=i;k<m;k++){ Qi.data[j][k] = F.data[j-i][k-i]; } } // multiply new Qi to old Qtemp temp = duplicate_matrix(Qt); destroy_matrix(&Qt); Qt = multiply_matrices(Qi,temp); destroy_matrix(&temp); // same with Rtemp temp = duplicate_matrix(Rt); destroy_matrix(&Rt); Rt = multiply_matrices(Qi,temp); destroy_matrix(&temp); // free other allocation used in this step destroy_matrix(&Qi); destroy_matrix(&F); destroy_vector(&xtemp); } transpose_matrix(&Qt); *Q = Qt; *R = Rt; return 0; }
int transform(const char * source, const char * destination, const char * output){ char src_pts_name[256]; char dest_pts_name[256]; char out_param_name[256]; int n=3; int m=0; int m2=0; int k,l; double **src_mat=NULL; double **dest_mat=NULL; double **dest_mat_T=NULL; double **src_mat_T=NULL; double **E_mat=NULL; double **C_mat=NULL; double **C_mat_interm=NULL; double **D_mat_interm=NULL; double **P_mat=NULL; double *D_vec=NULL; double *T_vec=NULL; double *one_vec=NULL; double **D_mat=NULL; double **Q_mat=NULL; double **P_mat_T=NULL; double **R_mat=NULL; double trace1=0.0; double trace2=0.0; double scal=0.0; double ppm=0.0; FILE *outfile; printf("\n*******************************\n"); printf( "* helmparms3d v%1.2f *\n",VERS); printf( "* (c) U. Niethammer 2011 *\n"); printf( "* http://helmparms3d.sf.net *\n"); printf( "*******************************\n"); memset(src_pts_name,0,sizeof(src_pts_name)); memset(dest_pts_name,0,sizeof(dest_pts_name)); memset(out_param_name,0,sizeof(out_param_name)); strcpy(src_pts_name, source); strcpy(dest_pts_name, destination); strcpy(out_param_name, output); m=get_m_size(src_pts_name); m2=get_m_size(dest_pts_name); if(m2!=m){ printf("Error, number of source and destination points is not equal!\n"); } else { src_mat=matrix(m,m, src_mat); dest_mat=matrix(m,m, dest_mat); read_points(src_pts_name, src_mat); read_points(dest_pts_name, dest_mat); D_vec=vector(n, D_vec); E_mat=matrix(m, m, E_mat); P_mat=matrix(m, m, P_mat); D_mat=matrix(m, m, D_mat); Q_mat=matrix(m, m, Q_mat); P_mat_T=matrix(m, m, P_mat_T); R_mat=matrix(m, m, R_mat); dest_mat_T=matrix(m, m, dest_mat_T); C_mat=matrix(m, m, C_mat); C_mat_interm=matrix(m, m, C_mat_interm); src_mat_T=matrix(m, m, src_mat_T); D_mat_interm=matrix(m, m, D_mat_interm); transpose_matrix(m, m, dest_mat, dest_mat_T); if(debug)printf("%s_T:\n",dest_pts_name); if(debug)plot_matrix(stdout, n, m, dest_mat_T); for(k=0;k<m;k++){ for(l=0;l<m;l++){ if(k!=l){ E_mat[k][l]=-1.0/(double)m; } else{ E_mat[k][l]=1.0-1.0/(double)m; } } } if(debug)printf("E:\n"); if(debug)plot_matrix(stdout, m, m, E_mat); if(debug)printf("dest_mat_T:\n"); if(debug)plot_matrix(stdout, n, m, dest_mat_T); matmult(dest_mat_T, m, m, E_mat, m, m, C_mat_interm, m, n); if(debug)printf("C_interm:\n"); if(debug)plot_matrix(stdout, n, m, C_mat_interm); matmult(C_mat_interm, n, m, src_mat, m, n, C_mat, n, n); if(debug)printf("C:\n"); if(debug)plot_matrix(stdout, n, n, C_mat); copy_matrix(n,n,C_mat,P_mat); if(debug)printf("P:\n"); if(debug)plot_matrix(stdout, n, n, P_mat); //Given matrix C[m][n], m>=n, using svd decomposition C = P D Q' to get P[m][n], diag D[n] and Q[n][n]. svd(n, n, C_mat, P_mat, D_vec, Q_mat); transpose_matrix(n, n, P_mat, P_mat_T); if(debug)printf("P\n"); if(debug)plot_matrix(stdout, n, n, P_mat); if(debug)printf("P_T\n"); if(debug)plot_matrix(stdout, n, n, P_mat_T); if(debug)printf("D_vec\n"); if(debug)plot_vector(stdout, n, D_vec); for(k=0;k<n;k++){ for(l=0;l<n;l++){ D_mat[k][l]=0.0; D_mat[l][l]=D_vec[l]; } } if(debug)printf("D\n"); if(debug)plot_matrix(stdout, n, n, D_mat); matmult(Q_mat, n, n, P_mat_T, n, n, R_mat, n, n); if(debug)printf("R_trans:\n"); if(debug)plot_matrix(stdout, n, n, R_mat); matmult(C_mat, m, n, R_mat, n, m, C_mat_interm, m, n); if(debug)printf("C_interm:\n"); if(debug)plot_matrix(stdout, n, n, C_mat_interm); trace1=trace(n,n,C_mat_interm); if(debug)printf("\ntra=%lf\n\n",trace1); transpose_matrix(m, m, src_mat, src_mat_T); if(debug)printf("%s_T:\n",src_pts_name); if(debug)plot_matrix(stdout, n, m, src_mat_T); init_matrix(m,m,C_mat); init_matrix(m,m,C_mat_interm); matmult(src_mat_T, m, m, E_mat, m, m, C_mat_interm, n, n); if(debug)printf("C_interm:\n"); if(debug)plot_matrix(stdout, n, m, C_mat_interm); matmult(C_mat_interm, n, m, src_mat, m, n, C_mat, n, n); if(debug)printf("C:\n"); if(debug)plot_matrix(stdout, n, n, C_mat); trace2=trace(n,n,C_mat); if(debug)printf("\ntra=%lf\n\n",trace2); scal=trace1/trace2; ppm=scal-1.0; if(debug)printf("\nscal = %10.10lf\nscal = %10.10lf ppm\n\n",scal, ppm); init_matrix(m,m,C_mat); init_matrix(m,m,C_mat_interm); matmult(src_mat, m, n, R_mat, n,m, D_mat_interm, m, n); if(debug)printf("C_mat_interm:\n"); if(debug)plot_matrix(stdout, m, n, D_mat_interm); scal_matrix(m, n, scal, D_mat_interm, C_mat_interm); if(debug)printf("C_mat_interm:\n"); if(debug)plot_matrix(stdout, m, n, C_mat_interm); subtract_matrix(m, n, dest_mat, C_mat_interm, D_mat_interm); if(debug)plot_matrix(stdout, m, n, D_mat_interm); scal_matrix(m, n, 1.0/m, D_mat_interm, C_mat_interm); if(debug)plot_matrix(stdout, m, n, C_mat_interm); init_matrix(m,m,src_mat_T); transpose_matrix(m, m, C_mat_interm, src_mat_T); if(debug)plot_matrix(stdout, n, m, src_mat_T); T_vec=vector(m, T_vec); one_vec=vector(m, one_vec); for(k=0;k<m;k++){ one_vec[k]=1.0; } matrix_multiply(n, m, src_mat_T, one_vec, T_vec); if(debug)printf("T:\n"); if(debug)plot_vector(stdout, 3, T_vec); outfile = fopen(out_param_name, "w"); if(outfile == NULL){ printf("Error writing %s\r\n",out_param_name); exit(-1); } init_matrix(m,m,src_mat_T); transpose_matrix(m, m, R_mat, src_mat_T); plot_matrix(outfile, n, n, src_mat_T); printf("R =\n");fflush(stdout); plot_matrix(stdout, n, n, src_mat_T); printf("\n");fflush(stdout); plot_vector(outfile, 3, T_vec); printf("T =\n");fflush(stdout); plot_vector(stdout, 3, T_vec); printf("\n");fflush(stdout); fprintf(outfile, "%10.10lf\n", scal); printf("s = %10.10lf (= %10.10lf ppm)\n\n",scal, ppm);fflush(stdout); fclose(outfile); freevector(D_vec); freevector(T_vec); freevector(one_vec); freematrix(m, src_mat); freematrix(m, dest_mat); freematrix(m, E_mat); freematrix(m, P_mat); freematrix(m, D_mat); freematrix(m, Q_mat); freematrix(m, P_mat_T); freematrix(m, R_mat); freematrix(m, dest_mat_T); freematrix(m, C_mat); freematrix(m, C_mat_interm); freematrix(m, src_mat_T); freematrix(m, D_mat_interm); printf("\n...done\n"); } }