void test_eigen_gen_results (const gsl_matrix * A, const gsl_matrix * B, const gsl_vector_complex * alpha, const gsl_vector * beta, const gsl_matrix_complex * evec, size_t count, const char * desc, const char * desc2) { const size_t N = A->size1; size_t i, j; gsl_matrix_complex *ma, *mb; gsl_vector_complex *x, *y; gsl_complex z_one, z_zero; ma = gsl_matrix_complex_alloc(N, N); mb = gsl_matrix_complex_alloc(N, N); y = gsl_vector_complex_alloc(N); x = gsl_vector_complex_alloc(N); /* ma <- A, mb <- B */ for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { gsl_complex z; GSL_SET_COMPLEX(&z, gsl_matrix_get(A, i, j), 0.0); gsl_matrix_complex_set(ma, i, j, z); GSL_SET_COMPLEX(&z, gsl_matrix_get(B, i, j), 0.0); gsl_matrix_complex_set(mb, i, j, z); } } GSL_SET_COMPLEX(&z_one, 1.0, 0.0); GSL_SET_COMPLEX(&z_zero, 0.0, 0.0); /* check eigenvalues */ for (i = 0; i < N; ++i) { gsl_vector_complex_const_view vi = gsl_matrix_complex_const_column(evec, i); gsl_complex ai = gsl_vector_complex_get(alpha, i); double bi = gsl_vector_get(beta, i); /* compute x = alpha * B * v */ gsl_blas_zgemv(CblasNoTrans, z_one, mb, &vi.vector, z_zero, x); gsl_blas_zscal(ai, x); /* compute y = beta * A v */ gsl_blas_zgemv(CblasNoTrans, z_one, ma, &vi.vector, z_zero, y); gsl_blas_zdscal(bi, y); /* now test if y = x */ for (j = 0; j < N; ++j) { gsl_complex xj = gsl_vector_complex_get(x, j); gsl_complex yj = gsl_vector_complex_get(y, j); gsl_test_abs(GSL_REAL(yj), GSL_REAL(xj), 1e8*GSL_DBL_EPSILON, "gen(N=%u,cnt=%u), %s, eigenvalue(%d,%d), real, %s", N, count, desc, i, j, desc2); gsl_test_abs(GSL_IMAG(yj), GSL_IMAG(xj), 1e8*GSL_DBL_EPSILON, "gen(N=%u,cnt=%u), %s, eigenvalue(%d,%d), real, %s", N, count, desc, i, j, desc2); } } gsl_matrix_complex_free(ma); gsl_matrix_complex_free(mb); gsl_vector_complex_free(y); gsl_vector_complex_free(x); } /* test_eigen_gen_results() */
void test_eigen_nonsymm_results (const gsl_matrix * m, const gsl_vector_complex * eval, const gsl_matrix_complex * evec, size_t count, const char * desc, const char * desc2) { size_t i,j; size_t N = m->size1; gsl_vector_complex * x = gsl_vector_complex_alloc(N); gsl_vector_complex * y = gsl_vector_complex_alloc(N); gsl_matrix_complex * A = gsl_matrix_complex_alloc(N, N); /* we need a complex matrix for the blas routines, so copy m into A */ for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { gsl_complex z; GSL_SET_COMPLEX(&z, gsl_matrix_get(m, i, j), 0.0); gsl_matrix_complex_set(A, i, j, z); } } for (i = 0; i < N; i++) { gsl_complex ei = gsl_vector_complex_get (eval, i); gsl_vector_complex_const_view vi = gsl_matrix_complex_const_column(evec, i); double norm = gsl_blas_dznrm2(&vi.vector); /* check that eigenvector is normalized */ gsl_test_rel(norm, 1.0, N * GSL_DBL_EPSILON, "nonsymm(N=%u,cnt=%u), %s, normalized(%d), %s", N, count, desc, i, desc2); gsl_vector_complex_memcpy(x, &vi.vector); /* compute y = m x (should = lambda v) */ gsl_blas_zgemv (CblasNoTrans, GSL_COMPLEX_ONE, A, x, GSL_COMPLEX_ZERO, y); /* compute x = lambda v */ gsl_blas_zscal(ei, x); /* now test if y = x */ for (j = 0; j < N; j++) { gsl_complex xj = gsl_vector_complex_get (x, j); gsl_complex yj = gsl_vector_complex_get (y, j); /* use abs here in case the values are close to 0 */ gsl_test_abs(GSL_REAL(yj), GSL_REAL(xj), 1e8*GSL_DBL_EPSILON, "nonsymm(N=%u,cnt=%u), %s, eigenvalue(%d,%d), real, %s", N, count, desc, i, j, desc2); gsl_test_abs(GSL_IMAG(yj), GSL_IMAG(xj), 1e8*GSL_DBL_EPSILON, "nonsymm(N=%u,cnt=%u), %s, eigenvalue(%d,%d), imag, %s", N, count, desc, i, j, desc2); } } gsl_matrix_complex_free(A); gsl_vector_complex_free(x); gsl_vector_complex_free(y); }
int gsl_linalg_complex_cholesky_invert(gsl_matrix_complex * LLT) { if (LLT->size1 != LLT->size2) { GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR); } else { size_t N = LLT->size1; size_t i, j; gsl_vector_complex_view v1; /* invert the lower triangle of LLT */ for (i = 0; i < N; ++i) { double ajj; gsl_complex z; j = N - i - 1; { gsl_complex z0 = gsl_matrix_complex_get(LLT, j, j); ajj = 1.0 / GSL_REAL(z0); } GSL_SET_COMPLEX(&z, ajj, 0.0); gsl_matrix_complex_set(LLT, j, j, z); { gsl_complex z1 = gsl_matrix_complex_get(LLT, j, j); ajj = -GSL_REAL(z1); } if (j < N - 1) { gsl_matrix_complex_view m; m = gsl_matrix_complex_submatrix(LLT, j + 1, j + 1, N - j - 1, N - j - 1); v1 = gsl_matrix_complex_subcolumn(LLT, j, j + 1, N - j - 1); gsl_blas_ztrmv(CblasLower, CblasNoTrans, CblasNonUnit, &m.matrix, &v1.vector); gsl_blas_zdscal(ajj, &v1.vector); } } /* for (i = 0; i < N; ++i) */ /* * The lower triangle of LLT now contains L^{-1}. Now compute * A^{-1} = L^{-H} L^{-1} * * The (ij) element of A^{-1} is column i of conj(L^{-1}) dotted into * column j of L^{-1} */ for (i = 0; i < N; ++i) { gsl_complex sum; for (j = i + 1; j < N; ++j) { gsl_vector_complex_view v2; v1 = gsl_matrix_complex_subcolumn(LLT, i, j, N - j); v2 = gsl_matrix_complex_subcolumn(LLT, j, j, N - j); /* compute Ainv[i,j] = sum_k{conj(Linv[k,i]) * Linv[k,j]} */ gsl_blas_zdotc(&v1.vector, &v2.vector, &sum); /* store in upper triangle */ gsl_matrix_complex_set(LLT, i, j, sum); } /* now compute the diagonal element */ v1 = gsl_matrix_complex_subcolumn(LLT, i, i, N - i); gsl_blas_zdotc(&v1.vector, &v1.vector, &sum); gsl_matrix_complex_set(LLT, i, i, sum); } /* copy the Hermitian upper triangle to the lower triangle */ for (j = 1; j < N; j++) { for (i = 0; i < j; i++) { gsl_complex z = gsl_matrix_complex_get(LLT, i, j); gsl_matrix_complex_set(LLT, j, i, gsl_complex_conjugate(z)); } } return GSL_SUCCESS; } } /* gsl_linalg_complex_cholesky_invert() */
int gsl_linalg_complex_cholesky_decomp(gsl_matrix_complex *A) { const size_t N = A->size1; if (N != A->size2) { GSL_ERROR("cholesky decomposition requires square matrix", GSL_ENOTSQR); } else { size_t i, j; gsl_complex z; double ajj; for (j = 0; j < N; ++j) { z = gsl_matrix_complex_get(A, j, j); ajj = GSL_REAL(z); if (j > 0) { gsl_vector_complex_const_view aj = gsl_matrix_complex_const_subrow(A, j, 0, j); gsl_blas_zdotc(&aj.vector, &aj.vector, &z); ajj -= GSL_REAL(z); } if (ajj <= 0.0) { GSL_ERROR("matrix is not positive definite", GSL_EDOM); } ajj = sqrt(ajj); GSL_SET_COMPLEX(&z, ajj, 0.0); gsl_matrix_complex_set(A, j, j, z); if (j < N - 1) { gsl_vector_complex_view av = gsl_matrix_complex_subcolumn(A, j, j + 1, N - j - 1); if (j > 0) { gsl_vector_complex_view aj = gsl_matrix_complex_subrow(A, j, 0, j); gsl_matrix_complex_view am = gsl_matrix_complex_submatrix(A, j + 1, 0, N - j - 1, j); cholesky_complex_conj_vector(&aj.vector); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_NEGONE, &am.matrix, &aj.vector, GSL_COMPLEX_ONE, &av.vector); cholesky_complex_conj_vector(&aj.vector); } gsl_blas_zdscal(1.0 / ajj, &av.vector); } } /* Now store L^H in upper triangle */ for (i = 1; i < N; ++i) { for (j = 0; j < i; ++j) { z = gsl_matrix_complex_get(A, i, j); gsl_matrix_complex_set(A, j, i, gsl_complex_conjugate(z)); } } return GSL_SUCCESS; } } /* gsl_linalg_complex_cholesky_decomp() */
int gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_hermv_workspace * w) { if (A->size1 != A->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR); } else if (eval->size != A->size1) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else if (evec->size1 != A->size1 || evec->size2 != A->size1) { GSL_ERROR ("eigenvector matrix must match matrix size", GSL_EBADLEN); } else { const size_t N = A->size1; double *const d = w->d; double *const sd = w->sd; size_t a, b; /* handle special case */ if (N == 1) { gsl_complex A00 = gsl_matrix_complex_get (A, 0, 0); gsl_vector_set (eval, 0, GSL_REAL(A00)); gsl_matrix_complex_set (evec, 0, 0, GSL_COMPLEX_ONE); return GSL_SUCCESS; } /* Transform the matrix into a symmetric tridiagonal form */ { gsl_vector_view d_vec = gsl_vector_view_array (d, N); gsl_vector_view sd_vec = gsl_vector_view_array (sd, N - 1); gsl_vector_complex_view tau_vec = gsl_vector_complex_view_array (w->tau, N-1); gsl_linalg_hermtd_decomp (A, &tau_vec.vector); gsl_linalg_hermtd_unpack (A, &tau_vec.vector, evec, &d_vec.vector, &sd_vec.vector); } /* Make an initial pass through the tridiagonal decomposition to remove off-diagonal elements which are effectively zero */ chop_small_elements (N, d, sd); /* Progressively reduce the matrix until it is diagonal */ b = N - 1; while (b > 0) { if (sd[b - 1] == 0.0 || isnan(sd[b - 1])) { b--; continue; } /* Find the largest unreduced block (a,b) starting from b and working backwards */ a = b - 1; while (a > 0) { if (sd[a - 1] == 0.0) { break; } a--; } { size_t i; const size_t n_block = b - a + 1; double *d_block = d + a; double *sd_block = sd + a; double * const gc = w->gc; double * const gs = w->gs; /* apply QR reduction with implicit deflation to the unreduced block */ qrstep (n_block, d_block, sd_block, gc, gs); /* Apply Givens rotation Gij(c,s) to matrix Q, Q <- Q G */ for (i = 0; i < n_block - 1; i++) { const double c = gc[i], s = gs[i]; size_t k; for (k = 0; k < N; k++) { gsl_complex qki = gsl_matrix_complex_get (evec, k, a + i); gsl_complex qkj = gsl_matrix_complex_get (evec, k, a + i + 1); /* qki <= qki * c - qkj * s */ /* qkj <= qki * s + qkj * c */ gsl_complex x1 = gsl_complex_mul_real(qki, c); gsl_complex y1 = gsl_complex_mul_real(qkj, -s); gsl_complex x2 = gsl_complex_mul_real(qki, s); gsl_complex y2 = gsl_complex_mul_real(qkj, c); gsl_complex qqki = gsl_complex_add(x1, y1); gsl_complex qqkj = gsl_complex_add(x2, y2); gsl_matrix_complex_set (evec, k, a + i, qqki); gsl_matrix_complex_set (evec, k, a + i + 1, qqkj); } } /* remove any small off-diagonal elements */ chop_small_elements (n_block, d_block, sd_block); } } { gsl_vector_view d_vec = gsl_vector_view_array (d, N); gsl_vector_memcpy (eval, &d_vec.vector); } return GSL_SUCCESS; } }
void get2Dnoisematrix(struct data *d,int mode) { int dim1,dim2,dim3,nr; double noisefrac; int h,i,j,k,l; int n=0; gsl_complex cx,cx1,cx2; #ifdef DEBUG struct timeval tp; double t1,t2; char function[20]; strcpy(function,"get2Dnoisematrix"); /* Set function name */ #endif /* Get noise if it has not been measured */ if (!d->noise.data) getnoise2D(d,mode); /* Equalize noise if it has not been done */ if (!d->noise.equal) equalizenoise2D(d,mode); #ifdef DEBUG fprintf(stdout,"\n%s: %s()\n",SOURCEFILE,function); gettimeofday(&tp, NULL); t1=(double)tp.tv_sec+(1.e-6)*tp.tv_usec; fflush(stdout); #endif /* Data dimensions */ dim1=d->np/2; dim2=d->nv; dim3=d->endpos-d->startpos; nr=d->nr; noisefrac=0.0; switch(mode) { case MK: /* Mask parameters */ switch(d->datamode) { case FID: noisefrac=*val("masknoisefrac",&d->p); if (!noisefrac) noisefrac=Knoisefraction; break; default: noisefrac=*val("masklvlnoisefrac",&d->p); if (!noisefrac) noisefrac=IMnoisefraction; } /* end datamode switch */ break; case SM: /* Sensitivity map parameters */ switch(d->datamode) { case FID: noisefrac=*val("smapnoisefrac",&d->p); if (!noisefrac) noisefrac=Knoisefraction; break; default: noisefrac=*val("masklvlnoisefrac",&d->p); if (!noisefrac) noisefrac=IMnoisefraction; } /* end datamode switch */ break; default: /* Default parameters */ switch(d->datamode) { case FID: noisefrac=Knoisefraction; break; default: noisefrac=IMnoisefraction; } /* end datamode switch */ } /* end mode switch */ /* Allocate memory for noise matrix */ /* Get noise if it has not been measured */ if (!d->noise.data) getnoise2D(d,mode); if ((d->noise.mat = (gsl_matrix_complex **)malloc(dim3*sizeof(gsl_matrix_complex *))) == NULL) nomem(); for (j=0;j<dim3;j++) d->noise.mat[j]=(gsl_matrix_complex *)gsl_matrix_complex_calloc(nr,nr); for (h=0;h<nr;h++) { for (i=0;i<nr;i++) { if (((d->datamode == FID) && d->shift) || ((d->datamode == IMAGE) && !d->shift)) { /* For shifted FID and not-shifted IMAGE the noise is at centre */ for (j=0;j<dim3;j++) { n=0; GSL_SET_COMPLEX(&cx,0.0,0.0); for(k=dim2/2-dim2*noisefrac/2;k<dim2/2+dim2*noisefrac/2;k++) { for (l=dim1/2-dim1*noisefrac/2;l<dim1/2+dim1*noisefrac/2;l++) { GSL_SET_REAL(&cx1,d->data[h][j][k*dim1+l][0]); GSL_SET_IMAG(&cx1,d->data[h][j][k*dim1+l][1]); GSL_SET_REAL(&cx2,d->data[i][j][k*dim1+l][0]); GSL_SET_IMAG(&cx2,d->data[i][j][k*dim1+l][1]); cx=gsl_complex_add(cx,gsl_complex_mul(cx1,gsl_complex_conjugate(cx2))); n++; } } /* Take the mean and normalize */ GSL_SET_COMPLEX(&cx,GSL_REAL(cx)/(n*d->noise.avM2),GSL_IMAG(cx)/(n*d->noise.avM2)); gsl_matrix_complex_set(d->noise.mat[j],h,i,cx); } } else { /* For not shifted FID and shifted IMAGE the noise is at edges */ for (j=0;j<dim3;j++) { n=0; GSL_SET_COMPLEX(&cx,0.0,0.0); for(k=0;k<dim2*noisefrac/2;k++) { for (l=0;l<dim1*noisefrac/2;l++) { GSL_SET_REAL(&cx1,d->data[h][j][k*dim1+l][0]); GSL_SET_IMAG(&cx1,d->data[h][j][k*dim1+l][1]); GSL_SET_REAL(&cx2,d->data[i][j][k*dim1+l][0]); GSL_SET_IMAG(&cx2,d->data[i][j][k*dim1+l][1]); cx=gsl_complex_add(cx,gsl_complex_mul(cx1,gsl_complex_conjugate(cx2))); n++; } for (l=dim1-dim1*noisefrac/2;l<dim1;l++) { GSL_SET_REAL(&cx1,d->data[h][j][k*dim1+l][0]); GSL_SET_IMAG(&cx1,d->data[h][j][k*dim1+l][1]); GSL_SET_REAL(&cx2,d->data[i][j][k*dim1+l][0]); GSL_SET_IMAG(&cx2,d->data[i][j][k*dim1+l][1]); cx=gsl_complex_add(cx,gsl_complex_mul(cx1,gsl_complex_conjugate(cx2))); n++; } } for(k=dim2-dim2*noisefrac/2;k<dim2;k++) { for (l=0;l<dim1*noisefrac/2;l++) { GSL_SET_REAL(&cx1,d->data[h][j][k*dim1+l][0]); GSL_SET_IMAG(&cx1,d->data[h][j][k*dim1+l][1]); GSL_SET_REAL(&cx2,d->data[i][j][k*dim1+l][0]); GSL_SET_IMAG(&cx2,d->data[i][j][k*dim1+l][1]); cx=gsl_complex_add(cx,gsl_complex_mul(cx1,gsl_complex_conjugate(cx2))); n++; } for (l=dim1-dim1*noisefrac/2;l<dim1;l++) { GSL_SET_REAL(&cx1,d->data[h][j][k*dim1+l][0]); GSL_SET_IMAG(&cx1,d->data[h][j][k*dim1+l][1]); GSL_SET_REAL(&cx2,d->data[i][j][k*dim1+l][0]); GSL_SET_IMAG(&cx2,d->data[i][j][k*dim1+l][1]); cx=gsl_complex_add(cx,gsl_complex_mul(cx1,gsl_complex_conjugate(cx2))); n++; } } /* Take the mean and normalize */ GSL_SET_COMPLEX(&cx,GSL_REAL(cx)/(n*d->noise.avM2),GSL_IMAG(cx)/(n*d->noise.avM2)); gsl_matrix_complex_set(d->noise.mat[j],h,i,cx); } } } } /* Set noise matrix flag */ d->noise.matrix=TRUE; #ifdef DEBUG gettimeofday(&tp, NULL); t2=(double)tp.tv_sec+(1.e-6)*tp.tv_usec; fprintf(stdout," Took %f secs\n",t2-t1); print2Dnoisematrix(d); fflush(stdout); #else /* Print Noise Matrix, if requested */ if (!(strcmp(*sval("printNM",&d->p),"y"))) print2Dnoisematrix(d); #endif }
int main(int argc, char * argv[]) { int num,i,*states,num_e,j,k; double *entry, *dos_vec, *eval_vec; double coef; char tmpc; gsl_vector *eval; gsl_matrix_view m; gsl_eigen_symm_workspace *w; gsl_matrix_complex * matrix2; gsl_complex z; gsl_permutation * p; char name[25]; FILE *out; if ((out = fopen(argv[1],"r")) != NULL) { num = 0; printf("reading from file: %s....\n",argv[1]); while(fscanf(out,"%lf",&coef) != EOF) num++; if (modf(sqrt(num),&coef) != 0) { printf("not a square matrix!\n\n"); return 1; } //printf("%d\n",num); fseek(out,0,SEEK_SET); num = sqrt(num); entry = (double *)malloc(sizeof(double) * num * num); i = 0; while (i < (num * num)) { *(entry + i) = 0; i++; } i = 0; printf("loading matrix into memory...\n"); while(fscanf(out,"%lf",&coef) != EOF) { *(entry + i) = coef; printf("entry %d = %g\n",i + 1,coef); i++; } flags += NUMPRINT; flags += READFROMFILE; } if (argc < 6 && (flags & READFROMFILE) == 0) { printf("usage: no. of layers, slope of cone/no. of atoms per layer, on-site energy, hopping parameter, model, (option)\n"); printf("\n Models are:\n1: Nanotube, square lattice\n2: Nanotube, hex lattice (armchair)\n"); printf("3: Nanohorn, square lattice\n4: Nanohorn hex lattice\n5: Nanotube, hex lattice (zig-zag)\n"); printf("\nOptions are: p - print symbolically\n n - print numerically\n\n"); return 1; } else if ((flags & READFROMFILE) != 0) { } else { num = atoi(argv[1]); Epsilon = atol(argv[3]); Gamma = atol(argv[4]); switch(atoi(argv[5])) { case 1: flags = flags + CNT_SQUARE; Alpha = atoi(argv[2]); num *= Alpha; entry = (double *)malloc(sizeof(double) * num * num); break; case 2: flags = flags + CNT_HEX_ARM; Alpha = atoi(argv[2]); i = Alpha; if ((i % 2) != 0) { printf("no. of atoms per layer must be even, changing to %d\n",i + 1); Alpha += 1; } num *= (Alpha); entry = (double *)malloc(sizeof(double) * num * num); break; case 3: flags = flags + HORN_SQUARE; i = 1; num_e = 0; while (i <= num) { num_e += i; i++; } num = num_e; entry = (double *)malloc(sizeof(double) * num * num); break; case 4: flags = flags + HORN_HEX; num = 0; entry = NULL; break; case 5: flags = flags + CNT_HEX_ZIG; Alpha = atoi(argv[2]); i = Alpha; while ((i % 4) != 0) { i++; } Alpha = i; num *= Alpha; entry = (double *)malloc(sizeof(double) * num * num); break; default: printf("No valid model choice!\n"); return 1; break; } i = 0; while (i < (num * num)) { *(entry + i) = 0; i++; } printf("Alpha = %g\n",Alpha); } printf("%d atoms\n",num); if (argc > 6) { if (strcmp("p\0",argv[6]) == 0) { //printf("print"); flags = flags + PRINT; } if (strcmp("n\0", argv[6]) == 0) { flags = flags + NUMPRINT; } } eval = gsl_vector_alloc(num); //printf("flags %d\n",flags); //k = (flags & PRINT); //printf("print ? %d\n",k); //printf("%lf",Alpha); //printf("%d",num); if (entry == NULL) { printf("could not allocate memory\n"); return 1; } i = 0; if ((flags & READFROMFILE) == 0) { printf("Populating Matrix...\n"); PopulateMatrix(entry,num); out = fopen("matrix","w"); i = 0; while (i < (num * num)) { fprintf(out,"%3.5lf ",*(entry + i)); if (((i + 1) % num) == 0) fprintf(out,"\n"); i++; } fclose(out); } else { } printf("Printing Matrix\n"); PrintMatrix(entry,num); //CalcEigenvalues(entry,num,eval); //Eigenvalue Calculation m = gsl_matrix_view_array (entry,num,num); //printf("87\n"); w = gsl_eigen_symm_alloc (num); //printf("89\n"); printf("Solving Eigenvalue equation....\n"); if(gsl_eigen_symm (&m.matrix, eval, w)) { printf("an error occurred solving the eigenvalue equation\n"); return 1; } //printf("\nworkspace location = %#x",w); gsl_eigen_symm_free(w); printf("\n\n"); //if (flags & NUMPRINT != 0 || flags & PRINT != 0) printf("Eigenvalues found. "); eval_vec = malloc(sizeof(double) * num); i = 0; while (i < num) { *(eval_vec + i) = gsl_vector_get(eval,i); i++; } gsl_vector_free(eval); tmpc = 0; printf("Ordering Eigenvalues...\n"); qsort(eval_vec,num,sizeof(double),comparedouble); division = ((*(eval_vec + num - 1) - *eval_vec) / num) * 10 * INTERVAL; num_e = ((*(eval_vec + num - 1) - *eval_vec))/ division; num_e++; //just in case while ((flags & FINISHED) == 0) { if (tmpc != -1) printf("(s)ave in file, (q)uit and discard, (p)rint (!), (d)ensity of states: "); scanf("%c",&tmpc); if (tmpc == 'p' || tmpc == 'P') { i = 0; while (i < num) { printf("Eigenvalue %d\t: %g\n",(i + 1),*(eval_vec + i)); i++; } printf("\n"); tmpc = -1; } else if (tmpc == 'q' || tmpc == 'Q') { printf("\nexiting...\n\n"); flags += FINISHED; } else if (tmpc == 'd' || tmpc == 'D') { tmpc = 0; dos_vec = malloc(sizeof(double) * num_e); states = malloc(sizeof(int) * num_e); printf("\nCalculating density of states...\n"); Calculate(eval_vec,num,dos_vec,states); i = 0; printf("\n"); out = fopen("dostube","w"); while (i < num_e && *(states + i) >= 0) { printf("Energy: % .5lf\tNo. of states: %d\n",*(dos_vec + i),*(states + i)); fprintf(out,"% .5lf\t%d\n",*(dos_vec + i),*(states + i)); i++; } num_e = i; fclose(out); flags += FINISHED; flags += DOS; } else if (tmpc == -1) //WHY?!! { tmpc = 0; } else if (tmpc == 's' || tmpc == 'S') //broken for some reason { printf("\nchoose filename: "); scanf("%s",name); //printf("%s",name); out = fopen(name,"r"); if (out != NULL) { printf("File already exists!\n"); fclose(out); } else { fclose(out); out = fopen(name,"w"); printf("Writing to file: %s",name); i = 0; while (i < num) { fprintf(out,"Eigenvalue %d\t: %g\n",(i + 1),*(eval_vec + i)); i++; } fclose(out); tmpc = -1; } } else { printf("unrecognised option!\n"); } } if ((flags & DOS) != 0) { while (j < num_e) { matrix2 = gsl_matrix_complex_alloc(sizeof(gsl_complex) * num,sizeof(gsl_complex) * num); i = 0; gsl_matrix_complex_set_identity(matrix2); z.dat[0] = *(dos_vec + j); z.dat[1] = 0.0001; gsl_matrix_complex_scale(matrix2,z); while (i < num) { k = 0; while(k < num) { z = gsl_matrix_complex_get(matrix2,i,k); z.dat[0] -= *(entry + i + (k * num)); gsl_matrix_complex_set(matrix2,i,k,z); k++; } i++; } out = fopen("matrix","w"); gsl_matrix_complex_fprintf(out,matrix2,"% 2.2lf"); fclose(out); free(entry); } } //printf("\neval location = %#x",eval); return 0; }
/* * Calculate eigenvectors and eigenvalues for a non-symmetric complex matrix * using the CLAPACK zgeev_ function. * */ int gsl_ext_eigen_zgeev(gsl_matrix_complex *A_gsl, gsl_matrix_complex *evec, gsl_vector_complex *eval) { //integer *pivot; integer n,i,j,info,lwork, ldvl, ldvr, lda; doublecomplex *A,*vr,*vl,*w,*work; doublereal *rwork; char jobvl,jobvr; n = A_gsl->size1; // pivot = (integer *)malloc((size_t)n * sizeof(int)); A = (doublecomplex *)malloc((size_t)n * n * sizeof(doublecomplex)); w = (doublecomplex *)malloc((size_t)n * sizeof(doublecomplex)); vr = (doublecomplex *)malloc((size_t)n * n * sizeof(doublecomplex)); vl = (doublecomplex *)malloc((size_t)n * n * sizeof(doublecomplex)); lwork = 16 * n; work = (doublecomplex *)malloc((size_t)lwork * sizeof(doublecomplex)); rwork = (doublereal *)malloc((size_t)lwork * sizeof(doublereal)); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { gsl_complex z; double re,im; z = gsl_matrix_complex_get(A_gsl, i, j); re = GSL_REAL(z); im = GSL_IMAG(z); A[j*n+i] = (doublecomplex){re,im}; } } jobvl='N'; jobvr='V'; lda = n; ldvr = n; ldvl = n; zgeev_(&jobvl, &jobvr, &n, A, &lda, w, vl, &ldvl, vr, &ldvr, work, &lwork, rwork, &info); //ZGEEVX(BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, W, VL, LDVL, VR, LDVR, ILO, IHI, SCALE, ABNRM, RCONDE, RCONDV, WORK, LWORK, RWORK, INFO ) for (i = 0; i < n; i++) { gsl_complex z; GSL_SET_COMPLEX(&z, w[i].r, w[i].i); gsl_vector_complex_set(eval, i, z); } for (j = 0; j < n; j++) { for (i = 0; i < n; i++) { gsl_complex z; GSL_SET_COMPLEX(&z, vr[j*n+i].r, vr[j*n+i].i); gsl_matrix_complex_set(evec, i, j, z); } } if (info != 0) { printf("zgeev_: error: info = %d\n", (int)info); } // free(pivot); free(A); free(w); free(vr); free(vl); free(work); free(rwork); return 0; }
void MAIAllocator::Setup() { //////// initialization of dynamic data structures Hmat = gsl_matrix_complex_alloc(N(),M()); Hchan = gsl_vector_complex_alloc(N()); Hperm = gsl_matrix_uint_alloc(N(),M()); p = gsl_permutation_alloc(N()); huserabs = gsl_vector_alloc(N()); nextcarr = gsl_vector_uint_alloc(M()); usedcarr = gsl_vector_uint_alloc(N()); errs = gsl_vector_uint_alloc(M()); habs = gsl_matrix_alloc(N(),M()); huu = gsl_matrix_complex_alloc(N(),M()); framecount = 0; ericount = 0; csicount = 0; noDecisions = 0; ostringstream cmd; // // time // time(&reporttime); // // Random Generator // ran = gsl_rng_alloc( gsl_rng_default ); // SIGNATURE FREQUENCIES INITIAL SETUP signature_frequencies = gsl_matrix_uint_alloc(M(),J()); signature_frequencies_init = gsl_matrix_uint_alloc(M(),J()); signature_powers = gsl_matrix_alloc(M(),J()); for (int i=0; i<M(); i++) for (int j=0; j<J(); j++) gsl_matrix_uint_set(signature_frequencies_init,i,j,(j*M()+i) % N()); // // INITIAL ALLOCATION // gsl_matrix_uint_memcpy(signature_frequencies, signature_frequencies_init); // maximum initial powers for all carriers gsl_matrix_set_all(signature_powers,INIT_CARR_POWER); gsl_vector_uint_set_zero(errs); // // // FFT Transform Matrix // // transform_mat = gsl_matrix_complex_calloc(N(),N()); double fftarg=-2.0*double(M_PI/N()); double fftamp=1.0/sqrt(double(N())); for (int i=0; i<N(); i++) for (int j=0; j<N(); j++) gsl_matrix_complex_set(transform_mat,i,j, gsl_complex_polar(fftamp,fftarg*i*j) ); switch (Mode()) { case 0: cout << BlockName << " - Allocator type FIXED_ALLOCATION selected" << endl; break; case 1: cout << BlockName << " - Allocator type GIVE_BEST_CARR selected" << endl; break; case 2: cout << BlockName << " - Allocator type SWAP_BAD_GOOD selected" << endl; break; case 3: cout << BlockName << " - Allocator type BEST_OVERLAP selected" << endl; break; case 4: cout << BlockName << " - Allocator type SOAR_AI selected" << endl; // // SOAR INITIALIZATION // max_errors = MAX_ERROR_RATE * ERROR_REPORT_INTERVAL * Nb() * K(); cout << BlockName << " - Max errors tuned to " << max_errors << " errors/frame." << endl; // // first we initialize the vectors and matrices // in the order of appearance in the header file. // umapUserVec = vector < Identifier * > (M()); umapUserUidVec = vector < IntElement * > (M()); umapUserErrsVec = vector < IntElement * > (M()); umapUserPowerVec = vector < FloatElement * > (M()); umapUserCarrMat = vector < Identifier * > (M()*J()); umapUserCarrCidMat = vector < IntElement * > (M()*J()); umapUserCarrPowerMat = vector < FloatElement * > (M()*J()); chansCoeffMat = vector < Identifier * > (M()*N()); chansCoeffUserMat = vector < IntElement * > (M()*N()); chansCoeffCarrMat = vector < IntElement * > (M()*N()); chansCoeffValueMat = vector < FloatElement * > (M()*N()); carmapCarrVec = vector < Identifier * > (N()); carmapCarrCidVec = vector < IntElement * > (N()); // // then we create an instance of the Soar kernel in our process // pKernel = Kernel::CreateKernelInNewThread() ; //pKernel = Kernel::CreateRemoteConnection() ; // Check that nothing went wrong. We will always get back a kernel object // even if something went wrong and we have to abort. if (pKernel->HadError()) { cerr << BlockName << ".SOAR - " << pKernel->GetLastErrorDescription() << endl ; exit(1); } // We check if an agent has been prevoiusly created, otherwise we create it // NOTE: We don't delete the agent pointer. It's owned by the kernel pAgent = pKernel->GetAgent("AIAllocator") ; if (! pKernel->IsAgentValid(pAgent)) { pAgent = pKernel->CreateAgent("AIAllocator") ; } // Check that nothing went wrong // NOTE: No agent gets created if there's a problem, so we have to check for // errors through the kernel object. if (pKernel->HadError()) { cerr << BlockName << ".SOAR - " << pKernel->GetLastErrorDescription() << endl ; exit(1); } // // load productions // pAgent->LoadProductions(SoarFn()); // spawn debugger #ifdef SPAWN_DEBUGGER pAgent->SpawnDebugger(); #endif // Check that nothing went wrong // NOTE: No agent gets created if there's a problem, so we have to check for // errors through the kernel object. if (pKernel->HadError()) { cerr << BlockName << ".SOAR - " << pKernel->GetLastErrorDescription() << endl ; exit(1); } // keypress //cout << "pause maillocator:203 ... (press ENTER key)" << endl; //cin.ignore(); // // we can now generate initial input link structure // // NO MORE adjust max-nil-output-cycle //cmd << "max-nil-output-cycles " << 120; //pAgent->ExecuteCommandLine(cmd.str().c_str()); // the input-link pInputLink = pAgent->GetInputLink(); // input-time input_time = 0; inputTime = pAgent->CreateIntWME(pInputLink,"input-time",input_time); // the usrmap structure (common wmes) umap = pAgent->CreateIdWME(pInputLink,"usrmap"); // BITS_PER_REPORT = ERROR_REPORT_INTERVAL * Nb() * K() // MAX_ERRORS = MAX_ERROR_RATE * BITS_PER_REPORT umapMaxerr = pAgent->CreateIntWME(umap,"maxerr",max_errors); umapPstep = pAgent->CreateFloatWME(umap,"pstep",POWER_STEP); umapPmax = pAgent->CreateFloatWME(umap,"pmax",MAX_POWER); // the channels chans = pAgent->CreateIdWME(pInputLink,"channels"); // the carmap carmap = pAgent->CreateIdWME(pInputLink,"carmap"); // the usrmap structure (users substructure) for (int i=0;i<M();i++) { // user loop umapUserVec[i] = pAgent->CreateIdWME(umap,"user"); umapUserUidVec[i] = pAgent->CreateIntWME(umapUserVec[i],"uid",i); umapUserErrsVec[i] = pAgent->CreateIntWME(umapUserVec[i],"errs",int(0)); umapUserPowerVec[i] = pAgent->CreateFloatWME(umapUserVec[i],"power",J()); // update the current allocation for (int j=0;j<J();j++) { // allocated carriers loop unsigned int usedcarr = gsl_matrix_uint_get(signature_frequencies,i,j); double usedpow = gsl_matrix_get(signature_powers,i,j); umapUserCarrMat[i*J()+j] = pAgent->CreateIdWME(umapUserVec[i],"carr"); umapUserCarrCidMat[i*J()+j] = pAgent->CreateIntWME(umapUserCarrMat[i*J()+j],"cid",usedcarr); umapUserCarrPowerMat[i*J()+j] = pAgent->CreateFloatWME(umapUserCarrMat[i*J()+j],"power",usedpow); } // allocated carriers loop // the channels for (int j=0;j<N();j++) { // all channels loop chansCoeffMat[i*N()+j] = pAgent->CreateIdWME(chans,"coeff"); chansCoeffUserMat[i*N()+j] = pAgent->CreateIntWME(chansCoeffMat[i*N()+j],"user",i); chansCoeffCarrMat[i*N()+j] = pAgent->CreateIntWME(chansCoeffMat[i*N()+j],"carr",j); chansCoeffValueMat[i*N()+j] = pAgent->CreateFloatWME(chansCoeffMat[i*N()+j],"value",0.0); } // all channels loop } // user loop // the carmap structure for (int j=0;j<N();j++) { // all carriers loop carmapCarrVec[j] = pAgent->CreateIdWME(carmap,"carr"); carmapCarrCidVec[j] = pAgent->CreateIntWME(carmapCarrVec[j],"cid",j); } // all carriers loop // // END OF SOAR INITIALIZAZION // break; default: cerr << BlockName << " - Unhandled allocator type !" << endl; exit(1); } //////// rate declaration for ports }
int main(void) { gsl_matrix *TS; /* the training set of real waveforms */ gsl_matrix_complex *cTS; /* the training set of complex waveforms */ size_t TSsize; /* the size of the training set (number of waveforms) */ size_t wl; /* the length of each waveform */ size_t k = 0, j = 0, i = 0, nbases = 0, cnbases = 0; REAL8 *RB = NULL; /* the real reduced basis set */ COMPLEX16 *cRB = NULL; /* the complex reduced basis set */ LALInferenceREALROQInterpolant *interp = NULL; LALInferenceCOMPLEXROQInterpolant *cinterp = NULL; gsl_vector *freqs; double tolerance = TOLERANCE; /* tolerance for reduced basis generation loop */ TSsize = TSSIZE; wl = WL; /* allocate memory for training set */ TS = gsl_matrix_calloc(TSsize, wl); cTS = gsl_matrix_complex_calloc(TSsize, wl); /* the waveform model is just a simple chirp so set up chirp mass range for training set */ double fmin0 = 48, fmax0 = 256, f0 = 0., m0 = 0.; double df = (fmax0-fmin0)/(wl-1.); /* model time steps */ freqs = gsl_vector_alloc(wl); /* times at which to calculate the model */ double Mcmax = 2., Mcmin = 1.5, Mc = 0.; gsl_vector_view fweights = gsl_vector_view_array(&df, 1); /* set up training sets (one real and one complex) */ for ( k=0; k < TSsize; k++ ){ Mc = pow(pow(Mcmin, 5./3.) + (double)k*(pow(Mcmax, 5./3.)-pow(Mcmin, 5./3.))/((double)TSsize-1), 3./5.); for ( j=0; j < wl; j++ ){ f0 = fmin0 + (double)j*(fmax0-fmin0)/((double)wl-1.); gsl_complex gctmp; COMPLEX16 ctmp; m0 = real_model(f0, Mc); ctmp = imag_model(f0, Mc); GSL_SET_COMPLEX(&gctmp, creal(ctmp), cimag(ctmp)); gsl_vector_set(freqs, j, f0); gsl_matrix_set(TS, k, j, m0); gsl_matrix_complex_set(cTS, k, j, gctmp); } } /* create reduced orthonormal basis from training set */ if ( (RB = LALInferenceGenerateREAL8OrthonormalBasis(&fweights.vector, tolerance, TS, &nbases)) == NULL){ fprintf(stderr, "Error... problem producing basis\n"); return 1; } if ( (cRB = LALInferenceGenerateCOMPLEX16OrthonormalBasis(&fweights.vector, tolerance, cTS, &cnbases)) == NULL){ fprintf(stderr, "Error... problem producing basis\n"); return 1; } /* free the training set */ gsl_matrix_free(TS); gsl_matrix_complex_free(cTS); gsl_matrix_view RBview = gsl_matrix_view_array(RB, nbases, wl); gsl_matrix_complex_view cRBview = gsl_matrix_complex_view_array((double*)cRB, cnbases, wl); fprintf(stderr, "No. nodes (real) = %zu, %zu x %zu\n", nbases, RBview.matrix.size1, RBview.matrix.size2); fprintf(stderr, "No. nodes (complex) = %zu, %zu x %zu\n", cnbases, cRBview.matrix.size1, cRBview.matrix.size2); /* get the interpolant */ interp = LALInferenceGenerateREALROQInterpolant(&RBview.matrix); cinterp = LALInferenceGenerateCOMPLEXROQInterpolant(&cRBview.matrix); /* free the reduced basis */ XLALFree(RB); XLALFree(cRB); /* now get the terms for the likelihood with and without the reduced order quadrature * and do some timing tests */ /* create the model dot model weights */ REAL8 varval = 1.; gsl_vector_view vars = gsl_vector_view_array(&varval, 1); gsl_matrix *mmw = LALInferenceGenerateREALModelModelWeights(interp->B, &vars.vector); gsl_matrix_complex *cmmw = LALInferenceGenerateCOMPLEXModelModelWeights(cinterp->B, &vars.vector); /* let's create some Gaussian random data */ const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); REAL8 *data = XLALCalloc(wl, sizeof(REAL8)); COMPLEX16 *cdata = XLALCalloc(wl, sizeof(COMPLEX16)); for ( i=0; i<wl; i++ ){ data[i] = gsl_ran_gaussian(r, 1.0); /* real data */ cdata[i] = gsl_ran_gaussian(r, 1.0) + I*gsl_ran_gaussian(r, 1.0); /* complex data */ } /* create the data dot model weights */ gsl_vector_view dataview = gsl_vector_view_array(data, wl); gsl_vector *dmw = LALInferenceGenerateREAL8DataModelWeights(interp->B, &dataview.vector, &vars.vector); gsl_vector_complex_view cdataview = gsl_vector_complex_view_array((double*)cdata, wl); gsl_vector_complex *cdmw = LALInferenceGenerateCOMPLEX16DataModelWeights(cinterp->B, &cdataview.vector, &vars.vector); /* pick a chirp mass and generate a model to compare likelihoods */ double randMc = 1.873; /* a random frequency to create a model */ gsl_vector *modelfull = gsl_vector_alloc(wl); gsl_vector *modelreduced = gsl_vector_alloc(nbases); gsl_vector_complex *cmodelfull = gsl_vector_complex_alloc(wl); gsl_vector_complex *cmodelreduced = gsl_vector_complex_alloc(cnbases); /* create models */ for ( i=0; i<wl; i++ ){ /* models at all frequencies */ gsl_vector_set(modelfull, i, real_model(gsl_vector_get(freqs, i), randMc)); COMPLEX16 cval = imag_model(gsl_vector_get(freqs, i), randMc); gsl_complex gcval; GSL_SET_COMPLEX(&gcval, creal(cval), cimag(cval)); gsl_vector_complex_set(cmodelfull, i, gcval); } /* models at interpolant nodes */ for ( i=0; i<nbases; i++ ){ /* real model */ gsl_vector_set(modelreduced, i, real_model(gsl_vector_get(freqs, interp->nodes[i]), randMc)); } for ( i=0; i<cnbases; i++ ){ /* complex model */ COMPLEX16 cval = imag_model(gsl_vector_get(freqs, cinterp->nodes[i]), randMc); gsl_complex gcval; GSL_SET_COMPLEX(&gcval, creal(cval), cimag(cval)); gsl_vector_complex_set(cmodelreduced, i, gcval); } /* timing variables */ struct timeval t1, t2, t3, t4; double dt1, dt2; /* start with the real model */ /* get the model model term with the full model */ REAL8 mmfull, mmred; gettimeofday(&t1, NULL); XLAL_CALLGSL( gsl_blas_ddot(modelfull, modelfull, &mmfull) ); /* real model */ gettimeofday(&t2, NULL); /* now get it with the reduced order quadrature */ gettimeofday(&t3, NULL); mmred = LALInferenceROQREAL8ModelDotModel(mmw, modelreduced); gettimeofday(&t4, NULL); dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6)); dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6)); fprintf(stderr, "Real Signal:\n - M dot M (full) = %le [%.9lf s], M dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", mmfull, dt1, mmred, dt2, dt1/dt2); /* get the data model term with the full model */ REAL8 dmfull, dmred; gettimeofday(&t1, NULL); XLAL_CALLGSL( gsl_blas_ddot(&dataview.vector, modelfull, &dmfull) ); gettimeofday(&t2, NULL); /* now get it with the reduced order quadrature */ gettimeofday(&t3, NULL); dmred = LALInferenceROQREAL8DataDotModel(dmw, modelreduced); gettimeofday(&t4, NULL); dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6)); dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6)); fprintf(stderr, " - D dot M (full) = %le [%.9lf s], D dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", dmfull, dt1, dmred, dt2, dt1/dt2); /* check difference in log likelihoods */ double Lfull, Lred, Lfrac; Lfull = mmfull - 2.*dmfull; Lred = mmred - 2.*dmred; Lfrac = 100.*fabs(Lfull-Lred)/fabs(Lfull); /* fractional log likelihood difference (in %) */ fprintf(stderr, " - Fractional difference in log likelihoods = %lf%%\n", Lfrac); XLALFree(data); gsl_vector_free(modelfull); gsl_vector_free(modelreduced); gsl_matrix_free(mmw); gsl_vector_free(dmw); /* check log likelihood difference is within tolerance */ if ( Lfrac > LTOL ) { return 1; } /* now do the same with the complex model */ /* get the model model term with the full model */ COMPLEX16 cmmred, cmmfull; gsl_complex cmmfulltmp; gettimeofday(&t1, NULL); XLAL_CALLGSL( gsl_blas_zdotc(cmodelfull, cmodelfull, &cmmfulltmp) ); /* complex model */ cmmfull = GSL_REAL(cmmfulltmp) + I*GSL_IMAG(cmmfulltmp); gettimeofday(&t2, NULL); gettimeofday(&t3, NULL); cmmred = LALInferenceROQCOMPLEX16ModelDotModel(cmmw, cmodelreduced); gettimeofday(&t4, NULL); dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6)); dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6)); fprintf(stderr, "Complex Signal:\n - M dot M (full) = %le [%.9lf s], M dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", creal(cmmfull), dt1, creal(cmmred), dt2, dt1/dt2); COMPLEX16 cdmfull, cdmred; gsl_complex cdmfulltmp; gettimeofday(&t1, NULL); XLAL_CALLGSL( gsl_blas_zdotc(&cdataview.vector, cmodelfull, &cdmfulltmp) ); cdmfull = GSL_REAL(cdmfulltmp) + I*GSL_IMAG(cdmfulltmp); gettimeofday(&t2, NULL); gettimeofday(&t3, NULL); cdmred = LALInferenceROQCOMPLEX16DataDotModel(cdmw, cmodelreduced); gettimeofday(&t4, NULL); dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6)); dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6)); fprintf(stderr, " - D dot M (full) = %le [%.9lf s], D dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", creal(cdmfull), dt1, creal(cdmred), dt2, dt1/dt2); /* check difference in log likelihoods */ Lfull = creal(cmmfull) - 2.*creal(cdmfull); Lred = creal(cmmred) - 2.*creal(cdmred); Lfrac = 100.*fabs(Lfull-Lred)/fabs(Lfull); /* fractional log likelihood difference (in %) */ fprintf(stderr, " - Fractional difference in log likelihoods = %lf%%\n", Lfrac); XLALFree(cdata); gsl_vector_complex_free(cmodelfull); gsl_vector_complex_free(cmodelreduced); gsl_matrix_complex_free(cmmw); gsl_vector_complex_free(cdmw); LALInferenceRemoveREALROQInterpolant( interp ); LALInferenceRemoveCOMPLEXROQInterpolant( cinterp ); /* check log likelihood difference is within tolerance */ if ( Lfrac > LTOL ) { return 1; } return 0; }
void Spectrometer::countDispersion_BS(Medium &Osrodek, QString DataName, QProgressBar *Progress, int factor) { //lsfgerhla double a=Osrodek.itsBasis.getLatticeConstant(); double thickness=Osrodek.itsStructure.getThickness(); int RecVec=itsRecVectors; int k_prec=itsK_Precision; double wi=itsFrequencies[0]; double w_prec=itsFrequencies[1]; double wf=itsFrequencies[2]; int half=3*(2*RecVec+1)*(2*RecVec+1); int dimension=6*(2*RecVec+1)*(2*RecVec+1); int EigValStrNumber=6*(2*RecVec+1)*(2*RecVec+1); int EigValNumber=9*(2*RecVec+1)*(2*RecVec+1); std::ofstream plik; DataName="results/"+ DataName + ".dat"; QByteArray bytes = DataName.toAscii(); const char * CDataName = bytes.data(); plik.open(CDataName); //inicjalizacje wektorów i macierzy gsl_matrix *gammaA=gsl_matrix_calloc(dimension, dimension); gsl_matrix *gammaB=gsl_matrix_calloc(dimension, dimension); gsl_matrix *gammaC=gsl_matrix_calloc(dimension, dimension); gsl_matrix *gammaD=gsl_matrix_calloc(dimension, dimension); gsl_eigen_genv_workspace *wspce=gsl_eigen_genv_alloc(dimension); gsl_eigen_genv_workspace *wspce2=gsl_eigen_genv_alloc(dimension); gsl_vector_complex *StrAlpha =gsl_vector_complex_alloc(dimension); gsl_vector *StrBeta = gsl_vector_alloc(dimension); gsl_matrix_complex *StrEigenVec=gsl_matrix_complex_calloc(dimension, dimension); gsl_vector_complex *BAlpha =gsl_vector_complex_alloc(dimension); gsl_vector *BBeta = gsl_vector_alloc(dimension); gsl_matrix_complex *BasisEigenVec=gsl_matrix_complex_calloc(dimension, dimension); gsl_matrix_complex *ChosenVectors = gsl_matrix_complex_calloc(half, EigValNumber); gsl_vector_complex *ChosenValues = gsl_vector_complex_calloc(EigValNumber); gsl_matrix_complex *Boundaries=gsl_matrix_complex_calloc(EigValNumber, EigValNumber); double kx, ky, krokx, kroky, boundary_x, boundary_y; double k_zred, k_zred0; double krok = M_PI/(k_prec*a); for (int droga=0; droga<3; droga++) { //int droga = 1; if (droga==0) //droga M->Gamma { kx=-M_PI/a; krokx=krok; boundary_x=0; ky=-M_PI/a; kroky=krok; boundary_y=0; k_zred0=-1*sqrt(pow(kx/(2*M_PI/a), 2)+pow(ky/(2*M_PI/a), 2)); } else if (droga==1) { kx=0; //droga Gamma->X krokx=krok; boundary_x=M_PI/a; ky=0; kroky=0; boundary_y=0; k_zred0=sqrt(2)/2; //k_zred0=0; } else if (droga==2) { kx=M_PI/a; //Droga X->M krokx=0; boundary_x=M_PI/a; ky=0; kroky=krok; boundary_y=M_PI/a; k_zred0=sqrt(2)/2; } //petla dla wektorów falowych for (; kx <= boundary_x && ky <= boundary_y; kx=kx+krokx, ky=ky+kroky) { if (droga==0) { k_zred = abs(k_zred0 + sqrt( pow(kx/(2*M_PI/a), 2)+pow(ky/(2*M_PI/a), 2))); } else { k_zred = k_zred0 + kx/(2*M_PI/a) + ky/(2*M_PI/a); } int postep=int(100*k_zred/1.7); Progress->setValue(postep); Progress->update(); QApplication::processEvents(); //pętla dla częstości w for (double w=wi; w<wf; w=w+w_prec) { gsl_matrix_complex_set_all(Boundaries, gsl_complex_rect (0,0)); //ustawienie wartosci wyznacznika na 0 gsl_matrix_set_all(gammaA, 0); gsl_matrix_set_all(gammaB, 0); gsl_matrix_set_all(gammaC, 0); gsl_matrix_set_all(gammaD, 0); gsl_vector_complex_set_all(StrAlpha, gsl_complex_rect (0,0)); gsl_vector_set_all(BBeta, 0); gsl_vector_complex_set_all(BAlpha, gsl_complex_rect (0,0)); gsl_vector_set_all(StrBeta, 0); gsl_matrix_complex_set_all(BasisEigenVec, gsl_complex_rect (0,0)); gsl_matrix_complex_set_all(StrEigenVec, gsl_complex_rect (0,0)); gsl_matrix_complex_set_all(ChosenVectors, gsl_complex_rect (0,0)); gsl_vector_complex_set_all(ChosenValues, gsl_complex_rect (0,0)); //gammaA,B dla struktury //gammaA,B dla struktury /* S - numeruje transformaty tensora sprężystoœci i gestosci i - numeruje wiersze macierzy j - numeruje kolumny macierzy half - druga polowa macierzy */ for(int Nx=-RecVec, i=0, S=0; Nx<=RecVec; Nx++) { for(int Ny=-RecVec; Ny<=RecVec; Ny++, i=i+3) { for(int Nx_prim=-RecVec, j=0; Nx_prim<=RecVec; Nx_prim++) { for(int Ny_prim=-RecVec; Ny_prim<=RecVec; Ny_prim++, j=j+3, S++) { double Elasticity[6][6]; itsRecStructureSubstance[S].getElasticity(Elasticity); double Density=itsRecStructureSubstance[S].getDensity(); double gx=2*M_PI*Nx/a; double gy=2*M_PI*Ny/a; double gx_prim=2*M_PI*Nx_prim/a; double gy_prim=2*M_PI*Ny_prim/a; gsl_matrix_set(gammaA, i, j, Elasticity[3][3]); gsl_matrix_set(gammaA, i+1, j+1, Elasticity[3][3]); gsl_matrix_set(gammaA, i+2, j+2, Elasticity[0][0]); gsl_matrix_set(gammaB, i+2, j, -Elasticity[0][1]*(kx+gx_prim)-Elasticity[3][3]*(kx+gx)); gsl_matrix_set(gammaB, i+2, j+1, -Elasticity[0][1]*(ky+gy_prim)-Elasticity[3][3]*(ky+gy)); gsl_matrix_set(gammaB, i, j+2, -Elasticity[0][1]*(kx+gx)-Elasticity[3][3]*(kx+gx_prim)); gsl_matrix_set(gammaB, i+1, j+2, -Elasticity[0][1]*(ky+gy)-Elasticity[3][3]*(ky+gy_prim)); gsl_matrix_set(gammaB, i, j+half, -Elasticity[0][0]*(kx+gx)*(kx+gx_prim)-Elasticity[3][3]*(ky+gy)*(ky+gy_prim)+Density*w*w); gsl_matrix_set(gammaB, i+1, j+half, -Elasticity[0][1]*(kx+gx_prim)*(ky+gy)-Elasticity[3][3]*(ky+gy_prim)*(kx+gx)); gsl_matrix_set(gammaB, i, j+half+1, -Elasticity[0][1]*(ky+gy_prim)*(kx+gx)-Elasticity[3][3]*(kx+gx_prim)*(ky+gy)); gsl_matrix_set(gammaB, i+1, j+half+1, -Elasticity[0][0]*(ky+gy_prim)*(ky+gy)-Elasticity[3][3]*(kx+gx_prim)*(kx+gx)+Density*w*w); gsl_matrix_set(gammaB, i+2, j+half+2, -Elasticity[3][3]*(ky+gy_prim)*(ky+gy)-Elasticity[3][3]*(kx+gx_prim)*(kx+gx)+Density*w*w); if (i==j) { gsl_matrix_set(gammaA, i+half, j+half, 1); gsl_matrix_set(gammaA, i+half+1, j+half+1, 1); gsl_matrix_set(gammaA, i+half+2, j+half+2, 1); gsl_matrix_set(gammaB, i+half, j, 1); gsl_matrix_set(gammaB, i+half+1, j+1, 1); gsl_matrix_set(gammaB, i+half+2, j+2, 1); } } } } } //rozwiazanie zagadnienienia własnego gsl_eigen_genv(gammaB, gammaA, StrAlpha, StrBeta, StrEigenVec, wspce); //gammaC,D dla Podłoża for(int Nx=-RecVec, i=0, S=0; Nx<=RecVec; Nx++) { for(int Ny=-RecVec; Ny<=RecVec; Ny++, i=i+3) { for(int Nx_prim=-RecVec, j=0; Nx_prim<=RecVec; Nx_prim++) { for(int Ny_prim=-RecVec; Ny_prim<=RecVec; Ny_prim++, j=j+3, S++) { double Elasticity[6][6]; itsRecBasisSubstance[S].getElasticity(Elasticity); double Density=itsRecBasisSubstance[S].getDensity(); double gx=2*M_PI*Nx/a; double gy=2*M_PI*Ny/a; double gx_prim=2*M_PI*Nx_prim/a; double gy_prim=2*M_PI*Ny_prim/a; gsl_matrix_set(gammaC, i, j, Elasticity[3][3]); gsl_matrix_set(gammaC, i+1, j+1, Elasticity[3][3]); gsl_matrix_set(gammaC, i+2, j+2, Elasticity[0][0]); gsl_matrix_set(gammaD, i+2, j, -Elasticity[0][1]*(kx+gx_prim)-Elasticity[3][3]*(kx+gx)); gsl_matrix_set(gammaD, i+2, j+1, -Elasticity[0][1]*(ky+gy_prim)-Elasticity[3][3]*(ky+gy)); gsl_matrix_set(gammaD, i, j+2, -Elasticity[0][1]*(kx+gx)-Elasticity[3][3]*(kx+gx_prim)); gsl_matrix_set(gammaD, i+1, j+2, -Elasticity[0][1]*(ky+gy)-Elasticity[3][3]*(ky+gy_prim)); gsl_matrix_set(gammaD, i, j+half, -Elasticity[0][0]*(kx+gx)*(kx+gx_prim)-Elasticity[3][3]*(ky+gy)*(ky+gy_prim)+Density*w*w); gsl_matrix_set(gammaD, i+1, j+half, -Elasticity[0][1]*(kx+gx_prim)*(ky+gy)-Elasticity[3][3]*(ky+gy_prim)*(kx+gx)); gsl_matrix_set(gammaD, i, j+half+1, -Elasticity[0][1]*(ky+gy_prim)*(kx+gx)-Elasticity[3][3]*(kx+gx_prim)*(ky+gy)); gsl_matrix_set(gammaD, i+1, j+half+1, -Elasticity[0][0]*(ky+gy_prim)*(ky+gy)-Elasticity[3][3]*(kx+gx_prim)*(kx+gx)+Density*w*w); gsl_matrix_set(gammaD, i+2, j+half+2, -Elasticity[3][3]*(ky+gy_prim)*(ky+gy)-Elasticity[3][3]*(kx+gx_prim)*(kx+gx)+Density*w*w); if (i==j) { gsl_matrix_set(gammaC, i+half, j+half, 1); gsl_matrix_set(gammaC, i+half+1, j+half+1, 1); gsl_matrix_set(gammaC, i+half+2, j+half+2, 1); gsl_matrix_set(gammaD, i+half, j, 1); gsl_matrix_set(gammaD, i+half+1, j+1, 1); gsl_matrix_set(gammaD, i+half+2, j+2, 1); } } } } } //rozwiazanie zagadnienienia własnego gsl_eigen_genv(gammaD, gammaC, BAlpha, BBeta, BasisEigenVec, wspce2); double imagL, realL; //części Re i Im wartości własnych int n=0; for (int i = 0; i<dimension; i++) { //przepisanie wartości i wektorów własnych struktury do macierzy Chosen* gsl_complex StrValue; StrValue= gsl_complex_div_real(gsl_vector_complex_get(StrAlpha, i), gsl_vector_get(StrBeta,i)); gsl_vector_complex_set(ChosenValues, i, StrValue); for (int j = half, m=0; j < dimension; j++, m++) { gsl_matrix_complex_set(ChosenVectors, m, i, gsl_matrix_complex_get(StrEigenVec, j, i)); } //wybieranie odpowiednich wartości i wektorów własnych dla podłoża i przepisanie do macierzy Chosen* gsl_complex BValue; BValue= gsl_complex_div_real(gsl_vector_complex_get(BAlpha, i), gsl_vector_get(BBeta,i)); imagL=GSL_IMAG(BValue); realL=GSL_REAL(BValue); if (imagL > 0.00001 && n+EigValStrNumber<EigValNumber) //warunek na wartości własne && żeby nie było ich więcej niż połowa { gsl_vector_complex_set(ChosenValues, n+EigValStrNumber, BValue); //wybranie wartości własnej for (int j = half, m=0; j < dimension; j++, m++) { gsl_matrix_complex_set(ChosenVectors, m, n+EigValStrNumber, gsl_complex_mul_real(gsl_matrix_complex_get(BasisEigenVec, j, i), -1)); //wybranie drugiej połowy wektora własnego } n++; } } if (n+EigValStrNumber<EigValNumber) { for (int i = 0; i<dimension; i++) { gsl_complex BValue; BValue= gsl_complex_div_real(gsl_vector_complex_get(BAlpha, i), gsl_vector_get(BBeta,i)); imagL=GSL_IMAG(BValue); realL=GSL_REAL(BValue); if (imagL < 0.00001 && imagL > -0.00001 && realL < -0.00001 && n+EigValStrNumber<EigValNumber) //warunek na wartości własne && żeby nie było ich więcej niż połowa { gsl_vector_complex_set(ChosenValues, n+EigValStrNumber, BValue); //wybranie wartości własnej for (int j = half, m=0; j < dimension; j++, m++) { gsl_matrix_complex_set(ChosenVectors, m, n+EigValStrNumber, gsl_complex_mul_real(gsl_matrix_complex_get(BasisEigenVec, j, i), -1)); //wybranie drugiej połowy wektora własnego } n++; } } } //wyznacznik warunków brzegowych - konstrukcja /* S, S' - numerujš transformaty tensora sprężystoœci i - numeruje wektory własne A w pętli dla G j - numeruje warunki brzegowe dla kolejnych wektorow odwrotnych G k - numeruje wektory własne A w pętli dla G' L - numeruje wartoœci własne */ for (int Nx=-RecVec, S=0, S_prim=0, i=0, j=0; Nx <= RecVec; Nx++) { for (int Ny=-RecVec; Ny <= RecVec; Ny++, j=j+9, i=i+3) { for (int L=0; L < EigValNumber; L++) { S_prim = S; for (int Nx_prim=-RecVec, k=0; Nx_prim <= RecVec; Nx_prim++) { for (int Ny_prim=-RecVec; Ny_prim <= RecVec; Ny_prim++, S_prim++, k=k+3) { double StrElasticity[6][6]; itsRecStructureSubstance[S_prim].getElasticity(StrElasticity); double BasisElasticity[6][6]; itsRecBasisSubstance[S_prim].getElasticity(BasisElasticity); double gx_prim=2*M_PI*Nx_prim/a; double gy_prim=2*M_PI*Ny_prim/a; if (L < EigValStrNumber) { //eksponens gsl_complex exponent = gsl_complex_polar(exp(GSL_IMAG(gsl_vector_complex_get(ChosenValues, L))*thickness), -1*GSL_REAL(gsl_vector_complex_get(ChosenValues, L))*thickness); //warunki zerowania się naprężenia na powierzchni gsl_complex w1 = gsl_complex_mul_real(exponent, StrElasticity[3][3]); gsl_complex w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+2, L), (kx+gx_prim)); gsl_complex w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k, L)); gsl_complex BCjL = gsl_complex_add(gsl_complex_mul(gsl_complex_add(w2, w3), w1), gsl_matrix_complex_get(Boundaries, j, L)); gsl_matrix_complex_set(Boundaries, j, L, BCjL); w1 = gsl_complex_mul_real(exponent, StrElasticity[3][3]); w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+2, L), (ky+gy_prim)); w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k+1, L)); BCjL = gsl_complex_add(gsl_complex_mul(gsl_complex_add(w2, w3), w1), gsl_matrix_complex_get(Boundaries, j+1, L)); gsl_matrix_complex_set(Boundaries, j+1, L, BCjL); w1 = gsl_complex_mul_real(exponent, StrElasticity[0][0]); gsl_complex w11 = gsl_complex_mul_real(exponent, StrElasticity[0][1]); w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k, L), (kx+gx_prim)); gsl_complex w22 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+1, L), (ky+gy_prim)); w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k+2, L)); gsl_complex w4 = gsl_complex_add(gsl_complex_mul(gsl_complex_add(w2, w22), w11), gsl_complex_mul(w3, w1)); BCjL = gsl_complex_add(w4, gsl_matrix_complex_get(Boundaries, j+2, L)); gsl_matrix_complex_set(Boundaries, j+2, L, BCjL); //warunki równości naprężeń na granicy ośrodków - część dla struktury w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+2, L), (kx+gx_prim)); w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k, L)); BCjL = gsl_complex_add(gsl_complex_mul_real(gsl_complex_add(w2, w3), StrElasticity[3][3]), gsl_matrix_complex_get(Boundaries, j+3, L)); gsl_matrix_complex_set(Boundaries, j+3, L, BCjL); w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+2, L), (ky+gy_prim)); w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k+1, L)); BCjL = gsl_complex_add(gsl_complex_mul_real(gsl_complex_add(w2, w3), StrElasticity[3][3]), gsl_matrix_complex_get(Boundaries, j+4, L)); gsl_matrix_complex_set(Boundaries, j+4, L, BCjL); w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k, L), (kx+gx_prim)); w22 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+1, L), (ky+gy_prim)); w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k+2, L)); w4 = gsl_complex_add(gsl_complex_mul_real(gsl_complex_add(w2, w22), StrElasticity[0][1]), gsl_complex_mul_real(w3, StrElasticity[0][0])); BCjL = gsl_complex_add(w4, gsl_matrix_complex_get(Boundaries, j+5, L)); gsl_matrix_complex_set(Boundaries, j+5, L, BCjL); } else { //warunki równości naprężeń na granicy ośrodków - część dla podłoża gsl_complex w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+2, L), (kx+gx_prim)); gsl_complex w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k, L)); gsl_complex BCjL = gsl_complex_add(gsl_complex_mul_real(gsl_complex_add(w2, w3), BasisElasticity[3][3]), gsl_matrix_complex_get(Boundaries, j+3, L)); gsl_matrix_complex_set(Boundaries, j+3, L, BCjL); w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+2, L), (ky+gy_prim)); w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k+1, L)); BCjL = gsl_complex_add(gsl_complex_mul_real(gsl_complex_add(w2, w3), BasisElasticity[3][3]), gsl_matrix_complex_get(Boundaries, j+4, L)); gsl_matrix_complex_set(Boundaries, j+4, L, BCjL); w2 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k, L), (kx+gx_prim)); gsl_complex w22 = gsl_complex_mul_real(gsl_matrix_complex_get(ChosenVectors, k+1, L), (ky+gy_prim)); w3 = gsl_complex_mul(gsl_vector_complex_get(ChosenValues, L), gsl_matrix_complex_get(ChosenVectors, k+2, L)); gsl_complex w4 = gsl_complex_add(gsl_complex_mul_real(gsl_complex_add(w2, w22), BasisElasticity[0][1]), gsl_complex_mul_real(w3, BasisElasticity[0][0])); BCjL = gsl_complex_add(w4, gsl_matrix_complex_get(Boundaries, j+5, L)); gsl_matrix_complex_set(Boundaries, j+5, L, BCjL); } } } // warunek równości wychyleń na granicy ośrodków gsl_matrix_complex_set(Boundaries, j+6, L, gsl_matrix_complex_get(ChosenVectors, i, L)); gsl_matrix_complex_set(Boundaries, j+7, L, gsl_matrix_complex_get(ChosenVectors, i+1, L)); gsl_matrix_complex_set(Boundaries, j+8, L, gsl_matrix_complex_get(ChosenVectors, i+2, L)); } S=S_prim; } } //skalowanie macierzy Boundaries gsl_complex scale=gsl_complex_rect(pow(10, factor), 0); gsl_matrix_complex_scale(Boundaries, scale); //obliczenie wyznacznika z Boundaries gsl_permutation *Bpermutation = gsl_permutation_alloc(EigValNumber); int Bsignum; gsl_linalg_complex_LU_decomp(Boundaries, Bpermutation, &Bsignum); double DetVal = gsl_linalg_complex_LU_lndet(Boundaries); //usuwanie NaN if(DetVal != DetVal) DetVal = 0; //zapisanie wartości do pliku plik << k_zred << "\t" << w << "\t" << DetVal << "\n"; } plik << "\n"; } } plik.close(); gsl_matrix_free(gammaA); gsl_matrix_free(gammaB); gsl_vector_free(BBeta); gsl_vector_free(StrBeta); gsl_matrix_free(gammaC); gsl_matrix_free(gammaD); gsl_vector_complex_free(StrAlpha); gsl_vector_complex_free(BAlpha); gsl_eigen_genv_free(wspce); gsl_eigen_genv_free(wspce2); gsl_matrix_complex_free(Boundaries); gsl_matrix_complex_free(ChosenVectors); gsl_vector_complex_free(ChosenValues); }
PetscErrorCode cHamiltonianMatrix::measurement(){ double *ALLdepart = new double[Nt]; double *ALLentropy = new double[Nt]; gsl_matrix* density1 = gsl_matrix_alloc(L,Nt);//background fermion density gsl_matrix* density2 = gsl_matrix_alloc(L,Nt);//background fermion density gsl_vector* corr12 = gsl_vector_alloc(Nt);//correlation betwen fermion up and down. // The density correlation is in fact proportional to the interacting energy. double var_rank; PetscScalar var_tmp, var_tmp2; gsl_complex var_tmp_gsl; Vec vectort; VecScatter ctx; ofstream output; VecScatterCreateToZero(WFt[0],&ctx,&vectort); if(rank==0) cout << size << endl; gsl_matrix_complex* RDM = gsl_matrix_complex_alloc(dim2,dim2); gsl_vector *eval_RDM = gsl_vector_alloc(dim2); gsl_eigen_herm_workspace* w_RDM = gsl_eigen_herm_alloc(dim2); for (int itime = 0; itime < Nt; ++itime) { if (rank==0&&itime%10==0) cout << "this is time " << itime << endl; // % ## departure ## var_rank = 0.0; for (int ivar = rstart; ivar < rend; ++ivar) { ierr = VecGetValues(WFt[itime],1,&ivar,&var_tmp);CHKERRQ(ierr); var_rank += pow(gsl_vector_get(rr,ivar)*PetscAbsComplex(var_tmp),2); } MPI_Reduce(&var_rank, &(ALLdepart[itime]), 1, MPI_DOUBLE, MPI_SUM, 0, PETSC_COMM_WORLD); ALLdepart[itime] = sqrt(ALLdepart[itime]); // % ## entropy ## VecScatterBegin(ctx,WFt[itime],vectort,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(ctx,WFt[itime],vectort,INSERT_VALUES,SCATTER_FORWARD); if(rank==0) { int ivar;double eigen_RDM; gsl_matrix_complex_set_zero(RDM); for (int row2 = 0; row2 < dim2; ++row2) { for (int col2 = row2; col2 < dim2; ++col2) { var_tmp_gsl.dat[0] = 0.0; var_tmp_gsl.dat[1] = 0.0; for (int jjj = 0; jjj < dim; ++jjj) { ivar = row2*dim+jjj; ierr = VecGetValues(vectort,1,&ivar,&var_tmp);CHKERRQ(ierr); ivar = col2*dim+jjj; ierr = VecGetValues(vectort,1,&ivar,&var_tmp2);CHKERRQ(ierr); var_tmp_gsl.dat[0] += PetscRealPart(var_tmp*PetscConj(var_tmp2)); var_tmp_gsl.dat[1] += PetscImaginaryPart(var_tmp*PetscConj(var_tmp2)); } gsl_matrix_complex_set(RDM,row2,col2,var_tmp_gsl); if (col2 != row2) { gsl_matrix_complex_set(RDM,col2,row2,gsl_matrix_complex_get(RDM,row2,col2)); } } } gsl_eigen_herm(RDM,eval_RDM,w_RDM); ALLentropy[itime] = 0; for (ivar = 0; ivar < dim2; ++ivar) { eigen_RDM = gsl_vector_get(eval_RDM, ivar); // cout << eigen_RDM << endl; ALLentropy[itime] += -eigen_RDM*log(eigen_RDM); } } // % ## density distribution of impurity fermion if(rank==0) { int ivar; for (int row2 = 0; row2 < dim2; ++row2) { for (int jpar = 0; jpar < N2; ++jpar) { double density_tmp=0; for (int jjj = 0; jjj < dim; ++jjj) { ivar = row2*dim+jjj; ierr = VecGetValues(vectort,1,&ivar,&var_tmp);CHKERRQ(ierr); density_tmp +=pow(PetscAbsComplex(var_tmp),2); } /*if (itime==0) { if (rank==0) cout << "density_tmp=" << density_tmp << endl; }*/ gsl_matrix_set(density2,gsl_matrix_get(basis2,jpar,row2)-1,itime,gsl_matrix_get(density2,gsl_matrix_get(basis2,jpar,row2)-1,itime)+density_tmp); } } } /*if (rank==0) { cout << "density of impurity:" << endl; for (int jpar =0; jpar < L; ++jpar) { cout << gsl_matrix_get(density2,jpar,itime) << "\t"; } cout << endl; }*/ // % ## density distribution of majority fermions if(rank==0) { int ivar; for (int jjj = 0; jjj < dim; ++jjj) { for (int jpar = 0; jpar < N; ++jpar) { double density_tmp=0; for (int row2 = 0; row2 < dim2; ++row2) { ivar = row2*dim+jjj; ierr = VecGetValues(vectort,1,&ivar,&var_tmp);CHKERRQ(ierr); density_tmp +=pow(PetscAbsComplex(var_tmp),2); } gsl_matrix_set(density1,gsl_matrix_get(basis1,jpar,jjj)-1,itime,gsl_matrix_get(density1,gsl_matrix_get(basis1,jpar,jjj)-1,itime)+density_tmp); } } } // correlation between impurity and majority fermion if(rank==0) { int ivar; double corr_tmp=0; for (int jimp=0; jimp<dim2; ++jimp) { for (int jmaj=0; jmaj<dim; ++jmaj) { for (int jpar=0; jpar<N; ++jpar) { if (gsl_matrix_get(basis1,jpar,jmaj)==jimp+1){ ivar = jimp*dim+jmaj; ierr = VecGetValues(vectort,1,&ivar,&var_tmp);CHKERRQ(ierr); corr_tmp+=pow(PetscAbsComplex(var_tmp),2); } } } } gsl_vector_set(corr12,itime,corr_tmp); }// end of correlation } if (rank == 0) { char filename[50]; sprintf(filename,"measurement.data"); output.open(filename); output.is_open(); output.precision(16); for (int itime = 0; itime < Nt; ++itime) { if (itime==0) { // cout << "time t[1] " << '\t' << "departure[2] " << '\t' << "entropy[3]" << '\t' << "density of majority [L]" <<'\t' << "density of impurity [L]" << endl; } output << dt*itime-3 << '\t' << ALLdepart[itime] << '\t' << ALLentropy[itime] << '\t'; for (int jpar = 0; jpar < L; ++jpar) { output << gsl_matrix_get(density1,jpar,itime) << '\t'; } for (int jpar = 0; jpar < L; ++jpar) { output << gsl_matrix_get(density2,jpar,itime) << '\t'; } output << gsl_vector_get(corr12,itime) << '\t'; output << endl; } output.close(); } // CopyFile(source,destination,FALSE); delete[] ALLdepart; VecScatterDestroy(&ctx); VecDestroy(&vectort); gsl_matrix_complex_free(RDM); gsl_vector_free(eval_RDM); gsl_eigen_herm_free(w_RDM); gsl_matrix_free(density1); gsl_matrix_free(density2); gsl_vector_free(corr12); // CopyFile(source,destination,FALSE); return ierr; }
void MCPMPCoeffs::Run() { gsl_complex z = gsl_complex_rect(0,0); gsl_complex o = gsl_complex_rect(1,0); // MODEL 1 // Single GeoInit // Multiple Update Positions every GeoUpdateInterval // if (runCount++ % GEO_UPDATE_INTERVAL == 0) { // uncomment for time continuous model //GeoUpdate(OFDM_SYMBOL_TIME_US * GEO_UPDATE_INTERVAL * 1.0e-6); // uncomment for snapshot model GeoInit(); SpatialChannelUpdate(); if (geoRenderEnabled) GeoRender(); //cout << "Updating node positions." << endl; //gsl_matrix_show(pathLoss); } // // // CHANNEL MODEL BASED ON // CAI AND GIANNAKIS: 2D CHANNEL SIMULATION MODEL FOR SHADOWING PROCESSES // IEEE Trans Veh Tech Vol 52, No. 6, Nov. 2003 // // // // Exponentially decaying power profile // // gsl_matrix_complex_set_all(ch,z); gsl_complex chcoeff; // cout << "MODIFIED CHANNEL !!!!!!!!!!!!!!!!" << endl; for (int i=0; i<_M; i++) { // user i (tx) for (int ii=0;ii<_M;ii++) { // user ii (rx) double plgain = gain * gsl_matrix_get(pathLoss,i,ii); for (int j=0; j<L(); j++) { // tap j double coeffstd=plgain*exp(-j/PTau())/sqrt(2.0); if (j==0) { // if this is the first tab chcoeff = gsl_complex_rect( gsl_ran_gaussian(ran,coeffstd) + coeffstd * gainrice, gsl_ran_gaussian(ran,coeffstd)); //chcoeff = o; } else { // this is not the first tap chcoeff = gsl_complex_rect( gsl_ran_gaussian(ran,coeffstd), gsl_ran_gaussian(ran,coeffstd)); } // if gsl_matrix_complex_set(ch,i*_M+ii,j,chcoeff); } // j loop } // ii loop } // i loop //} // if (runCount++ % GEO_UPDATE_INTERVAL == 0) // cout << "channel:" << endl; // gsl_matrix_complex_show(ch); //////// production of data mout1.DeliverDataObj( *ch ); }
void MBlockUser::Run() { // // Allocation Matrices // gsl_matrix_uint signature_frequencies=min2.GetDataObj(); gsl_matrix signature_powers=min3.GetDataObj(); // // input bits // gsl_matrix_uint inputbits = min1.GetDataObj(); // // outer loop: the users // for (int u=0;u<M();u++) { gsl_vector_complex_view tmpout = gsl_matrix_complex_column(outmat,u); // // // FETCH K INPUT SYMBOLS // // for (int j=0;j<K();j++) { symbol_id=0; //////// I take Nb bits from input and map it in new_symbol for (int i=0;i<Nb();i++) { symbol_id = (symbol_id << 1); // symbol_id += in1.GetDataObj(); symbol_id += gsl_matrix_uint_get(&inputbits,u,j*Nb()+i); } new_symbol = gsl_complex_polar(1.0, symbol_arg * double(gsl_vector_uint_get(gray_encoding, symbol_id))); gsl_vector_complex_set(tmp,j,new_symbol); } // // // SELECTION MATRIX UPDATE and POWER // // // gsl_matrix_complex_set_identity(selection_mat); gsl_matrix_complex_set_zero(selection_mat); for (int i=0;i<J(); i++) { unsigned int carrier=gsl_matrix_uint_get(&signature_frequencies,u,i); double power=gsl_matrix_get(&signature_powers,u,i); gsl_complex one=gsl_complex_polar(power,0.0); gsl_matrix_complex_set(selection_mat,carrier,i,one); } // // // PRECODING MATRIX UPDATE // // #ifdef GIANNAKIS_PRECODING double roarg=2.0*double(M_PI/N()); for (int i=0;i<J(); i++) { unsigned int carrier=gsl_matrix_uint_get(&signature_frequencies,u,i); for (int j=0; j<K(); j++) { gsl_complex ro=gsl_complex_polar(sqrt(1.0/double(J())),-j*carrier*roarg); gsl_matrix_complex_set(coding_mat,i,j,ro); } } #else double roarg=2.0*double(M_PI/J()); for (int i=0;i<J(); i++) { for (int j=0; j<K(); j++) { gsl_complex ro=gsl_complex_polar(sqrt(1.0/double(J())),-j*i*roarg); gsl_matrix_complex_set(coding_mat,i,j,ro); } } #endif #ifdef SHOW_MATRIX cout << endl << BlockName << " user: "******"coding matrix (theta) = " << endl; gsl_matrix_complex_show(coding_mat); cout << "T^h*T matrix = " << endl; gsl_matrix_complex_show(THT); cout << "T^h*T trace = " << GSL_REAL(trace) << ", " << GSL_IMAG(trace) << endl; gsl_matrix_complex_free(THT); #endif // // // PRECODING // // gsl_blas_zgemv(CblasNoTrans, gsl_complex_rect(1.0,0), coding_mat, tmp, gsl_complex_rect(0,0), tmp1); // // // CARRIER SELECTION // // gsl_blas_zgemv(CblasNoTrans, gsl_complex_rect(1.0,0), selection_mat, tmp1, gsl_complex_rect(0,0), tmp2); // // // IFFT TRANSFORM // // gsl_blas_zgemv(CblasNoTrans, gsl_complex_rect(1.0,0), transform_mat, tmp2, gsl_complex_rect(0,0), &tmpout.vector); // cout << "\n\n symbols (user " << u << ") = " << endl; // gsl_vector_complex_fprintf(stdout,tmp,"%f"); #ifdef SHOW_MATRIX cout << "\n\n symbols (user " << u << ") = " << endl; gsl_vector_complex_fprintf(stdout,tmp,"%f"); cout << "\n\n precoded = " << endl; gsl_vector_complex_fprintf(stdout,tmp1,"%f"); cout << "\n\n precoded selected = " << endl; gsl_vector_complex_fprintf(stdout,tmp2,"%f"); cout << "\n\n precoded selected transformed = " << endl; gsl_vector_complex_fprintf(stdout,&tmpout.vector,"%f"); #endif } // close user loop mout1.DeliverDataObj(*outmat); }
static void define_lambda(VALUE module) { gsl_complex z1, zm1, zi, zmi; size_t i; char name[8]; double sqrt3 = sqrt(3.0); z1.dat[0] = 1; z1.dat[1] = 0; zm1.dat[0] = -1; zm1.dat[1] = 0; zi.dat[0] = 0; zi.dat[1] = 1; zmi.dat[0] = 0; zmi.dat[1] = -1; for (i = 0; i < 8; i++) { Lambda[i] = gsl_matrix_complex_calloc(3, 3); VLambda[i] = Data_Wrap_Struct(cLambda, 0, gsl_matrix_complex_free, Lambda[i]); sprintf(name, "Lambda%d", (int) i+1); rb_define_const(module, name, VLambda[i]); } gsl_matrix_complex_set(Lambda[0], 0, 1, z1); gsl_matrix_complex_set(Lambda[0], 1, 0, z1); gsl_matrix_complex_set(Lambda[1], 0, 1, zmi); gsl_matrix_complex_set(Lambda[1], 1, 0, zi); gsl_matrix_complex_set(Lambda[2], 0, 0, z1); gsl_matrix_complex_set(Lambda[2], 1, 1, zm1); gsl_matrix_complex_set(Lambda[3], 0, 2, z1); gsl_matrix_complex_set(Lambda[3], 2, 0, z1); gsl_matrix_complex_set(Lambda[4], 0, 2, zmi); gsl_matrix_complex_set(Lambda[4], 2, 0, zi); gsl_matrix_complex_set(Lambda[5], 1, 2, z1); gsl_matrix_complex_set(Lambda[5], 2, 1, z1); gsl_matrix_complex_set(Lambda[6], 1, 2, zmi); gsl_matrix_complex_set(Lambda[6], 2, 1, zi); gsl_matrix_complex_set(Lambda[7], 0, 0, gsl_complex_mul_real(z1, 1.0/sqrt3)); gsl_matrix_complex_set(Lambda[7], 1, 1, gsl_complex_mul_real(z1, 1.0/sqrt3)); gsl_matrix_complex_set(Lambda[7], 2, 2, gsl_complex_mul_real(z1, -2.0/sqrt3)); }
// // // BlockUser // // void MBlockUser::Setup() { //////// initialization of dynamic data structures // number of symbols Ns=(1 << Nb()); /// vector and matrix allocation gray_encoding = gsl_vector_uint_alloc(Ns); symbol_arg = 2.0*double(PI/Ns); count=0; coding_mat = gsl_matrix_complex_calloc(J(),K()); selection_mat = gsl_matrix_complex_calloc(N(),J()); transform_mat = gsl_matrix_complex_calloc(N(),N()); outmat = gsl_matrix_complex_calloc(N(),M()); // outmat(i,j) = symbol at time i from user j tmp = gsl_vector_complex_calloc(K()); tmp1 = gsl_vector_complex_calloc(J()); tmp2 = gsl_vector_complex_calloc(N()); // tmpout = gsl_vector_complex_calloc(N()); // tmpout is a view from outmat // // // IFFT MATRIX UNITARY // // double ifftarg=2.0*double(M_PI/N()); double ifftamp=1.0/sqrt(double(N())); for (int i=0; i<N(); i++) for (int j=0; j<N(); j++) gsl_matrix_complex_set(transform_mat, i, j, gsl_complex_polar(ifftamp,ifftarg*i*j) ); //////// rate declaration for ports // in1.SetRate( Nb()*K()*M() ); // M users K symbols Nb bits ///////// Gray Encoder SetUp for (unsigned int i=0; i<Ns; i++) { gsl_vector_uint_set(gray_encoding,i,0); for (unsigned int k=0; k<Nb(); k++) { unsigned int t=(1<<k); unsigned int tt=2*t; unsigned int ttt= gsl_vector_uint_get(gray_encoding,i) + t * (((t+i)/tt) % 2); gsl_vector_uint_set(gray_encoding,i,ttt); } } }
static void define_eye(VALUE module) { gsl_complex z; Eye2 = gsl_matrix_complex_calloc(2, 2); VEye2 = Data_Wrap_Struct(cgsl_matrix_complex_const, 0, gsl_matrix_complex_free, Eye2); z.dat[0] = 1; z.dat[1] = 0; gsl_matrix_complex_set(Eye2, 0, 0, z); gsl_matrix_complex_set(Eye2, 1, 1, z); rb_define_const(module, "Eye2", VEye2); Eye4 = gsl_matrix_complex_calloc(4, 4); VEye4 = Data_Wrap_Struct(cgsl_matrix_complex_const, 0, gsl_matrix_complex_free, Eye4); z.dat[0] = 1; z.dat[1] = 0; gsl_matrix_complex_set(Eye4, 0, 0, z); gsl_matrix_complex_set(Eye4, 1, 1, z); gsl_matrix_complex_set(Eye4, 2, 2, z); gsl_matrix_complex_set(Eye4, 3, 3, z); rb_define_const(module, "Eye4", VEye4); IEye2 = gsl_matrix_complex_calloc(2, 2); VIEye2 = Data_Wrap_Struct(cgsl_matrix_complex_const, 0, gsl_matrix_complex_free, IEye2); z.dat[0] = 0; z.dat[1] = 1; gsl_matrix_complex_set(IEye2, 0, 0, z); gsl_matrix_complex_set(IEye2, 1, 1, z); rb_define_const(module, "IEye2", VIEye2); IEye4 = gsl_matrix_complex_calloc(4, 4); VIEye4 = Data_Wrap_Struct(cgsl_matrix_complex_const, 0, gsl_matrix_complex_free, IEye4); gsl_matrix_complex_set(IEye4, 0, 0, z); gsl_matrix_complex_set(IEye4, 1, 1, z); gsl_matrix_complex_set(IEye4, 2, 2, z); gsl_matrix_complex_set(IEye4, 3, 3, z); rb_define_const(module, "IEye4", VIEye4); }
/** ---------------------------------------------------------------------------- * Sort eigenvectors */ int gsl_ext_eigen_sort(gsl_matrix_complex *evec, gsl_vector_complex *eval, int sort_order) { gsl_complex z; gsl_matrix_complex *evec_copy; gsl_vector_complex *eval_copy; int *idx_map, i, j, idx_temp; double p1, p2; if ((evec->size1 != evec->size2) || (evec->size1 != eval->size)) { return -1; } evec_copy = gsl_matrix_complex_alloc(evec->size1, evec->size2); eval_copy = gsl_vector_complex_alloc(eval->size); idx_map = (int *)malloc(sizeof(int) * eval->size); gsl_matrix_complex_memcpy(evec_copy, evec); gsl_vector_complex_memcpy(eval_copy, eval); // calculate new eigenvalue order for (i = 0; i < eval->size; i++) { idx_map[i] = i; } for (i = 0; i < eval->size - 1; i++) { for (j = i+1; j < eval->size; j++) { idx_temp = -1; if (sort_order == GSL_EXT_EIGEN_SORT_ABS) { p1 = gsl_complex_abs(gsl_vector_complex_get(eval, idx_map[i])); p2 = gsl_complex_abs(gsl_vector_complex_get(eval, idx_map[j])); if (p1 > p2) { idx_temp = idx_map[i]; } } if (sort_order == GSL_EXT_EIGEN_SORT_PHASE) { p1 = gsl_complex_arg(gsl_vector_complex_get(eval, idx_map[i])); p2 = gsl_complex_arg(gsl_vector_complex_get(eval, idx_map[j])); if (p1 > M_PI) p1 -= 2*M_PI; if (p1 <= -M_PI) p1 += 2*M_PI; if (p2 > M_PI) p2 -= 2*M_PI; if (p2 <= -M_PI) p2 += 2*M_PI; //if (((p2 < p1) && (p1 - p2 < M_PI)) || ) if (p2 < p1) { idx_temp = idx_map[i]; } } if (idx_temp != -1) { // swap //idx_temp = idx_map[i]; idx_map[i] = idx_map[j]; idx_map[j] = idx_temp; } } } // reshuffle the eigenvectors and eigenvalues for (i = 0; i < eval->size; i++) { for (j = 0; j < eval->size; j++) { z = gsl_matrix_complex_get(evec_copy, idx_map[i], j); gsl_matrix_complex_set(evec, i, j, z); //z = gsl_matrix_complex_get(evec_copy, i, idx_map[j]); //gsl_matrix_complex_set(evec, i, j, z); } z = gsl_vector_complex_get(eval_copy, idx_map[i]); gsl_vector_complex_set(eval, i, z); } gsl_matrix_complex_free(evec_copy); gsl_vector_complex_free(eval_copy); free(idx_map); return 0; }
int gsl_linalg_complex_LU_decomp (gsl_matrix_complex * A, gsl_permutation * p, int *signum) { if (A->size1 != A->size2) { GSL_ERROR ("LU decomposition requires square matrix", GSL_ENOTSQR); } else if (p->size != A->size1) { GSL_ERROR ("permutation length must match matrix size", GSL_EBADLEN); } else { const size_t N = A->size1; size_t i, j, k; *signum = 1; gsl_permutation_init (p); for (j = 0; j < N - 1; j++) { /* Find maximum in the j-th column */ gsl_complex ajj = gsl_matrix_complex_get (A, j, j); double max = gsl_complex_abs (ajj); size_t i_pivot = j; for (i = j + 1; i < N; i++) { gsl_complex aij = gsl_matrix_complex_get (A, i, j); double ai = gsl_complex_abs (aij); if (ai > max) { max = ai; i_pivot = i; } } if (i_pivot != j) { gsl_matrix_complex_swap_rows (A, j, i_pivot); gsl_permutation_swap (p, j, i_pivot); *signum = -(*signum); } ajj = gsl_matrix_complex_get (A, j, j); if (!(GSL_REAL(ajj) == 0.0 && GSL_IMAG(ajj) == 0.0)) { for (i = j + 1; i < N; i++) { gsl_complex aij_orig = gsl_matrix_complex_get (A, i, j); gsl_complex aij = gsl_complex_div (aij_orig, ajj); gsl_matrix_complex_set (A, i, j, aij); for (k = j + 1; k < N; k++) { gsl_complex aik = gsl_matrix_complex_get (A, i, k); gsl_complex ajk = gsl_matrix_complex_get (A, j, k); /* aik = aik - aij * ajk */ gsl_complex aijajk = gsl_complex_mul (aij, ajk); gsl_complex aik_new = gsl_complex_sub (aik, aijajk); gsl_matrix_complex_set (A, i, k, aik_new); } } } } return GSL_SUCCESS; } }
static bool _convert(CMATRIX *_object, GB_TYPE type, GB_VALUE *conv) { if (THIS) { if (!COMPLEX(THIS)) { switch (type) { /*case GB_T_FLOAT: conv->_float.value = gsl_blas_dnrm2(MAT(THIS)); return FALSE; case GB_T_SINGLE: conv->_single.value = gsl_blas_dnrm2(MAT(THIS)); return FALSE; case GB_T_INTEGER: case GB_T_SHORT: case GB_T_BYTE: conv->_integer.value = gsl_blas_dnrm2(MAT(THIS)); return FALSE; case GB_T_LONG: conv->_long.value = gsl_blas_dnrm2(MAT(THIS)); return FALSE;*/ case GB_T_STRING: case GB_T_CSTRING: conv->_string.value.addr = _to_string(THIS, type == GB_T_CSTRING); conv->_string.value.start = 0; conv->_string.value.len = GB.StringLength(conv->_string.value.addr); return FALSE; default: return TRUE; } } else { switch (type) { /*case GB_T_FLOAT: conv->_float.value = gsl_blas_dznrm2(CMAT(THIS)); return FALSE; case GB_T_SINGLE: conv->_single.value = gsl_blas_dznrm2(CMAT(THIS)); return FALSE; case GB_T_INTEGER: case GB_T_SHORT: case GB_T_BYTE: conv->_integer.value = gsl_blas_dznrm2(CMAT(THIS)); return FALSE; case GB_T_LONG: conv->_long.value = gsl_blas_dznrm2(CMAT(THIS)); return FALSE;*/ case GB_T_STRING: case GB_T_CSTRING: conv->_string.value.addr = _to_string(THIS, type == GB_T_CSTRING); conv->_string.value.start = 0; conv->_string.value.len = GB.StringLength(conv->_string.value.addr); return FALSE; default: return TRUE; } } } else if (type >= GB_T_OBJECT) { /*if (type == CLASS_Complex) { CCOMPLEX *c = (CCOMPLEX *)conv->_object.value; CMATRIX *m = MATRIX_create(2, 2, FALSE, FALSE); gsl_matrix_set(MAT(m), 0, 0, GSL_REAL(c->number)); gsl_matrix_set(MAT(m), 1, 1, GSL_REAL(c->number)); gsl_matrix_set(MAT(m), 0, 1, -GSL_IMAG(c->number)); gsl_matrix_set(MAT(m), 1, 0, GSL_IMAG(c->number)); conv->_object.value = m; return FALSE; } else*/ if (GB.Is(conv->_object.value, CLASS_Array)) { GB_ARRAY array = (GB_ARRAY)conv->_object.value; GB_ARRAY array2; int height = GB.Array.Count(array); int width = 0; GB_TYPE atype = GB.Array.Type(array); GB_TYPE atype2; int i, j, w; GB_VALUE temp; void *data; CMATRIX *m; CCOMPLEX *c; bool complex; if (atype >= GB_T_OBJECT) { complex = FALSE; for (i = 0; i < height; i++) { data = GB.Array.Get(array, i); array2 = *((void **)data); if (!array2 || !GB.Is(array2, CLASS_Array)) return TRUE; w = GB.Array.Count(array2); if (w > width) width = w; atype2 = GB.Array.Type(array2); if (atype2 == GB_T_VARIANT || atype2 == CLASS_Complex) complex = TRUE; else if (!(atype2 > GB_T_BOOLEAN && atype2 <= GB_T_FLOAT)) return TRUE; } //fprintf(stderr, "create: %d %d %d\n", width, height, complex); m = MATRIX_create(width, height, complex, TRUE); for (i = 0; i < height; i++) { array2 = *((void **)GB.Array.Get(array, i)); atype2 = GB.Array.Type(array2); w = GB.Array.Count(array2); if (atype2 > GB_T_BOOLEAN && atype2 <= GB_T_FLOAT) { for (j = 0; j < w; j++) { data = GB.Array.Get(array2, j); GB.ReadValue(&temp, data, atype2); GB.Conv(&temp, GB_T_FLOAT); if (complex) gsl_matrix_complex_set(CMAT(m), i, j, gsl_complex_rect(temp._float.value, 0)); else gsl_matrix_set(MAT(m), i, j, temp._float.value); } } else if (atype2 == GB_T_VARIANT) { for (j = 0; j < w; j++) { GB.ReadValue(&temp, GB.Array.Get(array2, j), atype2); GB.BorrowValue(&temp); GB.Conv(&temp, CLASS_Complex); c = temp._object.value; if (c) gsl_matrix_complex_set(CMAT(m), i, j, c->number); else gsl_matrix_complex_set(CMAT(m), i, j, COMPLEX_zero); GB.ReleaseValue(&temp); } } else if (atype2 == CLASS_Complex) { for (j = 0; j < w; j++) { c = *((CCOMPLEX **)GB.Array.Get(array2, j)); if (c) gsl_matrix_complex_set(CMAT(m), i, j, c->number); else gsl_matrix_complex_set(CMAT(m), i, j, COMPLEX_zero); } } } conv->_object.value = m; return FALSE; } } } /*else if (type > GB_T_BOOLEAN && type <= GB_T_FLOAT) { CMATRIX *m = MATRIX_create(2, 2, FALSE, TRUE); double value; if (type == GB_T_FLOAT) value = conv->_float.value; else if (type == GB_T_SINGLE) value = conv->_single.value; else value = conv->_integer.value; gsl_matrix_set(MAT(m), 0, 0, value); gsl_matrix_set(MAT(m), 1, 1, value); conv->_object.value = m; return FALSE; }*/ return TRUE; }
int main(int argc, char *argv[]){ int i,j,k, c, N; int dflag=0, eflag=0, gflag=0, vflag=0, hflag=0; float w; /* frec */ //char *lvalue=NULL; double **M, // XYZ coordinates dos, lambda=0; while((c = getopt (argc, argv, "degvhl:")) != -1){ switch (c){ case 'd': dflag = 1; break; case 'e': eflag = 1; break; case 'g': gflag = 1; break; case 'v': vflag = 1; break; case 'h': hflag = 1; break; case 'l': lambda = atof(optarg); break; } } scanf("%d",&N); M = (double **) malloc (N*sizeof(double *)); // coordinate matrix // read coordinates (XYZ format file) for (int i=0; i<N; i++){ char null[5]; // discard element double *tmp = (double *) malloc (3 * sizeof(double)); // 3 coordinates scanf("%s%lf%lf%lf", null, &tmp[0], &tmp[1], &tmp[2]); M[i] = tmp; // printf("- %.2f %.2f\n",M[i][0], M[i][1]); // DEBUG } /* M: coordinate matrix, N: number of atoms, l: spin-orbit parameter (set to 0 to tight-binding)*/ gsl_matrix_complex * Hso = hamiltonian(M, N, lambda); /* print hamiltonial */ if (hflag){ printComMat(Hso,N*SPIN*ORB); return 0; } /* eigenvalues */ gsl_matrix_complex * evec = gsl_matrix_complex_alloc(N*SPIN*ORB, N*SPIN*ORB); gsl_vector * eval = gsl_vector_alloc(N*SPIN*ORB); gsl_eigen_hermv_workspace * ws = gsl_eigen_hermv_alloc(N*SPIN*ORB); gsl_matrix_complex * A = Hso; // gsl_eigen_hermv() destroys Hso matrix, use a copy instead gsl_eigen_hermv (A, eval, evec, ws); gsl_eigen_hermv_sort (eval, evec, GSL_EIGEN_SORT_VAL_ASC); gsl_eigen_hermv_free(ws); if (eflag){ for (int i=0; i<N*SPIN*ORB; i++) printf("%d %.4g \n", i, gsl_vector_get(eval,i)); return 0; } if (vflag){ printComMat(evec, N*SPIN*ORB); return 0; } /* calculate DoS * __ __ * \ \ Hij Hji * DOS(E) = -imag /_ /_ ---------------- * i j E - En + i*eta * * where H is the hamiltonian, and n is the state. * NOTE: i and j 0-indexed list. i*eta */ double eval_min = gsl_vector_min (eval), /* lower bound */ eval_max = gsl_vector_max (eval); /* upper bound */ if (dflag) for (w = eval_min; w < eval_max; w += 1e-3){ dos = 0; #pragma omp parallel num_threads(4) { int tid = omp_get_thread_num(); #pragma omp for private(i,k) reduction (+:dos) for (i=0; i<N*SPIN*ORB; i++) for (k=0; k<N*SPIN*ORB; k++){ gsl_complex h = gsl_matrix_complex_get (Hso, i, k); double l = gsl_vector_get (eval ,k); gsl_complex z = gsl_complex_rect(0,5e-3); /* parte imaginaria */ gsl_complex num = gsl_complex_mul(h,gsl_complex_conjugate(h)); /* numerador */ gsl_complex den = gsl_complex_add_real(z, w-l); /* denominador */ gsl_complex g = gsl_complex_div(num,den); dos += GSL_IMAG(g); } if (dflag && tid==0) printf("%.3g %g \n", w, -dos/PI); } } /* Green's function * * <i|n> <n|j> * Gij(E) = ---------------- * E - En + i*eta * * where i and j are atoms, and n is the state. * NOTE: i and j 0-indexed list. */ int list[]={0,1,2,5,6,7}; /* atoms to get conductance */ int NL = (int) sizeof(list)/sizeof(list[0]); gsl_matrix_complex * G = gsl_matrix_complex_alloc(NL*SPIN*ORB, NL*SPIN*ORB); // Green if (gflag) for (double E = eval_min; E < eval_max; E += 1e-3){ // energy gsl_matrix_complex_set_all(G, GSL_COMPLEX_ZERO); // init for (int n=0; n<N*SPIN*ORB; n++) // states for (i=0; i<NL; i++) // atoms for (j=0; j<NL; j++) // atoms for (int k0=0; k0<SPIN*ORB; k0++){ // orbitals for (int k1=0; k1<SPIN*ORB; k1++){ // orbitals gsl_complex in = gsl_matrix_complex_get (evec, n, list[i]*SPIN*ORB+k0); gsl_complex nj = gsl_matrix_complex_get (evec, n, list[j]*SPIN*ORB+k1); double En = gsl_vector_get (eval ,n); gsl_complex eta = gsl_complex_rect(0,5e-3); /* delta */ gsl_complex num = gsl_complex_mul(in, gsl_complex_conjugate(nj)); /* num */ gsl_complex den = gsl_complex_add_real(eta, E - En); /* den */ gsl_complex Gij = gsl_complex_div(num,den); gsl_complex tmp = gsl_matrix_complex_get(G, i*SPIN*ORB+k0, j*SPIN*ORB+k1); gsl_complex sum = gsl_complex_add(tmp, Gij); gsl_matrix_complex_set(G, i*SPIN*ORB+k0, j*SPIN*ORB+k1, sum); } } dos = 0 ; for(int i=0; i<NL*SPIN*ORB; i++) dos += GSL_IMAG( gsl_matrix_complex_get(G, i, i) ); printf("%.3g %g\n", E, -dos/PI); // printComMat(G, NL*SPIN*ORB); } gsl_matrix_complex_free(G); gsl_vector_free(eval); gsl_matrix_complex_free(evec); return 0; }