示例#1
0
文件: dirac.c 项目: Fudge/rb-gsl
static void define_pauli(VALUE module)
{
  gsl_complex z;

  Pauli[0] = gsl_matrix_complex_calloc(2, 2);
  VPauli[0] = Data_Wrap_Struct(cPauli, 0, 
			   gsl_matrix_complex_free, Pauli[0]);
  z.dat[0] = 1; z.dat[1] = 0;
  gsl_matrix_complex_set(Pauli[0], 0, 1, z);
  gsl_matrix_complex_set(Pauli[0], 1, 0, z);
  rb_define_const(module, "Pauli1", VPauli[0]);

  Pauli[1] = gsl_matrix_complex_calloc(2, 2);
  VPauli[1] = Data_Wrap_Struct(cPauli, 0, 
			   gsl_matrix_complex_free, Pauli[1]);
  z.dat[0] = 0; z.dat[1] = -1;
  gsl_matrix_complex_set(Pauli[1], 0, 1, z);
  z.dat[0] = 0; z.dat[1] = 1;
  gsl_matrix_complex_set(Pauli[1], 1, 0, z);
  rb_define_const(module, "Pauli2", VPauli[1]);

  Pauli[2] = gsl_matrix_complex_calloc(2, 2);
  VPauli[2] = Data_Wrap_Struct(cPauli, 0, 
			   gsl_matrix_complex_free, Pauli[2]);
  z.dat[0] = 1; z.dat[1] = 0;
  gsl_matrix_complex_set(Pauli[2], 0, 0, z);
  z.dat[0] = -1; z.dat[1] = 0;
  gsl_matrix_complex_set(Pauli[2], 1, 1, z);
  rb_define_const(module, "Pauli3", VPauli[2]);
}
示例#2
0
mMatComplex *
qlua_newMatComplex(lua_State *L, int sl, int sr)
{
    mMatComplex *m = qlua_newMatrix(L, sizeof (mMatComplex), mtnMatComplex);
    m->l_size = sl;
    m->r_size = sr;
    m->m = gsl_matrix_complex_calloc(sl, sr);
    if (m->m == 0) {
        lua_gc(L, LUA_GCCOLLECT, 0);
        m->m = gsl_matrix_complex_calloc(sl, sr);
        if (m->m == 0)
            luaL_error(L, "not enough memory");
    }
    return m;
}
示例#3
0
/* 
 *      FUNCTION  
 *         Name:  entropy_of_state
 *  Description:  Calculate the Von Neumann entropy of state 'rho'
 * 
 */
double entropy_of_state ( const gsl_vector* rho )
{
	double entr = 0 ;

	/* Finding the eigenvalues */
	gsl_eigen_herm_workspace* rho_ei = gsl_eigen_herm_alloc(2);
	gsl_matrix_complex* dens = gsl_matrix_complex_calloc (2,2);
	gsl_matrix_complex_set (dens, 0, 0, gsl_complex_rect(1+VECTOR(rho, 3),0));
	gsl_matrix_complex_set (dens,0,1,gsl_complex_rect(VECTOR(rho,1),-VECTOR(rho,2)));
	gsl_matrix_complex_set (dens,1,0,gsl_complex_rect(VECTOR(rho,1),VECTOR(rho,2)));
	gsl_matrix_complex_set (dens,1,1,gsl_complex_rect(1-VECTOR(rho,3),0));
	gsl_matrix_complex_scale (dens, gsl_complex_rect(0.5,0));
	gsl_vector* eigenvalues = gsl_vector_calloc(2) ;
	gsl_eigen_herm (dens, eigenvalues, rho_ei) ;
	
	/* Calculating entropy */
	double norm = gsl_hypot3( VECTOR(rho,1), VECTOR(rho,2),	VECTOR(rho,3) ) ;
	if ( gsl_fcmp(norm, 1, 1e-9) > 0 )
		entr = 0 ;
	else
		entr = - (VECTOR(eigenvalues,0)*gsl_sf_log(VECTOR(eigenvalues,0)) +
			VECTOR(eigenvalues,1)*gsl_sf_log(VECTOR(eigenvalues,1))) ;

	return (entr);
}		/* -----  end of function entropy_of_state  ----- */
示例#4
0
文件: dirac.c 项目: Fudge/rb-gsl
static void define_alpha(VALUE module)
{
  size_t i, j, k;
  char name[7];
  for (i = 0; i < 3; i++) {
    Alpha[i] = gsl_matrix_complex_calloc(4, 4);

    for (j = 2; j < 4; j++) {
      for (k = 0; k < 2; k++) {
	gsl_matrix_complex_set(Alpha[i], j, k, 
			       gsl_matrix_complex_get(Pauli[i], j-2, k));
      }
    }
    for (j = 0; j < 2; j++) {
      for (k = 2; k < 4; k++) {
	gsl_matrix_complex_set(Alpha[i], j, k, 
			       gsl_matrix_complex_get(Pauli[i], j, k-2));
      }
    }
    VAlpha[i] = Data_Wrap_Struct(cAlpha, 0, 
			    gsl_matrix_complex_free, Alpha[i]);
    sprintf(name, "Alpha%d", (int) i+1);
    rb_define_const(module, name, VAlpha[i]);
  }
  
}
示例#5
0
文件: dirac.c 项目: Fudge/rb-gsl
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));
}
示例#6
0
void MCPMPChan::Setup() {

//////// initialization of dynamic data structures

  gsl_rng_env_setup();
  noisestd = sqrt( noisevar() );
  ran = gsl_rng_alloc( gsl_rng_default );

  cout << BlockName << ".gsl_rng_default_seed=" << gsl_rng_default_seed << endl;

  outmat = gsl_matrix_complex_calloc(N(),M());
  user_chan = gsl_matrix_complex_calloc(N(),N());

//////// rate declaration for ports


}
示例#7
0
void CPMPChan::Setup() {

//////// initialization of dynamic data structures

  user_chan = gsl_matrix_complex_calloc(N(),N());

//////// rate declaration for ports


}
示例#8
0
static CMATRIX *MATRIX_create(int width, int height, bool complex, bool init)
{
	CMATRIX *m = GB.Create(CLASS_Matrix, NULL,NULL);
	
	if (complex)
		m->matrix = init ? gsl_matrix_complex_calloc(height, width) : gsl_matrix_complex_alloc(height, width);
	else
		m->matrix = init ? gsl_matrix_calloc(height, width) : gsl_matrix_alloc(height, width);
	
	m->complex = complex;
	return m;
}
示例#9
0
文件: dirac.c 项目: Fudge/rb-gsl
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);
}
示例#10
0
文件: invert_main.c 项目: pa345/lib
int
print_correlation(const char *filename, poltor_workspace *w)
{
  int s = 0;
  const size_t p = w->p;
  const size_t nmax = GSL_MIN(w->nmax_int, w->nmax_sh);
  const size_t mmax = GSL_MIN(w->mmax_int, w->mmax_sh);
  gsl_matrix_complex *B;
  size_t n;
  FILE *fp;

  fp = fopen(filename, "w");
  if (!fp)
    {
      fprintf(stderr, "print_correlation: unable to open %s: %s\n",
              filename, strerror(errno));
      return -1;
    }

  B = gsl_matrix_complex_calloc(p, p);

  /* compute correlation matrix */
  s = lls_complex_correlation(B, w->lls_workspace_p);

  for (n = 1; n <= nmax; ++n)
    {
      int ni = (int) GSL_MIN(n, mmax);
      int m;

      for (m = -ni; m <= ni; ++m)
        {
          size_t idx1 = poltor_nmidx(POLTOR_IDX_PINT, n, m, w);
          size_t idx2 = poltor_jnmidx(0, n, m, w);
          gsl_complex z = gsl_matrix_complex_get(B, idx1, idx2);

          fprintf(fp, "%3zu %3d %e\n",
                  n,
                  m,
                  gsl_complex_abs(z));
        }

      fprintf(fp, "\n\n");
    }

  gsl_matrix_complex_free(B);

  fclose(fp);

  return s;
} /* print_correlation() */
示例#11
0
文件: dirac.c 项目: Fudge/rb-gsl
static void define_gamma(VALUE module)
{
  size_t i;
  char name[7];
  gsl_complex z;
  for (i = 1; i <= 3; i++) {
    Gamma[i] = gsl_matrix_complex_calloc(4, 4);
    gsl_matrix_complex_mul(Gamma[i], Beta, Alpha[i-1]);
    VGamma[i] = Data_Wrap_Struct(cGamma, 0, 
			    gsl_matrix_complex_free, Gamma[i]);
    sprintf(name, "Gamma%d", (int) i);
    rb_define_const(module, name, VGamma[i]);
  }
  Gamma[4] = gsl_matrix_complex_calloc(4, 4);
  z.dat[0] = 1.0; z.dat[1] = 0.0;
  gsl_matrix_complex_set(Gamma[4], 0, 2, z);
  gsl_matrix_complex_set(Gamma[4], 1, 3, z);
  gsl_matrix_complex_set(Gamma[4], 2, 0, z);
  gsl_matrix_complex_set(Gamma[4], 3, 1, z);
  VGamma[4] = Data_Wrap_Struct(cGamma, 0, 
			  gsl_matrix_complex_free, Gamma[4]);
  rb_define_const(module, "Gamma5", VGamma[4]);
}
示例#12
0
文件: dirac.c 项目: Fudge/rb-gsl
static void define_beta(VALUE module)
{
  gsl_complex z;

  Beta = gsl_matrix_complex_calloc(4, 4);
  VGamma[0] = Data_Wrap_Struct(cGamma, 0, 
			   gsl_matrix_complex_free, Beta);
  z.dat[0] = 1; z.dat[1] = 0;
  gsl_matrix_complex_set(Beta, 0, 0, z);
  gsl_matrix_complex_set(Beta, 1, 1, z);
  z.dat[0] = -1; z.dat[1] = 0;
  gsl_matrix_complex_set(Beta, 2, 2, z);
  gsl_matrix_complex_set(Beta, 3, 3, z);
  rb_define_const(module, "Beta", VGamma[0]);
  rb_define_const(module, "Gamma0", VGamma[0]);
}
示例#13
0
文件: evcache.c 项目: tflovorn/ctetra
EvecCache* init_EvecCache(int na, int nb, int nc, int num_bands, int G_order[3], int G_neg[3], UEInputFn UEfn) {
    int num_ks = (na+1)*(nb+1)*(nc+1);
    int i, j, k;
    EvecCache *evCache = (EvecCache*)malloc(sizeof(EvecCache));
    evCache->na = na;
    evCache->nb = nb;
    evCache->nc = nc;
    evCache->num_bands = num_bands;
    for (i = 0; i < 3; i++) {
        evCache->G_order[i] = G_order[i];
        evCache->G_neg[i] = G_neg[i];
    }
    evCache->UEfn = UEfn;

    // Initialize and calculate the value of the band energies and 
    // eigenvectors at each k-point.
    gsl_vector **energies = (gsl_vector**)malloc(num_ks * sizeof(gsl_vector*));
    evCache->energies = energies;
    gsl_matrix_complex **evecs = (gsl_matrix_complex**)malloc(num_ks * sizeof(gsl_matrix_complex*));
    evCache->evecs = evecs;

    for (k = 0; k < nc+1; k++) {
        for (j = 0; j < nb+1; j++) {
            for (i = 0; i < na+1; i++) {
                int kN = submesh_ijk_index(na, nb, nc, i, j, k);
                evCache->energies[kN] = gsl_vector_calloc(num_bands);
                evCache->evecs[kN] = gsl_matrix_complex_calloc(num_bands, num_bands);

                double k_opt[3] = {0, 0, 0};
                double k_orig[3] = {0, 0, 0};
                submesh_ijk_to_k(na, nb, nc, i, j, k, k_opt);
                get_k_orig(k_opt, G_order, G_neg, k_orig);
                UEfn(k_orig, evCache->energies[kN], evCache->evecs[kN]);
                verify_sort(evCache->energies[kN]);
            }
        }
    }

    return evCache;
}
示例#14
0
文件: blas3.c 项目: rbalint/rb-gsl
static VALUE rb_gsl_blas_zgemm(int argc, VALUE *argv, VALUE obj)
{
  gsl_matrix_complex *A = NULL, *B = NULL, *C = NULL;
  gsl_complex *pa = NULL, *pb = NULL;
  CBLAS_TRANSPOSE_t TransA, TransB;
  int flag = 0;
  (*pa).dat[0] = 1.0; (*pa).dat[1] = 0.0;
  (*pb).dat[0] = 0.0; (*pb).dat[1] = 0.0;
  switch (argc) {
  case 2:
    CHECK_MATRIX_COMPLEX(argv[0]);
    CHECK_MATRIX_COMPLEX(argv[1]);
    Data_Get_Struct(argv[0], gsl_matrix_complex, A);
    Data_Get_Struct(argv[1], gsl_matrix_complex, B);
    C = gsl_matrix_complex_calloc(A->size1, B->size2);
    TransA = CblasNoTrans;  TransB = CblasNoTrans;
    flag = 1;
    break;
  case 5:
    CHECK_FIXNUM(argv[0]);
    CHECK_FIXNUM(argv[1]);
    CHECK_COMPLEX(argv[2]);
    CHECK_MATRIX_COMPLEX(argv[3]);
    CHECK_MATRIX_COMPLEX(argv[4]);
    TransA = FIX2INT(argv[0]);
    TransB = FIX2INT(argv[1]);
    Data_Get_Struct(argv[2], gsl_complex, pa);
    Data_Get_Struct(argv[3], gsl_matrix_complex, A);
    Data_Get_Struct(argv[4], gsl_matrix_complex, B);
    C = gsl_matrix_complex_calloc(A->size1, B->size2);
    flag = 1;
    break;
  case 6:
    CHECK_FIXNUM(argv[0]);
    CHECK_FIXNUM(argv[1]);
    CHECK_COMPLEX(argv[2]);
    CHECK_MATRIX_COMPLEX(argv[3]);
    CHECK_MATRIX_COMPLEX(argv[4]);
    CHECK_COMPLEX(argv[5]);
    TransA = FIX2INT(argv[0]);
    TransB = FIX2INT(argv[1]);
    Data_Get_Struct(argv[2], gsl_complex, pa);
    Data_Get_Struct(argv[3], gsl_matrix_complex, A);
    Data_Get_Struct(argv[4], gsl_matrix_complex, B);
    Data_Get_Struct(argv[5], gsl_complex, pb);
    C = gsl_matrix_complex_calloc(A->size1, B->size2);
    flag = 1;
    break;
  case 7:
    CHECK_FIXNUM(argv[0]);
    CHECK_FIXNUM(argv[1]);
    CHECK_COMPLEX(argv[2]);
    CHECK_MATRIX_COMPLEX(argv[3]);
    CHECK_MATRIX_COMPLEX(argv[4]);
    CHECK_COMPLEX(argv[5]);
    CHECK_MATRIX_COMPLEX(argv[6]);
    TransA = FIX2INT(argv[0]);
    TransB = FIX2INT(argv[1]);
    Data_Get_Struct(argv[2], gsl_complex, pa);
    Data_Get_Struct(argv[3], gsl_matrix_complex, A);
    Data_Get_Struct(argv[4], gsl_matrix_complex, B);
    Data_Get_Struct(argv[5], gsl_complex, pb);
    Data_Get_Struct(argv[6], gsl_matrix_complex, C);
    break;
  default:
    rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or 7)", argc);
    break;
  }
  gsl_blas_zgemm(TransA, TransB, *pa, A, B, *pb, C);
  if (flag == 1) return Data_Wrap_Struct(cgsl_matrix_complex, 0, gsl_matrix_complex_free, C);
  else return argv[6];
}
示例#15
0
文件: blas3.c 项目: rbalint/rb-gsl
static VALUE rb_gsl_blas_zhemm(int argc, VALUE *argv, VALUE obj)
{
  gsl_matrix_complex *A = NULL, *B = NULL, *C = NULL;
  gsl_complex alpha, beta, *pa = &alpha, *pb = &beta;
  CBLAS_SIDE_t Side;
  CBLAS_UPLO_t Uplo;
  int flag = 0;
  alpha = gsl_complex_rect(1.0, 0.0);
  beta = gsl_complex_rect(0.0, 0.0);
  switch (argc) {
  case 2:
    CHECK_MATRIX_COMPLEX(argv[0]);
    CHECK_MATRIX_COMPLEX(argv[1]);
    Data_Get_Struct(argv[0], gsl_matrix_complex, A);
    Data_Get_Struct(argv[1], gsl_matrix_complex, B);
    C = gsl_matrix_complex_calloc(A->size1, B->size2);
    Side = CblasLeft;  Uplo = CblasUpper;
    flag = 1;
    break;
  case 5:
    CHECK_FIXNUM(argv[0]);
    CHECK_FIXNUM(argv[1]);
    CHECK_COMPLEX(argv[2]);
    CHECK_MATRIX_COMPLEX(argv[3]);
    CHECK_MATRIX_COMPLEX(argv[4]);
    Side = FIX2INT(argv[0]);
    Uplo = FIX2INT(argv[1]);
    Data_Get_Struct(argv[2], gsl_complex, pa);
    Data_Get_Struct(argv[3], gsl_matrix_complex, A);
    Data_Get_Struct(argv[4], gsl_matrix_complex, B);
    C = gsl_matrix_complex_calloc(A->size1, B->size2);
    flag = 1;
    break;
  case 6:
    CHECK_FIXNUM(argv[0]);
    CHECK_FIXNUM(argv[1]);
    CHECK_COMPLEX(argv[2]);
    CHECK_MATRIX_COMPLEX(argv[3]);
    CHECK_MATRIX_COMPLEX(argv[4]);
    CHECK_COMPLEX(argv[5]);
    CHECK_MATRIX_COMPLEX(argv[6]);
    Side = FIX2INT(argv[0]);
    Uplo = FIX2INT(argv[1]);
    Data_Get_Struct(argv[2], gsl_complex, pa);
    Data_Get_Struct(argv[3], gsl_matrix_complex, A);
    Data_Get_Struct(argv[4], gsl_matrix_complex, B);
    Data_Get_Struct(argv[5], gsl_complex, pb);
    C = gsl_matrix_complex_calloc(A->size1, B->size2);
    flag = 1;
    break;
  case 7:
    CHECK_FIXNUM(argv[0]);
    CHECK_FIXNUM(argv[1]);
    CHECK_COMPLEX(argv[2]);
    CHECK_MATRIX_COMPLEX(argv[3]);
    CHECK_MATRIX_COMPLEX(argv[4]);
    CHECK_COMPLEX(argv[5]);
    CHECK_MATRIX_COMPLEX(argv[6]);
    Side = FIX2INT(argv[0]);
    Uplo = FIX2INT(argv[1]);
    Data_Get_Struct(argv[2], gsl_complex, pa);
    Data_Get_Struct(argv[3], gsl_matrix_complex, A);
    Data_Get_Struct(argv[4], gsl_matrix_complex, B);
    Data_Get_Struct(argv[5], gsl_complex, pb);
    Data_Get_Struct(argv[6], gsl_matrix_complex, C);
    break;
  default:
    rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or 7)", argc);
    break;
  }
  gsl_blas_zhemm(Side, Uplo, *pa, A, B, *pb, C);
  if (flag == 1) return Data_Wrap_Struct(cgsl_matrix_complex, 0, gsl_matrix_complex_free, C);
  else return argv[6];
}
示例#16
0
//
//
// 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);
      }
    }
}
示例#17
0
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);

}
示例#18
0
文件: noise2D.c 项目: tesch1/Xrecon
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

}
示例#19
0
void DAESolver::initialize(Real variable_array_differential[], 
    Real variable_array_algebraic[], 
    const Integer a_variable_array_size,
    const Integer a_variable_array_size_differential)
{
    the_value_differential_.resize(a_variable_array_size_differential);
    memcpy(&the_value_differential_[0], variable_array_differential, 
        a_variable_array_size_differential * sizeof(Real));
    the_value_differential_buffer_ = the_value_differential_;

    const VariableArray::size_type n_algebraic(
        a_variable_array_size - a_variable_array_size_differential);
    the_value_algebraic_.resize(n_algebraic);
    memcpy(&the_value_algebraic_[0], variable_array_algebraic, 
        n_algebraic * sizeof(Real));
    the_value_algebraic_buffer_ = the_value_algebraic_;

    the_last_time_ = the_current_time_;

    is_interrupted_ = true;
    the_taylor_series_.resize(boost::extents[5]
        [static_cast< RealMatrix::index >(a_variable_array_size)]);

    eta_ = 1.0;
    the_stopping_criterion_ = std::max(10.0 * uround_ / rtoler_,
        std::min(0.03, sqrt(rtoler_)));
  
    the_first_step_flag_ = true;
    the_jacobian_calculate_flag_ = true;


    const VariableArray::size_type a_size(a_variable_array_size);
 
    if (the_system_size_ != a_size)
    {
        the_system_size_ = a_variable_array_size;
        the_function_differential_size_ = a_variable_array_size_differential;

        the_activity_algebraic_buffer_.clear();
        the_activity_algebraic_buffer_.resize(
            the_system_size_ - the_function_differential_size_);

        the_jacobian_.resize(a_size);
        for (VariableArray::size_type c(0); c < a_size; c++)
        {
            the_jacobian_[c].resize(a_size);
        }

        if (the_jacobian_matrix1_)
        {
            gsl_matrix_free(the_jacobian_matrix1_);
            the_jacobian_matrix1_ = NULLPTR;
        }
	
        if (a_size > 0)
        {
            the_jacobian_matrix1_ = gsl_matrix_calloc(a_size, a_size);
        }

        if (the_permutation1_)
        {
            gsl_permutation_free(the_permutation1_);
            the_permutation1_ = NULLPTR;
        }
	
        if (a_size > 0)
        {
            the_permutation1_ = gsl_permutation_alloc(a_size);
        }

        if (the_velocity_vector1_)
        {
            gsl_vector_free(the_velocity_vector1_);
            the_velocity_vector1_ = NULLPTR;
        }
        if (a_size > 0)
        {
            the_velocity_vector1_ = gsl_vector_calloc(a_size);
        }

        if (the_solution_vector1_)
        {
            gsl_vector_free(the_solution_vector1_);
            the_solution_vector1_ = NULLPTR;
        }
        if (a_size > 0)
        {
            the_solution_vector1_ = gsl_vector_calloc(a_size);
        }

        the_w_.resize(a_size * 3);

        if (the_jacobian_matrix2_)
        {
            gsl_matrix_complex_free(the_jacobian_matrix2_);
            the_jacobian_matrix2_ = NULLPTR;
        }
        if (a_size > 0)
        {
            the_jacobian_matrix2_ = gsl_matrix_complex_calloc(a_size, a_size);
        }

        if (the_permutation2_)
        {
            gsl_permutation_free(the_permutation2_);
            the_permutation2_ = NULLPTR;
        }
        if (a_size > 0)
        {
            the_permutation2_ = gsl_permutation_alloc(a_size);
        }

        if (the_velocity_vector2_)
        {
            gsl_vector_complex_free(the_velocity_vector2_);
            the_velocity_vector2_ = NULLPTR;
        }
        if (a_size > 0)
        {
            the_velocity_vector2_ = gsl_vector_complex_calloc(a_size);
        }

        if (the_solution_vector2_)
        {
            gsl_vector_complex_free(the_solution_vector2_);
            the_solution_vector2_ = NULLPTR;
        }
        if (a_size > 0)
        {
            the_solution_vector2_ = gsl_vector_complex_calloc(a_size);
        }
    }
}
示例#20
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);

}
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;
}
示例#22
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


}